def test_whitespace(self): """ Runs all test cases in test/whitespace directory. """ test_file_names = glob.glob( os.path.dirname(os.path.abspath(__file__)) + '/whitespace/*.sdoc') config_path = glob.glob( os.path.dirname(os.path.abspath(__file__)) + '/whitespace/sdoc.cfg') for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): application = Application() application.add(SDocCommand()) command = application.find('sdoc') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name()), ('config.cfg', config_path), ('main.sdoc', test_file_name)]) with open('output.html', 'r') as actual: actual_text = actual.read() self.assertIn( 'chapter <a href="#chap:bug" title="Bug">1</a> in', actual_text) self.assertIn( 'sentence <a href="#chap:bug" title="Bug">1</a>.', actual_text) self.assertIn( 'chapter <a href="#chap:bug" title="Bug">1</a> item', actual_text) self.assertIn('item <a href="#chap:bug" title="Bug">1</a>.', actual_text)
def test_substitute(self): """ Runs all test cases in the test/debug directory. """ test_file_names = glob.glob( os.path.dirname(os.path.abspath(__file__)) + "/error/*.sdoc1") for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): pre, ext = os.path.splitext(test_file_name) text_file_name = pre + '.txt' with open(text_file_name, 'r') as file: expected = file.read() expected = expected.strip() application = Application() application.add(SDoc1Command()) command = application.find('sdoc1') command_tester = CommandTester(command) status = command_tester.execute([('command', command.get_name()), ('main.sdoc', test_file_name), ('output.sdoc2', 't.sdoc2')]) actual = command_tester.get_display().rstrip() self.assertTrue(actual.endswith(expected)) self.assertNotEqual(0, status)
def test_ids(self): """ Runs all test cases in test/id directory. """ test_file_names = glob.glob(os.path.dirname(os.path.abspath(__file__)) + '/_numbering_id/*.sdoc') config_path = glob.glob(os.path.dirname(os.path.abspath(__file__)) + '/numbering_id/sdoc.cfg') for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): application = Application() application.add(SDocCommand()) command = application.find('sdoc') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name()), ('config.cfg', config_path), ('main.sdoc', test_file_name)]) with open('output.html', 'r') as actual: actual_text = actual.read() self.assertIn('<h1 id="#chapter:1">1 chapter 1</h1>', actual_text) self.assertIn('<h2 id="#section:1.1">1.1 ololol</h2>', actual_text) self.assertIn('<div class="part" id="#part:1-1">1 First part</div>', actual_text) self.assertIn('<h1 id="#chapter:1-1">1 Cchapter 2</h1>', actual_text) self.assertIn('<h2 id="#section:1-1.1">1.1 ololol2</h2>', actual_text) self.assertIn('<div class="part" id="#part:2-2">2 Second part, YEAH!!!</div>', actual_text) self.assertIn('<h1 id="#chapter:2-1">1 CHAPTER 1</h1>', actual_text) self.assertIn('<h2 id="#section:2-1.1">1.1 section12</h2>', actual_text)
def test_references(self): """ Runs all test cases in test/refs directory. """ test_file_names = glob.glob(os.path.dirname(os.path.abspath(__file__)) + '/refs/*.sdoc') config_path = glob.glob(os.path.dirname(os.path.abspath(__file__)) + '/refs/sdoc.cfg') for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): application = Application() application.add(SDocCommand()) command = application.find('sdoc') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name()), ('config.cfg', config_path), ('main.sdoc', test_file_name)]) with open('output.html', 'r') as actual: actual_text = actual.read() self.assertIn('<h3 id="chap:intro">1 Introduction</h3>', actual_text) self.assertIn('chapter <a class="sdoc.reference" href="#chap:awesome" title="Awesome">2</a>', actual_text) self.assertIn('<h3 id="chap:awesome">2 Awesome</h3>', actual_text) self.assertIn('chapter <a class="sdoc.reference" href="#chap:intro" title="Introduction">1</a>', actual_text)
def test_substitute(self): """ Runs all test cases in the test/debug directory. """ test_file_names = glob.glob(os.path.dirname(os.path.abspath(__file__)) + "/substitute/*.sdoc1") for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): pre, ext = os.path.splitext(test_file_name) text_file_name = pre + '.sdoc2' with open(text_file_name, 'r') as file: expected = file.read() application = Application() application.add(SDoc1Command()) command = application.find('sdoc1') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name()), ('main.sdoc', test_file_name), ('output.sdoc2', 't.sdoc2')]) with open('t.sdoc2', 'r') as file: actual = file.read() actual = re.sub(r'\\position\{[^\}]*\}', '', actual) self.assertEqual(expected.strip(), actual.strip())
def test_numbering(self): """ Runs all test cases in the test/enumeration directory. """ test_file_names = glob.glob(os.path.dirname(os.path.abspath(__file__)) + "/enumeration/*.sdoc") config_path = glob.glob(os.path.dirname(os.path.abspath(__file__)) + "/enumeration/sdoc.cfg") for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): pre, ext = os.path.splitext(test_file_name) csv_file_name = pre + '.csv' application = Application() application.add(SDoc2Command()) command = application.find('sdoc2') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name()), ('config.cfg', config_path), ('main.sdoc2', test_file_name)]) root = in_scope(1) sdoc2.node_store.number_numerable() numbers = root.get_enumerated_items() actual = self.create_list_of_items(numbers) expected = self.csv_to_tuple(csv_file_name) self.assertEqual(expected, actual)
def test_numbering(self): """ Runs all test cases in the test/enumeration directory. """ test_file_names = glob.glob( os.path.dirname(os.path.abspath(__file__)) + "/enumeration/*.sdoc") config_path = glob.glob( os.path.dirname(os.path.abspath(__file__)) + "/enumeration/sdoc.cfg") for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): pre, ext = os.path.splitext(test_file_name) csv_file_name = pre + '.csv' application = Application() application.add(SDoc2Command()) command = application.find('sdoc2') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name()), ('config.cfg', config_path), ('main.sdoc2', test_file_name)]) root = in_scope(1) sdoc2.node_store.number_numerable() numbers = root.get_enumerated_items() actual = self.create_list_of_items(numbers) expected = self.csv_to_tuple(csv_file_name) self.assertEqual(expected, actual)
def test_execute(): application = Application() application.add(DcpCommand()) command = application.find("dcp") command_tester = CommandTester(command) with pytest.raises(FileNotFoundError): command_tester.execute("orders.csv mysql://localhost:3306/mydb/orders")
def test_boom(self): """ Test extractie boombestanden. """ application = Application() application.add(ShredderCommand()) command = application.find('kerapu:shredder') command_tester = CommandTester(command) status = command_tester.execute([ ('command', command.get_name()), ('XML-bestand', 'test/var/lib/20190101 BoomBestanden v20180920.xml'), ('folder', 'test/var/lib') ]) output = command_tester.get_display().rstrip() self.assertEqual(0, status) for tabel in [ 'BeslisRegels', 'AttribuutGroepen', 'AttribuutGroepKoppelingen', 'Attributen', 'BoomParameters' ]: self.assertRegex(output, r'Wrote \s*\d+ rows to {}.csv'.format(tabel), tabel)
def test_value_error_on_unknown_model_getter(): application = Application() application.add(InitCommand()) module_name = "foo" module_file_path = module_name + ".py" save_path = "foo-config/model.py" content = """ import torch def init(**args): return torch.nn.Conv2d(10, 10, 10) """ with open(module_file_path, "a") as the_file: the_file.write(content) command = application.find("init") command_tester = CommandTester(command) with pytest.raises(ValueError, match=r".*{fn_name}.*".format(fn_name="get_model")): command_tester.execute(module_name + " --save=" + save_path) os.remove(module_file_path) shutil.rmtree(os.path.dirname(save_path))
def test_substitute(self): """ Runs all test cases in the test/debug directory. """ test_file_names = glob.glob(os.path.dirname(os.path.abspath(__file__)) + "/error/*.sdoc1") for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): pre, ext = os.path.splitext(test_file_name) text_file_name = pre + '.txt' with open(text_file_name, 'r') as file: expected = file.read() expected = expected.strip() application = Application() application.add(SDoc1Command()) command = application.find('sdoc1') command_tester = CommandTester(command) status = command_tester.execute([('command', command.get_name()), ('main.sdoc', test_file_name), ('output.sdoc2', 't.sdoc2')]) actual = command_tester.get_display().rstrip() self.assertTrue(actual.endswith(expected)) self.assertNotEqual(0, status)
def test_debug(self): """ Runs all test cases in the test/debug directory. """ test_file_names = glob.glob( os.path.dirname(os.path.abspath(__file__)) + "/debug/*.sdoc") for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): pre, ext = os.path.splitext(test_file_name) text_file_name = pre + '.txt' with open(text_file_name, 'r') as file: text = file.read() application = Application() application.add(SDoc1Command()) command = application.find('sdoc1') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name()), ('main.sdoc', test_file_name), ('output.sdoc2', 't.sdoc2')]) self.assertTrue(command_tester.get_display().rstrip().endswith( text.strip()))
def test_referentie(self): """ Test extractie referentietabellen. """ application = Application() application.add(ShredderCommand()) command = application.find('kerapu:shredder') command_tester = CommandTester(command) status = command_tester.execute([ ('command', command.get_name()), ('XML-bestand', 'test/var/lib/20190101 Referenties v20180920.xml'), ('folder', 'test/var/lib') ]) output = command_tester.get_display().rstrip() self.assertEqual(0, status) for tabel in [ 'AfsluitRedenen', 'BehandelKlassen', 'Diagnosen', 'Geslachten', 'LimitatieMachtigingen', 'Specialismen', 'VertaalZorgActiviteiten', 'ZorgProductGroepen', 'ZorgTypen', 'ZorgVragen' ]: self.assertRegex(output, r'Wrote \s*\d+ rows to {}.csv'.format(tabel), tabel)
def application(tempdir: Path): """Commandline application fixture.""" app = Application() for cmd_class in (ListProjects, AddProject, RemoveProject, Execute): command = cmd_class(config_file=tempdir / "config.toml") app.add(command) return app
def build_application(): config = Config("clevercsv", __version__) app = Application(config=config, complete=False) app.add(ViewCommand()) app.add(DetectCommand()) app.add(StandardizeCommand()) app.add(CodeCommand()) app.add(ExploreCommand()) return app
def test_value_error_on_unknown_module(): application = Application() application.add(InitCommand()) command = application.find("init") command_tester = CommandTester(command) unknown_module_name = "some_module" with pytest.raises(ValueError, match=r".*%s.*" % unknown_module_name): command_tester.execute(unknown_module_name)
def test_init_error_custom_config_with_list(): application = Application() application.add(InitCommand()) invalid_config = '[{"conf_key": "value"}]' module_name = "foo" command = application.find("init") command_tester = CommandTester(command) with pytest.raises(ValueError): command_tester.execute(module_name + " --config '" + invalid_config + "'")
class TestCommands(TestCase): def setUp(self): super().setUp() self.application = Application() self.application.add(InstallCommand()) cmd = self.application.find("install:inertia") # self.install_cmd = CommandTester(InstallCommand()) self.install_cmd = CommandTester(cmd) def test_install_package(self): self.install_cmd.execute()
class Orator(object): def __init__(self, app=None): self.Model = BaseModel self.cli = None self._db = None if app is not None: self.init_app(app) def init_app(self, app): if 'ORATOR_DATABASES' not in app.config: raise RuntimeError('Missing "ORATOR_DATABASES" configuration') # Register request hooks self.register_handlers(app) # Getting config databases self._config = app.config['ORATOR_DATABASES'] # Initializing database manager self._db = DatabaseManager(self._config) self.Model.set_connection_resolver(self._db) # Setting current page resolver def current_page_resolver(): return int(request.args.get('page', 1)) Paginator.current_page_resolver(current_page_resolver) # Setting commands self.init_commands() def init_commands(self): self.cli = Application(orator_application.get_name(), orator_application.get_version()) self.cli.add(InstallCommand(self)) self.cli.add(MigrateCommand(self)) self.cli.add(MigrateMakeCommand(self)) self.cli.add(RollbackCommand(self)) self.cli.add(StatusCommand(self)) self.cli.add(ResetCommand(self)) def register_handlers(self, app): teardown = app.teardown_appcontext @teardown def disconnect(_): return self._db.disconnect() def __getattr__(self, item): return getattr(self._db, item)
def test_value_error_on_invalid_config_with_decoding(): application = Application() application.add(InitCommand()) invalid_config = '{"unclosed_key: 15}' module_name = "foo" command = application.find("init") command_tester = CommandTester(command) with pytest.raises(ValueError, match=r".*{reason}.*".format(reason="invalid")): command_tester.execute(module_name + " --config '" + invalid_config + "'")
def test_value_error_on_invalid_config_with_single_quotes(): application = Application() application.add(InitCommand()) invalid_config = "{'output_size': 10}" module_name = "foo" command = application.find("init") command_tester = CommandTester(command) with pytest.raises(ValueError, match=r".*{reason}.*".format(reason="double quotes")): command_tester.execute(module_name + ' --config "' + invalid_config + '"')
def main(): application = Application(complete=False) application.add(CreateCommand()) application.add(MultiCommand()) application.add(RemoveCommand()) application.add(ValidateCommand()) application.run()
def test_success_load_custom_user_config(): application = Application() application.add(InitCommand()) custom_config = { "batch_size": 512, "device": "cuda:0", "dataset": "torch.blah", "learning_rate": 0.2, } # set up file path variables module_name = "tmp_module1_init" module_file_path = module_name + ".py" save_path = "tmp-test-save/model.py" # clean up possible existing files if os.path.exists(module_file_path): os.remove(module_file_path) if os.path.exists(save_path): shutil.rmtree(os.path.dirname(save_path)) # write model to file path from which we want to import from content = """ import torch def get_model(**args): return torch.nn.Conv2d(10, 10, 10) """ with open(module_file_path, "a") as the_file: the_file.write(content) command = application.find("init") command_tester = CommandTester(command) # Act command_tester.execute(module_name + " --config {json_config}".format( json_config=shlex.quote(json.dumps(custom_config))) + " --save=" + save_path) assert os.path.exists(save_path) # Load metadata from saved path # TODO schema validation # reader = pkmd.MetadataReader() # reader.read(os.path.join(os.path.dirname(save_path), 'config.json')) # Cleanup os.remove(module_file_path) shutil.rmtree(os.path.dirname(save_path))
def main(): application = Application() application.add(AboutCommand()) application.add(ImportTimelineCommand()) application.add(ExportTimelineCommand()) application.add(BuildCommand()) application.add(InitCommand()) application.run()
def test_that_command_works(self): application = Application() application.add(InstallCommand()) command = application.find("lang:install") tester = CommandTester(command) result = tester.execute([("command", command.get_name()), ("--mock")]) expect(result).to.be.an(int) expect(result).to.be(0) output = tester.get_display() expect(output).to.match("Mock mode activated") expect(output).to.match("Installed /resources/lang/default") expect(output).to.match("Installed /config/language.py")
def run_command(self, command, options=None): """ Run the command. :type command: cleo.commands.command.Command :type options: list or None """ if options is None: options = [] options = [("command", command.get_name())] + options application = Application() application.add(command) command_tester = CommandTester(command) command_tester.execute(options) return command_tester
def test_that_command_works(self): application = Application() application.add(NewCommand()) command = application.find("lang:new") tester = CommandTester(command) result = tester.execute([ ("command", command.get_name()), ("name", "en"), ("title", "English"), ("--mock"), ]) expect(result).to.be.an(int) expect(result).to.be(0) output = tester.get_display() expect(output).to.match("Mock mode activated") expect(output).to.match("Installed /resources/lang/en")
def test_success_init_simple_model(): # Arrange # set up application with command application = Application() application.add(InitCommand()) # set up file path variables module_name = "bar" module_file_path = module_name + ".py" save_path = "bar-config/model.py" # clean up possible existing files if os.path.exists(module_file_path): os.remove(module_file_path) if os.path.exists(save_path): shutil.rmtree(os.path.dirname(save_path)) # write model to file path from which we want to import from content = """ import torch def get_model(**args): return torch.nn.Conv2d(10, 10, 10) """ with open(module_file_path, "a") as the_file: the_file.write(content) # load command and build tester object to act on command = application.find("init") command_tester = CommandTester(command) # Act command_tester.execute(module_name + " --save=" + save_path) # Cleanup os.remove(module_file_path) shutil.rmtree(os.path.dirname(save_path))
def run_command(self, command, options=None, input_stream=None): """ Run the command. :type command: cleo.commands.command.Command :type options: list or None """ if options is None: options = [] options = [('command', command.get_name())] + options application = Application() application.add(command) if input_stream: dialog = command.get_helper('question') dialog.__class__.input_stream = input_stream command_tester = CommandTester(command) command_tester.execute(options) return command_tester
def test_debug(self): """ Runs all test cases in the test/debug directory. """ test_file_names = glob.glob(os.path.dirname(os.path.abspath(__file__)) + "/debug/*.sdoc") for test_file_name in sorted(test_file_names): with self.subTest(test_file_name=test_file_name): pre, ext = os.path.splitext(test_file_name) text_file_name = pre + '.txt' with open(text_file_name, 'r') as file: text = file.read() application = Application() application.add(SDoc1Command()) command = application.find('sdoc1') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name()), ('main.sdoc', test_file_name), ('output.sdoc2', 't.sdoc2')]) self.assertTrue(command_tester.get_display().rstrip().endswith(text.strip()))
class Orator(DatabaseManager): def __init__(self, app=None): self.Model = BaseModel self.cli = None super(Orator, self).__init__({}) if app is not None: self.init_app(app) def init_app(self, app): if 'ORATOR_DATABASES' not in app.config: raise RuntimeError('Missing "ORATOR_DATABASES" configuration') self._config = app.config['ORATOR_DATABASES'] self.Model.set_connection_resolver(self) # Setting current page resolver def current_page_resolver(): return int(request.args.get('page', 1)) Paginator.current_page_resolver(current_page_resolver) self.init_commands(app) def init_commands(self, app): self.cli = Application(orator_application.get_name(), orator_application.get_version()) self.cli.add(InstallCommand(self)) self.cli.add(MigrateCommand(self)) self.cli.add(MigrateMakeCommand(self)) self.cli.add(RollbackCommand(self)) self.cli.add(StatusCommand(self)) self.cli.add(ResetCommand(self))
def main(): copy = Copy() copy_question = CopyQuestion() copy_collection = CopyCollection() application = Application() application.add(copy) application.add(copy_question) application.add(copy_collection) application.run()
# -*- coding: utf-8 -*- import os import pytest from cleo import Application from cleo import CommandTester from .fixtures.hello_command import HelloCommand from .fixtures.command_with_colons import CommandWithColons app = Application() app.add(HelloCommand()) app.add(CommandWithColons()) def test_invalid_shell(): command = app.find("completions") tester = CommandTester(command) with pytest.raises(ValueError): tester.execute("pomodoro") def test_bash(mocker): mocker.patch( "clikit.api.args.args.Args.script_name", new_callable=mocker.PropertyMock, return_value="/path/to/my/script", ) mocker.patch(
# -*- coding: utf-8 -*- from cleo import Application from ..version import VERSION from .migrations import ( InstallCommand, MigrateCommand, MigrateMakeCommand, RollbackCommand, StatusCommand, ResetCommand ) application = Application('Orator', VERSION) application.add(InstallCommand()) application.add(MigrateCommand()) application.add(MigrateMakeCommand()) application.add(RollbackCommand()) application.add(StatusCommand()) application.add(ResetCommand())
class Orator(object): def __init__(self, app=None, manager_class=DatabaseManager): self.Model = BaseModel self.cli = None self._db = None self._manager_class = manager_class if app is not None: self.init_app(app) def init_app(self, app): if 'ORATOR_DATABASES' not in app.config: raise RuntimeError('Missing "ORATOR_DATABASES" configuration') # Register request hooks self.register_handlers(app) # Getting config databases self._config = app.config['ORATOR_DATABASES'] # Initializing database manager self._db = self._manager_class(self._config) self.Model.set_connection_resolver(self._db) # Setting current page resolver Paginator.current_page_resolver(self._current_page_resolver) # Setting commands self.init_commands() def _current_page_resolver(self): return int(request.args.get('page', 1)) def init_commands(self): self.cli = Application( orator_application.get_name(), orator_application.get_version(), complete=True ) for command in orator_application.all().values(): if isinstance(command, Command): self.cli.add(command.__class__(self._db)) else: self.cli.add(command) def register_handlers(self, app): self._register_error_handlers(app) teardown = app.teardown_appcontext @teardown def disconnect(_): return self._db.disconnect() def _register_error_handlers(self, app): @app.errorhandler(ModelNotFound) def model_not_found(error): response = make_response(error.message, 404) return response def __getattr__(self, item): return getattr(self._db, item)
try: prod = Producer( payload, qtd=int(self.option("events")), exchange_name=os.getenv("PUBLISH_EXCHANGE_NAME", self.option("exchange")), routing_key=os.getenv("PUBLISH_ROUTING_KEY", self.option("key")), host=self.option("host"), port=self.option("port"), login=self.option("login"), password=self.option("pass"), ssl=self.option("ssl"), verify_ssl=self.option("verify"), channel_max=int(self.option("channels")), ) prod.send_event() self.line( "<info>!></info> <options=bold>event successfully submitted!</>" ) except OSError: self.line("<error>Failure to connect to RabbitMQ.</error>") application = Application("rabbit-client", f"{__version__}") application.add(ConsumerCommand()) application.add(EventCommand()) if __name__ == "__main__": application.run()
# -*- coding: utf-8 -*- from cleo import Application from ..version import VERSION application = Application('Orator', VERSION, complete=True) # Migrations from .migrations import ( InstallCommand, MigrateCommand, MigrateMakeCommand, RollbackCommand, StatusCommand, ResetCommand, RefreshCommand ) application.add(InstallCommand()) application.add(MigrateCommand()) application.add(MigrateMakeCommand()) application.add(RollbackCommand()) application.add(StatusCommand()) application.add(ResetCommand()) application.add(RefreshCommand()) # Seeds from .seeds import SeedersMakeCommand, SeedCommand application.add(SeedersMakeCommand()) application.add(SeedCommand()) # Models from .models import ModelMakeCommand
# -*- coding: utf-8 -*- import os import pytest from cleo import Application, CommandTester from cleo.exceptions.input import InvalidArgument from .fixtures.hello_command import HelloCommand from .fixtures.command_with_colons import CommandWithColons app = Application() app.add(HelloCommand()) app.add(CommandWithColons()) def test_invalid_shell(): command = app.find('completions') tester = CommandTester(command) with pytest.raises(InvalidArgument): tester.execute([('shell', 'pomodoro')]) def test_bash(mocker): mocker.patch( 'cleo.commands.completions_command.CompletionsCommand._get_script_full_name', return_value='/path/to/my/script') mocker.patch( 'cleo.commands.completions_command.CompletionsCommand._generate_function_name', return_value='_my_function')
#1/usr/bin/env/python # -*- coding: utf-8 -*- from app.command.fakeItCommand import FakeIt from cleo import Application application = Application() application.add(FakeIt()) if __name__ == '__main__': application.run()