Mocking of timestamps
Closed this issue · 0 comments
I have asked this question also on Stack Overflow, but perhaps this is a better location to ask this.
I have created a function that writes a list of lists of strings to an Excel file, and now I want to write a unittest for it, in which I compare the output file with a reference output file. However, when I save it, the real timestamp is stored in the file, so when I compare the two files (which are binary), they are not the same. How can I mock the timestamp in the Excel file creation, such that I can compare a written Excel file with a reference file?
This testcase indicates what I want to achieve. Without the sleep(2), it works. When I open the generated Excel file using TextWrangle, I can see in docProps/core.xml
the following tag: <dcterms:modified xsi:type="dcterms:W3CDTF">2018-09-12T13:44:57Z</dcterms:modified>
. This is the timestamp I want to mock.
def test_that_same_input_leads_to_same_file(self):
def write_xlsx(filename: str):
from openpyxl import Workbook
workbook = Workbook()
worksheet = workbook.active
worksheet.title = 'Matrix'
for line in content:
worksheet.append(line)
workbook.save(filename)
return filename
content = [['a', 'b', 'c', 'd'], [None, 1, 2, 3], [1, 2, 3, 4]]
file_1 = write_xlsx('file_1.xlsx')
sleep(2)
file_2 = write_xlsx('file_2.xlsx')
import filecmp
self.assertTrue(filecmp.cmp(file_1, file_2))
If I perform the function in a patch wrapper, then this function passes. However, when I then don't create file_2, and compare it from a previous run, it still fails. It takes one timestamp for both files in a single run, but another timestamp in another run.
from django.utils import timezone
MY_DATE = timezone.datetime(year=2017, month=1, day=2, hour=3, minute=4, second=5, tzinfo=timezone.utc)
with patch('time.time', return_value=MY_DATE.timestamp()):
# Create Excel file here