Search code examples
pythontestinghttpretty

How to execute a python test using httpretty/sure


I'm new to python tests so don't hesitate to provide any obvious information.

Basically I want to do some RESTful tests using python, and found the httpretty and sure libraries which look really nice.

I have a python file containing:

#!/usr/bin/python
from sure import expect
import requests, httpretty

@httpretty.activate 
def RestTest():
    httpretty.register_uri(httpretty.GET, "http://localhost:8090/test.json",
                           body='{"status": "ok"}',
                           content_type="application/json")

    response = requests.get("http://localhost:8090/test.json")
    expect(response.json()).to.equal({"status": "ok"}

Which is basically the same as the example code provided at https://github.com/gabrielfalcao/HTTPretty

My question is; how do I simply run this test to see it either passing or failing? I tried just executing it using ./pythonFile but that doesn't work.


Solution

  • If your test is implemented as a Python function, then of course simply trying to execute the file isn't going to run the test: nothing in that file actually calls RestTest.

    You need some sort of test framework that will call your tests and collate the results.

    One such solution is python-nose, which will look for methods named test_* and run them. So if you were to rename RestTest to test_rest, you could run:

    $ nosetests myfile.py
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.012s
    
    OK
    

    The nosetests command has a variety of options that control which tests are run, how errors are handled and reported, and more.

    Python 3 includes similar functionality in the unittest module, which is also available as a backport for Python 2 called unittest2. You could modify your code to take advantage of unittest like this:

    #!/usr/bin/python
    from sure import expect
    import requests, httpretty
    import unittest
    
    class RestTest(unittest.TestCase):
        @httpretty.activate 
        def test_rest(self):
            httpretty.register_uri(httpretty.GET, "http://localhost:8090/test.json",
                                   body='{"status": "ok"}',
                                   content_type="application/json")
    
            response = requests.get("http://localhost:8090/test.json")
            expect(response.json()).to.equal({"status": "ok"})
    
    if __name__ == '__main__':
        unittest.main()
    

    Running your file would now provide output similar to what we saw with nosetests:

    $ python myfile.py
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.012s
    
    OK