I have module report_generator.py,
from datetime import datetime
def prepart_report():
# some code to generate report
report_name = 'my_report_{}.xlsx'.format(started_at)
if __name__ == '__main__':
started_at = datetime.now()
log_file_name = 'my_repot_{}.log'.format(started_at)
'started_at' global variable used in log file name and report file name.
test module test_report_generator.py,
import report_generator
class TestReportGenerator(unittest.TestCase):
def test_prepare_report(self):
started_at = datetime.now()
with path.object(report_generator, 'started_at', started_at):
report_generator.prepare_report()
In test case, I am trying to patch started_at variable. I am getting module does not have attribute 'started_at' error. Reason for the error is when I import my module in test case module __ name__ will not be "__ main__". So, how do I patch this or what is the best approach to write test cases for this ,
Following solutions I found by googling,
- I can move "started_at" out of __ main__ block
- use imp module to import my module. stackoverflow
- I can send started_at as function argument,
def prepart_report(started_at=started_at):
- stackoverflow link