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/ diff --git a/.vscode/launch.json b/.vscode/launch.json index b80908c..421f6bc 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,15 +1,47 @@ { - // 使用 IntelliSense 了解相关属性。 + // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: 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: 当前文件", - "type": "python", - "request": "launch", + // "args": [ + // "-v", + // "-s", + // // "--disable-pytest-warnings", + // ], + "console": "integratedTerminal", + // "debugOptions": [ + // "WaitOnAbnormalExit", + // "WaitOnNormalExit", + // "RedirectOutput" + // ], + "env": { + // "PYTEST_ADDOPTS": "--no-cov" + }, + "envFile": "${workspaceFolder}/.env/dev.env", + "name": "Python: The Current File", "program": "${file}", - "console": "integratedTerminal" + "request": "launch", + "type": "python", } ] -} \ No newline at end of file +} diff --git a/.vscode/settings.json b/.vscode/settings.json index aa16905..5c492cf 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", @@ -83,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/__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() diff --git a/case/argparse/conftest.py b/case/argparse/conftest.py new file mode 100644 index 0000000..80906df --- /dev/null +++ b/case/argparse/conftest.py @@ -0,0 +1,32 @@ +# -*- 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(): + ''' _temp_dir ''' + temp = tempfile.mkdtemp(prefix='argprase-') + print('\n') + logging.debug('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') + 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.py deleted file mode 100644 index 09382e9..0000000 --- a/case/argparse/test_argparse.py +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding:utf-8 -*- - -import argparse - -# -# python -m test_argparse.py --help -parser = argparse.ArgumentParser(description='Command-line example.') - -# 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__ diff --git a/case/argparse/test_argparse_0.py b/case/argparse/test_argparse_0.py new file mode 100644 index 0000000..770d92b --- /dev/null +++ b/case/argparse/test_argparse_0.py @@ -0,0 +1,38 @@ +# -*- coding:utf-8 -*- + +import argparse + + +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() diff --git a/case/argparse/test_argparse_1.py b/case/argparse/test_argparse_1.py new file mode 100644 index 0000000..6a5ee51 --- /dev/null +++ b/case/argparse/test_argparse_1.py @@ -0,0 +1,42 @@ +# -*- coding:utf-8 -*- + +import argparse +import sys + + +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() 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() diff --git a/case/argparse/test_script.py b/case/argparse/test_script.py new file mode 100644 index 0000000..4056c62 --- /dev/null +++ b/case/argparse/test_script.py @@ -0,0 +1,96 @@ +# -*- 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.') + + +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_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] + + +# 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 + 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): + ''' the execute ''' + try: + args = generic_cmd_args + 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('the error script command line that is skipped.') + 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/__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..f0f20cf --- /dev/null +++ b/case/pytest/conftest.py @@ -0,0 +1,66 @@ +# -*- 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 + + +@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_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/pytest/test_ids.py b/case/pytest/test_ids.py new file mode 100644 index 0000000..452f2fe --- /dev/null +++ b/case/pytest/test_ids.py @@ -0,0 +1,42 @@ +# -*- 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 ''' + 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 new file mode 100644 index 0000000..298a5d8 --- /dev/null +++ b/case/pytest/test_module.py @@ -0,0 +1,56 @@ +# -*- coding:utf-8 -*- + +import os +import pytest + + +@pytest.fixture(scope="module", params=["mod1", "mod2", pytest.param('mod3', marks=pytest.mark.skip)]) +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 ''' + 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) 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) diff --git a/case/pytest/test_setenv.py b/case/pytest/test_setenv.py new file mode 100644 index 0000000..1e8cb6b --- /dev/null +++ b/case/pytest/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) 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) 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() 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