### Complete Project Integration Example Source: https://context7.com/testerliferaymond/beautifulreport/llms.txt This example demonstrates a full project structure and integration for using BeautifulReport. It includes a test runner script to discover and execute tests, generate reports, and manage directories. ```python """ 项目结构: project/ ├── tests/ │ ├── __init__.py │ ├── test_user.py │ └── test_order.py ├── img/ # 截图保存目录 ├── report/ # 报告输出目录 └── run_tests.py # 测试运行入口 """ # run_tests.py - 测试运行入口文件 import os import unittest from BeautifulReport import BeautifulReport def run_all_tests(): """运行所有测试并生成报告""" # 确保必要目录存在 for dir_path in ['img', 'report']: if not os.path.exists(dir_path): os.makedirs(dir_path) # 自动发现 tests 目录下所有 test_*.py 文件中的测试用例 test_suite = unittest.defaultTestLoader.discover( start_dir='./tests', pattern='test*.py', top_level_dir='.' ) # 创建报告生成器 report = BeautifulReport(test_suite) # 生成报告 report.report( filename='完整测试报告', description='项目自动化测试报告 - 包含用户模块和订单模块', log_path='./report' ) def run_specific_tests(test_class): """运行指定测试类""" suite = unittest.TestLoader().loadTestsFromTestCase(test_class) report = BeautifulReport(suite) report.report( filename=f'{test_class.__name__}_report', description=f'{test_class.__doc__ or test_class.__name__}', log_path='./report' ) if __name__ == '__main__': run_all_tests() # 或者运行指定模块的测试 # from tests.test_user import UserTestCase # run_specific_tests(UserTestCase) ``` -------------------------------- ### Install BeautifulReport Source: https://github.com/testerliferaymond/beautifulreport/blob/master/README.md Clone the repository and copy the BeautifulReport directory into your Python site-packages. ```shell >>> git clone https://github.com/TesterlifeRaymond/BeautifulReport >>> cp -R BeautifulReport to/python/site-packages/ ``` -------------------------------- ### Generate HTML Test Report with BeautifulReport Source: https://context7.com/testerliferaymond/beautifulreport/llms.txt Use BeautifulReport to generate an HTML test report from a unittest TestSuite. Specify the report filename, description, and log path for output. This example demonstrates discovering tests and generating a report for user login functionality. ```python import unittest from BeautifulReport import BeautifulReport # 定义测试用例 class MyTestCase(unittest.TestCase): """用户登录功能测试""" def test_login_success(self): """测试正确的用户名密码登录成功""" username = "admin" password = "123456" # 模拟登录验证 result = (username == "admin" and password == "123456") self.assertTrue(result) def test_login_fail_wrong_password(self): """测试错误密码登录失败""" username = "admin" password = "wrong_password" result = (username == "admin" and password == "123456") self.assertFalse(result) @unittest.skip("功能暂未实现") def test_login_with_captcha(self): """测试带验证码的登录""" pass if __name__ == '__main__': # 方式1: 使用 discover 自动发现测试用例 test_suite = unittest.defaultTestLoader.discover('./tests', pattern='test*.py') # 方式2: 手动加载指定测试类 # test_suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase) # 创建 BeautifulReport 实例 result = BeautifulReport(test_suite) # 生成测试报告 result.report( filename='测试报告', # 报告文件名,不带后缀则自动添加.html description='用户登录模块测试报告', # 报告标题/描述 log_path='./report' # 报告输出目录 ) # 输出: 测试已全部完成, 可前往/path/to/report查询测试报告 ``` -------------------------------- ### Run Sample Test Source: https://github.com/testerliferaymond/beautifulreport/blob/master/README.md Execute the sample.py script to run tests and generate a report. ```shell >>> python sample.py ``` -------------------------------- ### Generate Basic Test Report Source: https://github.com/testerliferaymond/beautifulreport/blob/master/README.md Use BeautifulReport to generate a visual report from a unittest test suite. Specify report filename, description, and log path. ```python import unittest from BeautifulReport import BeautifulReport if __name__ == '__main__': test_suite = unittest.defaultTestLoader.discover('../tests', pattern='test*.py') result = BeautifulReport(test_suite) result.report(filename='测试报告', description='测试deafult报告', log_path='report') ``` -------------------------------- ### BeautifulReport Usage Source: https://github.com/testerliferaymond/beautifulreport/blob/master/README.md This snippet demonstrates how to integrate BeautifulReport into your unittest workflow to generate visual reports. ```APIDOC ## Basic Usage This section shows how to use BeautifulReport to generate a visual report from your unittest test suite. ### Method ```python import unittest from BeautifulReport import BeautifulReport if __name__ == '__main__': test_suite = unittest.defaultTestLoader.discover('../tests', pattern='test*.py') result = BeautifulReport(test_suite) result.report(filename='测试报告', description='测试deafult报告', log_path='report') ``` ### Report API * **BeautifulReport.report** * `report(filename='report.html', description='Test Report', log_path='.')` * `filename` (str): The name of the report file. Defaults to 'report.html'. * `description` (str): The description displayed in the report. * `log_path` (str): The directory where the log file will be written. Defaults to the current directory. ``` -------------------------------- ### img2base Method for Image to Base64 Conversion Source: https://context7.com/testerliferaymond/beautifulreport/llms.txt Use the static BeautifulReport.img2base() method to convert image files to base64 encoded strings. This is useful for manual image embedding in reports or when the add_test_img decorator is not used. ```python from BeautifulReport import BeautifulReport # 将图片转换为 base64 字符串 img_path = './img' # 图片所在目录 file_name = 'screenshot.png' # 图片文件名 # 调用 img2base 方法 base64_string = BeautifulReport.img2base(img_path, file_name) # 返回的 base64 字符串可以直接用于 HTML img 标签 html_img = f'' print(html_img[:100] + '...') # 在测试用例中手动打印带图片的 HTML(会显示在报告的日志区域) HTML_IMG_TEMPLATE = """

""" # 使用示例 import unittest class ManualImageTest(unittest.TestCase): def test_with_manual_image(self): """手动嵌入图片到测试报告""" # 执行测试逻辑 result = 1 + 1 # 手动嵌入图片 try: data = BeautifulReport.img2base('./img', 'test_result.png') print(HTML_IMG_TEMPLATE.format(data, data)) except FileNotFoundError: print("截图文件不存在") self.assertEqual(result, 2) ``` -------------------------------- ### Execute Tests and Generate API Report Source: https://context7.com/testerliferaymond/beautifulreport/llms.txt This snippet shows how to use the report() method of BeautifulReport to run API test cases and generate a specific HTML report. It allows customization of the filename, description, and output directory for the report. ```python import unittest from BeautifulReport import BeautifulReport class APITestCase(unittest.TestCase): """API接口测试用例""" def test_get_user_list(self): """获取用户列表接口测试""" import time time.sleep(0.5) # 模拟接口请求 response_code = 200 self.assertEqual(response_code, 200) def test_create_user(self): """创建用户接口测试""" user_data = {"name": "张三", "age": 25} # 模拟创建成功 created = True self.assertTrue(created) def test_delete_user(self): """删除用户接口测试 - 预期失败示例""" # 模拟删除失败的情况 self.assertEqual(404, 200, "用户不存在,删除失败") if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(APITestCase) report = BeautifulReport(suite) # report() 参数说明: # filename: 报告文件名,默认为 'report.html' # description: 报告标题,默认为 '自动化测试报告' # log_path: 报告保存路径,默认为当前目录 '.' report.report( filename='api_test_report.html', description='API接口自动化测试报告', log_path='.' ) ``` -------------------------------- ### Adding Images to Reports Source: https://github.com/testerliferaymond/beautifulreport/blob/master/README.md This snippet explains how to use the `add_test_img` decorator to include screenshots in your BeautifulReport. ```APIDOC ## Adding Images to Reports This section details how to use the `add_test_img` decorator to embed images, such as screenshots, within your test reports. ### Method * **BeautifulReport.add_test_img** * `add_test_img(*pargs)` * This method is used as a decorator on test methods. * It allows you to associate an image file with a specific test case. * The image will be displayed as a thumbnail in the report, and clicking it will show the full-size image. ### Usage Example ```python import unittest from BeautifulReport import BeautifulReport # Assume save_some_img is a function that saves an image to the specified path def save_some_img(filename): # Placeholder for image saving logic pass class UnittestCaseSecond(unittest.TestCase): """ Test case with image inclusion """ @BeautifulReport.add_test_img('测试报告.png') def test_with_image(self): """ Test method that includes an image """ save_some_img('测试报告.png') self.assertTrue(True) ``` ### Notes * By default, images are stored in an 'img' folder relative to the test execution path. Ensure this folder exists. * The image file does not need to exist before running the test; it can be generated during the test execution. * Clicking the thumbnail in the report will open the full-sized image. ``` -------------------------------- ### Add Screenshot to Test Report Source: https://github.com/testerliferaymond/beautifulreport/blob/master/README.md Use the add_test_img decorator to include screenshots in your test reports. Ensure an 'img' folder exists in your project's root directory. ```python import unittest from BeautifulReport import BeautifulReport class UnittestCaseSecond(unittest.TestCase): """ 测试代码生成与loader 测试数据""" def test_equal(self): """ test 1==1 :return: """ import time time.sleep(1) self.assertTrue(1 == 1) @BeautifulReport.add_test_img('测试报告.png') def test_is_none(self): """ test None object :return: """ save_some_img('测试报告.png') self.assertIsNone(None) ``` -------------------------------- ### add_test_img Decorator for Test Screenshots Source: https://context7.com/testerliferaymond/beautifulreport/llms.txt Use the @BeautifulReport.add_test_img decorator to embed screenshots in test reports. It supports multiple image names and automatically saves screenshots on test failure if save_img() is defined. ```python import os import unittest from selenium import webdriver from BeautifulReport import BeautifulReport class UITestCase(unittest.TestCase): """UI自动化测试用例 - 带截图功能""" driver = None img_path = 'img' # 截图保存目录 @classmethod def setUpClass(cls): """测试类初始化 - 启动浏览器""" cls.driver = webdriver.Chrome() cls.driver.implicitly_wait(10) # 确保截图目录存在 if not os.path.exists(cls.img_path): os.makedirs(cls.img_path) @classmethod def tearDownClass(cls): """测试类清理 - 关闭浏览器""" if cls.driver: cls.driver.quit() def save_img(self, img_name): """ 保存截图方法 - 必须定义此方法才能使用自动截图功能 :param img_name: 截图文件名(不含扩展名) """ self.driver.get_screenshot_as_file( '{}/{}.png'.format(os.path.abspath(self.img_path), img_name) ) @BeautifulReport.add_test_img('登录页面截图') def test_login_page_display(self): """测试登录页面正常显示""" self.driver.get('https://example.com/login') # 手动保存截图 self.save_img('登录页面截图') title = self.driver.title self.assertIn('登录', title) @BeautifulReport.add_test_img('操作前截图', '操作后截图') def test_multi_screenshots(self): """测试多张截图 - 操作前后对比""" self.driver.get('https://example.com') self.save_img('操作前截图') # 执行某些操作 button = self.driver.find_element_by_id('submit') button.click() self.save_img('操作后截图') self.assertTrue(True) @BeautifulReport.add_test_img('错误截图') def test_auto_screenshot_on_error(self): """ 测试失败时自动截图功能 当测试失败且定义了 save_img 方法时,会自动保存截图 """ self.driver.get('https://example.com') # 以下断言会失败,触发自动截图 element = self.driver.find_element_by_xpath('//不存在的元素') if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(UITestCase) report = BeautifulReport(suite) report.report( filename='ui_test_report', description='UI自动化测试报告(含截图)', log_path='.' ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.