2016-09-05 4 views
4

スレッドではMock.call_countが正しく動作しないようです。例えば:mock.call_countのスレッドセーフなバージョン

import threading 
import time 
from mock import MagicMock 


def f(): 
    time.sleep(0.1) 

def test_1(): 
    mock = MagicMock(side_effect=f) 
    nb_threads = 100000 
    threads = [] 
    for _ in range(nb_threads): 
     thread = threading.Thread(target=mock) 
     threads.append(thread) 
     thread.start() 

    for thread in threads: 
     thread.join() 

    assert mock.call_count == nb_threads, mock.call_count 

test_1() 

このコードは、次のような出力生成:

Traceback (most recent call last): 
    File "test1.py", line 24, in <module> 
    test_1() 
    File "test1.py", line 21, in test_1 
    assert mock.call_count == nb_threads, mock.call_count 
AssertionError: 99994 

をIコードのマルチスレッド部分内call_count(または類似の)を使用することができる方法はありますか?私はMagicMockを自分で書き直す必要がないようにしたいと思います...

答えて

1

最後に、副作用方法とロックにリンクされたカウンターを使って動作させました。

import threading 
import time 
from mock import MagicMock 

lock_side_effect = threading.Lock() 

def f(): 
    with lock_side_effect: 
     f.call_count += 1 
    time.sleep(0.1) 

f.call_count = 0 

def test_1(): 
    mock = MagicMock(side_effect=f) 
    nb_threads = 100000 
    threads = [] 
    for _ in range(nb_threads): 
     thread = threading.Thread(target=mock) 
     threads.append(thread) 
     thread.start() 

    for thread in threads: 
     thread.join() 

    assert f.call_count == nb_threads, f.call_count 

test_1() 

その結果、私はf代わりのmockのコール数を数えるんだけど、期待通りの結果が動作します。

関連する問題