2

I want to test my flask application which is hosted on different machine (eg - staging machie to verify if all the api unit tests are passing), Can I override the flask base url in flask test client?

Currently all tests are run on DEV local machine.

class TestAPI(unittest.TestCase):
    def setUp(self):
    self.app = create_app('testing')
    self.app_context = self.app.app_context()
    self.app_context.push()
    db.create_all()
    create_fake_data(db)
    self.client = self.app.test_client()

    def tearDown(self):
        ....

    def test_post_panel_with_good_data(self):    
        # data
        r = self.client.post('/customer',
                            data=json.dumps(data),
                            follow_redirects=True)  
        print(r.data)      
        self.assertEqual(r.status_code, 200)

Here flask test client self.client.post('/customer' ... ) generates the final URL using local machine but I want to pass custom base url so that final url can look something like this http://192.168.12.8/customer.

        r = self.client.post('/customer',
                            data=json.dumps(data),
                            follow_redirects=True)  

Please suggest a way to run test using custom base url.

Murtuza Z
  • 5,639
  • 1
  • 28
  • 52

1 Answers1

0

Probably a bit late to the party but this is my attempt using pytest.

Generate a custom FlaskClient that appends /api/v1/ to each request:

from flask.testing import FlaskClient

class CustomClient(FlaskClient):
    def open(self, *args, **kwargs):
        args = ('/api/v1/' + args[0],)
        return super().open(*args, **kwargs)

Set your "setup" fixture and make it use your CustomClient by default

@pytest.fixture()
def app():
    from app import db

    app = Flask(__name__)

    app.config.from_object("app.config.test")
    with app.app_context():
        # setup your flasks here
        db.init_app(app)
        db.create_all()
        app.test_client_class = CustomClient

        yield app

        # clean up
        db.drop_all()

Setup a fixture that yields your client when you need it.

@pytest.fixture()
def client(app):
    with app.app_context():
        client = app.test_client()
        yield client

Finally, test something with your client. This should actually request to '/api/v1/endpoint/'

def test_something(client, app):
    res = client.post("endpoint/", json={'name': 'john',
                                         'email': 'john.doe@mail.com'})
    assert res.status_code == 201
lejeunel
  • 1
  • 1