2014-12-21 44 views
1

我试图用HTMLTestRunner生成的报告设置单元测试。测试运行正常,但生成的报告不包含完整的测试用例名称,而只是测试用例名称的最后一部分(最后一个点之后的部分)打印在报告中。Python 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()) 

回答

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