python 单元测试的简单面试问题(pyunit)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 单元测试的简单面试问题(pyunit)相关的知识,希望对你有一定的参考价值。

#/usr/bin/python env

import abc
import unittest


class StringUtilities(object):
    @staticmethod
    def is_palindrome(s):
        if not isinstance(s, str):
            return False
        s = [x.lower() for x in s if x.isalnum()]
        length = len(s)
        for x in range(length >> 1):
            if s[x] != s[length - x - 1]:
                return False
        return True if length else False

    @staticmethod
    def reverse(s):
        # using API
        # return s[::-1]
        if not isinstance(s, str):
            return
        s = list(s)
        length = len(s)
        for x in range(length >> 1):
            index = length - 1 - x
            s[x], s[index] = s[index], s[x]
        return "".join(s)


class BaseTest(unittest.TestCase):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def _test(self, input):
        raise NotImplementedError

    @classmethod
    def runner(cls, test_cases):
        def test(value, expected):
            return lambda self: self._test(value, expected)
        for value, expected in test_cases:
            test_name = "test_%s" % str(value)
            setattr(cls, test_name, test(value, expected))


class TestPalindrome(BaseTest):
    def _test(self, value, expected):
        result = StringUtilities.is_palindrome(value)
        if expected:
            self.assertTrue(result)
        else:
            self.assertFalse(result)


class TestReverse(BaseTest):
    def _test(self, value, expected):
        result = StringUtilities.reverse(value)
        self.assertEqual(result, expected)


TestPalindrome.runner([
    ("", False),
    ("abc", False),
    ("madam", True),
    ("Madam", True),
    (None, False),
    (1221, False),
    ("1221", True),
    ("12.21", True),
    ("A man, a plan, a canal, Panama!", True)
])

TestReverse.runner([
    ("abc", "cba"),
    ("12", "21"),
    (None, None)
])

if __name__ == "__main__":
    runner = unittest.TextTestRunner(verbosity=2)
    unittest.main(testRunner=runner)

以上是关于python 单元测试的简单面试问题(pyunit)的主要内容,如果未能解决你的问题,请参考以下文章

Python单元测试PyUnit框架轻度整改

PyUnit (unittest) 的用法

python unittest单元测试框架中,如何对一个testcase参数化,具体如何实现

PyUnit的学习

Python之自动单元测试之一(unittest使用实例)

Selenium with Python 010 - unittest 框架(又称PyUnit 框架)