Re: [問題] 如何測試 sub function

看板Python作者 (surfers'paradise)時間6年前 (2018/05/18 15:50), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《chan15 (ChaN)》之銘言: : # -*- coding: utf-8 -*- : def run(): : def the_name(): : if not hasattr(the_name, 'name'): : the_name.name = 'test' : return the_name.name : for i in range(3): : print(the_name()) : run() : print('') : run() : print('') : run() : 各位好,我想針對上面的 code 寫單元測試 : 主要是想判斷第一次執行時還沒有 the_name.name : 執行第一次之後便存在這個 property 因此直接回覆 the_name.name : 本是想用 self.assertFalse(getattr(run.the_name.name)) : 不過顯然不能這樣用,不知道怎麼可以達成需求 簡單講,**不行** https://stackoverflow.com/questions/13606178/ 如果只是回文要來回答不行,大概會被眾人圍毆吧 原則上,要直接 call inner function,沒辦法 所以解法就要先設計過,這裡我想到三種解法: Method 1. 預先藏一個變數 In [77]: def a(): ...: def b(): ...: print("Hello b") ...: a._inner = b ...: b() ...: print("Hello a") ...: In [78]: a() Hello b Hello a In [79]: a._inner() Hello b Method 2. 用 class 定義 function In [80]: class A(object): ...: def __call__(self): ...: self.b() ...: print("hello a") ...: ...: def b(self): ...: print("hello b") ...: In [81]: a = A() In [82]: a() hello b hello a In [83]: a.b() hello b Method 3. 重新思考這個 inner function 重要性 可以把這個 function 提升到 global function (怎麼這麼久才想到簡單明瞭的解法 ,果然老了) 原 PO 的目的是 unit test 要 unit test 表示有一定的重要性 我會頃向拉到 global function 藏起來的 inner function,我會把它跟外面的 function 看成是一體的 unit test 就只會測試外面的 function test case 就要想辦法去測試到 inner function 番外篇: 當然,如過要硬幹,還是有辦法把 inner function 抓出來 不過,如果你不是要搞你家的 RD team member 的話,請不要參考一下方法 定義我們的 a function In [84]: def a(): ...: def b(): ...: print("Hello b") ...: b() ...: print("Hello a") ...: In [85]: a() Hello b Hello a 來看看他 disassembled 之後會變什麼東西: In [86]: dis.dis(a) 2 0 LOAD_CONST 1 (<code object b at 0x109978c00, file "<ipython-input-84-59fd33a9812d>", line 2>) 2 LOAD_CONST 2 ('a.<locals>.b') 4 MAKE_FUNCTION 0 ... 下略 ... 其中的 code object b at 0x109978c00 是我們要的東西 然後 a 有個變數叫做 __code__,透過它,把我們要的東西抓出來 再用 eval 執行它 In [88]: eval(list(dis.get_instructions(a.__code__))[0].argval) Hello b 成功了,腦細胞也死光光了 .............. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.143.20.81 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1526629846.A.94F.html
文章代碼(AID): #1Q_eNMbF (Python)
文章代碼(AID): #1Q_eNMbF (Python)