在单元测试用例中操作变量值 python

manipulating variable value in unit test case python

我有下面这个方法:

    def pagination_logic(self, topic_name):
        """Pagination logic to fetch the complete data.

        :param topic_name:str, kafka topic name.
        """
        while self.next_page_cursor:

            self.fetch_response_from_api()

            records = self.extract_records()

            self.publish_records(records, topic_name)

            if not self.flag:
                break

            self.extract_next_page_cursor()

            self.page += 1

        else:
            logger.info("Finished fetching data")

我需要编写一个单元测试方法。下面是我的单元测试方法

    def test_pagination_logic(self):
        """Test for pagination logic."""
        allow(self.slack).fetch_response_from_api.and_return(None)

        allow(self.slack).extract_records.and_return(RESPONSE.get('entries'))

        allow(self.slack).publish_records.and_return(None)

        allow(self.slack).extract_next_page_cursor.and_return(None)

        self.slack.next_page_cursor = 'abc'
        self.slack.flag = 0

        result = self.slack.pagination_logic('topic_name')

        assert result is None

我知道我可以通过将 self.flag 的值设置为第一次迭代的 1 和第二次迭代的 0 来实现 100% 的覆盖率。 但是我怎样才能做到这一点呢?

尝试这样做。这有点老套,但我认为这可能有效:

class Helper:
    
    def __init__(self):
        self.s_obj = None

    def update_flag():
        if self.s_obj.flag == 1:
            self.s_obj.flag = 0

class YourTestClass:
    def test_pagination_logic(self):
        """Test for pagination logic."""
        
        ...
        h_obj = Helper()
        h_obj.s_obj = self.slack
 
 
        allow(self.slack).extract_next_page_cursor.and_return_result_of(h_obj.update_flag)
        
        self.slack.flag = 1
    
        result = self.slack.pagination_logic('topic_name')

        ....