mercredi 20 mai 2020

How to pass value from a pytest fixture to another function

I have this test scenario -

  1. Get token from a webpage
  2. Use token as Auth token to hit API

I have this directory structure -

|-testdir
|   - chromedriver
|   - config
|        - config.py
|   - endpoints
|        - api1post.py
|   - tests
|        - conftest.py    
|        - test_api1.py
|   - utils

I have the basic config like baseURL etc in the config.py, the endpoints directory contains the files where I make the api test calls and tests folder contain the test file.

I have completed step 1 mentioned above by have a fixture in the conftest.py file -

@pytest.fixture(scope='session',autouse=True)
def setup(request):
    print("initiating chrome driver")
    driver = webdriver.Chrome(chrome_path)
    driver.get(config.URL)
    driver.maximize_window()
    fake_name = fake.name()
    fake_email = fake.email()
    fake_password = fake.password(length=12)
    driver.find_element_by_id('id1').send_keys(fake_name)
    driver.find_element_by_id('id2').send_keys(fake_email)
    driver.find_element_by_id('id3').send_keys(fake_password)
    driver.find_element_by_id('id4').send_keys(fake_password)
    driver.find_element_by_name('name1').click()
    driver.find_element_by_id('id5').send_keys('sometext')
    driver.find_element_by_name('name2').click()
    token = driver.find_element_by_css_selector('some_css').get_attribute('value')
    print(token)
    request.token = token
    yield token
    driver.quit()

Now I want to use this token in the API tests as Auth token. For this, the endpoints/api1post.py file looks like this

@pytest.mark.usefixtures("setup")
class SomeClass:
    def __init__(self):
        self.url = config.SERVER + config.URL_PATH



    def CreatePOSTAPI(self, token):
        print('Auth token is %s' % self.token)
        result = requests.post(url=self.url, headers={'Authorization': 'Bearer %s' % self.token,
                                        'Content-Type': 'application/json'},
                               json={"id:1})

        print('Body is ',result.request.body)

However, this line print('Auth token is %s' % self.token) outputs Auth token is </htm, which means something is wrong? What is that I am doing wrong.

PS - For the tests, I am doing this inside the tests/test_api1.py

 @pytest.mark.usefixtures("setup")
    def test_newpostupdate(token):
        # This test registers a new user.
        postup = SomeClass()
        result = postup.v(token)
        print(result.json())
        #assert result.status_code == 200

I've gone through this link, but I'm not sure if the fix is applicable for my situation.My experience in Pytest is limited so, please point out if this is an obvious mistake.

Aucun commentaire:

Enregistrer un commentaire