簡體   English   中英

如何對用unittest.mock調用的Django模型方法進行單元測試?

[英]How to unittest that a django model method called with unittest.mock?

我很難理解如何使用unittest.mock庫。
我有這個模型:

from django.db import models

class Data(models.Model):
    field1 = models.CharField(max_length=50)
    field2 = models.CharField(max_length=50)
    // ... more fields

    _PASSWORD_KEY = 'some_random_password_key'
    _password = models.CharField(max_length=255, db_column='password')

    def _set_password(self, raw_password):
        """
        Encode raw_password and save as self._password
        """
        // do some Vigenère magic

    def _get_password(self):
        """
        Decode encrypted password with _PASSWORD_KEY and return the original.
        """
        return raw_password

    password = property(_get_password, _set_password)

我想測試在執行data = Data(password='password')時是否調用了_set_password
我手動確認了它的調用,但是此單元測試失敗了(這是從unittest.mock文檔的示例中帶來的):

from mock import patch
from someapp.models import Data

def test_set_password_is_called(self):
    with patch.object(Data, '_set_password') as password_method:
        data = Data(password='password123')

    password_method.assert_called_once_with('password123')

帶有此消息:

Failure
Traceback (most recent call last):
  File "/Users/walkman/project/someapp/tests.py", line 75, in test_set_password_is_called
    password_method.assert_called_once_with('password123')
  File "/usr/local/lib/python2.7/site-packages/mock.py", line 845, in assert_called_once_with
    raise AssertionError(msg)
AssertionError: Expected to be called once. Called 0 times.

我做錯了什么?

因為密碼是一個屬性,並且屬性類的getter和setter屬性在調用堆棧中使用,所以您最終不會在該類上調用修補的屬性。 您可以更改測試,類似於此處所述

http://www.voidspace.org.uk/python/weblog/arch_d7_2011_06_04.shtml

注意這項工作

class Test(object):

def test(self):
    return self.test2()


def test2(self):
    print("This was Called")

和測試

with patch.object(Test, 'test2') as mock_method:
    d = Test()
    d.test()

mock_method.assert_called()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM