Python HTMLTestRunner测试报告仅包含部分测试用例名称

时间:2014-12-21 16:57:43

标签: python unit-testing python-unittest

我正在尝试使用HTMLTestRunner生成的报告设置单元测试。测试运行正常,但生成的报告不包含完整的测试用例名称,而是仅在测试用例名称的最后部分(最后一个点之后的部分)打印在报告中。

测试用例名称以以下形式动态生成:test_ +用户代理字符串。用户代理字符串包含空格和点,这是报告中不完整的测试用例名称的根本原因。

如何在不对代理用户代理名称进行任何字符串替换的情况下获取报告中的完整测试用例名称的任何想法?我需要能够轻松地从报告中复制/粘贴原始用户代理。

HTMLTestRunner报告

HTMLTestRunner Report

终端输出

ok test_HTC_Desire_X Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 (__main__.TestUserAgents)
F  test_Mozilla/5.0 (Android; Mobile; rv:24.0) Gecko/24.0 Firefox/24.0 (__main__.TestUserAgents)
F  test_Mozilla/5.0 (Linux; Android 4.1.2; GT-I9105P Build/JZO54K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19 (__main__.TestUserAgents)
ok test_Mozilla/5.0 (Linux; U; Android 4.0.4; nl-nl; GT-N8010 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 (__main__.TestUserAgents)
F  test_Opera/9.80 (Android; Opera Mini/7.5.33361/31.1448; U; en) Presto/2.8.119 Version/11.1010 (__main__.TestUserAgents)

测试用例动态生成:

import unittest
import csv 
import requests
import HTMLTestRunner


class TestUserAgents(unittest.TestCase):
    '''Placeholder class. Test methods are added dynamically
    via for/in loop at the end of the file. 
    '''
    pass

def create_test(ua):
    url = 'http://example.com'
    def test(self):
        user_agent = {'User-agent': '%s' % ua} 
        response = requests.get(url, headers = user_agent)
        self.assertTrue('teststring' not in response.url)
    return test

def suite():
    s1 = unittest.TestLoader().loadTestsFromTestCase(TestUserAgents)
    return unittest.TestSuite([s1])

def run(suite, report = "report.html"):
    with open(report, "w") as f:
        HTMLTestRunner.HTMLTestRunner(
            stream = f,
            title = 'Test User Agents Report',
            verbosity = 2,
            description = 'Test UserAgents description'
            ).run(suite)

if __name__ == '__main__':
    ua_file = open('user_agents_sample.csv')
    user_agents = csv.reader(ua_file)

    for os, browser, ua in user_agents:    
        test_func = create_test(ua)
        setattr(TestUserAgents, 'test_{0}'.format(ua), test_func)

    run(suite())

2 个答案:

答案 0 :(得分:0)

通过修改生成测试报告的HTMLTestRunner.py中的函数来解决它。这不是一个理想的解决方案,但工作得很好。请注意name变量,该变量现在与test_分开,这是我动态生成的测试用例的自定义前缀。

def _generate_report_test(self, rows, cid, tid, n, t, o, e): 
    # e.g. 'pt1.1', 'ft1.1', etc
    has_output = bool(o or e)
    tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)
    # name = t.id().split('.')[-1]
    name = t.id().split('test_')[-1]
    doc = t.shortDescription() or ""
    desc = doc and ('%s: %s' % (name, doc)) or name
    tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL

答案 1 :(得分:0)

安装 HTMLTestRunner-rv

pip install HTMLTestRunner-rv

解决问题,支持Python3.X