I am writing unit tests for my scraper project. Here is my function:
def last_date_method(self) -> datetime.datetime:
"""
Returns date from json file (if date and file exist)
Returns date if date not in file but file exist
Returns a date and create a file if file not exist
:return: datetime.datetime
"""
try:
with open(os.path.join(THIS_DIR, "data_file.json"), mode='r') as json_file:
try:
data = datetime.datetime.strptime(json.load(json_file)[self.site],
'%Y-%m-%d %H:%M:%S')
return data
except:
return datetime.datetime(1970, 1, 1)
except:
with open(os.path.join(THIS_DIR, "data_file.json"), mode='a') as json_file:
json.dump({}, json_file)
json_file.close()
return datetime.datetime(1970, 1, 1)
I also have a method:
def check_if_actuall(self) -> bool:
""" Checks if new comics is available """
return self.last_date >= self.get_site_date()
I want test it so I think I should mock a data_file.json return, or at least mock my self.last_date. In code below I can mock a self.get_site_date return, but I don't know how to mock self.last_date or return of JSON:
def test_check_if_actuall(self):
with patch.object(ScraperLefthandedtoons, 'get_site_date', return_value=datetime.datetime(2018, 2, 27)):
lht = ScraperLefthandedtoons()
self.assertTrue(lht.check_if_actuall())