Pytest Advice - sharing a token between tests
Hey all, hopefully this question falls within the scope of this subreddit. I'm hoping I can get some advice for a test suite I'm building with pytest.
General overview: I'm working on a platform that consists of several apps that are isolated by function. Each app has a RESTful API that I can interact with, but almost all of them require some form of authentication.
I've actually successfully written some tests for our auth app. I can create a user with a dict of basic information (e.g. uname, password, email) and login with their information. I'm using pytest's fixtures to create a user with random info at the session level, so that the same user is persisted through each of my tests.
I'm able to log in and get a token, which I can use to authenticate calls to the other services. The basic flow I'm looking for is something like this:
- Create user
- Authenticate user (get token)
- Use token to test a route on the account app to, say, get a list of that user's contacts
Is there a way to get the token in step 2 and use it in step 3? Or could I use a fixture at the top of the contacts module where I set a value and expose it to all the tests within that module? Something like:
# in contacts.py
default_user = {'username': 'test', 'email': 'test@mysite.com', 'password': 'hunter2'}
@pytest.fixture(scope='module', autouse=True, params=[default_user], ids=['default_user'])
def authenticate(request):
user_token = auth_with_params(params)
def test_get_contacts(authenticate):
# maybe global user_token? seems icky
response = get_user_contacts(user_token)
assert len(response) > 0
I'd love to hear how others would solve this particular problem. Maybe would you just hit the '/login' route at the beginning of each test? Thanks in advance!
P.S. I realize some of this is kind of vague (want to be careful about honoring my NDA), but I may be able to be more specific, depending on what would be helpful to know.
Posted Feb 25, 2016, 1:02 AM UTC