Here is what I want to test:
test.py
class MyTest(TestCase)
def test1(self):
data = crawl_data()
Check data lengh and current data in DB...
function2()
Again, Check data lengh and current data in DB...
And program code:
a.py
def crawl_data():
"""
crawl data from web
"""
.
.
return web_crawled_data
b.py
from a import crawl_data
def function2():
"""
crawl data and store new data in database
"""
.
.
result = crawl_data()
.
.
update data and update Database
.
.
What I want to do is testing function2()
. Problem is though function2()
call crawl_data()
inside.
I don't want crawl_data()
to crawl data from web in the test, So I tried mocking this function.
@patch("a.crawl_data")
def test1(self, crawl_data):
crawl_data.return_value = [("112233", "ABCDEF"), ("222233", "EFGHIJ")]
data = crawl_data()
Check data length and current data in DB
function2()
Check the database whether new data stored in DB
When I run the test, function2()
still crawl data from the web in real!
The reason that I don't want to mock function2 is that, when I start the test, test framework use virtual database (provided by django
)!
So, What I want to do is make crawl_data()
as a mock when the function2()
call it inside.
How can I do that?
EDIT
I followed the solution "Martijn Pieters♦" gave, and implement code like below:
a.py
def sum():
return 1
b.py
from a import sum
def calling_sum():
return sum()
test1.py
@patch("b.sum")
def test_sum(self, sum):
sum.return_value = 10
print(calling_sum())
result
It print out "1", not 10....
I tried to change @patch("b.sum")
to @patch("b.fake_sum")
to check whether it import correctly, and @patch("b.fake_sum")
occured error(something like fake_sum not exsits
) so I think importing module
works well
Still doesn't work..