第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何將文件傳遞給 unittest.mock.mock_open()?

如何將文件傳遞給 unittest.mock.mock_open()?

炎炎設(shè)計(jì) 2022-04-27 13:28:06
我有一個(gè)讀取日志文件和過(guò)濾結(jié)果的函數(shù),我想測(cè)試以確保它正確過(guò)濾。我的代碼import osimport randomimport unittestfrom unittest.mock import patch, mock_open__SAMPLE_LOG__ = os.path.join(settings.BASE_DIR, "apps/tests/log_viewer/sample_logs/sample_manager_log.log")class FilterLog(unittest.TestCase):    def setUp(self):        with open(__SAMPLE_LOG__) as f:            self.sample_data = f.read()    @patch('builtins.open', new_callable = mock_open, read_data = self.sample_data)    def test_filterDate(self, mock_file):                day = '08'        month = '08'        year = '2019'        results = filter_log(filter_by = 'date', day = day, month = month, year = year)        self.assertEqual(open(settings.ACTIVITY_LOG_FILE).read(), self.sample_data)錯(cuò)誤@patch('builtins.open', new_callable = mock_open, read_data = self.sample_data)NameError:名稱“自我”未定義我的問(wèn)題我應(yīng)該如何將數(shù)據(jù)傳遞到mock_open()?我覺(jué)得with open() ... read()在文件頂部有一個(gè)不好的做法,我也不能把它作為一個(gè)類變量(可以嗎?),那么我有什么選擇呢?文件說(shuō)什么從文檔 read_data中獲取一個(gè)字符串,所以我需要以某種方式將文件讀入一個(gè)變量并將其傳入。但是在哪里讀取文件合適?在模塊的頂部,在課程的開頭,還是在setUp()?
查看完整描述

1 回答

?
侃侃無(wú)極

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊

這應(yīng)該有效。我把 sample_data 帶出了課堂。


import os

import random

import unittest

from unittest.mock import patch, mock_open


__SAMPLE_LOG__ = os.path.join(settings.BASE_DIR, "apps/tests/log_viewer/sample_logs/sample_manager_log.log")


# read your test data in sample_data

with open(__SAMPLE_LOG__) as f:

    sample_data = f.read()


class FilterLog(unittest.TestCase):


    @patch('builtins.open', new_callable = mock_open, read_data = sample_data)

    def test_filterDate(self, mock_file):


        day = '08'

        month = '08'

        year = '2019'

        results = filter_log(filter_by = 'date', day = day, month = month, year = year)


        self.assertEqual(open(settings.ACTIVITY_LOG_FILE).read(), sample_data)


查看完整回答
反對(duì) 回復(fù) 2022-04-27
  • 1 回答
  • 0 關(guān)注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)