Creating a test for a flask app using nose2

244 Views Asked by At

I have a flask app that works (tested with postman).

I am now writing unittest for it as I am trying with Travis and CI on my repository, I use nose2.

The test class I wrote is this:

import unittest
import requests
from myapp import app


class ProjectTests(unittest.TestCase):

    ############################
    #### setup and teardown ####
    ############################

    # executed prior to each test
    def setUp(self):
        app.config["TESTING"] = True
        app.config["DEBUG"] = False
        self.app = app.test_client()

        self.assertEquals(app.debug, False)

    # executed after each test
    def tearDown(self):
        pass

    ########################
    #### helper methods ####
    ########################

    ###############
    #### tests ####
    ###############

    def test_main_page(self):
        response = self.app.get("/", follow_redirects=True)
        # self.assertIn(b"Hello World!", response.data)
        # response = app.test_client().get('/')

        assert response.status_code == 200
        # print(response.data)
        assert response.data == b"Hello, world!"

    def test_register(self):
        # import requests

        url = "http://127.0.0.1:5000/register"

        payload = '{\n\t"username": "bruno",\n\t"password": "asdf"\n}\n'
        headers = {"Content-Type": "application/json"}

        response = requests.request("POST", url, headers=headers, data=payload)

        # print(response.text.encode("utf8"))
        print(response.json()["message"])
        assert response.status_code == 400  # user already exists
if __name__ == "__main__":
unittest.main()

If I run the app and then I copy and paste the test_register method, i.e.

import requests
url = "http://127.0.0.1:5000/register"

payload = '{\n\t"username": "bruno",\n\t"password": "asdf"\n}\n'
headers = {"Content-Type": "application/json"}

response = requests.request("POST", url, headers=headers, data=payload)

# print(response.text.encode("utf8"))
print(response.json()["message"])

everything is fine. It fails if I run nose2 and I get a connection refused error. If I comment the test_register method and nose2 runs fine. I reckon I am implementing the two tests differently.

Any help on how to fix this?

0

There are 0 best solutions below