LoginSignup
0
0

More than 1 year has passed since last update.

unitest/jinja2のそれぞれで呼び出される特殊メソッドについて

Last updated at Posted at 2021-10-08

目的

  • unittestでは「プログラムが期待通りの構造でデータを返す」を確認する。
    • そのオブジェクトを識別できる文字列でOK
  • 実際の利用場面(Jinja2)では指定した書式の文字列を渡す。
    • HTMLタグを使った複雑な文字列
    • この機能については別途テストケースを用意することで対応したい。

結果

  • unittest
    • テスト時は __eq__ が利用される。
    • テストが失敗した時は __repr__ の情報を見せる。
  • jinja2
    • __str__ が利用される。

確認

サンプル

#!/usr/bin/python
import unittest
from jinja2 import Template

class aclass(object):
    def __str__(self):
        return "__str__"
    def __repr__(self):
        return "__repr__"
    def __eq__(self, other):
        return "cccc" == other

a = aclass()

tpl_text = 'a = {{ value }}'
template = Template(tpl_text)

data = {'value': a}
disp_text = template.render(data)
print(disp_text)

test = (1, 2, a, 4)
rslt1 = (1, 2, 'bbbb', 4)
rslt2 = (1, 3, 'cccc', 4)
rslt3 = (1, 2, 'cccc', 4)

class testKanaText(unittest.TestCase):
    def test01_astext(self):
        self.assertEqual(test, rslt1)
    def test02_astext(self):
        self.assertEqual(test, rslt2)
    def test03_astext(self):
        self.assertEqual(test, rslt3)

unittest.main()

実行結果

$ ./zzz.py
a = __str__
FF.
======================================================================
FAIL: test01_astext (__main__.testKanaText)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./zzz.py", line 29, in test01_astext
    self.assertEqual(test, rslt1)
AssertionError: Tuples differ: (1, 2, __repr__, 4) != (1, 2, 'bbbb', 4)

First differing element 2:
__repr__
'bbbb'

- (1, 2, __repr__, 4)
+ (1, 2, 'bbbb', 4)

======================================================================
FAIL: test02_astext (__main__.testKanaText)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./zzz.py", line 31, in test02_astext
    self.assertEqual(test, rslt2)
AssertionError: Tuples differ: (1, 2, __repr__, 4) != (1, 3, 'cccc', 4)

First differing element 1:
2
3

- (1, 2, __repr__, 4)
+ (1, 3, 'cccc', 4)

----------------------------------------------------------------------
Ran 3 tests in 0.002s

FAILED (failures=2)

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0