How to get return / yield value of pytest dependency
I am using pytest-dependency
to create dependency on tests. I want the dependent test to get return value from another test.
Example:
@pytest.mark.dependency()
def test_owner_create_book(app):
response = app.post(...)
return response["data"]["id"]
@pytest.mark.dependency(depends=["test_owner_create_book"])
def test_owner_read_book(app):
# I want to get the id from previous response here
How can I get the response from dependency?
Packages in use:
pytest = "^6.1.1"
pytest-dependency = "^0.5.1"
See also questions close to this topic
-
How to constantly update values from different sources?
I have telegram bot which takes the values from postgresSQL and google spreadsheet. However when i'm running it taking only static values from this sources. But i need to constantly update them. Snippet:
import pandas as pd import gspread from oauth2client.service_account import ServiceAccountCredentials import telebot from telebot import types import psycopg2 bot = telebot.TeleBot("TOKEN") scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] #--------------Getting Spreadsheet Values creds = ServiceAccountCredentials.from_json_keyfile_name('.json', scope) client = gspread.authorize(creds) sh = client.open('SPREADSHEET') sheet2 = sh.worksheet("WORKSHEET") coordinates = sheet2.col_values(5) arrive = sheet2.col_values(6) unit = sheet2.col_values(1) #--------------Getting PostgreSQL Values connection = psycopg2.connect(user="USER", password="PASSWORD", host="HOST", port="PORT",) cursor = connection.cursor() querry = "SELECT * FROM TABLE" cursor.execute(querry) ds = pd.read_sql(querry, connection) unit_s = ds['name'] engine_state = ds["engine_state"] reverse_geo = ds["reverse_geo"] speed = ds["speed_miles_per_hour"] #--------------Def for replying Telebot def value(type): unique_index = pd.Index(unit) m = unique_index.get_loc(type) arr = arrive[m] number = unit[m] info1 = status[m] geo = reverse_geo[m] final = str(f"UNIT : {number}\nSTATUS : {info1}\nENGINE STATE : {engine}\nDEPART LOCATION : {info2}\nCURRENT LOCATION : {geo} return final #--------------Keyboard Markup num1 = unit[:16] num2 = unit[16:] markup = telebot.types.ReplyKeyboardMarkup(row_width=3) for i,n in zip(num1,num2): txt = str(i) mxt = str(n) markup.row(txt,mxt) @bot.message_handler(commands=['start']) def start_message(message): bot.send_message(message.chat.id, 'Hello U Wrote Me /start', reply_markup=markup) @bot.message_handler(content_types=['text']) def send_text(message): response = message.text.lower() response1 = str(response) text = value(response) if message.text.lower() == str(response): bot.send_message(message.chat.id, str(text)) elif message.text.lower() != '': bot.send_message(message.chat.id, 'NaN') bot.delete_webhook() bot.polling()
I tried to use threding on Specifically to Getting Spreadsheet Values And Getting SQl values But i did'n figure out how to use threading with other def values
-
Increase the speed of the snake in the snake game on python
I want to increase the speed of the snake when the score goes up but it doesn't seem to work. What should i do ? I tried 2 codes unssuccessfully:
def levelup1(): if score > 10 : snake.direction == "up" y = snake.ycor() snake.sety(y + 30) if score > 10 : snake.direction == "down" y = snake.ycor() snake.sety(y - 30) if score > 10 : snake.direction == "right" x = snake.xcor() snake.setx(x + 30) if score > 10 : snake.direction == "left" x = snake.xcor() snake.setx(x - 30)
-
how to read from text in a style of dictionary?
I want to make a program that reads info from text (dictionary). If key does not exist, program should add this key and keyvalue also must be added to the text file line by line. I did something but in reading part, there is problem saying list index out of range. Can anyone help ?
with open('text.txt','r') as file: x={} for line in file: key = line.rstrip().split(':')[0] keyvalue = line.rstrip().split(':')[1] x[key]=keyvalue while True: name = input('whose hobby you wanna learn?:') if name in x: print('Name found') print("%s's hobby is %s" %(name,x[name])) else: print('i do not know',name) answer = input('do you wanna add this person?(yes or no)') if answer == ('yes'): new_user= input('type the name of new person:') new_user_hobby = input('type the hobby of that person:') x[new_user] = new_user_hobby with open('text.txt','a') as file: file.write('\n') file.write(new_user) file.write(':') file.write(new_user_hobby) print('person created successfully!')
-
Pytest fixtures not found when called inside a non-test function
I want to do call pytest fixtures on a normal function (not a test function). For example:
Below code is sitting inside
conftest.py
DATA_PATH_TEMP = '/data/data_temp.yaml' @pytest.fixture() def datapath(): return DATA_PATH_TEMP
I have my test function on a test file:
@pytest.fixture() def data_metadata(datapath): return datapath + '.yaml' def cleanup_data(*args): for arg in args: if os.path.exists(arg): os.remove(arg) def test_data_tmp(datapath): xxxxx cleanup_data(datapath, data_metadata)
I tried this code and it didn't work and threw me an error that
datapath
fixture is not recognized. I also wonder if it is possible to save that fixture as a global variable, so that I can make something like this:DATAPATH = ... # the return of the fixture def cleanup_data(): if os.path.exists(DATAPATH): os.remove(DATAPATH)
Thanks!
-
Unable to scroll real android app screen using python Appium
I am unable to scroll real android app screen using python Appium. I am using following code:
from appium.webdriver.common.touch_action import TouchAction TouchAction(driver).press(x=296, y=1135).move_to(x=302, y=672).release().perform()
-
How to pytest a Flask Endpoint
I'm getting started with Flask and Pytest in order to implemente a rest service with unit test, but i'm having some troouble.
I'll like to make a simple test for my simple endpoint but i keep getting a
Working outside of application context.
error when running the test.This is the end point:
from flask import jsonify, request, Blueprint STATUS_API = Blueprint('status_api', __name__) def get_blueprint(): """Return the blueprint for the main app module""" return STATUS_API @STATUS_API.route('/status', methods=['GET']) def get_status(): return jsonify({ 'status' : 'alive' })
And this is how I'm trying to test it (i know it should fail the test):
import pytest from routes import status_api def test_get_status(): assert status_api.get_status() == ''
I'm guessing I just cant try the method with out building the whole app. But if that's the case i dont really know how to aproach this problem
-
pytest dependency skips parameterized tests
I am writing tests using pytest. I have two tests, one depends on the other, I use pytest-dependency==0.5.1 for that. Something odd happens when I have two tests which depend on one another, but both parameterized - the dependent test is skipped even if the independent test succeeds. This is my code:
import pytest @pytest.mark.parametrize('par1', ['val1', 'val2', 'val3']) @pytest.mark.dependency() def test_a(par1): print('hi from test a') assert 1 == 1 @pytest.mark.parametrize('par2', ['val21', 'val22', 'val23']) @pytest.mark.dependency(depends=["test_a"]) def test_b(par2): print('hi from test c')
when I run pytest, I get:
pytest --log-cli-level=INFO ================================================================================================= test session starts ================================================================================================== platform linux -- Python 3.7.9, pytest-6.1.2, py-1.9.0, pluggy-0.13.1 rootdir: /home/username/dev/tests/test plugins: dependency-0.5.1, mock-3.1.1, anyio-2.0.2, dash-1.16.1, celery-4.4.7, allure-pytest-2.8.21 collected 6 items test_something.py::test_a[val1] PASSED [ 16%] test_something.py::test_a[val2] PASSED [ 33%] test_something.py::test_a[val3] PASSED [ 50%] test_something.py::test_b[val21] SKIPPED [ 66%] test_something.py::test_b[val22] SKIPPED [ 83%] test_something.py::test_b[val23] SKIPPED [100%] ============================================================================================= 3 passed, 3 skipped in 0.05s =============================================================================================
If I take down the parameterization, all is well:
pytest --log-cli-level=INFO ================================================================================================= test session starts ================================================================================================== platform linux -- Python 3.7.9, pytest-6.1.2, py-1.9.0, pluggy-0.13.1 rootdir: /home/username/dev/tests/test plugins: dependency-0.5.1, mock-3.1.1, anyio-2.0.2, dash-1.16.1, celery-4.4.7, allure-pytest-2.8.21 collected 2 items test_something.py::test_a PASSED [ 50%] test_something.py::test_b PASSED [100%] ================================================================================================== 2 passed in 0.01s ===================================================================================================
Why is it happening and how do I work around it?
-
pytest not acknowledging PASSED dependency in base class results in SKIPPED tests in derived class
I have this little project where I use pytest and pytest-dependency with tox to develop integration tests on some code. Until now I used one base class (
BTestClass
) with some common tests in the root directory and the specific tests for each code component in atest_Component.py file
next to it implementing aTestC
class that inherits fromBTestClass
.Everything worked fine until then. Now I want to add a
BTestClass2
for another set of components. So I added another layer of inheritance, but now it doesn't work, pytest validates the commonA
tests but then skips the tests that depend on it. I have no idea why.Here's the filesystem layout:
λ tree /F Folder PATH listing Volume serial number is F029-7357 C:. │ B.py │ requirements-tox.txt │ tox.ini │ ├───app_C │ └───tests │ test_C.py │ └───common A.py
common\A.py
import pytest class ATestClass(): @pytest.mark.dependency(name='test_a') def test_a(self): assert True
B.py
import pytest from common.A import ATestClass class BTestClass(ATestClass): @pytest.mark.dependency(name='test_b', depends=['test_a']) def test_b(self): assert True
test_C.py
import pytest import sys sys.path.append('.') from B import * class TestC(BTestClass): @pytest.mark.dependency(name='test_c', depends=['test_b']) def test_c(self): assert True
pytest output:
λ tox -- -rs py38 installed: ... py38 run-test-pre: PYTHONHASHSEED='367' py38 run-test: commands[0] | pytest -x -v -rs =============================================== test session starts =============================================== platform win32 -- Python 3.8.1, pytest-6.1.1, py-1.9.0, pluggy-0.13.1 -- ...\poc\.tox\py38\scripts\python.exe cachedir: .tox\py38\.pytest_cache rootdir: ...\poc plugins: dependency-0.5.1 collected 3 items app_C/tests/test_C.py::TestC::test_b SKIPPED [ 33%] app_C/tests/test_C.py::TestC::test_c SKIPPED [ 66%] app_C/tests/test_C.py::TestC::test_a PASSED [100%] ============================================= short test summary info ============================================= SKIPPED [1] .tox\py38\lib\site-packages\pytest_dependency.py:103: test_b depends on test_a SKIPPED [1] .tox\py38\lib\site-packages\pytest_dependency.py:103: test_c depends on test_b ===================================== 1 passed, 2 skipped, 1 warning in 0.14s ===================================== _____________________________________________________ summary _____________________________________________________ py38: commands succeeded congratulations :)
Any idea why
test_b
is skipped and not executed?Edit: If I make
BTestClass
standalone, removingA
/ATestClass
from the picture, it works fine.collected 2 items app_C/tests/test_C.py::TestC::test_b PASSED [ 50%] app_C/tests/test_C.py::TestC::test_c PASSED [100%]