简体   繁体   中英

How to return multiple value from a pytest fixture with scope = session

I have created pytest fixture in conftest.py for creating user and auto login

@pytest.fixture(scope="session")
def api_client():
   from rest_framework.test import APIClient
   return APIClient()

@pytest.fixture(scope="session")
@pytest.mark.django_db
def create_user():
    def make_user(**kwargs):
        # employee = e_ge_employee.objects.create()
        kwargs['password'] = 'strong-test-pass'
        if 'username' not in kwargs:
            kwargs['username'] = 'test-user'
        # if 'employee' not in kwargs:
        #     kwargs['employee'] = employee
        return e_ge_user.objects.create_user(**kwargs)
    return make_user

@pytest.fixture(scope="session")
@pytest.mark.django_db
def auto_login_user(api_client, create_user):
    def make_auto_login():
        print("_+==--=-=-=-===--=-=-==----=-=-=-=")
        user = create_user()
        api_client.login(username=user.username, password='strong-test-pass')
        return api_client, user
    return make_auto_login

Now how to call the get, post method using API client and how to access user in multiple test cases written in test_views.p

@pytest.mark.django_db
class TestViews:

    def test_generate_token_views_post(self,auto_login_user):
        **"To be Answered"**
        assert True == True

    def test_generate_token_views_post2(self,auto_login_user):
        **"To be Answered"**
        assert True == True

You can invoke make_auto_login() in the fixture , this will execute the function and return api_client and user . After that in the tests auto_login_user will be a tuple with the values

conftest.py :

@pytest.fixture(scope="session")
@pytest.mark.django_db
def auto_login_user(api_client, create_user):
    def make_auto_login():
        print("_+==--=-=-=-===--=-=-==----=-=-=-=")
        user = create_user()
        api_client.login(username=user.username, password='strong-test-pass')
        return api_client, user
    return make_auto_login()

test_views.py

class TestViews:

    def test_generate_token_views_post(self, auto_login_user):
        api_client, user = auto_login_user
        assert True

    def test_generate_token_views_post2(self, auto_login_user):
        api_client, user = auto_login_user
        assert True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM