3,613 questions
1
vote
1
answer
117
views
How to test the calling sequence of methods of a class?
Sometimes when I develop by TDD (Test Driven Development) I need to test the calling order of some class methods. In general I write Python code so I'll show the last test case that I have just ...
-1
votes
1
answer
31
views
Python unittest.mock fails when using pydantic.BaseModel
I have come across this problem when making my unit tests.
from unittest.mock import AsyncMock, patch
import pydantic
# class Parent(): # Using non-pydantic class works
class Parent(pydantic....
0
votes
1
answer
73
views
Python unittest fails with No module loaded in VScode
I have the following directory structure
when I use the test runner I get
File "/home/kyle/dev/tests/test_foo.py", line 2, in <module> import foo ModuleNotFoundError: No module named ...
1
vote
1
answer
62
views
CheckConstraint in Django model not triggering in unittest.TestCase (AssertionError: IntegrityError not raised)
I have a Model class with a series of constraints that I am attempting to test, and I am unable to get these constraints to return an IntegrityError in testing. The class is as follows:
from django.db ...
1
vote
0
answers
60
views
Python: Running tests with all combinations of feature flags
We have several modules that require mandatory feature / backout flags. These flags are defined at module level.
module.py:
from enabled import is_enabled
FLAGS = {flag : is_enabled(flag) for flag in ...
-1
votes
1
answer
81
views
How to forcefully terminate a running Python test in VSCode
Closely related to my question is VSCode: how to interrupt a running Python test?, however in my case the standard method of pressing the square in the Test Results tap does not work.
What is ...
1
vote
0
answers
80
views
How to Test Password Reset Endpoint Using a Token That Doesn’t Exist in the Database in FastAPI?
I'm building a backend system using FastAPI, and I'm currently working on implementing unit tests for the password reset functionality that involves using tokens.
Here’s the snippet of the code I'm ...
0
votes
1
answer
74
views
Difference between mock.patch.dict as function decorator and context manager in Python unittest
I have a configuration module, config with data config.data where I want to add a value for testing.
Ideally, I want to use mock.patch.dict as a context manager because the value is a class attribute ...
4
votes
1
answer
395
views
RuntimeError: Event loop is closed - unittest, pytest
I have been working on yet another API using FastAPI and trying to write test cases for the APIs, but facing error that event loop is closed.
My setup:
So, I am using asyncpg driver/library to connect ...
1
vote
0
answers
85
views
importlib resources files -> not a package, empty module
I tend to alwasy run the testers from inside the module folder, but this breaks the "resources.files" functionality, as it seems not to be able to find the module any more
module folder
...
1
vote
2
answers
49
views
How to combine unittest with trace module to produce coverage like report?
I know how to use coverage module to get "human readable" coverage output (using popular third party coverage module). This can be used with pytest or unittest (with some differences in the ...
1
vote
1
answer
64
views
How can I apply side effects to a function of an instance that is created in a function that is tested?
I have a custom class in the file MyClass.py
class MyClass:
def __init__(self):
self.fetched_data = False
def get_data(self):
self.fetched_data = True
...
0
votes
2
answers
61
views
Running Django tests ends with MigrationSchemaMissing exception
I'm writing because I have a big problem. Well, I have a project in Django where I am using django-tenants. Unfortunately, I can't run any tests as these end up with the following error when calling ...
1
vote
1
answer
179
views
Mock asyncio.sleep to be faster in unittest
I want to mock asyncio.sleep to shorten the delay, e.g. by a factor of 10, to speed up my tests while also trying to surface any possible race conditions or other bugs as a crude sanity check. However ...
2
votes
1
answer
44
views
Test that unittest.Mock was called with some specified and some unspecified arguments [duplicate]
We can check if a unittest.mock.Mock has any call with some specified arguments.
I now want to test that some of the arguments are correct, while I do not know about the other ones.
Is there some ...
1
vote
1
answer
60
views
How to patch global class in python correctly
My project structure:
├── core
| └── service
| └── file.py
└── tests
└── test_file.py
I have a function fun that uses a class method.
file.py
from another_module import myClass
...
0
votes
1
answer
114
views
How can we mock an Object instantiation in python?
I have a scenario where I create a git.repo.base.Repo object in a "someFile.py":
def someFunction():
//some part of code
repo = Repo(path)
repo.head.reference = repo.commit(...
0
votes
0
answers
23
views
Using unittest.Mock in Odoo 17
In odoo 17 I need to use unitest.mock to mock the return value of a function
The function is called cfdi_cancel.
It is located in mymodulename module, inside that module is the 'models' folder, inside ...
0
votes
0
answers
66
views
Test failed even though it shouldn't
I keep getting failed test results with a correct output. I.e:
======================================================================
FAIL: test_block_to_block_type_code (tests.test_block_parser....
1
vote
1
answer
46
views
Detecting testcases created dynamically while running unittest module
I've faced a problem. In my situation I create testcases dynamically like this
class TestMetrics(unittest.TestCase):
@staticmethod
def generate_test(test: ElementaryTestCase):
def ...
0
votes
1
answer
92
views
I can't make a mock on my environment variables
I have problems when testing the way in which I choose the db to connect to in a condition of my scope where I will perform the deplyoment:
from app.resources import secrets
from app.resources.scope ...
0
votes
0
answers
25
views
Mocking in pony orm
I am looking for a way to mock db_session in pony. An example I have now is the following test method:
import unittest
from unittest.mock import MagicMock
from mock import patch
from fireguard....
1
vote
2
answers
129
views
How to assert an http.client.HTTPSConnection.request
My code tries to make HTTP requests to Gitlab API to make different actions such as create projects, branches, milestones etc. I'm not using external modules like requests because I want to keep my ...
0
votes
0
answers
40
views
Getting "AttributeError: 'LoginTests' object has no attribute '_testMethodName'" error when running unittest tests
I am new, really new to the programming field (I just went through a QA Automation course with Python) and I am trying to work on a Unittest suite, but when I try to run an individual test (Ex: ...
0
votes
0
answers
35
views
How to understand mock patching as it relates to import structures and what are alternatives?
I am having an issue where the patch method from the unittest.mock module is only working when I patch attributes of imported modules in other files. I do not understand if this is an issue of my ...
0
votes
1
answer
27
views
Python testing: How can I verify that no error logs were thrown?
In my test I want to verify that no error log was done during the test. How do I do that?
I tried with self.assertLogs("", level="ERROR") as error_logs:. This can capture the error ...
1
vote
1
answer
140
views
Pytest chain mocking between sync and async functions
I want to mock:
async with aiohttp.ClientSession() as session:
async with session.post("xyz.com") as resp:
x = await resp.json()
Currently, I am doing:
# patched aiohttp as ...
0
votes
1
answer
33
views
Can't assert folder creation path with unittest patch
I'm trying to assert all paths that passed through os.makedirs to test that a folder structured has been created. The code isn't complicated and I'm sure it works find but my test reports that the ...
0
votes
1
answer
50
views
Mock - Change return value depending on Mock object
I'm trying to mock some objects in unittest but I need to have a different boolean value returned depending on the Mock object being evaluated in an if statement.
The function I'm testing looks ...
0
votes
1
answer
20
views
Path.touch() patch assertion failed to find calls
I'm creating files with pathlib.Path.touch with the following method that I'd like to assert in a unittest using unitest.mock.patch decorator:
sessions.py
def generate_folders(paths: list):
for p ...
0
votes
0
answers
79
views
How to patch a conditionally imported module in pytest?
I have Python code that works locally and when run on Databricks. For saving the results, a different function is used depending on where to code is run.
On Databricks, several things are ...
0
votes
1
answer
101
views
Visual Studio Code does not find python unit tests in sub folders
I am setting up a Python project in VisualStudio Code. My folder and file structure looks like follows:
Base project folder
source_folder
package1_folder
module1.py
package2_folder
module2.py
...
-1
votes
1
answer
49
views
How do I mock the function in a module which is being called inside it from another function?
I am currently writing a pytest file and need some help regarding it.
In my conftest.py I am initialising the spark session in a function let's session
def session():
spark - Spark.Session ...
My ...
2
votes
3
answers
133
views
Mock date.today() but leave other date methods alone
I am trying to test some python code that involves setting/comparing dates, and so I am trying to leverage unittest.mock in my testing (using pytest). The current problem I'm hitting is that using ...
1
vote
1
answer
89
views
Failed creating mock folders with pyfakefs
I'm working on a project that uses pyfakefs to mock my filesystem to test folder creation and missing folders in a previously defined tree structure. I'm using Python 3.13 on Windows and get this ...
-1
votes
1
answer
44
views
How to mock in python an inherited attribute that contains the reference to an object
I'm trying to figure out how to use the Patch decorator (or in general the unittest library) for the following python code (I'm using 3.5 version):
class C:
def __init__(self):
self....
0
votes
0
answers
20
views
Testing of cdk eks KubernetesManifest in python
I am trying to write unit tests for my python CDK code. From the AWS doc I understand that templates are generated easily for the level-2 & level-1 constructs so that the template can be tested. I ...
2
votes
1
answer
194
views
Why is Python's IsolatedAsyncioTestCase so slow?
I'm working on writing test cases for some Python code that uses asyncio. I'm noticing a significant performance degradation when my test classes inherit from unittest.IsolatedAsyncioTestCase vs. ...
0
votes
1
answer
178
views
QtTest + unittest: How to use QSignalSpy?
How to use QtTest.QSignalSpy with unittest?
It is not clear from the documentation; there are few examples.
from PySide6.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout, QPushButton
from ...
0
votes
0
answers
50
views
Python unittest - how to unit test function to open files of specific file pattern
I'm trying to write a unit test with unittest which tests that the behaviour of the below function only opens files that have a filename pattern of test_*.json.
import glob
import json
def get_tests()...
1
vote
1
answer
106
views
How to patch a 3rd party lib in a unit test with FastAPI client
I have an app/main.py for FastAPI which does:
import qdrant_client as QdrantClient
...
qdrant_client = QdrantClient(url=...)
qdrant_client.create_collection(...)
...
app = FastAPI()
...
@app.get(&...
0
votes
1
answer
69
views
How to mock properly recv method in python and use settimeout
I'm trying to use and test sockets in python (I have to use 3.5 version).
Consider this code:
import socket
def send_recv(xml_message):
try:
address = ('127.0.0.1', 12000)
...
1
vote
1
answer
65
views
How to unit test import error of a module that is actually available at testime?
How can I mock an import error of the module foo in the unit test?
# file: bla.py
try:
import foo
except ImportError:
print("error")
sys.exit(1)
Baseline for the unit test:
...
0
votes
1
answer
43
views
VSCode's testing framework breaks when referencing a file in a tertiary folder
I have a super simple test framework in VSCode as follows:
/.vscode
launch.json
settings.json
/python
/resources
some_data.tsv
/src
myapp.py
/test
...
0
votes
1
answer
126
views
How to "inject" a local variable when importing a python module?
Is it possible to declare a local variable before it's imported?
For example to get this code to run as expected:
# a.py
# do magic here to make b.foo = "bar"
import b
b.printlocal()
# b....
0
votes
2
answers
66
views
Is it possible to run 2 Python unitttests that have different patches in a single file?
Let's say you want to test a function that requires input and another that prints output. This requires two different patches. I created two distinct classes, but only 1 of them runs. The sample ...
0
votes
2
answers
169
views
Python 3.11: No module named "unittest.mock" [closed]
I have tried to run a program using pytorch. It stopped with the error 'No module named "unittest.mock"'
Then I wrote a minimal python program:
import unittest.mock
if __name__ == '__main__':...
1
vote
0
answers
64
views
SQLAlchemy 2.0 session issue unittest tests
I'm trying to upgrade my Flask project from using SQLAlchemy 1.3 to 2.0. I'm following the guidance described here (https://docs.sqlalchemy.org/en/20/changelog/migration_20.html)
I've gone through all ...
0
votes
1
answer
207
views
unittest.AsyncMock: side_effect results in an coroutine instead of raising the Exception
Here's a minimal reproducible example.
This is with python 3.11. Besides pytest, no other dependency.
# minum_reproducible_example.py
from typing import Literal
from unittest.mock import Mock, patch
...
1
vote
0
answers
32
views
unittest.mock patch decorator is not called depending on the pytest target
Running
docker compose -f docker-compose.local.yml run --rm django pytest ./project/app/
the following test passes perfectly, meaning patch method is being used
@patch("project.app....