0

Related post on Mocking global variables

outgoing.py
table_data = []
def outgoing_data():
    record = *do some stuff*
    table_data.append(record)

In a unit test I want to verify that table_data is updated. I tried setting it up as shown in the related post but that seems more aimed at using that global variable inside the function by setting its value in the patch. I have been successful in patching the global variable with data to be used in other methods using: @patch('outgoing.outgoing_data.table_data', [{'action_hist_id': 1, 'page_num': 1, 'row_num': 1}]) as a decorator.

I tried @patch('outgoing.outgoing_data.table_data', []) but that didn't work as expected. I was anticipating that a mock would be generated by patch, which it probably was, but I couldn't see it in the debug window to find out if it was called etc.

Let me know if the question isn't clear or needs more info. Thanks in advance.

nathanjw
  • 832
  • 2
  • 13
  • 23
  • 3
    my recommendation: don't have a global variable. explicitly pass it to and return it from your functions – Paul H Feb 18 '21 at 17:27
  • 2
    `outgoing.table_data` is the name to patch. The function `outgoing.outgoing_data` doesn't have a function attribute, so creating one that the function won't use doesn't accomplish anything. – chepner Feb 18 '21 at 17:27
  • @PaulH i was trying to avoid refactoring the code but that might be the way to go. @chepner it's possible that I typed out my example code wrong. my intention is to call `outgoing_data` and then test that it updated `table_data` – nathanjw Feb 18 '21 at 17:40
  • I posted my solution to my question just for completeness but in the end I refactored as was suggested by @PaulH – nathanjw Feb 18 '21 at 22:26

1 Answers1

0
@patch('outgoing.table_data')
def my_test(mock_table_data):
    outgoing_data()
    self.assertEqual(expected_result, mock_table_data.method_calls[0][1])

This was ran inside a test class, hence the use of self. method_calls[0] is the first call made to the mock object. method_calls[0][0] returns the name of the call, in this case append and method_calls[0][1] returns the data passed.

Python docs on Mock.method_calls

nathanjw
  • 832
  • 2
  • 13
  • 23