I am new to Unit testing. I have used mocking, patching in the past but the case I have is a little bit complicated for me to create unit tests.
So I have a file: parent.py
with the following data class
import multiprocessing
from dataclasses import dataclass
@dataclass
class ParentClass:
cpu_count: int = multiprocessing.cpu_count()
I have another module child.py
with the following data class
from stackoverflow.parent import ParentClass
from dataclasses import dataclass
@dataclass
class ChildClass(ParentClass):
some_attribute_1: int = 1
some_attribute_2: int = 2
....
Finally, I have a third module actual_function.py
that uses these data classes.
from stack_overflow.child import ChildClass
def get_cpu_count_and_attributes(cc: ChildClass):
return cc.cpu_count, cc.some_attribute_1
Here, I want to unit test print_cpu_count_and_attributes
function. How does patching work here? I created the following test case and it fails. The cpu_count in my system is 16 but I want to mock it with return value 8 so that it works on other machines with different number of cores
from unittest import mock
from stack_overflow.actual_function import *
from stack_overflow.child import ChildClass
@mock.patch('stack_overflow.parent.multiprocessing.cpu_count', return_value=8)
def test_print_cpu_count_and_attributes():
cc = ChildClass()
assert get_cpu_count_and_attributes(cc) == (8, 1)
Here is the folder structure.
stackoverflow
├── __init__.py
├── actual_function.py
├── child.py
├── parent.py
└── test_function.py
Aucun commentaire:
Enregistrer un commentaire