我正在編寫c-extension並希望在pytest中測試它。瞭解python引用計數以調試c-extensions
我測試的部分內容是引用計數是否在我的對象上正確。因此,我在建純Python一個小的測試,讓我爲難......
從IPython中我得到:
In [1]: x = 153513514215
In [2]: import sys
In [3]: sys.getrefcount(x)
Out[3]: 2
所以票價從分配好,1個參考和1從主叫方。
但是下面的腳本(stackoverflow_test.py)得出以下結果
import sys
def test_ref_count_int():
x = 677461248192962146784178
assert sys.getrefcount(x) == 2
def test_ref_count_str():
y = 'very long and probbably very unique string'
assert sys.getrefcount(y) == 2
def normal_te_st():
x = 222677461248192962146784178
y = '!!!!very long and probbably unique string!!!!'
print ('x refcount = {}'.format(sys.getrefcount(x)))
print ('y refcount = {}'.format(sys.getrefcount(y)))
if __name__ == '__main__':
normal_te_st()
當我運行它作爲一個正常的python腳本
$ python3 stackoverflow_test.py
x refcount = 4
y refcount = 4
爲什麼4,而不是2?
當我與pytest
$ python3 -m pytest stackoverflow_test.py
=================== test session starts ===================
platform linux -- Python 3.4.3, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /opt/projects/0001_Intomics/00005_TextMining/jcr/textmining/tests, inifile:
collected 2 items
stackoverflow_test.py FF
======================== FAILURES =========================
___________________ test_ref_count_int ____________________
def test_ref_count_int():
x = 677461248192962146784178
> assert sys.getrefcount(x) == 2
E assert 3 == 2
E + where 3 = <built-in function getrefcount>(677461248192962146784178)
E + where <built-in function getrefcount> = sys.getrefcount
stackoverflow_test.py:7: AssertionError
___________________ test_ref_count_str ____________________
def test_ref_count_str():
y = 'very long and probbably very unique string'
> assert sys.getrefcount(y) == 2
E AssertionError: assert 3 == 2
E + where 3 = <built-in function getrefcount>('very long and probbably very unique string')
E + where <built-in function getrefcount> = sys.getrefcount
stackoverflow_test.py:11: AssertionError
爲什麼3而不是2運行呢?
問:怎麼說,
- 蟒蛇= 4裁判計數
- pytest = 3裁判計數
- IPython的會話= 2裁判計數
我就指望它在所有3種情況下都像ipython一樣行事,任何人都可以解釋發生了什麼,並給出一些提示,以便如何最好地測試我創建的對象。
感謝您的參考,我需要咀嚼它,但這個答案是我所希望的... – jcr