Questions tagged [python-unittest]

Python's standard library framework for testing.

Filter by
Sorted by
Tagged with
0 votes
1 answer
11 views

`unittest.TestCase` makes global `warnings.filterwarnings` obsolete

I have a module with some methods that do raise an enormous number of warnings. As it happens, the warnings are raised by an external module. In the given context they are not really useful but by ...
SchEma's user avatar
  • 96
0 votes
0 answers
27 views

Test fails with FileNotFound while normal execution works

Using Intellij with Python plugin I'm writing some code. I have some classes, modules, packages. Now I decided to go for tests. In package I've created directory "tests" and put my test_*.py ...
Smok's user avatar
  • 101
0 votes
2 answers
49 views

how to mock in python API testing

I'm trying to mock a sample function below. Somehow I'm getting error. For example, I've a class as below myclass.py: import os, requests class MyClass: def __init__(self, login_url): ...
Temp Expt's user avatar
  • 301
0 votes
1 answer
51 views

How do I get this code to pass through the unittest module? [closed]

I have a code that I need to pass by the unittest module but I got a failure error. This is the code I need to test: def iter_insert(S, positions): R = S for pos in positions: R = R[:...
SJ Brigante's user avatar
1 vote
0 answers
38 views

Python unittests do not immediately run

I have a test suite in a file called: my_tests.py which looks similar to below: class TestSomeClass(unittest.TestCase): @classmethod def setUpClass(cls): ... ... cls....
kp_opp's user avatar
  • 11
0 votes
2 answers
28 views

How to mock pathlib.Path.read_text for a particular file

The unittest docs show you how to use mock_open to mock direct calls to builtins.open. But how about mocking pathlib's read_text like this: import pathlib pathlib.Path("/path/to/file")....
LondonRob's user avatar
  • 73.3k
0 votes
0 answers
14 views

vscode's testing interface does not work properly with django

unittest does not create a test database and runs on the production database. `"python.testing.unittestEnabled": true,` pytest creates a test database but fails with psycopg2.errors....
FreeDom Sy's user avatar
0 votes
2 answers
26 views

How to mock tested class' member that is a list of objects and assert_called on object's method?

I have the following scenario (simplified): Project structure: ├── main.py ├── README.md ├── src │ ├── __init__.py │ ├── member.py │ └── myclass.py └── tests ├── __init__.py └── ...
Max OfLondon's user avatar
1 vote
1 answer
39 views

Why does Python unittest auto-discovery not work when running in a subprocess?

I'd like to be able to run Python's unittest module programmatically via a subprocess (e.g. subprocess.Popen(), subprocess.run(), asyncio.create_subprocess_exec()) and have it auto-discover tests. I ...
Shaun Scovil's user avatar
  • 3,927
0 votes
0 answers
13 views

How to mock a queryset passed as an argument in python unittest

I need to create a testcase for below function. a queryset is passed as an argument in function. I have to mock that for filter.How to do that def get_weekly_user_data(req_date, data, weeks, ...
twinkle's user avatar
  • 11
0 votes
0 answers
25 views

How to mock a database session scoped in python - fastapi working with SQLAlchemy as ORM to create Unit Test?

I don't have much experience with unit tests and mocks. I work with Python 3.8, pandas==2.0.1, sqlalchemy==2.0.15 and fastapi==0.87.0. My application uses SQLAlchemy as ORM to connect to a database, ...
Jorge Lopez Marcos's user avatar
-2 votes
0 answers
25 views

Question for the PRO's. Understand Python's Unittest Mock Library code

Context. After applying a patch mocking a method inside a class I was trying to understand the content of the resulting mock object and started to explore Python's Unittest Mock Library code. My ...
jojosilva's user avatar
0 votes
1 answer
29 views

patch() from unittest.mock doesn't work in a subprocess

It seems that patch() from unittest.mock does not work as expected in subprocesses spawned with multiprocessing module for me. Here is my code: a.py import multiprocessing from unittest.mock import ...
Danio's user avatar
  • 1,074
-1 votes
0 answers
25 views

Factory session to mock context manager doesnt work

I can mock a context manager for a sqlalchemy session with: @patch("app.path_to_code.Session") def test_get_users_to_query(self, mock_session) -> None: self.engine = create_engine(&...
abinitio's user avatar
  • 607
0 votes
0 answers
31 views

SQLalchemy: how to patch session from context manager and replace with in memory DB session

Say I have an SQLalchemy model like: from app.data_structures.base import ( Base class User(Base): __tablename__ = "users" user_name: Mapped[str] = mapped_column(primary_key=...
abinitio's user avatar
  • 607
0 votes
0 answers
21 views

Using Python unittest patch with side_effect, how you can get the the exact thing that the mock returned?

Let's imagine we have some base class that holds some common logic and then some instances to that base class for solving some specific problems. We also have some interface function that returns the ...
Iced Tea's user avatar
-2 votes
1 answer
44 views

Python patching order is unexpected

Given the following code: import os from unittest.mock import patch def sys_exit_new1(): print("sys_exit_new1:", os.environ.get("BANANA")) def sys_exit_new2(): print(&...
Blazes's user avatar
  • 4,719
0 votes
1 answer
31 views

Unable to mock error in fastAPI dependency

Im writing tests for my status check endpoint. Here is the endpoint. @router.get("/", response_model=HealthStatus, summary="Database Health Check") async def db_health_check(_: ...
Roitko's user avatar
  • 117
2 votes
1 answer
33 views

How to use assertRaises in table-driven tests where some tests raise and others do not

How can I avoid calling the function I'm testing in two different places when writing table-driven tests where some of the tests should raise but others should not? This is what I want to do but it ...
Thomas David Baker's user avatar
-1 votes
1 answer
42 views

SQLalchemy unittesting - how to pass an in memory session to a mocked session

Say I have an SQLalchemy model like: from app.data_structures.base import ( Base class User(Base): __tablename__ = "users" user_name: Mapped[str] = mapped_column(primary_key=...
abinitio's user avatar
  • 607
0 votes
0 answers
38 views

Not sure where to add unittest

I have a function called welcome_message() that executes the user_id_validation function. The latter takes in the user_id entered in a tkinter entry box and validates that user_id. I am planning to ...
amsi_25's user avatar
  • 11
0 votes
1 answer
33 views

Python Mocking / Patching multiple nested functions / variables

I am new to Python and GCP but I am trying to create some tests for my GCF function that moves a file from one bucket to another. Simplified Python code: import functions_framework from google.cloud ...
AylaWinters's user avatar
  • 1,161
0 votes
1 answer
47 views

How would I test from one subdirectory to another in vscode using unittest?

I have a project that is put together in the format of the python packaging tutorial in the documentation. Project_Directory/ ├── src/ │ └── PROJECT_NAME/ │ ├── __init__.py │ └── ...
Bryce P's user avatar
0 votes
0 answers
27 views

Python can't resolve modules import when running unittests

I have a project with the following structure: project/ source/ __init__.py module1.py module2.py integration_tests/ __init__.py test_module1.py test_module2.py In the file integration_tests/...
João Pedro Schmitt's user avatar
0 votes
1 answer
22 views

cannot static file through static url using django.test.client

1.env python : 3.8.14 django version : '4.2.4' 2.Purpose Make sure that the static file is saved Make sure that the static file can be accessed from the web browser 3.Issue The problem is that ...
Soulduck's user avatar
  • 569
1 vote
2 answers
43 views

Pytest: When to use with pytest.raises vs xfail

I have a method which is expected to raise an exception when an incorrect format of input is provided. I am wondering which is the correct way to test, when an incorrect input is supplied mark the ...
user19898808's user avatar
0 votes
0 answers
21 views

Mocking Functions with Complex Module Structures

I have a function funcA that lives in folderA.folderB.foo.py def funcA(): ... return 0 if (some condition) else 1 That is then used in classB.funcB in folderA.folderC.bar.py. from folderA....
saxity90120's user avatar
0 votes
0 answers
37 views

How to mock write csv/xlsx function pytest/unittest

New to Unit testing and getting difficulties while mocking write file function. def write_files(a, b): if os.path.dirname(arg1): os.makedirs(os.path.dirname(arg1), exist_ok=True) if &...
Digital_AI's user avatar
0 votes
1 answer
50 views

Mocking file-like gzipped csv for boto3's StreamingBody

My real S3 helper does the following: def read_gzipped_csv_from_s3(self, key): return self.bucket.Object(key).get() obj = S3Helper().read_gzipped_csv_from_s3(key) df = pd.read_csv(obj['Body'], ...
ellryn's user avatar
  • 13
0 votes
0 answers
14 views

Python Unit Test Coverage and Caller function coverage

I'm using Python 3.7, Unittest, moto for boto3 to create unit tests for my application. I find a problem with the coverage report generaged by Coverage. those files where I put functions and create ...
mingzhao.pro's user avatar
0 votes
0 answers
14 views

python pyunit generating multiple test reports

For the below code, I expect the a consolidated test report for all the test case files as whole. but instead we are getting seperate report for each file. import unittest import HTMLTestRunner ...
Just another object's user avatar
0 votes
2 answers
72 views

How can I assert that a pdf file was returned in python?

I am working on asserting that a pdf is returned from my request. Here is what my test looks like so far. @mock.patch('path.to.class._get_file', return_value=MockResponse(status.HTTP_200_OK, '...
Damon's user avatar
  • 4,171
0 votes
0 answers
34 views

Getting 'object has no attribute' error although I did everything correctly

Now, I have tried learning unittest in python to test websites from the techwithtim series on selenium. I am trying to test the python.org website. I am trying to run a test using unittest in Python. ...
Mr MuscleMan's user avatar
1 vote
1 answer
33 views

Python test to mock/patch to change internal function arguments, while still running function

I'm looking to mock (or patch) a function so that I can replace the arguments it receives. An example of what I want to do: # my_module.my_submodule from some_library import some_module as x def ...
Brendan's user avatar
  • 1,905
1 vote
1 answer
71 views

Unable to run python unittest in debug mode with reference to test folder in VSCODE

I recently upgraded my VSCode (1.80.1 from 1.78.X) and all of a sudden I can no longer run the unittests I wrote in debug mode. My Python package has the following structure myPackage/ |-- ...
SimonV's user avatar
  • 11
1 vote
1 answer
43 views

Python unittest C extension call to exit() [duplicate]

TLDR I can't get unittest to run a test where I am trying to check that my Python C extensions calls exit(1) from stdlib.h. The setup I have a Python unit test and C extension which looks like the ...
oliversm's user avatar
  • 1,787
0 votes
1 answer
957 views

ModuleNotFoundError: No module named

I want to perform an api test. I send an image and I receive a json containing predictions. I created an app/api.py script that contains a method to send the image and receive the response. I can't ...
dia05's user avatar
  • 57
-1 votes
2 answers
54 views

Python unit test failing in Docker

I am trying to run a Python unit test within a docker image. This is the Dockerfile used to create the image FROM python:3.8-alpine COPY lambda/ /app WORKDIR /app RUN pip install -r requirements.txt ...
Eduardo Rodrigues's user avatar
0 votes
0 answers
34 views

Patching a method that is referenced in a constants file, whose constant is pulled into a method under test

I've got a constants file which contains configuration that developers can modify as needed. It's broken apart for readability and so the structure looks something like this: from app.configuration....
Ben's user avatar
  • 733
-2 votes
1 answer
64 views

How to mock a method of a class instance?

I have code like this: a.py from app.cache import Cache my_cache = Cache(cache_prefix='xxxxx') b.py from a import my_cache class MyApp: def run_app(): my_cache.get(1,2) test_b.py ...
user2611836's user avatar
-2 votes
1 answer
115 views

VScode does not count tests that throw exceptions (0/0 tests passed)

My dev environment is: vscode 1.80.1 python 3.10 using the python extension for vscode v2023.12.0 My test file: import unittest class MyTestCase(unittest.TestCase): def test_say_hello(self) -&...
MyUsername112358's user avatar
0 votes
1 answer
21 views

Flask unit test uses/accesses development databse even after creating a temporary database to test

I have created a flask App and this is the app.py file from flask_migrate import Migrate from dotenv import load_dotenv import os from src.app import create_app, db load_dotenv() app = create_app() ...
Glen Veigas's user avatar
1 vote
1 answer
94 views

Visual Studio Code triggers use of pytest when configured for unittest

I've successfully used the standard python unittest framework in several projects recently, but in the last few days it fails to work as before. One issue is that it now seems to try to use pytest ...
Colin Frame's user avatar
0 votes
0 answers
20 views

Python unittest, pass argument to switch between target types

I am working on a python/cython project that involves communication with external devices. The code is covered by unit tests that can both be run against simulated hardware communication and external ...
fkh746351's user avatar
0 votes
1 answer
69 views

pytest unittest spark java.io.FileNotFoundException: HADOOP_HOME and hadoop.home.dir are unset

Running unit testing using pytest for pyspark code. Code snippet sample from code given below. Looks like spark runtime or hadoop runtime libraries expected , but i thought unit testing does not ...
Mohan Rayapuvari's user avatar
0 votes
0 answers
26 views

How to fail unittest test suite even when all test cases pass

I am using python unit test framework to run automated test cases. Currently I want to have the ability to fail the test suite if a condition is not met even if all the test cases pass. I want the ...
tyleax's user avatar
  • 1,566
0 votes
2 answers
54 views

Python Unittest case failing in jupyter notebook, but running alright in spyder

I am new to testing in python and I was trying to work on this code in Jupyter notebook, and it keeps on showing failed, ever if the cases are correct. But I tried to run the same code in Spyder and ...
Anki's user avatar
  • 1
0 votes
1 answer
18 views

Python Unittest fails if all tests are run, but each passes individually

I created a Unittest for an ETL process with SQLAlchemy as an ORM. The testfile is in the "test" folder and is called "test_static_basics.py" I have a setUp-, and tearDown method ...
Link's user avatar
  • 1
0 votes
0 answers
46 views

How to mock JClass call in python unit tests

I am new to python unit test mocking. I am using jpype library in the code like below: def my_func(): #some code instance. = JClass("myapp.myclass")() #some code This is the test code:...
lakshmiravali rimmalapudi's user avatar
2 votes
1 answer
57 views

Mocking list elements in Python using unittest Mock

I'm trying to test a function which accesses one of its attributes which is expected to be a list object and checks its content. Example below: def render_link(self, token: span_token.Link) -> str: ...
eminakgn's user avatar

1
2 3 4 5
70