Questions tagged [pytest]
Simple powerful no-boilerplate testing with Python. Please also add the `python` tag for questions tagged with `pytest`.
7,981
questions
1
vote
1
answer
13
views
Test is not executed when pytest.fixture is used
I have a simple Python library, for which I use the following command to run tests:
python setup.py pytest
The following test works as expected:
def test_out():
assert 1 == 2
Test result:
...
0
votes
1
answer
34
views
Execution of python code on remote machines
I'm building a testing suite using Python Pytest library,
my challenge is that I want to run the test on remote windows machines without the overhead of deploying my python code on those remote ...
0
votes
0
answers
15
views
Pytest lookup rules when combining fixture, parameterize and mocks
I have an existing pytest function which utilizes several different pytest features. I'll try and boil down to the essential question:
@pytest.fixture
def mock_prereqs():
...
return prereqs
@...
1
vote
0
answers
15
views
load base class for tests from conftest in pytest
We have a lot of repeated tests for many applications (testinfra). I want to create BaseClass to be inherited by app-specific test classes to reduce boilerplate of repeated tests (is this service ...
0
votes
0
answers
21
views
Pytest - Test for database connection using object Mocking
I have class MySQL contains methods to fetch all databases user has access to. Which uses decorator for database connection. I don't want to do the actual database call so I want to mock.
I want to ...
0
votes
0
answers
20
views
How to parametrize the pytest cases below with patch.dict?
def test_index_file_generator_windows(self):
# ARRANGE
# ACT
actual: str = index_file_name_generator(...)
# ASSERT
folder = "."
expected: str = os.path.join(...
0
votes
0
answers
15
views
pytest-qt error: Widget: Must construct a QApplication before a QWidget
Problem:
I am trying to write a test for my PyQt5 GUI with pytest-qt. The problem is that when I try to run the test the error Widget: Must construct a QApplication before a QWidget occurs which is ...
0
votes
0
answers
22
views
How to pass the webdriver to conftest.py?
Now I have a problem:
I have defined a PO model with the following code:
from selenium import webdriver
class Base(object):
def __init__(self, driver=None):
if driver:
self....
1
vote
1
answer
27
views
pytest make sure your test modules/packages have valid Python names -- can't import
I have this file structure.
When ı wrote pytest in my terminal.
ı have this issue !
ModuleNotFoundError: No module named 'money_transactions_test'
Hint: make sure your test modules/packages have ...
1
vote
1
answer
21
views
Pytest AssertionError even if status code is correct
Why do I keep getting AssertionError when actually 400 is returned as in line 14 is set?
14 assert status_code == 400
15 AssertionError: assert (400, 'Please fulfill all parts!') == 400
Thanks!
-1
votes
0
answers
10
views
How to execute multiple set of pytest commands with different input parameters in pycharm terminal (command line)
We need to execute automation suit in command line for our Python-pytest pytestBDD automation framework. And the execution commands are executed one after another.
Command1:
pytest -m "Run1" ...
1
vote
0
answers
21
views
Catching Exception with pytest
I want to catch exceptions with pytest.
but I am not getting the actual output.
Here is my code:
def main():
x = input("fraction: ") # Accepting string
print(convert(x))
def ...
-1
votes
0
answers
24
views
Getting 500 internal server error when testing API endpoint
I've written some basic asserts for my delete endpoint and I encountered an interesting error, which I am unable to understand really. For the purpose of the test I had to insert a row into database ...
0
votes
0
answers
10
views
Pytest abruptly stops with %
When I run my tests pytest abruptly stops with %.
Setup:
latest docker on mac pro max m1
python 3.5
command pytest services
There is no error in the container or in the logs of pytest. I have tried ...
0
votes
0
answers
17
views
Using pytest SubRequest inside a fixture parameter
PARAMS = {"good": [1], "bad": [2]}
@pytest.fixture(scope="function")
def fixture_good(request: SubRequest) -> List[str]:
good_ans = []
try:
good_ans = ...
1
vote
1
answer
28
views
Adding custom pytest marker to skip test based on input
I would like to add a custom pytest marker which skips a test whenever a specific file is found in the directory:
@pytest.mark.file_exists("my_file.txt")
def test_mytest():
assert True
...
0
votes
0
answers
10
views
PyTest-BDD Single Scenario Outline Multiple Examples
I'd like to define a single PyTest-BDD based Scenario Outline that has multiple Examples. Sample snippet:
Scenario Outline: front to back validation
When tester executes access view ...
0
votes
1
answer
39
views
pytest cannot be executed from Python 3.10.4
I already saw one old post regarding this topic - An error while trying to execute tests on python 3.10 with pytest,
I am having the same problem, Python 3.10.4 and pytest 7.1.2, when I start command:
...
0
votes
1
answer
12
views
AttributeError: type object 'WebTablePage' has no attribute 'load' in selenium using pytest
I am learning selenium in python with pytest, I am facing this below error. I have searched this error all over the internet and tried all the possible advice, but nothing is working.
I am just trying ...
1
vote
1
answer
33
views
pytest.mark.parametrize a copy of a test case without altering the original
Background
We have a big suite of reusable test cases which we run in different environments. For our suite with test case ...
@pytest.mark.system_a
@pytest.mark.system_b
# ...
@pytest.mark.system_z
...
0
votes
0
answers
13
views
Asserting several fields, with different priorities, in the same test with Pytest
I'm using pytest to test the output of a function for different test data (too cumbersome to transform them into individual tests).
I'm using fixture @pytest.mark.parametrize for that.
In our test, we'...
0
votes
1
answer
11
views
Pytest Collect Setup/Teardown
Is there any way to collect Setup/Teardown ? If case setup/teardown error , i can restitute it? For example , I test an app.
collection = list()
SESSION:
setup -> sucess # record it in to my ...
0
votes
0
answers
36
views
Python mock multiple return values - MagicMock
file_1.py
from client import Client
def generate_data():
for surface in Client().get_surface(url):
for volume in Client().get_all_pages(surface['url']):
# processing
client....
0
votes
0
answers
13
views
What is the best way to share the sqlalchemy db session between FastAPI and pytest
I am using FastAPI to design the GUI and RESTFul APIs. When one API is called, it will trigger the pytest as background task. I want to use a table in the database to monitor the progress of the test ...
0
votes
0
answers
12
views
Developing and Testing an Asynchronous API with FastAPI and Pytest - Notes table not created
i'm following the tutorial here:
https://testdriven.io/blog/fastapi-crud/
At about midway through the tutorial, "Add a notes model to src/app/db.py:", when I complete these step and get ...
1
vote
1
answer
34
views
In Palantir Foundry, how can I only run tests on some branches of my Python Transform?
My tests currently run as part of Checks on every Commit, but they take a while to run. Is there a way I can only run the tests on certain branches (e.g., a staging branch)?
1
vote
1
answer
39
views
retrieve pytest results programmatically when run via pytest.main()
I'd like to run pytest and then store results and present them to users on demand (e.g. store pytest results to a db and then expose them through web service)
I could run pytest from a command line ...
0
votes
1
answer
24
views
Pytest plugin content in custom final section
I'm using the pytest-rerunfailures plugin to mark flaky tests in a large test suite. I like the addition the plugin makes to the output format as tests execute: I can see each test's status as it ...
0
votes
0
answers
21
views
How to add a custom flag to pytest, using the short form
I was following this answer about how to add custom arguments to pytest in order to skip tests with the custom marker. It works, but I can't seem to customize it to use a short version of the flag.
I'...
0
votes
0
answers
27
views
print the failed test output right after and not only at the end pytest
I have multiple tests that run as part of a GitLab pipline, the issue is that the tests run became very long and when a test in the middle fails one need to wait to the end of the run to see the ...
0
votes
0
answers
19
views
How to mock PostgresSQL database with pytest fixture
I have a file with two functions that I must test that look like this:
def create_conn(config):
conn = psycopg2.connect(dbname = config['dbname'], ...)
return conn
def use_conn():
conn = ...
0
votes
1
answer
15
views
Selenium Pytest - Unrecognized argument html report
I created some test scripts using selenium python and they have been working okay. However, I have had trouble when I tried to generate an html report or an allure report.
I used the following command ...
0
votes
2
answers
30
views
pytest + django giving me a database error when fixture scope is 'module'
I have the following inside conftest.py
@pytest.mark.django_db
@pytest.fixture(scope='module')
def thing():
print('sleeping') # represents a very expensive function that i want to only ever once ...
1
vote
1
answer
38
views
How do I patch a class attribute in pytest?
I have a service class that connections to AWS S3. The connection uses boto3 within the __init__() method. I would like to mock this to use a moto s3 instance I've defined in a fixture, but I just can'...
0
votes
0
answers
22
views
How to pass values from shared steps defined in conftest.py to the tests in pytest-bdd?
I have a feature file with backgrouned steps defined in conftest.py. I want to access that step objects in my actuall test. How can I achieve this? Below is the example.
exmpl.feature
Freature: login ...
0
votes
1
answer
27
views
How to access Pytest item outside a test function
I want to retrive pytest current running test item and then append my function running data into item.user_properties.
I tried to create dummy plugin and impl pytest_runtest_protocol, update running ...
0
votes
0
answers
12
views
pycharm pytest.main(['xx:py::xx::xx']) should be run single function, however it always run all the tests
E.g.
import pytest
def test1():
print("test1")
def test2():
print("test2")
if __name__ == '__main__':
pytest.main(['test_main.py::test1'])
pic below show the result
...
-1
votes
0
answers
41
views
How to write test-cases for fastapi app which has authlib oauth authentication?
I have these api endpoints. Anyone trying to access the app will be redirected to login page of a mock-oidc server where we have to pass username & password, if not authenticated before. Now while ...
0
votes
1
answer
33
views
Pytest - Testing the datatype of columns with a definition file
I have a xlsx file with the values:
Product Person Quantity
Egg Emma 2
milk Jack 3
Note : My code essentially needs to read this file in openpyxl.
While reading ...
0
votes
0
answers
13
views
is it possible that use simultaneously params and autouse in pytest.fixture
E.g.
@pytest.fixture(scope='class', params=['zhangsan', 'lisi', 'lala'], autouse=True)
def my_fixture(request):
return request.param
class Test1():
def test_02_login1(self):
print('login2'...
0
votes
1
answer
38
views
AttributeError: module 'sys' has no attribute 'append' , Pytest , FastAPI [closed]
Test file code for my fastapi app.
Using Mas Os
from fastapi.testclient import TestClient
import json
import os
import sys
sys.append.path(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))...
0
votes
0
answers
8
views
Ignore submodules for pytest in vsc
I am using VSC with pytest to debug my code. This worked fine until I added a submodule which I used in the past. The Codebase in the submodule has not the same standard as my main module and causes ...
0
votes
0
answers
22
views
Error while loading the pytest module in Django project
I am trying to run pytest in a django project with it is showing me error of no module loading. I have created init.py in test folders, but that also not worked for me to resolve this issue.
...
1
vote
1
answer
31
views
identity test game of life
I'm writing the conway's game code in python. My code is like this:
def update_board(board: list[list[int]]) -> list[list[int]]:
rows = len(board)
cols = len(board[0])
count = 0
...
0
votes
0
answers
37
views
pytest can't find module for tests
I have a structure like (not exact names)
- my_project
- app
- repo
- __init__.py
- my_repo.py
- services
- __init__.py
- my_service.py
- utils
- ...
1
vote
0
answers
40
views
Pytest: run teardown once for all workers using pytest-xdist
I have a pytest fixture that I need to run only once across all pytest workers.
@pytest.fixture(scope="session")
@shared # this will call setup once for all processes
def cache(request):
...
0
votes
1
answer
29
views
Parametrizing with class method, then calling that method with object
(pseudo-code)
I have class Node with properties:
class Node(WebElement):
def __init__(self, element):
super().__init__(element)
...
@property
def name(self):
<...
0
votes
1
answer
44
views
python: clear / reset `@lru_cache` functool caching with every pytest testcase for undisturbed mocking
I combine mocking and caching in my code. The mocking is (kind of) random for each pytest as I do not know exactly, what will be returned in the real case. Hence I want to mock the very same function (...
0
votes
0
answers
23
views
Using pytest with FastAPI + Tortoise : tortoise.exceptions.DBConnectionError: Can't establish connection to database
I have two postgres databases, one for prod and another for testing in "DATABASE_URI" and "TESTDATABASE_URI" respectively. The app seems to working perfectly, whether I use either ...
0
votes
0
answers
13
views
Using an existing database for a specific test in pytest
we have a gitlab pipeline with some integration tests where the REST API server and the database are defined in a docker-compose file. In the docker-compose file, an additional service is defined to ...