def test_simple_testcase_fails_when_accessing_base_url(self): runner = Runner(mock.MagicMock()) runner.context = Context(runner) SimpleTestRunner().patch_context(runner.context) SimpleTestRunner().setup_testclass(runner.context) with pytest.raises(AssertionError): assert runner.context.base_url == 'should raise an exception!'
def run_tests(room, vendor, tags, override): def on_snapshot(snapshot, plan): event = { 'snapshot': snapshot, 'plan': plan, } socketio.emit('snapshot', event, room=room) try: output = io.StringIO() output_stream = StreamOpener(stream=output) config = Configuration( outputs=[output_stream], format=['json.chunked'], on_snapshot=on_snapshot, vendor=vendor, override=override, command_args=[], tags=[','.join(tags)], ) runner = Runner(config) runner.run() except Exception as err: # pylint: disable=broad-except socketio.emit('global_error', str(err)) finally: socketio.emit('tests_complete', room=room)
def test_simple_testcase_fails_when_calling_get_url(self): runner = Runner(mock.MagicMock()) runner.context = Context(runner) SimpleTestRunner().patch_context(runner.context) SimpleTestRunner().setup_testclass(runner.context) with pytest.raises(AssertionError): runner.context.get_url()
def runTest(self, result=None): print "run: features_dir=%s" % (self.features_dir) stream = self.behave_config.output runner = Runner(self.behave_config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def runTest(self, result=None): """Run behave on a single directory.""" # from behave/__main__.py runner = Runner(self.behave_config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def handle(path): file_conf = ConfigObj(os.path.join(path, 'features', 'config.ini')) behave_options = file_conf['behave']['options'] conf = Configuration(behave_options) conf.paths = [os.path.join(path, 'features')] runner = Runner(conf) runner.run()
def main(): config = Configuration() if config.version: print "behave " + __version__ sys.exit(0) if config.tags_help: print TAG_HELP sys.exit(0) if config.lang_list: iso_codes = languages.keys() iso_codes.sort() print "Languages available:" for iso_code in iso_codes: native = languages[iso_code]['native'][0] name = languages[iso_code]['name'][0] print u'%s: %s / %s' % (iso_code, native, name) sys.exit(0) if config.lang_help: if config.lang_help not in languages: sys.exit('%s is not a recognised language: try --lang-list' % config.lang_help) trans = languages[config.lang_help] print u"Translations for %s / %s" % (trans['name'][0], trans['native'][0]) for kw in trans: if kw in 'name native'.split(): continue print u'%16s: %s' % (kw.title().replace('_', ' '), u', '.join(w for w in trans[kw] if w != '*')) sys.exit(0) if not config.format: format0 = config.defaults["format0"] config.format = [ format0 ] elif 'help' in config.format: print "Available formatters:" formatters.list_formatters(sys.stdout) sys.exit(0) # -- SANITY: Use at most one formatter, more cause various problems. # PROBLEM DESCRIPTION: # 1. APPEND MODE: configfile.format + --format # 2. Daisy chaining of formatter does not work # => behave.formatter.formatters.get_formatter() # => Stream methods, stream.write(), stream.flush are missing # in Formatter interface if DISABLE_MULTI_FORMATTERS: config.format = config.format[-1:] runner = Runner(config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def main(): # pylint: disable=R0912,R0915 # R0912 Too many branches (17/12) # R0915 Too many statements (57/50) config = Configuration() if config.version: print "behave " + __version__ sys.exit(0) if config.tags_help: print TAG_HELP sys.exit(0) if config.lang_list: iso_codes = languages.keys() iso_codes.sort() print "Languages available:" for iso_code in iso_codes: native = languages[iso_code]["native"][0] name = languages[iso_code]["name"][0] print u"%s: %s / %s" % (iso_code, native, name) sys.exit(0) if config.lang_help: if config.lang_help not in languages: sys.exit("%s is not a recognised language: try --lang-list" % config.lang_help) trans = languages[config.lang_help] print u"Translations for %s / %s" % (trans["name"][0], trans["native"][0]) for kw in trans: if kw in "name native".split(): continue print u"%16s: %s" % (kw.title().replace("_", " "), u", ".join(w for w in trans[kw] if w != "*")) sys.exit(0) if not config.format: format0 = config.defaults["format0"] config.format = [format0] elif "help" in config.format: print "Available formatters:" formatters.list_formatters(sys.stdout) sys.exit(0) # -- SANITY: Use at most one formatter, more cause various problems. # PROBLEM DESCRIPTION: # 1. APPEND MODE: configfile.format + --format # 2. Daisy chaining of formatters does not work # => behave.formatter.formatters.get_formatter() # => Stream methods, stream.write(), stream.flush are missing # in Formatter interface config.format = config.format[-1:] stream = config.output runner = Runner(config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def main(): config = Configuration() if config.version: print "behave " + __version__ sys.exit(0) if config.tags_help: print TAG_HELP sys.exit(0) if config.lang_list: iso_codes = languages.keys() iso_codes.sort() print "Languages available:" for iso_code in iso_codes: native = languages[iso_code]["native"][0] name = languages[iso_code]["name"][0] print u"%s: %s / %s" % (iso_code, native, name) sys.exit(0) if config.lang_help: if config.lang_help not in languages: sys.exit("%s is not a recognised language: try --lang-list" % config.lang_help) trans = languages[config.lang_help] print u"Translations for %s / %s" % (trans["name"][0], trans["native"][0]) for kw in trans: if kw in "name native".split(): continue print u"%16s: %s" % (kw.title().replace("_", " "), u", ".join(w for w in trans[kw] if w != "*")) sys.exit(0) if not config.format: default_format = config.defaults["default_format"] config.format = [default_format] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. default_format = config.defaults["default_format"] config.format.append(default_format) if "help" in config.format: print "Available formatters:" formatters.list_formatters(sys.stdout) sys.exit(0) if len(config.outputs) > len(config.format): print "CONFIG-ERROR: More outfiles (%d) than formatters (%d)." % (len(config.outputs), len(config.format)) sys.exit(1) runner = Runner(config) try: failed = runner.run() except ParserError, e: sys.exit("ParseError: %s" % e)
def runTest(self, result=None): # run behave on a single directory # from behave/__main__.py #stream = self.behave_config.output runner = BehaveRunner(self.behave_config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def runTest(self, result=None): # run behave on a single directory print "run: features_dir=%s" % (self.features_dir) # from behave/__main__.py runner = Runner(self.behave_config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def runTest(self, result=None): DjangoTestCaseAccessor.test_case = self # run behave on a single directory print "Run test in transaction for feature_paths=%s" % self.feature_paths # from behave/__main__.py runner = Runner(self.behave_config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def handle(path, args=None): file_conf = ConfigObj(os.path.join(path, "features", "config.ini")) try: behave_options = file_conf["behave"]["options"] except KeyError: raise ValueError("Behave config not found." " Are you running with the right path?") if args: behave_options += " " + " ".join(args) conf = Configuration(behave_options) conf.paths = [os.path.join(path, "features")] runner = Runner(conf) runner.run()
def handle(path, args=None): file_conf = ConfigObj(os.path.join(path, 'features', 'config.ini')) try: behave_options = file_conf['behave']['options'] except KeyError: raise ValueError("Behave config not found." " Are you running with the right path?") if args: behave_options += ' ' + ' '.join(args) conf = Configuration(behave_options) conf.paths = [os.path.join(path, 'features')] runner = Runner(conf) return runner.run()
def run_model_with_cmdline(model, cmdline): reset_model(model.features) command_args = cmdline config = Configuration(command_args, load_config=False, default_format="null", stdout_capture=True, stderr_capture=True, log_capture=False, junit=True) model_runner = ModelRunner(config, model.features) runner = Runner(model_runner) runner.setup_paths() return runner.run()
def main(): config = Configuration() if config.version: print "behave " + __version__ sys.exit(0) if config.tags_help: print TAG_HELP sys.exit(0) if config.lang_list: iso_codes = languages.keys() iso_codes.sort() print "Languages available:" for iso_code in iso_codes: native = languages[iso_code]['native'][0] name = languages[iso_code]['name'][0] print u'%s: %s / %s' % (iso_code, native, name) sys.exit(0) if config.lang_help: if config.lang_help not in languages: sys.exit('%s is not a recognised language: try --lang-list' % config.lang_help) trans = languages[config.lang_help] print u"Translations for %s / %s" % (trans['name'][0], trans['native'][0]) for kw in trans: if kw in 'name native'.split(): continue print u'%16s: %s' % (kw.title().replace('_', ' '), u', '.join(w for w in trans[kw] if w != '*')) sys.exit(0) if not config.format: config.format = ['pretty'] elif 'help' in config.format: print "Available formatters:" formatters.list_formatters(sys.stdout) sys.exit(0) stream = config.output runner = Runner(config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def feature_new(request): print(request.POST) form = json.loads(request.body.decode('utf-8')) feature = Feature(description=form['description'], finality=form['finality'], who=form['who'], purpose=form['purpose'], project_id=form['project']) feature.save() scenario = Scenario(given=form['given'], when=form['when'], then=form['then'], title=form['title'], feature=feature) scenario.save() gen_feature_file(feature.id) conf = Configuration('media/features/{}.feature'.format(feature.id)) conf.format = [ conf.default_format ] runner = Runner(conf) runner.run() filename = make_test_funcs(runner.undefined_steps, feature.id) add_to_repo(filename, feature.description) return HttpResponse()
def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) if request.method != 'POST': form = FeatureForm() return render(request, 'app/index.html', context_instance=RequestContext( request, { 'title': 'Home Page', 'year': datetime.now().year, 'form': form, })) else: form = FeatureForm(request.POST) if form.is_valid(): feature = Feature(description=form.cleaned_data['description'], finality=form.cleaned_data['finality'], who=form.cleaned_data['who'], purpose=form.cleaned_data['purpose']) feature.save() scenario = Scenario(given=form.cleaned_data['given'], when=form.cleaned_data['when'], then=form.cleaned_data['then'], title=form.cleaned_data['title'], feature=feature) scenario.save() gen_feature_file(feature.id) conf = Configuration( os.path.join(settings.PROJECT_ROOT, 'media', 'features', '{}.feature'.format(feature.id))) conf.format = [conf.default_format] runner = Runner(conf) runner.run() filename = make_test_funcs(runner.undefined_steps, feature.id) add_to_repo(filename, feature.description) return render(request, 'app/index.html', context_instance=RequestContext( request, { 'title': 'Home Page', 'year': datetime.now().year, 'form': form, }))
def get_rules_from(features_list): """Execute gherkins and return rules.""" base_context = {'final_rules': []} runner = Runner(Configuration()) with empty_argv(): for data in features_list: with local_context(base_context, runner) as context: parse_feature(data.strip(), None, None).run(runner) yield from context.final_rules
def runTest(self, result=None): # run behave on a single directory # from behave/__main__.py #stream = self.behave_config.output runner = BehaveRunner(self.behave_config) try: failed = runner.run() except ParserError as e: sys.exit(str(e)) except ConfigError as e: sys.exit(str(e)) try: undefined_steps = runner.undefined_steps except AttributeError: undefined_steps = runner.undefined if self.behave_config.show_snippets and undefined_steps: msg = u"\nYou can implement step definitions for undefined steps with " msg += u"these snippets:\n\n" printed = set() if sys.version_info[0] == 3: string_prefix = "('" else: string_prefix = u"(u'" for step in set(undefined_steps): if step in printed: continue printed.add(step) msg += u"@" + step.step_type + string_prefix + step.name + u"')\n" msg += u"def impl(context):\n" msg += u" assert False\n\n" sys.stderr.write(escapes['undefined'] + msg + escapes['reset']) sys.stderr.flush() if failed: sys.exit(1)
def runTest(self, result=None): # run behave on a single directory # from behave/__main__.py # stream = self.behave_config.output runner = BehaveRunner(self.behave_config) try: failed = runner.run() except ParserError as e: sys.exit(str(e)) except ConfigError as e: sys.exit(str(e)) try: undefined_steps = runner.undefined_steps except AttributeError: undefined_steps = runner.undefined if self.behave_config.show_snippets and undefined_steps: msg = u"\nYou can implement step definitions for undefined steps with " msg += u"these snippets:\n\n" printed = set() if sys.version_info[0] == 3: string_prefix = "('" else: string_prefix = u"(u'" for step in set(undefined_steps): if step in printed: continue printed.add(step) msg += u"@" + step.step_type + string_prefix + step.name + u"')\n" msg += u"def impl(context):\n" msg += u" assert False\n\n" sys.stderr.write(escapes["undefined"] + msg + escapes["reset"]) sys.stderr.flush() if failed: sys.exit(1)
def launch_test(self, path, batch_id): c = Configuration("") if not c.format: c.format = [c.default_format] c.paths = [path] c.userdata['lang_code'] = self.lang_code c.userdata['target_id'] = self.target_id c.userdata['base_url'] = self.target_id.target_id.url c.userdata['batch_id'] = batch_id.id c.userdata['scenario_id'] = self.scenario_id.id c.userdata['scenario_line_id'] = self.scenario_line_id.id c.userdata['empty_batch'] = self.empty_batch c.userdata['browser_vm_url'] = self.env[ 'ir.config_parameter'].get_param('test_builder.vm_url') self.config = c r = Runner(c) r.run() if self.scenario_line_id: return r.feature.status else: return c.userdata.get('run_id', None)
def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) if request.method != 'POST': form = FeatureForm() return render( request, 'app/index.html', context_instance = RequestContext(request, { 'title':'Home Page', 'year':datetime.now().year, 'form': form, }) ) else: form = FeatureForm(request.POST) if form.is_valid(): feature = Feature(description=form.cleaned_data['description'], finality=form.cleaned_data['finality'], who=form.cleaned_data['who'], purpose=form.cleaned_data['purpose']) feature.save() scenario = Scenario(given=form.cleaned_data['given'], when=form.cleaned_data['when'], then=form.cleaned_data['then'], title=form.cleaned_data['title'], feature=feature) scenario.save() gen_feature_file(feature.id) conf = Configuration(os.path.join(settings.PROJECT_ROOT, 'media', 'features', '{}.feature'.format(feature.id))) conf.format = [ conf.default_format ] runner = Runner(conf) runner.run() filename = make_test_funcs(runner.undefined_steps, feature.id) add_to_repo(filename, feature.description) return render( request, 'app/index.html', context_instance = RequestContext(request, { 'title':'Home Page', 'year':datetime.now().year, 'form': form, }) )
def runTest(self, result=None): # run behave on a single directory # from behave/__main__.py #stream = self.behave_config.output runner = BehaveRunner(self.behave_config) runner.test_case = self failed = runner.run() try: undefined_steps = runner.undefined_steps except AttributeError: undefined_steps = runner.undefined if self.behave_config.show_snippets and undefined_steps: msg = u"\nYou can implement step definitions for undefined steps with " msg += u"these snippets:\n\n" printed = set() if sys.version_info[0] == 3: string_prefix = "('" else: string_prefix = u"(u'" for step in set(undefined_steps): if step in printed: continue printed.add(step) msg += u"@" + step.step_type + string_prefix + step.name + u"')\n" msg += u"def impl(context):\n" msg += u" assert False\n\n" sys.stderr.write(escapes['undefined'] + msg + escapes['reset']) sys.stderr.flush() if failed: raise AssertionError('There were behave failures, see output above')
def run_tests(room, vendor, tags, override): app = create_app() with app.app_context(): test_run = TestRun(vendor, tags) db.session.add(test_run) db.session.commit() def on_snapshot(snapshot, plan): test_run.save_snapshot(snapshot, plan) socketio.emit('snapshot', test_run.event, room=room) db.session.commit() def on_payload(payload): socketio.emit('payload', payload, room=room) try: output = io.StringIO() output_stream = StreamOpener(stream=output) config = Configuration( outputs=[output_stream], format=['json.chunked'], on_snapshot=on_snapshot, on_payload=on_payload, vendor=vendor, override=override, command_args=[], tags=[','.join(tags)], ) runner = Runner(config) runner.run() except Exception as err: # pylint: disable=broad-except import traceback traceback.print_exc() socketio.emit('global_error', str(err), room=room) finally: socketio.emit('tests_complete', room=room)
def feature_new(request): print(request.POST) form = json.loads(request.body.decode('utf-8')) feature = Feature(description=form['description'], finality=form['finality'], who=form['who'], purpose=form['purpose'], project_id=form['project']) feature.save() scenario = Scenario(given=form['given'], when=form['when'], then=form['then'], title=form['title'], feature=feature) scenario.save() gen_feature_file(feature.id) conf = Configuration('media/features/{}.feature'.format(feature.id)) conf.format = [conf.default_format] runner = Runner(conf) runner.run() filename = make_test_funcs(runner.undefined_steps, feature.id) add_to_repo(filename, feature.description) return HttpResponse()
def run_tests(room, vendor): def on_snapshot(snapshot, plan): event = { 'snapshot': snapshot, 'plan': plan, } socketio.emit('snapshot', event, room=room) try: output = io.StringIO() output_stream = StreamOpener(stream=output) config = Configuration( outputs=[output_stream], format=['json.chunked'], on_snapshot=on_snapshot, vendor=vendor, command_args=[] ) runner = Runner(config) runner.run() finally: socketio.emit('tests_complete', room=room)
def load(path): """ Load the given path that contains the features and steps. :param path: Path where the feature and steps files can be found. :type path: :class:`str` :returns: A behave runner. :rtype: :class:`behave.runner.Runner` """ try: config = Configuration(path) runner = Runner(config) features = parse_features( [f.filename for f in runner.feature_locations()] ) scrape_features(features) return runner except Exception as error: # pylint: disable=broad-except logging.exception( "Unexpected error creating configuration %r: %r", path, error ) raise argparse.ArgumentTypeError(error)
def main(): """Entry point.""" args = parser.parse_args() config = Configuration(args.command_args) runner = Runner(config) with runner.path_manager: runner.setup_paths() runner.load_step_definitions() # This populates the step_registry. exit_code = run(steps=step_registry.registry.steps, output_to=args.path) return sys.exit(exit_code)
def test_async_step_raises_exception(self): """ENSURE: Failures in async-steps are detected correctly.""" step_container = SimpleStepContainer() with use_step_import_modules(step_container): # -- STEP-DEFINITIONS EXAMPLE (as MODULE SNIPPET): # VARIANT 1: Use async def step_impl() from behave import when from behave.api.async_step import async_run_until_complete @when('an async-step raises exception') @async_run_until_complete async def when_async_step_raises_exception(context): 1 / 0 # XFAIL-HERE: Raises ZeroDivisionError # -- RUN ASYNC-STEP: Verify that raised exception is detected. context = Context(runner=Runner(config={})) with pytest.raises(ZeroDivisionError): when_async_step_raises_exception(context)
def test_async_step_fails(self): """ENSURE: Failures in async-steps are detected correctly.""" step_container = SimpleStepContainer() with use_step_import_modules(step_container): # -- STEP-DEFINITIONS EXAMPLE (as MODULE SNIPPET): # VARIANT 1: Use async def step_impl() from behave import when from behave.api.async_step import async_run_until_complete @when('an async-step fails') @async_run_until_complete async def when_async_step_fails(context): assert False, "XFAIL in async-step" # -- RUN ASYNC-STEP: Verify that AssertionError is detected. context = Context(runner=Runner(config={})) with pytest.raises(AssertionError): when_async_step_fails(context)
def test_step_decorator_async_run_until_complete1(self): step_container = SimpleStepContainer() with use_step_import_modules(step_container): # -- STEP-DEFINITIONS EXAMPLE (as MODULE SNIPPET): # VARIANT 1: Use async def step_impl() from behave import step from behave.api.async_step import async_run_until_complete import asyncio @step('an async coroutine step waits "{duration:f}" seconds') @async_run_until_complete async def step_async_step_waits_seconds(context, duration): await asyncio.sleep(duration) # -- USES: async def step_impl(...) as async-step (coroutine) AsyncStepTheory.validate(step_async_step_waits_seconds) # -- RUN ASYNC-STEP: Verify that it is behaving correctly. # ENSURE: Execution of async-step matches expected duration. context = Context(runner=Runner(config={})) with StopWatch() as stop_watch: step_async_step_waits_seconds(context, 0.2) assert abs(stop_watch.duration - 0.2) <= 0.05
def test_simple_testcase_fails_when_calling_get_url(self): runner = Runner(mock.MagicMock()) runner.context = Context(runner) SimpleTestRunner().before_scenario(runner.context) with pytest.raises(AssertionError): runner.context.get_url()
if __name__ == "__main__": from behave.formatter import _registry from behave.configuration import Configuration from behave.runner import Runner from teamcity.jb_behave_formatter import TeamcityFormatter _registry.register_as("TeamcityFormatter", TeamcityFormatter) configuration = Configuration() configuration.format = ["TeamcityFormatter"] configuration.stdout_capture = False configuration.stderr_capture = False Runner(configuration).run()
def main(): config = Configuration() if config.version: print("behave " + __version__) sys.exit(0) if config.tags_help: print(TAG_HELP) sys.exit(0) if config.lang_list: iso_codes = list(languages.keys()) iso_codes.sort() print("Languages available:") for iso_code in iso_codes: native = languages[iso_code]['native'][0] name = languages[iso_code]['name'][0] print('%s: %s / %s' % (iso_code, native, name)) sys.exit(0) if config.lang_help: if config.lang_help not in languages: sys.exit('%s is not a recognised language: try --lang-list' % config.lang_help) trans = languages[config.lang_help] print("Translations for %s / %s" % (trans['name'][0], trans['native'][0])) for kw in trans: if kw in 'name native'.split(): continue print('%16s: %s' % (kw.title().replace('_', ' '), ', '.join(w for w in trans[kw] if w != '*'))) sys.exit(0) if not config.format: default_format = config.defaults["default_format"] config.format = [ default_format ] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. default_format = config.defaults["default_format"] config.format.append(default_format) if 'help' in config.format: print("Available formatters:") formatters.list_formatters(sys.stdout) sys.exit(0) if len(config.outputs) > len(config.format): print('CONFIG-ERROR: More outfiles (%d) than formatters (%d).' % \ (len(config.outputs), len(config.format))) sys.exit(1) runner = Runner(config) try: failed = runner.run() except ParserError as e: sys.exit("ParseError: %s" % e) except ConfigError as e: sys.exit("ConfigError: %s" % e) except FileNotFoundError as e: sys.exit("FileNotFoundError: %s" % e) except InvalidFileLocationError as e: sys.exit("InvalidFileLocationError: %s" % e) except InvalidFilenameError as e: sys.exit("InvalidFilenameError: %s" % e) if config.show_snippets and runner.undefined: msg = "\nYou can implement step definitions for undefined steps with " msg += "these snippets:\n\n" printed = set() for step in runner.undefined: if step in printed: continue printed.add(step) msg += make_undefined_step_snippet(step) # -- OOPS: Unclear if stream supports ANSI coloring. sys.stderr.write(escapes['undefined'] + msg + escapes['reset']) sys.stderr.flush() if failed: sys.exit(1) # -- OTHERWISE: Successful run. sys.exit(0)
def make_context(): return Context(runner=Runner(config={}))
def start(): u''' Точка входа в приложение, которая активируется при запуске его из командной строки. ''' setup_logging() config = {} try: arg_delim_index = sys.argv.index('--') behave_args = sys.argv[arg_delim_index+1:] sys.argv = sys.argv[:arg_delim_index] except ValueError: behave_args = [] opt_parser = OptionParser() opt_parser.add_option('', '--var-file', dest='var_file', help='Load template variables from .py file.', metavar='<FILE>') opt_parser.add_option('', '--cfg-file', dest='cfg_file', help='Load configuration from YAML file.', metavar='<FILE>') (options, _) = opt_parser.parse_args() if options.cfg_file: cfg_fn = options.cfg_file try: with open(cfg_fn, 'r') as fp: config = yaml.load(fp.read()) or {} except Exception as ex: logger.error('Can\'t load {0}: {1}'.format(cfg_fn, unicode(ex))) else: logger.info('Loaded configuration from {0}.'.format(cfg_fn)) if options.var_file: template_vars = load_vars_from_pyfile(options.var_file) # Есть смысл включать режим шаблонизации только при наличии переменных, # ради которых все и затевалось if template_vars: template_vars.pop('__builtins__', {}) sys.meta_path = [TemplateImportHooker(template_vars)] # Изменяем sys.argv для обхода поведения behave<=1.2.3, который # всегда пытается получить опции из командной строки. # TODO: с выходом стабильной 1.2.4 поменять на передачу command_args sys.argv = [sys.argv[0], ] + behave_args behave_cfg = Configuration() if not behave_cfg.format: behave_cfg.format = ['pretty', ] from behave.runner import Runner runner = Runner(behave_cfg) if 'enabled_plugins' in config: runner.hooks = StackedHookDictWrapper() # Ищем все доступные плагины... plugins = find_plugins() plugin_configs = config.get('plugins', {}) for p_id in config['enabled_plugins']: # TODO: убрать, если будет возможность подключать свои плагины assert p_id in plugins, 'Unknown plugin: {}!'.format(p_id) plugin = plugins[p_id] # Подключаем ещё один набор функций окружения. С точки зрения # behave'а, это будет одна функция, которая в свою очередь # по порядку будет вызывать обработчики _каждого_ плагина. logger.info('Loading plugin "{}"...'.format(p_id)) custom_hooks = plugin.prepare_environment(plugin_configs.get(p_id, {})) logger.debug('Plugin "{}" sets hooks: {}'.format(p_id, ', '.join(custom_hooks.keys()))) for hook, handler in custom_hooks.items(): runner.hooks[hook] = handler runner.run()
def main(args=None): config = Configuration(args) if config.version: print "behave " + __version__ return 0 if config.tags_help: print TAG_HELP return 0 if config.lang_list: from behave.i18n import languages iso_codes = languages.keys() iso_codes.sort() print "Languages available:" for iso_code in iso_codes: native = languages[iso_code]['native'][0] name = languages[iso_code]['name'][0] print u'%s: %s / %s' % (iso_code, native, name) return 0 if config.lang_help: from behave.i18n import languages if config.lang_help not in languages: print '%s is not a recognised language: try --lang-list' % \ config.lang_help return 1 trans = languages[config.lang_help] print u"Translations for %s / %s" % (trans['name'][0], trans['native'][0]) for kw in trans: if kw in 'name native'.split(): continue print u'%16s: %s' % (kw.title().replace('_', ' '), u', '.join( w for w in trans[kw] if w != '*')) return 0 if not config.format: default_format = config.defaults["default_format"] config.format = [default_format] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. default_format = config.defaults["default_format"] config.format.append(default_format) if 'help' in config.format: from behave.formatter import formatters print "Available formatters:" formatters.list_formatters(sys.stdout) return 0 if len(config.outputs) > len(config.format): print 'CONFIG-ERROR: More outfiles (%d) than formatters (%d).' % \ (len(config.outputs), len(config.format)) return 1 failed = True runner = Runner(config) try: failed = runner.run() except ParserError, e: print "ParseError: %s" % e
def main(): # pylint: disable=R0912,R0915 # R0912 Too many branches (17/12) # R0915 Too many statements (57/50) config = Configuration() if config.version: print "behave " + __version__ sys.exit(0) if config.tags_help: print TAG_HELP sys.exit(0) if config.lang_list: iso_codes = languages.keys() iso_codes.sort() print "Languages available:" for iso_code in iso_codes: native = languages[iso_code]['native'][0] name = languages[iso_code]['name'][0] print u'%s: %s / %s' % (iso_code, native, name) sys.exit(0) if config.lang_help: if config.lang_help not in languages: sys.exit('%s is not a recognised language: try --lang-list' % config.lang_help) trans = languages[config.lang_help] print u"Translations for %s / %s" % (trans['name'][0], trans['native'][0]) for kw in trans: if kw in 'name native'.split(): continue print u'%16s: %s' % (kw.title().replace('_', ' '), u', '.join(w for w in trans[kw] if w != '*')) sys.exit(0) if not config.format: default_format = config.defaults["default_format"] config.format = [ default_format ] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. default_format = config.defaults["default_format"] config.format.append(default_format) elif 'help' in config.format: print "Available formatters:" formatters.list_formatters(sys.stdout) sys.exit(0) if len(config.outputs) > len(config.format): print 'CONFIG-ERROR: More outfiles (%d) than formatters (%d).' % \ (len(config.outputs), len(config.format)) sys.exit(1) runner = Runner(config) try: failed = runner.run() except ParserError, e: sys.exit(str(e))
def main(args=None): config = Configuration(args) if config.version: print "behave " + __version__ return 0 if config.tags_help: print TAG_HELP return 0 if config.lang_list: from behave.i18n import languages iso_codes = languages.keys() iso_codes.sort() print "Languages available:" for iso_code in iso_codes: native = languages[iso_code]['native'][0] name = languages[iso_code]['name'][0] print u'%s: %s / %s' % (iso_code, native, name) return 0 if config.lang_help: from behave.i18n import languages if config.lang_help not in languages: print '%s is not a recognised language: try --lang-list' % \ config.lang_help return 1 trans = languages[config.lang_help] print u"Translations for %s / %s" % (trans['name'][0], trans['native'][0]) for kw in trans: if kw in 'name native'.split(): continue print u'%16s: %s' % (kw.title().replace('_', ' '), u', '.join(w for w in trans[kw] if w != '*')) return 0 if not config.format: default_format = config.defaults["default_format"] config.format = [ default_format ] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. default_format = config.defaults["default_format"] config.format.append(default_format) if 'help' in config.format: from behave.formatter import formatters print "Available formatters:" formatters.list_formatters(sys.stdout) return 0 if len(config.outputs) > len(config.format): print 'CONFIG-ERROR: More outfiles (%d) than formatters (%d).' % \ (len(config.outputs), len(config.format)) return 1 failed = True runner = Runner(config) try: failed = runner.run() except ParserError, e: print "ParseError: %s" % e
def test_simple_testcase_fails_when_accessing_base_url(self): runner = Runner(mock.MagicMock()) runner.context = Context(runner) SimpleTestRunner().before_scenario(runner.context) with pytest.raises(AssertionError): assert runner.context.base_url == 'should raise an exception!'
def main(args=None): config = Configuration(args) if config.version: print("behave " + __version__) return 0 if config.tags_help: print(TAG_HELP) return 0 if config.lang_list: from behave.i18n import languages stdout = sys.stdout if six.PY2: # -- PYTHON2: Overcome implicit encode problems (encoding=ASCII). stdout = codecs.getwriter("UTF-8")(sys.stdout) iso_codes = languages.keys() print("Languages available:") for iso_code in sorted(iso_codes): native = languages[iso_code]["native"][0] name = languages[iso_code]["name"][0] print(u"%s: %s / %s" % (iso_code, native, name), file=stdout) return 0 if config.lang_help: from behave.i18n import languages if config.lang_help not in languages: print("%s is not a recognised language: try --lang-list" % config.lang_help) return 1 trans = languages[config.lang_help] print(u"Translations for %s / %s" % (trans["name"][0], trans["native"][0])) for kw in trans: if kw in "name native".split(): continue print(u"%16s: %s" % (kw.title().replace("_", " "), u", ".join(w for w in trans[kw] if w != "*"))) return 0 if not config.format: config.format = [config.default_format] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. config.format.append(config.default_format) if "help" in config.format: print_formatters("Available formatters:") return 0 if len(config.outputs) > len(config.format): print("CONFIG-ERROR: More outfiles (%d) than formatters (%d)." % (len(config.outputs), len(config.format))) return 1 failed = True runner = Runner(config) try: failed = runner.run() except ParserError as e: print(u"ParseError: %s" % e) except ConfigError as e: print(u"ConfigError: %s" % e) except FileNotFoundError as e: print(u"FileNotFoundError: %s" % e) except InvalidFileLocationError as e: print(u"InvalidFileLocationError: %s" % e) except InvalidFilenameError as e: print(u"InvalidFilenameError: %s" % e) except Exception as e: # -- DIAGNOSTICS: text = _text(e) print(u"Exception %s: %s" % (e.__class__.__name__, text)) raise if config.show_snippets and runner.undefined_steps: print_undefined_step_snippets(runner.undefined_steps, colored=config.color) return_code = 0 if failed: return_code = 1 return return_code
def main(args=None): # pylint: disable=too-many-branches, too-many-statements, too-many-return-statements config = Configuration(args) if config.version: print("behave " + __version__) return 0 if config.tags_help: print(TAG_HELP) return 0 if config.lang_list: from behave.i18n import languages stdout = sys.stdout if six.PY2: # -- PYTHON2: Overcome implicit encode problems (encoding=ASCII). stdout = codecs.getwriter("UTF-8")(sys.stdout) iso_codes = languages.keys() print("Languages available:") for iso_code in sorted(iso_codes): native = languages[iso_code]["native"][0] name = languages[iso_code]["name"][0] print(u"%s: %s / %s" % (iso_code, native, name), file=stdout) return 0 if config.lang_help: from behave.i18n import languages if config.lang_help not in languages: print("%s is not a recognised language: try --lang-list" % \ config.lang_help) return 1 trans = languages[config.lang_help] print(u"Translations for %s / %s" % (trans["name"][0], trans["native"][0])) for kw in trans: if kw in "name native".split(): continue print(u"%16s: %s" % (kw.title().replace("_", " "), u", ".join( w for w in trans[kw] if w != "*"))) return 0 if not config.format: config.format = [config.default_format] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. config.format.append(config.default_format) if "help" in config.format: print_formatters("Available formatters:") return 0 if len(config.outputs) > len(config.format): print("CONFIG-ERROR: More outfiles (%d) than formatters (%d)." % \ (len(config.outputs), len(config.format))) return 1 failed = True runner = Runner(config) try: failed = runner.run() except ParserError as e: print(u"ParserError: %s" % e) except ConfigError as e: print(u"ConfigError: %s" % e) except FileNotFoundError as e: print(u"FileNotFoundError: %s" % e) except InvalidFileLocationError as e: print(u"InvalidFileLocationError: %s" % e) except InvalidFilenameError as e: print(u"InvalidFilenameError: %s" % e) except Exception as e: # -- DIAGNOSTICS: text = _text(e) print(u"Exception %s: %s" % (e.__class__.__name__, text)) raise if config.show_snippets and runner.undefined_steps: print_undefined_step_snippets(runner.undefined_steps, colored=config.color) return_code = 0 if failed: return_code = 1 return return_code
def run(self): first_runner = Runner(self.config) first_runner.run()
def main(args=None): config = Configuration(args) if config.version: print("behave " + __version__) return 0 if config.tags_help: print(TAG_HELP) return 0 if config.lang_list: from behave.i18n import languages iso_codes = languages.keys() iso_codes.sort() print("Languages available:") for iso_code in iso_codes: native = languages[iso_code]['native'][0] name = languages[iso_code]['name'][0] print(u'%s: %s / %s' % (iso_code, native, name)) return 0 if config.lang_help: from behave.i18n import languages if config.lang_help not in languages: print('%s is not a recognised language: try --lang-list' % \ config.lang_help) return 1 trans = languages[config.lang_help] print(u"Translations for %s / %s" % (trans['name'][0], trans['native'][0])) for kw in trans: if kw in 'name native'.split(): continue print(u'%16s: %s' % (kw.title().replace('_', ' '), u', '.join(w for w in trans[kw] if w != '*'))) return 0 if not config.format: config.format = [ config.default_format ] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. config.format.append(config.default_format) if 'help' in config.format: print_formatters("Available formatters:") return 0 if len(config.outputs) > len(config.format): print('CONFIG-ERROR: More outfiles (%d) than formatters (%d).' % \ (len(config.outputs), len(config.format))) return 1 failed = True runner = Runner(config) try: failed = runner.run() except ParserError as e: print(u"ParseError: %s" % e) except ConfigError as e: print(u"ConfigError: %s" % e) except FileNotFoundError as e: print(u"FileNotFoundError: %s" % e) except InvalidFileLocationError as e: print(u"InvalidFileLocationError: %s" % e) except InvalidFilenameError as e: print(u"InvalidFilenameError: %s" % e) except Exception as e: # -- DIAGNOSTICS: text = _text(e) print(u"Exception %s: %s" % (e.__class__.__name__, text)) raise if config.show_snippets and runner.undefined_steps: print_undefined_step_snippets(runner.undefined_steps, colored=config.color) return_code = 0 if failed: return_code = 1 return return_code
def main(args=None): config = Configuration(args) if config.version: print("behave " + __version__) return 0 if config.tags_help: print(TAG_HELP) return 0 if config.lang_list: from behave.i18n import languages iso_codes = languages.keys() iso_codes.sort() print("Languages available:") for iso_code in iso_codes: native = languages[iso_code]['native'][0] name = languages[iso_code]['name'][0] print(u'%s: %s / %s' % (iso_code, native, name)) return 0 if config.lang_help: from behave.i18n import languages if config.lang_help not in languages: print('%s is not a recognised language: try --lang-list' % \ config.lang_help) return 1 trans = languages[config.lang_help] print(u"Translations for %s / %s" % (trans['name'][0], trans['native'][0])) for kw in trans: if kw in 'name native'.split(): continue print(u'%16s: %s' % (kw.title().replace('_', ' '), u', '.join(w for w in trans[kw] if w != '*'))) return 0 if not config.format: config.format = [ config.default_format ] elif config.format and "format" in config.defaults: # -- CASE: Formatter are specified in behave configuration file. # Check if formatter are provided on command-line, too. if len(config.format) == len(config.defaults["format"]): # -- NO FORMATTER on command-line: Add default formatter. config.format.append(config.default_format) if 'help' in config.format: from behave.formatter import formatters print("Available formatters:") formatters.list_formatters(sys.stdout) return 0 if len(config.outputs) > len(config.format): print('CONFIG-ERROR: More outfiles (%d) than formatters (%d).' % \ (len(config.outputs), len(config.format))) return 1 failed = True runner = Runner(config) try: failed = runner.run() except ParserError as e: print("ParseError: %s" % e) except ConfigError as e: print("ConfigError: %s" % e) except FileNotFoundError as e: print("FileNotFoundError: %s" % e) except InvalidFileLocationError as e: print("InvalidFileLocationError: %s" % e) except InvalidFilenameError as e: print("InvalidFilenameError: %s" % e) if config.show_snippets and runner.undefined_steps: print_undefined_step_snippets(runner.undefined_steps, colored=config.color) return_code = 0 if failed: return_code = 1 return return_code