everydayminder

learn something everyday

Archive for February 2009

python class의 메소드별 단위 테스트 (unittest pyUnit vs py.test)

with one comment

여러가지 단위 테스트 프로그램이 존재하나,
그 중, standard library로 포함되어 있는 pyUnit (unittest) 과 py.test를 비교하여 간략하게
비교한다.

ㅁ 테스트를 위한 클래스

class A:
    def getA(self):
        return ‘a’

    def getWrongA(self):
        return ‘b’

if __name__ == ‘__main__’:
    aa = A()
    print aa.getA()

* 위의 코드에서 보는 바와 같이, 테스트 메소드는 두 개(getA와 getWrongA)이다.
* 각 메소드는 정상 상황(‘a’를 리턴할 것이라 예상하는 상황에서 실제로 ‘a’를 리턴)과 오류 상황(‘a’를 리턴할 것이라 예상하는 상황에서 실제로는 ‘a’가 아닌 다른 값을 리턴)을 나타낸다.

ㅁ 설치 방법
  1. pyUnit : 별도의 설치 과정 불필요
  2. py.test : 별도의 설치 과정 필요 (http://pypi.python.org/pypi/py 참고)

ㅁ 테스트 코드 작성 방법
   1. pyUnit

from a import A

import unittest

class ATester(unittest.TestCase):
    def setUp(self):
        print ‘setUp called..’
        self.aa = A()

    def testGetA(self):
        print ‘testGetA..’
        self.assertEquals(self.aa.getA(), ‘a’)

    def testGetWrongA(self):
        print ‘testGetWrongA..’
        self.assertEquals(self.aa.getWrongA(), ‘a’)

    def tearDown(self):
        print ‘tearDown called..’

if __name__ == ‘__main__’:
    testSuite = unittest.TestSuite()
    for testmethod in (‘testGetA’, ‘testGetWrongA’):
        testSuite.addTest(ATester(testmethod))

    runner = unittest.TextTestRunner()
    runner.run(testSuite)


   2. py.test

from a import A

def test_getA():
    aa = A()
    assert aa.getA() == ‘a’

def test_getWrongA():
    aa = A()
    assert aa.getWrongA() == ‘b’

ㅁ 실행 방법
  1. pyUnit

python test_with_unittest.py  (위의 예제 파일 이름이 test_with_unittest.py임)

  2. py.test

py.test (이름 지정하지 않아도 찾아서 테스트 실시)

ㅁ 실행 결과
1. pyUnit

setUp called..
testGetA..
tearDown called..
.setUp called..
testGetWrongA..
FtearDown called..

======================================================================
FAIL: testGetWrongA (__main__.ATester)
———————————————————————-
Traceback (most recent call last):
  File “test_with_unittest.py”, line 16, in testGetWrongA
    self.assertEquals(self.aa.getWrongA(), ‘a’)
AssertionError: ‘b’ != ‘a’

———————————————————————-
Ran 2 tests in 0.000s

FAILED (failures=1)

2. py.test

================================ test process starts ================================
executable:   /usr/bin/python  (2.5.2-final-0)
using py lib: /root/jhkim/lib/py-0.9.2/py <rev unknown>

test_with_py.py[2] .F

======================================================================================
________________________________entrypoint: test_getWrongA _____________________________
    def test_getWrongA():
        aa = A()
E       assert aa.getWrongA() == ‘a’
>       assert ‘b’ == ‘a’
         +  where ‘b’ = <a.A instance at 0x838392c>.getWrongA()

/root/test/test_with_py.py:9: AssertionError
_______________________________________________________________________________________
tests finished: 1 passed, 1 failed in 0.18 seconds ========================================================

 사용 목적이나 규모에 따라, 사용자 기호에 따라 각각 장단점이 존재한다!

Written by everydayminder

February 12, 2009 at 05:04

Posted in python

Tagged with , , , ,

현재 클래스의 이름 얻기 + 현재 클래스의 메소드 얻기

leave a comment »

1. 현재 클래스의 메소드 이름 얻기

class Base 에 대해,

Base.__dict__ 라고 하면, Base에 선언된 정보를 얻을 수 있으나,
이중, 메소드 이름만 추출하고 싶다면,

from types import *

def getMethodNames():
  result = []
  for attr, val in Base.__dict__.items():
    if type(val) == FunctionType:
       result.append(attr)
  return result

과 같이 함으로써, method 이름을 추출할 수 있다.

2. 그러나,  이미 특정 class로부터 instance를 만든 경우에는 위의 방법을 그대로 사용할 수 없다.
즉, Base.getMethodNames()라고 하면 결과를 얻을 수 있지만,

aa = Base()
aa.getMethodNames()


라고 하면, 데이터를 얻을 수 없다.

따라서, aa 로부터 instance하기 전의 클래스가 무엇인지 알아내야 한다.

self.__class__

라고 하면, 현재의 클래스를 리턴한다.

따라서, 위의 for 문에서

Base.__dict__items()  대신, self.__class__.__dict__.items()

라고 쓰면 된다.

이때, 클래스의 이름을 self.__class__.__name__ 으로 하여 확인할 수도 있는데,

self.__class__.__dict__.itesm() 와 eval(self.__class__.__name__).__dict__.items()는
동일한 결과물을 뽑아준다.


즉, class와 eval(class의 이름)이 동일하게 취급된다는 것.

Written by everydayminder

February 4, 2009 at 08:51

너무 좋아서 사실이라고 믿기지 않아

leave a comment »

This is too good to be true.

Written by everydayminder

February 3, 2009 at 23:23

Posted in Life/English