【问题标题】:unittest for both python 2 and 3python 2和3的单元测试
【发布时间】:2016-12-01 19:13:33
【问题描述】:

我正在努力在 2.7.3 和 3.2.3(ubuntu 12.04 附带的版本)中进行单元测试

基本上问题是:

  • 我需要 assertEqual 具有 unicode 的字符串,所以 python2 使用 u'asdf' 而 python 3.2 没有这样的东西(我相信它们在 3.3 中被重新引入)。有没有办法可以将字符串参数表示为assertEqual,使其比较等于u'asdf'并在python 3.2中编译?

  • 我需要assertRegex 一些输出,但在 python2.7 中它称为assertRegexpMatched。我应该根据运行代码的版本创建一种使用正确方法的自定义方法吗?怎么样?

【问题讨论】:

    标签: python python-2.7 python-unittest python-3.2


    【解决方案1】:

    我最终创建了这个函数来替换 u"asdf":

    def u(s):
        if sys.version_info[0]==3:
            return s
        else:
            return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
    

    并在我的测试类中添加这个方法:

    def assertRegexp(self, a, b):
        if sys.version_info >= (3,2):
            return self.assertRegex(a, b)
        else:
            return self.assertRegexpMatches(a, b)
    

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 1970-01-01
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 2017-04-26
      相关资源
      最近更新 更多