如何使用 pyinstaller 运行单元测试

问题描述 投票:0回答:1

我正在使用 pyinstaller 来捆绑我的 python 项目。我的项目中也有一些单元测试,我想知道是否有一种方法可以在 pyinstaller 将所有内容捆绑在一起之前运行单元测试。是否可以?这是我的规格文件

# -*- mode: python -*-

block_cipher = None
import os
import sys

a = Analysis(['src/hub/Driver.py'],
             pathex=['src'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='BiRadExtractor',
          debug=False,
          strip=False,
          upx=True,
          console=True )

我需要在规范文件中添加一些命令来运行单元测试吗?

python python-3.6 pyinstaller python-unittest
1个回答
0
投票

是的,可以在将项目与 PyInstaller 捆绑之前运行单元测试。您可以创建一个构建脚本,该脚本首先运行单元测试,并且仅在所有测试通过后才继续进行 PyInstaller 构建。

这是一个示例设置,假设您的项目组织正确:

my_project/
|-- my_module/
|   |-- __init__.py
|   |-- some_module.py
|-- tests/
|   |-- __init__.py
|   |-- test_some_module.py
|-- main.py
|-- build.py

这是一个用于实现此目的的 build.py 脚本:

import os
import unittest
import PyInstaller.__main__

version = '0.0.1'

def main():
    if run_tests():
        PyInstaller.__main__.run([
            'main.py',
            f'--name=MyAppName-v{version}',
            '--distpath=dist',
            f'--add-data=images/app.ico{os.pathsep}./images',
            f'--add-data=images/logo.png{os.pathsep}./images',
            '--clean',
            '--onefile',
            '--specpath=build',
            '--windowed',
            '--noconsole',
        ])
    else:
        print("Tests failed. Build aborted.")

def run_tests():
    loader = unittest.TestLoader()
    suite = loader.discover('tests')
    runner = unittest.TextTestRunner()
    result = runner.run(suite)
    return result.wasSuccessful()

if __name__ == '__main__':
    main()

请记住调整 PyInstaller 参数(如 --add-data)以适合您的项目,希望这对某人有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.