From 68d11f1bdbf1619b6901a97bd8fbf8986e5d958b Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Fri, 19 Nov 2021 14:10:13 +0800 Subject: [PATCH 01/17] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20ABCMeta=20=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- case/__init__.py | 1 + case/abc/__init__.py | 1 + case/abc/test_abc.py | 79 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 case/__init__.py create mode 100644 case/abc/__init__.py create mode 100644 case/abc/test_abc.py diff --git a/case/__init__.py b/case/__init__.py new file mode 100644 index 0000000..380474e --- /dev/null +++ b/case/__init__.py @@ -0,0 +1 @@ +# -*- coding:utf-8 -*- diff --git a/case/abc/__init__.py b/case/abc/__init__.py new file mode 100644 index 0000000..380474e --- /dev/null +++ b/case/abc/__init__.py @@ -0,0 +1 @@ +# -*- coding:utf-8 -*- diff --git a/case/abc/test_abc.py b/case/abc/test_abc.py new file mode 100644 index 0000000..a9a33b9 --- /dev/null +++ b/case/abc/test_abc.py @@ -0,0 +1,79 @@ +# -*- coding:utf-8 -*- + +import abc +import pytest + +class Base_ABC(): + + __metaclass__ = abc.ABCMeta # python 2.x + ''' + the ABC class + + 多态性是指具有不同功能的函数可以使用相同的函数名,这样就可以用一个函数名调用不同内容的函数。 + 在面向对象方法中一般是这样表述多态性: + + 向不同的对象发送同一条消息,不同的对象在接收时会产生不同的行为(即方法)也就是说,每个对象可以用自己的方式去响应共同的消息。所谓消息,就是调用函数,不同的行为就是指不同的实现,即执行不同的函数。 + ''' + def __init__(self): + super(Base_ABC, self).__init__() + + @abc.abstractmethod + def onCallback(self): + 'the abstract oncallback method' + # raise AttributeError('the subclasses need to be implemented.') + raise NotImplementedError('the subclasses need to be implemented.') + +class D(Base_ABC): + + def __init__(self): + super(D, self).__init__() + + def onCallback(self): + print('class D onCallback method') + pass + + +class E(Base_ABC): + + def __init__(self): + super(E, self).__init__() + + def onCallback(self): + print('class E onCallback method') + pass + +@pytest.fixture() +def method_abc(): + 'the method abc' + return Base_ABC() + +@pytest.fixture() +def method_d(): + 'the method d' + return D() + +@pytest.fixture() +def method_e(): + 'the method e' + return E() + +def test_needsfiles(tmpdir): + 'the test temp files' + print(tmpdir) + +def test_inherit(method_abc): + 'the test inherit' + # with pytest.raises(Exception) as e: + # pass + try: + method_abc.onCallback() + except TypeError as e: + pass + +def test_inherit_with_d(method_d): + 'the test inherit with d' + method_d.onCallback() + +def test_inherit_with_e(method_e): + 'the test inherit with e' + method_e.onCallback() From 794c75df32a21da71d76e905f11b4bfb4fa4b2fb Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Tue, 30 Nov 2021 14:55:16 +0800 Subject: [PATCH 02/17] the ignore upgrade --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.gitignore b/.gitignore index 269eb98..defefcb 100644 --- a/.gitignore +++ b/.gitignore @@ -83,6 +83,12 @@ celerybeat-schedule # Environments .env +.env/ +# dev.env +# test.env +# prep.env +# prod.env +*.env .venv env/ venv/ From b6a6441944c2afe5a4e6394119d1fd98b16798e0 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Tue, 30 Nov 2021 16:27:27 +0800 Subject: [PATCH 03/17] the python debug environment upgrade --- .vscode/launch.json | 12 +++++++++--- .vscode/settings.json | 5 ++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index b80908c..65f9514 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,5 +1,5 @@ { - // 使用 IntelliSense 了解相关属性。 + // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", @@ -9,7 +9,13 @@ "type": "python", "request": "launch", "program": "${file}", - "console": "integratedTerminal" + "args": [ + "1", + "-l", + "${workspaceFolder}/build/asc.txt" + ], + "console": "integratedTerminal", + "envFile": "${workspaceFolder}/.env/dev.env" } ] -} \ No newline at end of file +} diff --git a/.vscode/settings.json b/.vscode/settings.json index aa16905..4efa043 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -50,7 +50,10 @@ // "python.defaultInterpreterPath": "${workspaceFolder}/venv2/bin/python", // "python.defaultInterpreterPath": "venv2/bin/python", // "python.diagnostics.sourceMapsEnabled": true, - "python.envFile": "${workspaceFolder}/.env", + "python.envFile": "${workspaceFolder}/.env/dev.env", + // "python.envFile": "${workspaceFolder}/.env/test.env", + // "python.envFile": "${workspaceFolder}/.env/pred.env", + // "python.envFile": "${workspaceFolder}/.env/prod.env", // "python.pythonPath": "${workspaceFolder}/venv2/bin/python", // "python.pythonPath": "venv2/bin/python", // "python.pythonPath": "venv2\\Scripts\\python.exe", From 12380de81159998a40a20e2dd9c354fa1b879f02 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Tue, 30 Nov 2021 16:27:49 +0800 Subject: [PATCH 04/17] the argparse upgrade --- case/argparse/conftest.py | 32 ++++++++++++++++ case/argparse/test_argparse.py | 9 +++-- case/argparse/test_argparse_1.py | 65 ++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 case/argparse/conftest.py create mode 100644 case/argparse/test_argparse_1.py diff --git a/case/argparse/conftest.py b/case/argparse/conftest.py new file mode 100644 index 0000000..8286b9c --- /dev/null +++ b/case/argparse/conftest.py @@ -0,0 +1,32 @@ +# -*- coding:utf-8 -*- + +import os +import shutil +import tempfile +import pytest + + +@pytest.fixture(scope="session") +def _temp_dir(): + temp = tempfile.mkdtemp(prefix='argprase-') + print('\n') + print('the current temp dir is {}'.format(temp)) + yield temp + shutil.rmtree(temp) + + +@pytest.fixture(scope="session") +def _temp_file(): + fd, temp = tempfile.mkstemp(prefix='argprase-', suffix='.tmp') + # print('\n') + print('the current temp path is {}'.format(temp)) + yield temp + os.remove(temp) + + +# @pytest.mark.xfail(raises=ZeroDivisionError) +# def test_zero_division(): +# ''' test zero division''' +# 1/0 +# with pytest.raises(ZeroDivisionError): +# 1 / 0 diff --git a/case/argparse/test_argparse.py b/case/argparse/test_argparse.py index 09382e9..7fbd926 100644 --- a/case/argparse/test_argparse.py +++ b/case/argparse/test_argparse.py @@ -3,8 +3,11 @@ import argparse # -# python -m test_argparse.py --help -parser = argparse.ArgumentParser(description='Command-line example.') +# the command line srcipt: +# +# python test_argparse.py --help +# +parser = argparse.ArgumentParser(description='这是一个基本描述信息。') # Add optional switches parser.add_argument('-v', @@ -31,4 +34,4 @@ help='input filenames (default is stdin)') args = parser.parse_args() -print args.__dict__ +print(args.__dict__) diff --git a/case/argparse/test_argparse_1.py b/case/argparse/test_argparse_1.py new file mode 100644 index 0000000..6985a99 --- /dev/null +++ b/case/argparse/test_argparse_1.py @@ -0,0 +1,65 @@ +# -*- coding:utf-8 -*- + +import argparse +import os +import subprocess +import pytest +import sys + + +def test_cmd_1(execute): + ''' the test cmd ''' + print('the test_cmd_1 ended.') + # pytest -v -s ./case/argparse/test_argparse_1.py + # pytest -v -s test_argparse_1.py + pass + + +@pytest.fixture() +def execute(_temp_dir, _temp_file): + try: + args = [sys.executable, __file__, '1'] + # args = [sys.executable, __file__, '-h'] + subprocess.check_output(args=args, ) + subprocess.check_call(args=args, ) + finally: + print('the execute...') + + +def function_argparse(): + # + # the command line srcipt: + # + # python test_argparse_1.py --help + # python test_argparse_1.py 1 + # python test_argparse_1.py 2 + # python test_argparse_1.py 12 -l lasc.txt + # python test_argparse_1.py 12 --log asc.txt + # + parser = argparse.ArgumentParser(description='sum the integers at the command line') + # 位置参数 + parser.add_argument('integers', metavar='int', nargs='+', type=int, help='an integer to be summed') + # 可选参数 + parser.add_argument('-l', + '--log', + default=sys.stdout, + type=argparse.FileType('w'), + help='the file where the sum should be written') + # parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity") + # 可选参数,互斥选项 + group = parser.add_mutually_exclusive_group() + group.add_argument("-v", "--verbose", action="store_true", help='the verbose info') + group.add_argument("-q", "--quiet", action="store_true", help='the quiet info') + args = parser.parse_args() + + # if args.integers: + # args.integers = args.integers**2 + if args.log: + args.log.write('%s' % sum(args.integers)) + args.log.close() + + +if __name__ == "__main__": + ''' the main point ''' + function_argparse() + # pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) From bba4ff5b46f53806233a9cb65f869c0ddd5694f7 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 10:41:47 +0800 Subject: [PATCH 05/17] the pytest ids with generic --- .vscode/launch.json | 12 +++++------ case/argparse/test_ids.py | 43 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 6 deletions(-) create mode 100644 case/argparse/test_ids.py diff --git a/.vscode/launch.json b/.vscode/launch.json index 65f9514..1620194 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -5,15 +5,15 @@ "version": "0.2.0", "configurations": [ { - "name": "Python: 当前文件", + "name": "Python: The Current File", "type": "python", "request": "launch", "program": "${file}", - "args": [ - "1", - "-l", - "${workspaceFolder}/build/asc.txt" - ], + // "args": [ + // "1", + // "-l", + // "${workspaceFolder}/build/asc.txt" + // ], "console": "integratedTerminal", "envFile": "${workspaceFolder}/.env/dev.env" } diff --git a/case/argparse/test_ids.py b/case/argparse/test_ids.py new file mode 100644 index 0000000..4840dde --- /dev/null +++ b/case/argparse/test_ids.py @@ -0,0 +1,43 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +@pytest.fixture(params=[0, 1, 2], ids=["spam", "ham", "asc"]) +def a(request): + ''' a ''' + return request.param + + +def test_a(a): + ''' test_a ''' + pass + + +def idfn(fixture_value): + ''' idfn ''' + if fixture_value == 0: + return "eggs" + else: + return None + + +@pytest.fixture(params=[0, 1, 2], ids=idfn) +def b(request): + ''' b ''' + return request.param + + +def test_b(b): + ''' test_b ''' + pass + + +if __name__ == "__main__": + ''' the main point ''' + # function_argparse() + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) From 20a5c85558ff6bc1fb727d4d78121a77fc255c9b Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 10:46:44 +0800 Subject: [PATCH 06/17] the pytest fixture with params that request.param only --- case/argparse/test_argparse.py | 90 +++++++++++++++++++++------------- 1 file changed, 57 insertions(+), 33 deletions(-) diff --git a/case/argparse/test_argparse.py b/case/argparse/test_argparse.py index 7fbd926..7415e86 100644 --- a/case/argparse/test_argparse.py +++ b/case/argparse/test_argparse.py @@ -1,37 +1,61 @@ # -*- coding:utf-8 -*- import argparse +import os +import pytest -# -# the command line srcipt: -# -# python test_argparse.py --help -# -parser = argparse.ArgumentParser(description='这是一个基本描述信息。') - -# Add optional switches -parser.add_argument('-v', - action='store_true', - dest='is_verbose', - help='produce verbose output') -parser.add_argument('-o', - action='store', - dest='output', - metavar='FILE', - help='direct output to FILE instead of stdout') -parser.add_argument('-C', - action='store', - type=int, - dest='context', - metavar='NUM', - default=0, - help='display NUM lines of added context') - -# Allow any number of additional arguments. -parser.add_argument(nargs='*', - action='store', - dest='inputs', - help='input filenames (default is stdin)') - -args = parser.parse_args() -print(args.__dict__) + +def test_cmd_1(execute): + ''' the test cmd ''' + print('\ntest_cmd_1: {}'.format(execute)) + print('the test_cmd_1 ended.') + # pytest -v -s ./case/argparse/test_argparse.py + # pytest -v -s test_argparse.py + pass + + +@pytest.fixture(scope='session', params=['a', 'b', pytest.param('c', marks=pytest.mark.skip)]) +def execute(_temp_dir, _temp_file, request): + ''' the execute ''' + value = request.param + print('\nexecute: {}'.format(value)) + return value + + +def function_argparse(): + # + # the command line srcipt: + # + # python test_argparse.py --help + # + parser = argparse.ArgumentParser(description='这是一个基本描述信息。') + + # Add optional switches + parser.add_argument('-v', action='store_true', dest='is_verbose', help='produce verbose output') + parser.add_argument('-o', + action='store', + dest='output', + metavar='FILE', + help='direct output to FILE instead of stdout') + parser.add_argument('-C', + action='store', + type=int, + dest='context', + metavar='NUM', + default=0, + help='display NUM lines of added context') + + # Allow any number of additional arguments. + parser.add_argument(nargs='*', action='store', dest='inputs', help='input filenames (default is stdin)') + + args = parser.parse_args() + print(args.__dict__) + + +if __name__ == "__main__": + ''' the main point ''' + # function_argparse() + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) From 985674cf7b7421236efe49262bafef2fd152f236 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 11:12:24 +0800 Subject: [PATCH 07/17] Automatic grouping of tests by fixture instances --- case/argparse/test_module.py | 57 ++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 case/argparse/test_module.py diff --git a/case/argparse/test_module.py b/case/argparse/test_module.py new file mode 100644 index 0000000..8b799cc --- /dev/null +++ b/case/argparse/test_module.py @@ -0,0 +1,57 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +@pytest.fixture(scope="module", params=["mod1", "mod2"]) +def modarg(request): + ''' modarg ''' + param = request.param + print("\n SETUP modarg %s" % param) + yield param + print("\n TEARDOWN modarg %s" % param) + + +@pytest.fixture(scope="function", params=[1, 2], ids=["func1", "func2"]) +def funarg(request): + ''' funarg ''' + param = request.param + print("\n SETUP funarg %s" % param) + yield param + print("\n TEARDOWN funarg %s" % param) + + +def test_0(funarg): + ''' test_0 ''' + print(' test scope: function') + print(" RUN test0 with funarg %s" % funarg) + + +def test_1(modarg): + ''' test_1 ''' + print(' test scope: module') + print(" RUN test1 with modarg %s" % modarg) + + +def test_2(funarg, modarg): + ''' test_2 ''' + print(' test scope: function and module') + print(" RUN test2 with funarg %s and modarg %s" % (funarg, modarg)) + + +if __name__ == "__main__": + ''' the main point ''' + # function_argparse() + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # + # test function scope + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_0')]) + # test module scope + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_1')]) + # test scope with union function and module + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_2')]) + # + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) From 0c5b615814d14373c8e4034ff864ee3213c6c3d4 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 11:50:32 +0800 Subject: [PATCH 08/17] the using fixtures from classes, modules or projects --- case/argparse/conftest.py | 10 ++++++++++ case/argparse/test_ids.py | 1 - case/argparse/test_module.py | 1 - case/argparse/test_setenv.py | 26 ++++++++++++++++++++++++++ 4 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 case/argparse/test_setenv.py diff --git a/case/argparse/conftest.py b/case/argparse/conftest.py index 8286b9c..c74a160 100644 --- a/case/argparse/conftest.py +++ b/case/argparse/conftest.py @@ -8,6 +8,7 @@ @pytest.fixture(scope="session") def _temp_dir(): + ''' _temp_dir ''' temp = tempfile.mkdtemp(prefix='argprase-') print('\n') print('the current temp dir is {}'.format(temp)) @@ -17,6 +18,7 @@ def _temp_dir(): @pytest.fixture(scope="session") def _temp_file(): + ''' _temp_file ''' fd, temp = tempfile.mkstemp(prefix='argprase-', suffix='.tmp') # print('\n') print('the current temp path is {}'.format(temp)) @@ -24,6 +26,14 @@ def _temp_file(): os.remove(temp) +@pytest.fixture() +def cleandir(): + ''' cleandir ''' + newpath = tempfile.mkdtemp() + os.chdir(newpath) + print('\nthe current temp dir is {}'.format(newpath)) + + # @pytest.mark.xfail(raises=ZeroDivisionError) # def test_zero_division(): # ''' test zero division''' diff --git a/case/argparse/test_ids.py b/case/argparse/test_ids.py index 4840dde..452f2fe 100644 --- a/case/argparse/test_ids.py +++ b/case/argparse/test_ids.py @@ -36,7 +36,6 @@ def test_b(b): if __name__ == "__main__": ''' the main point ''' - # function_argparse() retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) diff --git a/case/argparse/test_module.py b/case/argparse/test_module.py index 8b799cc..349cce1 100644 --- a/case/argparse/test_module.py +++ b/case/argparse/test_module.py @@ -42,7 +42,6 @@ def test_2(funarg, modarg): if __name__ == "__main__": ''' the main point ''' - # function_argparse() retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) # # test function scope diff --git a/case/argparse/test_setenv.py b/case/argparse/test_setenv.py new file mode 100644 index 0000000..1e8cb6b --- /dev/null +++ b/case/argparse/test_setenv.py @@ -0,0 +1,26 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +@pytest.mark.usefixtures("cleandir") +class TestDirectoryInit(object): + ''' TestDirectoryInit ''' + def test_cwd_starts_empty(self): + ''' test_cwd_starts_empty ''' + assert os.listdir(os.getcwd()) == [] + with open("myfile", "w") as f: + f.write("hello") + + def test_cwd_again_starts_empty(self): + ''' test_cwd_again_starts_empty ''' + assert os.listdir(os.getcwd()) == [] + + +if __name__ == "__main__": + ''' the main point ''' + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) From e814bcdffd7fc87944cec8e200889edd6e08dcf7 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 13:36:02 +0800 Subject: [PATCH 09/17] pytest autouse fixtures --- case/argparse/conftest.py | 16 ------- case/pytest/__init__.py | 1 + case/pytest/conftest.py | 42 ++++++++++++++++++ case/pytest/test_db_transact.py | 54 ++++++++++++++++++++++++ case/{argparse => pytest}/test_ids.py | 0 case/{argparse => pytest}/test_module.py | 0 case/{argparse => pytest}/test_setenv.py | 0 7 files changed, 97 insertions(+), 16 deletions(-) create mode 100644 case/pytest/__init__.py create mode 100644 case/pytest/conftest.py create mode 100644 case/pytest/test_db_transact.py rename case/{argparse => pytest}/test_ids.py (100%) rename case/{argparse => pytest}/test_module.py (100%) rename case/{argparse => pytest}/test_setenv.py (100%) diff --git a/case/argparse/conftest.py b/case/argparse/conftest.py index c74a160..1ab088a 100644 --- a/case/argparse/conftest.py +++ b/case/argparse/conftest.py @@ -24,19 +24,3 @@ def _temp_file(): print('the current temp path is {}'.format(temp)) yield temp os.remove(temp) - - -@pytest.fixture() -def cleandir(): - ''' cleandir ''' - newpath = tempfile.mkdtemp() - os.chdir(newpath) - print('\nthe current temp dir is {}'.format(newpath)) - - -# @pytest.mark.xfail(raises=ZeroDivisionError) -# def test_zero_division(): -# ''' test zero division''' -# 1/0 -# with pytest.raises(ZeroDivisionError): -# 1 / 0 diff --git a/case/pytest/__init__.py b/case/pytest/__init__.py new file mode 100644 index 0000000..380474e --- /dev/null +++ b/case/pytest/__init__.py @@ -0,0 +1 @@ +# -*- coding:utf-8 -*- diff --git a/case/pytest/conftest.py b/case/pytest/conftest.py new file mode 100644 index 0000000..c74a160 --- /dev/null +++ b/case/pytest/conftest.py @@ -0,0 +1,42 @@ +# -*- coding:utf-8 -*- + +import os +import shutil +import tempfile +import pytest + + +@pytest.fixture(scope="session") +def _temp_dir(): + ''' _temp_dir ''' + temp = tempfile.mkdtemp(prefix='argprase-') + print('\n') + print('the current temp dir is {}'.format(temp)) + yield temp + shutil.rmtree(temp) + + +@pytest.fixture(scope="session") +def _temp_file(): + ''' _temp_file ''' + fd, temp = tempfile.mkstemp(prefix='argprase-', suffix='.tmp') + # print('\n') + print('the current temp path is {}'.format(temp)) + yield temp + os.remove(temp) + + +@pytest.fixture() +def cleandir(): + ''' cleandir ''' + newpath = tempfile.mkdtemp() + os.chdir(newpath) + print('\nthe current temp dir is {}'.format(newpath)) + + +# @pytest.mark.xfail(raises=ZeroDivisionError) +# def test_zero_division(): +# ''' test zero division''' +# 1/0 +# with pytest.raises(ZeroDivisionError): +# 1 / 0 diff --git a/case/pytest/test_db_transact.py b/case/pytest/test_db_transact.py new file mode 100644 index 0000000..fcc68a9 --- /dev/null +++ b/case/pytest/test_db_transact.py @@ -0,0 +1,54 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +class DB(object): + ''' db ''' + def __init__(self): + self.intransaction = [] + + def begin(self, name): + ''' begin ''' + print('\nDB::begin: {}'.format(name)) + self.intransaction.append(name) + + def rollback(self): + ''' rollback ''' + item = self.intransaction.pop() + print('\nDB::rollback: {}'.format(item)) + + +@pytest.fixture(scope="module") +def db(): + ''' db ''' + return DB() + + +class TestClass(object): + ''' TestClass ''' + @pytest.fixture(autouse=True) + def transact(self, request, db): + ''' transact ''' + db.begin(request.function.__name__) + yield + db.rollback() + + def test_method1(self, db): + ''' test_method1 ''' + print('\nTestClass::test_method1: {}'.format(db)) + assert db.intransaction == ["test_method1"] + + def test_method2(self, db): + ''' test_method2 ''' + print('\nTestClass::test_method2: {}'.format(db)) + assert db.intransaction == ["test_method2"] + + +if __name__ == "__main__": + ''' the main point ''' + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) diff --git a/case/argparse/test_ids.py b/case/pytest/test_ids.py similarity index 100% rename from case/argparse/test_ids.py rename to case/pytest/test_ids.py diff --git a/case/argparse/test_module.py b/case/pytest/test_module.py similarity index 100% rename from case/argparse/test_module.py rename to case/pytest/test_module.py diff --git a/case/argparse/test_setenv.py b/case/pytest/test_setenv.py similarity index 100% rename from case/argparse/test_setenv.py rename to case/pytest/test_setenv.py From fdc73615c13a3268e3295ab7a4dace78d70c3147 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 14:03:20 +0800 Subject: [PATCH 10/17] pytest override a fixture with direct test parametrization --- case/pytest/conftest.py | 24 ++++++++++++ case/pytest/test_something.py | 61 ++++++++++++++++++++++++++++++ case/pytest/test_something_else.py | 26 +++++++++++++ 3 files changed, 111 insertions(+) create mode 100644 case/pytest/test_something.py create mode 100644 case/pytest/test_something_else.py diff --git a/case/pytest/conftest.py b/case/pytest/conftest.py index c74a160..f0f20cf 100644 --- a/case/pytest/conftest.py +++ b/case/pytest/conftest.py @@ -40,3 +40,27 @@ def cleandir(): # 1/0 # with pytest.raises(ZeroDivisionError): # 1 / 0 + + +@pytest.fixture +def username(): + ''' username ''' + return 'username' + + +@pytest.fixture +def other_username(username): + ''' other_username ''' + return 'other-' + username + + +@pytest.fixture(params=['one', 'two', 'three']) +def parametrized_username(request): + ''' parametrized_username ''' + return request.param + + +@pytest.fixture +def non_parametrized_username(request): + ''' non_parametrized_username ''' + return 'username' diff --git a/case/pytest/test_something.py b/case/pytest/test_something.py new file mode 100644 index 0000000..315ca5a --- /dev/null +++ b/case/pytest/test_something.py @@ -0,0 +1,61 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +def test_username_0(username): + ''' test_username_0 ''' + assert username == 'username' + + +@pytest.mark.parametrize('username', ['directly-overridden-username']) +def test_username_1(username): + ''' test_username_1 ''' + assert username == 'directly-overridden-username' + + +@pytest.mark.parametrize('username', ['directly-overridden-username-other-repaired']) +def test_username_other(username, other_username): + ''' test_username_other ''' + print('\n\n test_username_other::username: {}'.format(username)) + print(' test_username_other::other_username: {}'.format(other_username)) + assert username == 'directly-overridden-username-other-repaired' + assert other_username == 'other-directly-overridden-username-other-repaired' + + +@pytest.fixture +def parametrized_username(): + ''' parametrized_username ''' + return 'overridden-username' + + +@pytest.fixture(params=['one', 'two', 'three']) +def non_parametrized_username(request): + ''' non_parametrized_username ''' + return request.param + + +def test_parametrized_username_0(parametrized_username): + ''' test_parametrized_username_0 ''' + assert parametrized_username == 'overridden-username' + + +def test_parametrized_username_1(non_parametrized_username): + ''' test_parametrized_username_1 ''' + assert non_parametrized_username in ['one', 'two', 'three'] + + +if __name__ == "__main__": + ''' the main point ''' + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_username_0')]) + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_username_1')]) + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_username_other')]) + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_parametrized_username_0')]) + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_parametrized_username_1')]) + # + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) diff --git a/case/pytest/test_something_else.py b/case/pytest/test_something_else.py new file mode 100644 index 0000000..ebf423d --- /dev/null +++ b/case/pytest/test_something_else.py @@ -0,0 +1,26 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +def test_parametrized_username_0(parametrized_username): + ''' test_parametrized_username_0 ''' + assert parametrized_username in ['one', 'two', 'three'] + + +def test_parametrized_username_1(non_parametrized_username): + ''' test_parametrized_username_1 ''' + assert non_parametrized_username == 'username' + + +if __name__ == "__main__": + ''' the main point ''' + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_parametrized_username_0')]) + # retcode = pytest.main(args=['-v', '-s', '{}::{}'.format(os.path.abspath(__file__), 'test_parametrized_username_1')]) + # + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) From e90471d2d61dc42410562b820fa71297f9b09a71 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 16:28:43 +0800 Subject: [PATCH 11/17] the choices pytest that not allow unittest --- .vscode/launch.json | 42 +++++++++++++++++++++++++++++++-------- .vscode/settings.json | 21 ++++++++++++-------- case/argparse/conftest.py | 6 ++++++ 3 files changed, 53 insertions(+), 16 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 1620194..421f6bc 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,18 +4,44 @@ // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + // { + // "args": [ + // "${file}", + // // "1", + // // "-l", + // // "${workspaceFolder}/build/asc.txt", + // // "-h", + // ], + // "console": "integratedTerminal", + // "env": { + // // "PYTEST_ADDOPTS": "--no-cov" + // }, + // "module": "pytest", + // "name": "Python: Pytest", + // // "program": "${file}", + // "request": "launch", + // "type": "python", + // }, { - "name": "Python: The Current File", - "type": "python", - "request": "launch", - "program": "${file}", // "args": [ - // "1", - // "-l", - // "${workspaceFolder}/build/asc.txt" + // "-v", + // "-s", + // // "--disable-pytest-warnings", // ], "console": "integratedTerminal", - "envFile": "${workspaceFolder}/.env/dev.env" + // "debugOptions": [ + // "WaitOnAbnormalExit", + // "WaitOnNormalExit", + // "RedirectOutput" + // ], + "env": { + // "PYTEST_ADDOPTS": "--no-cov" + }, + "envFile": "${workspaceFolder}/.env/dev.env", + "name": "Python: The Current File", + "program": "${file}", + "request": "launch", + "type": "python", } ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 4efa043..5c492cf 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -86,16 +86,21 @@ // "python.testing.autoTestDiscoverOnSaveEnabled": true, "python.testing.cwd": "${workspaceFolder}", "python.testing.nosetestsEnabled": false, - "python.testing.pytestEnabled": false, - "python.testing.unittestEnabled": true, - // https://github.com/microsoft/vscode-python/discussions/15997#discussioncomment-636389 - "python.testing.unittestArgs": [ - "-v", + "python.testing.pytestEnabled": true, + "python.testing.pytestArgs": [ + // "--disable-pytest-warnings", "-s", - ".", - "-p", - "test_*.py" + "-v", ], + "python.testing.unittestEnabled": false, + // https://github.com/microsoft/vscode-python/discussions/15997#discussioncomment-636389 + // "python.testing.unittestArgs": [ + // "-v", + // "-s", + // ".", + // "-p", + // "test_*.py" + // ], // "workbench.settings.openDefaultSettings": true, // "workbench.settings.editor": "ui", // "workbench.settings.openDefaultKeybindings": true, diff --git a/case/argparse/conftest.py b/case/argparse/conftest.py index 1ab088a..738bcc9 100644 --- a/case/argparse/conftest.py +++ b/case/argparse/conftest.py @@ -1,10 +1,16 @@ # -*- coding:utf-8 -*- +import logging import os import shutil import tempfile + +from com.dvsnier.config.journal.common_config import config import pytest +kwargs = {'output_dir_name': 'pytest', 'file_name': 'log', 'level': logging.DEBUG} +config(kwargs) + @pytest.fixture(scope="session") def _temp_dir(): From 0f302abfb94a609bf805fe24e76de5b81603afbc Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 17:02:16 +0800 Subject: [PATCH 12/17] to add pytest demo --- case/pytest/test_pytest_demo.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 case/pytest/test_pytest_demo.py diff --git a/case/pytest/test_pytest_demo.py b/case/pytest/test_pytest_demo.py new file mode 100644 index 0000000..8346a27 --- /dev/null +++ b/case/pytest/test_pytest_demo.py @@ -0,0 +1,17 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +def test_cmd_0(): + ''' the test cmd ''' + print('\nthe test_cmd_0 ended.') + + +if __name__ == "__main__": + ''' the main point ''' + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) From 55e72b229108a54bfa1bc21c4cc9f42071362722 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Wed, 1 Dec 2021 18:12:43 +0800 Subject: [PATCH 13/17] to add argparse test script --- case/argparse/conftest.py | 4 +- .../{test_argparse.py => test_argparse_0.py} | 25 +------- case/argparse/test_argparse_1.py | 23 -------- case/argparse/test_script.py | 58 +++++++++++++++++++ case/pytest/test_module.py | 2 +- 5 files changed, 62 insertions(+), 50 deletions(-) rename case/argparse/{test_argparse.py => test_argparse_0.py} (59%) create mode 100644 case/argparse/test_script.py diff --git a/case/argparse/conftest.py b/case/argparse/conftest.py index 738bcc9..80906df 100644 --- a/case/argparse/conftest.py +++ b/case/argparse/conftest.py @@ -17,7 +17,7 @@ def _temp_dir(): ''' _temp_dir ''' temp = tempfile.mkdtemp(prefix='argprase-') print('\n') - print('the current temp dir is {}'.format(temp)) + logging.debug('the current temp dir is {}'.format(temp)) yield temp shutil.rmtree(temp) @@ -27,6 +27,6 @@ def _temp_file(): ''' _temp_file ''' fd, temp = tempfile.mkstemp(prefix='argprase-', suffix='.tmp') # print('\n') - print('the current temp path is {}'.format(temp)) + logging.debug('the current temp path is {}'.format(temp)) yield temp os.remove(temp) diff --git a/case/argparse/test_argparse.py b/case/argparse/test_argparse_0.py similarity index 59% rename from case/argparse/test_argparse.py rename to case/argparse/test_argparse_0.py index 7415e86..770d92b 100644 --- a/case/argparse/test_argparse.py +++ b/case/argparse/test_argparse_0.py @@ -1,25 +1,6 @@ # -*- coding:utf-8 -*- import argparse -import os -import pytest - - -def test_cmd_1(execute): - ''' the test cmd ''' - print('\ntest_cmd_1: {}'.format(execute)) - print('the test_cmd_1 ended.') - # pytest -v -s ./case/argparse/test_argparse.py - # pytest -v -s test_argparse.py - pass - - -@pytest.fixture(scope='session', params=['a', 'b', pytest.param('c', marks=pytest.mark.skip)]) -def execute(_temp_dir, _temp_file, request): - ''' the execute ''' - value = request.param - print('\nexecute: {}'.format(value)) - return value def function_argparse(): @@ -54,8 +35,4 @@ def function_argparse(): if __name__ == "__main__": ''' the main point ''' - # function_argparse() - retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) - # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) - # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) - print(retcode) + function_argparse() diff --git a/case/argparse/test_argparse_1.py b/case/argparse/test_argparse_1.py index 6985a99..6a5ee51 100644 --- a/case/argparse/test_argparse_1.py +++ b/case/argparse/test_argparse_1.py @@ -1,31 +1,9 @@ # -*- coding:utf-8 -*- import argparse -import os -import subprocess -import pytest import sys -def test_cmd_1(execute): - ''' the test cmd ''' - print('the test_cmd_1 ended.') - # pytest -v -s ./case/argparse/test_argparse_1.py - # pytest -v -s test_argparse_1.py - pass - - -@pytest.fixture() -def execute(_temp_dir, _temp_file): - try: - args = [sys.executable, __file__, '1'] - # args = [sys.executable, __file__, '-h'] - subprocess.check_output(args=args, ) - subprocess.check_call(args=args, ) - finally: - print('the execute...') - - def function_argparse(): # # the command line srcipt: @@ -62,4 +40,3 @@ def function_argparse(): if __name__ == "__main__": ''' the main point ''' function_argparse() - # pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) diff --git a/case/argparse/test_script.py b/case/argparse/test_script.py new file mode 100644 index 0000000..4ed925c --- /dev/null +++ b/case/argparse/test_script.py @@ -0,0 +1,58 @@ +# -*- coding:utf-8 -*- + +import logging +import os +import subprocess +import pytest +import sys + + +def test_cmd_1(execute): + ''' the test cmd ''' + print('\n the test_cmd_1 ended.') + logging.info('the test_cmd_1 ended.') + + +# @pytest.fixture(scope='session', params=['test_argparse_0.py']) +@pytest.fixture(scope='session', params=['test_argparse_1.py']) +# @pytest.fixture(scope='session', params=['test_argparse_0.py', 'test_argparse_1.py']) +def generic_cmd_prefix(_temp_dir, _temp_file, request): + ''' the generic command prefix ''' + dest_script_name = os.path.join(os.path.dirname(__file__), request.param) + logging.debug('the generic_cmd_prefix dest_script_name is {}'.format(dest_script_name)) + return [sys.executable, dest_script_name] + + +@pytest.fixture(params=[['1'], ['-h']]) +def generic_cmd_args(generic_cmd_prefix, request): + ''' the generic command args ''' + dest_script_args = generic_cmd_prefix + request.param + logging.debug('the current generic_cmd_args dest_script_args: {}'.format(dest_script_args)) + return dest_script_args + + +@pytest.fixture() +def execute(generic_cmd_args): + try: + args = generic_cmd_args + logging.warning('the parameters required for current execution, the command script: [\"{}\"]'.format( + ' '.join(args))) + std_output = subprocess.check_output(args) + if type(std_output) == bytes: + # logging.warning(str(std_output, encoding='utf-8')) + logging.info('the capture std output from subprocess:\n {}'.format(str(std_output, encoding='utf-8'))) + else: + logging.warning(std_output) + retcode = subprocess.check_call(args) + if retcode == 0: + logging.info('the script verify passed.') + finally: + logging.debug('the execute ended') + + +if __name__ == "__main__": + ''' the main point ''' + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) diff --git a/case/pytest/test_module.py b/case/pytest/test_module.py index 349cce1..298a5d8 100644 --- a/case/pytest/test_module.py +++ b/case/pytest/test_module.py @@ -4,7 +4,7 @@ import pytest -@pytest.fixture(scope="module", params=["mod1", "mod2"]) +@pytest.fixture(scope="module", params=["mod1", "mod2", pytest.param('mod3', marks=pytest.mark.skip)]) def modarg(request): ''' modarg ''' param = request.param From c1656203a21e36db4c20ae7bbeb359894b795e5b Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Thu, 2 Dec 2021 10:25:23 +0800 Subject: [PATCH 14/17] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20argparse=20=E8=87=AA?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- case/argparse/test_argparse_2.py | 99 ++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 case/argparse/test_argparse_2.py diff --git a/case/argparse/test_argparse_2.py b/case/argparse/test_argparse_2.py new file mode 100644 index 0000000..e134f1a --- /dev/null +++ b/case/argparse/test_argparse_2.py @@ -0,0 +1,99 @@ +# -*- coding:utf-8 -*- + +import argparse +import logging +import sys + + +def function_argparse(): + ''' + function_argparse + + reference link: + + 1. https://docs.python.org/zh-cn/2.7/library/argparse.html + 2. https://docs.python.org/zh-cn/3.8/library/argparse.html + + usage: python -m build [-h] [--version] [--sdist] [--wheel] [--outdir OUTDIR] [--skip-dependency-check] [--no-isolation] + [--config-setting CONFIG_SETTING] + [srcdir] + ''' + # + # the command line srcipt: + # + # python -m build -h + # python test_argparse_2.py --help + # python test_argparse_2.py -h + # python test_argparse_2.py ./a ./b + # python test_argparse_2.py ./a ./b -vs + # python test_argparse_2.py ./a ./b -v1 0 + # python test_argparse_2.py ./a ./b -v1 1 + # python test_argparse_2.py ./a ./b -v1 2 + # python test_argparse_2.py ./a ./b -v2 + # python test_argparse_2.py ./a ./b -v2 -v2 + # python test_argparse_2.py ./a ./b -v + # python test_argparse_2.py ./a ./b -q + # python test_argparse_2.py ./a ./b -vs -v1 0 + # python test_argparse_2.py ./a ./b -vs -v1 1 + # python test_argparse_2.py ./a ./b -vs -v1 2 + # python test_argparse_2.py ./a ./b -vs -v1 0 -v2 + # python test_argparse_2.py ./a ./b -vs -v1 1 -v2 + # python test_argparse_2.py ./a ./b -vs -v1 2 -v2 + # python test_argparse_2.py ./a ./b -vs -v1 0 -v2 -v2 + # python test_argparse_2.py ./a ./b -vs -v1 1 -v2 -v2 + # python test_argparse_2.py ./a ./b -vs -v1 2 -v2 -v2 + # python test_argparse_2.py ./a ./b -vs -v1 0 -v2 -v + # python test_argparse_2.py ./a ./b -vs -v1 1 -v2 -v + # python test_argparse_2.py ./a ./b -vs -v1 2 -v2 -v + # python test_argparse_2.py ./a ./b -vs -v1 0 -v2 -q + # python test_argparse_2.py ./a ./b -vs -v1 1 -v2 -q + # python test_argparse_2.py ./a ./b -vs -v1 2 -v2 -q + # + parser = argparse.ArgumentParser(description='这个是命令行总体多行文本描述信息.') + # 位置参数 + parser.add_argument('srcdir', metavar='srcdir', type=str, help='这是一个 srcdir 位置参数') + parser.add_argument('destdir', metavar='destdir', type=str, help='这是一个 destdir 位置参数') + # 可选参数 + parser.add_argument('-vs', '--version', action="store_true", help='可选参数:显示版本号,并退出') + parser.add_argument("-v1", "--verbosity_1", type=int, choices=[0, 1, 2], default=0, help="可选参数: 默认值形式") + parser.add_argument("-v2", "--verbosity_2", action="count", default=0, help="可选参数: 默认值count 类型形式") + # parser.add_argument('-l', + # '--log', + # default=sys.stdout, + # type=argparse.FileType('w'), + # help='the file where the sum should be written') + # 可选参数,互斥选项 + group = parser.add_mutually_exclusive_group() + group.add_argument("-v", "--verbose", action="store_true", help='可选参数,互斥参数: the verbose info') + group.add_argument("-q", "--quiet", action="store_true", help='可选参数,互斥参数: the quiet info') + args = parser.parse_args() + + if args.srcdir: + print('the args.srcdir: {}'.format(args.srcdir)) + logging.debug('the args.srcdir: {}'.format(args.srcdir)) + if args.destdir: + print('the args.destdir: {}'.format(args.destdir)) + logging.debug('the args.destdir: {}'.format(args.destdir)) + if args.version: + print('the args.version: {}'.format(args.version)) + logging.debug('the args.version: {}'.format(args.version)) + if args.verbosity_1 >= 0: + print('the args.verbosity_1: {}'.format(args.verbosity_1)) + logging.debug('the args.verbosity_1: {}'.format(args.verbosity_1)) + if args.verbosity_2: + print('the args.verbosity_2: {}'.format(args.verbosity_2)) + logging.debug('the args.verbosity_2: {}'.format(args.verbosity_2)) + if args.verbose: + print('the args.verbose: {}'.format(args.verbose)) + logging.debug('the args.verbose: {}'.format(args.verbose)) + if args.quiet: + print('the args.quiet: {}'.format(args.quiet)) + logging.debug('the args.quiet: {}'.format(args.quiet)) + # if args.log: + # args.log.write('%s' % sum(args.integers)) + # args.log.close() + + +if __name__ == "__main__": + ''' the main point ''' + function_argparse() From 137a1484c0f942c8e212336f422430d2cdc4381c Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Thu, 2 Dec 2021 12:22:13 +0800 Subject: [PATCH 15/17] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20argparse=20=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- case/argparse/test_script.py | 66 ++++++++++++++++++++++++++++-------- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/case/argparse/test_script.py b/case/argparse/test_script.py index 4ed925c..4056c62 100644 --- a/case/argparse/test_script.py +++ b/case/argparse/test_script.py @@ -13,17 +13,47 @@ def test_cmd_1(execute): logging.info('the test_cmd_1 ended.') +IS_DEBUG_ONLY = False +# IS_SKIP = True + + +@pytest.fixture(scope='session', autouse=True) +def generic_cmd_env(_temp_dir, _temp_file): + ''' generic cmd env ''' + pass + + # @pytest.fixture(scope='session', params=['test_argparse_0.py']) -@pytest.fixture(scope='session', params=['test_argparse_1.py']) -# @pytest.fixture(scope='session', params=['test_argparse_0.py', 'test_argparse_1.py']) -def generic_cmd_prefix(_temp_dir, _temp_file, request): +# @pytest.fixture(scope='session', params=['test_argparse_1.py']) +# @pytest.fixture(scope='session', params=['test_argparse_2.py']) +@pytest.fixture(scope='session', + params=[ + pytest.param('test_argparse_0.py', marks=pytest.mark.skip), + pytest.param('test_argparse_1.py', marks=pytest.mark.skip), 'test_argparse_2.py' + ]) +# @pytest.mark.parametrize('script_name', ['test_argparse_0.py', 'test_argparse_1.py', 'test_argparse_2.py']) +def generic_cmd_prefix(request): ''' the generic command prefix ''' dest_script_name = os.path.join(os.path.dirname(__file__), request.param) logging.debug('the generic_cmd_prefix dest_script_name is {}'.format(dest_script_name)) return [sys.executable, dest_script_name] -@pytest.fixture(params=[['1'], ['-h']]) +# the test_argparse_2.py script only +PARAMS_ARGPARSE_2 = [['-h'], ['./a', './b'], ['./a', './b', '-vs'], ['./a', './b', '-v1', '0'], + ['./a', './b', '-v1', '1'], ['./a', './b', '-v1', '2'], ['./a', './b', '-v2'], + ['./a', './b', '-v2', '-v2'], ['./a', './b', '-v'], ['./a', './b', '-q'], + ['./a', './b', '-vs', '-v1', '0'], ['./a', './b', '-vs', '-v1', '1'], + ['./a', './b', '-vs', '-v1', '2'], ['./a', './b', '-vs', '-v1', '0', '-v2'], + ['./a', './b', '-vs', '-v1', '1', '-v2'], ['./a', './b', '-vs', '-v1', '2', '-v2'], + ['./a', './b', '-vs', '-v1', '0', '-v2', '-v2'], ['./a', './b', '-vs', '-v1', '1', '-v2', '-v2'], + ['./a', './b', '-vs', '-v1', '2', '-v2', '-v2'], ['./a', './b', '-vs', '-v1', '0', '-v2', '-v'], + ['./a', './b', '-vs', '-v1', '1', '-v2', '-v'], ['./a', './b', '-vs', '-v1', '2', '-v2', '-v'], + ['./a', './b', '-vs', '-v1', '0', '-v2', '-q'], ['./a', './b', '-vs', '-v1', '1', '-v2', '-q'], + ['./a', './b', '-vs', '-v1', '2', '-v2', '-q']] + + +@pytest.fixture(params=PARAMS_ARGPARSE_2) def generic_cmd_args(generic_cmd_prefix, request): ''' the generic command args ''' dest_script_args = generic_cmd_prefix + request.param @@ -33,19 +63,27 @@ def generic_cmd_args(generic_cmd_prefix, request): @pytest.fixture() def execute(generic_cmd_args): + ''' the execute ''' try: args = generic_cmd_args - logging.warning('the parameters required for current execution, the command script: [\"{}\"]'.format( - ' '.join(args))) - std_output = subprocess.check_output(args) - if type(std_output) == bytes: - # logging.warning(str(std_output, encoding='utf-8')) - logging.info('the capture std output from subprocess:\n {}'.format(str(std_output, encoding='utf-8'))) + if args: + logging.warning('the parameters required for current execution, the command script: [\"{}\"]'.format( + ' '.join(args))) + if IS_DEBUG_ONLY: + pass + else: + std_output = subprocess.check_output(args) + if type(std_output) == bytes: + # logging.warning(str(std_output, encoding='utf-8')) + logging.info('the capture std output from subprocess:\n {}'.format(str(std_output, + encoding='utf-8'))) + else: + logging.warning(std_output) + retcode = subprocess.check_call(args) + if retcode == 0: + logging.info('the script verify passed.') else: - logging.warning(std_output) - retcode = subprocess.check_call(args) - if retcode == 0: - logging.info('the script verify passed.') + logging.warning('the error script command line that is skipped.') finally: logging.debug('the execute ended') From 3e5060c488465079acce2908620df263192c943a Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Fri, 3 Dec 2021 10:13:20 +0800 Subject: [PATCH 16/17] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20setup.py=20=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- setup.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 setup.py diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..4052902 --- /dev/null +++ b/setup.py @@ -0,0 +1,5 @@ +# -*- coding:utf-8 -*- + +from setuptools import setup + +setup() From 7e3cdbc0795d5b13f965475a71d73f7d16e55c63 Mon Sep 17 00:00:00 2001 From: zhenwei-li Date: Fri, 3 Dec 2021 10:17:28 +0800 Subject: [PATCH 17/17] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20unittest=20=E5=92=8C?= =?UTF-8?q?=20pytest=20=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- template/test_template_with_pytest.py | 17 +++++++++++++++++ ...mplate.py => test_template_with_unittest.py} | 0 2 files changed, 17 insertions(+) create mode 100644 template/test_template_with_pytest.py rename template/{test_template.py => test_template_with_unittest.py} (100%) diff --git a/template/test_template_with_pytest.py b/template/test_template_with_pytest.py new file mode 100644 index 0000000..ceabb61 --- /dev/null +++ b/template/test_template_with_pytest.py @@ -0,0 +1,17 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +def test_xxx(): + ''' the test case method ''' + pass + + +if __name__ == "__main__": + ''' the pytest main point ''' + retcode = pytest.main(args=['-v', '-s', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--fixtures', os.path.abspath(__file__)]) + # retcode = pytest.main(args=['--collect-only', os.path.abspath(__file__)]) + print(retcode) diff --git a/template/test_template.py b/template/test_template_with_unittest.py similarity index 100% rename from template/test_template.py rename to template/test_template_with_unittest.py