0

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,

  1. I can move "started_at" out of __ main__ block
  2. use imp module to import my module. stackoverflow
  3. I can send started_at as function argument, def prepart_report(started_at=started_at):
  4. stackoverflow link
John Prawyn
  • 1,423
  • 3
  • 19
  • 28

1 Answers1

2

Since the attribute does not exist you can just set it.

import report_generator

class TestReportGenerator(unittest.TestCase):
    def test_prepare_report(self):
        started_at = datetime.now()
        report_generator.started_at = started_at
        report_generator.prepare_report()
blues
  • 4,547
  • 3
  • 23
  • 39