def _istrue(self): if hasattr(self, 'result'): return self.result if self.holder: if self.holder.args or 'condition' in self.holder.kwargs: self.result = False # "holder" might be a MarkInfo or a MarkDecorator; only # MarkInfo keeps track of all parameters it received in an # _arglist attribute marks = getattr(self.holder, '_marks', None) \ or [self.holder.mark] for _, args, kwargs in marks: if 'condition' in kwargs: args = (kwargs['condition'],) for expr in args: self.expr = expr if isinstance(expr, py.builtin._basestring): d = self._getglobals() result = cached_eval(self.item.config, expr, d) else: if "reason" not in kwargs: # XXX better be checked at collection time msg = "you need to specify reason=STRING " \ "when using booleans as conditions." fail(msg) result = bool(expr) if result: self.result = True self.reason = kwargs.get('reason', None) self.expr = expr return self.result else: self.result = True return getattr(self, 'result', False)
def test_not_in_right_mode(self): cli = self.createSshConnection(user=mock()) try: cli.check_prereq(1) fail() except: pass
def test_executingWithNoJsonRaises(): cliProcessingJson = CliProcessingJson("garbage") try: cliProcessingJson.execute() fail() except: pass
def test_connectingFails(self): pexpectObject = mock() cli = self.createSshConnection(pexpectObject) when(pexpectObject).spawn(any()).thenReturn(None) try: cli.connectWithSsh() fail() except: pass
def check_strict_xfail(pyfuncitem): """check xfail(strict=True) for the given PASSING test""" evalxfail = pyfuncitem._evalxfail if evalxfail.istrue(): strict_default = pyfuncitem.config.getini('xfail_strict') is_strict_xfail = evalxfail.get('strict', strict_default) if is_strict_xfail: del pyfuncitem._evalxfail explanation = evalxfail.getexplanation() fail('[XPASS(strict)] ' + explanation, pytrace=False)
def _getfixturevalue(self, fixturedef): # prepare a subrequest object before calling fixture function # (latter managed by fixturedef) argname = fixturedef.argname funcitem = self._pyfuncitem scope = fixturedef.scope try: param = funcitem.callspec.getparam(argname) except (AttributeError, ValueError): param = NOTSET param_index = 0 if fixturedef.params is not None: frame = inspect.stack()[3] frameinfo = inspect.getframeinfo(frame[0]) source_path = frameinfo.filename source_lineno = frameinfo.lineno source_path = py.path.local(source_path) if source_path.relto(funcitem.config.rootdir): source_path = source_path.relto(funcitem.config.rootdir) msg = ( "The requested fixture has no parameter defined for the " "current test.\n\nRequested fixture '{0}' defined in:\n{1}" "\n\nRequested here:\n{2}:{3}".format( fixturedef.argname, getlocation(fixturedef.func, funcitem.config.rootdir), source_path, source_lineno, ) ) fail(msg) else: # indices might not be set if old-style metafunc.addcall() was used param_index = funcitem.callspec.indices.get(argname, 0) # if a parametrize invocation set a scope it will override # the static scope defined with the fixture function paramscopenum = funcitem.callspec._arg2scopenum.get(argname) if paramscopenum is not None: scope = scopes[paramscopenum] subrequest = SubRequest(self, scope, param, param_index, fixturedef) # check if a higher-level scoped fixture accesses a lower level one subrequest._check_scope(argname, self.scope, scope) # clear sys.exc_info before invoking the fixture (python bug?) # if its not explicitly cleared it will leak into the call exc_clear() try: # call the fixture function val = fixturedef.execute(request=subrequest) finally: # if fixture function failed it might have registered finalizers self.session._setupstate.addfinalizer(fixturedef.finish, subrequest.node) return val
def _getfixturevalue(self, fixturedef): # prepare a subrequest object before calling fixture function # (latter managed by fixturedef) argname = fixturedef.argname funcitem = self._pyfuncitem scope = fixturedef.scope try: param = funcitem.callspec.getparam(argname) except (AttributeError, ValueError): param = NOTSET param_index = 0 if fixturedef.params is not None: frame = inspect.stack()[3] frameinfo = inspect.getframeinfo(frame[0]) source_path = frameinfo.filename source_lineno = frameinfo.lineno source_path = py.path.local(source_path) if source_path.relto(funcitem.config.rootdir): source_path = source_path.relto(funcitem.config.rootdir) msg = ( "The requested fixture has no parameter defined for the " "current test.\n\nRequested fixture '{0}' defined in:\n{1}" "\n\nRequested here:\n{2}:{3}".format( fixturedef.argname, getlocation(fixturedef.func, funcitem.config.rootdir), source_path, source_lineno, )) fail(msg) else: # indices might not be set if old-style metafunc.addcall() was used param_index = funcitem.callspec.indices.get(argname, 0) # if a parametrize invocation set a scope it will override # the static scope defined with the fixture function paramscopenum = funcitem.callspec._arg2scopenum.get(argname) if paramscopenum is not None: scope = scopes[paramscopenum] subrequest = SubRequest(self, scope, param, param_index, fixturedef) # check if a higher-level scoped fixture accesses a lower level one subrequest._check_scope(argname, self.scope, scope) # clear sys.exc_info before invoking the fixture (python bug?) # if its not explicitly cleared it will leak into the call exc_clear() try: # call the fixture function val = fixturedef.execute(request=subrequest) finally: # if fixture function failed it might have registered finalizers self.session._setupstate.addfinalizer(fixturedef.finish, subrequest.node) return val
def _check_scope(self, argname, invoking_scope, requested_scope): if argname == "request": return if scopemismatch(invoking_scope, requested_scope): # try to report something helpful lines = self._factorytraceback() fail("ScopeMismatch: You tried to access the %r scoped " "fixture %r with a %r scoped request object, " "involved factories\n%s" % ( (requested_scope, argname, invoking_scope, "\n".join(lines))), pytrace=False)
def test_cannotLogin(self): cli = self.createSshConnection(user=Root(password="******")) connection = cli._connection cli.trace = True when(connection).expect(any()).thenReturn(-1) cli.debug=True try: cli.loginSsh() fail() except: pass verify(connection).close()
def _check_scope(self, argname, invoking_scope, requested_scope): if argname == "request": return if scopemismatch(invoking_scope, requested_scope): # try to report something helpful lines = self._factorytraceback() fail( "ScopeMismatch: You tried to access the %r scoped " "fixture %r with a %r scoped request object, " "involved factories\n%s" % ((requested_scope, argname, invoking_scope, "\n".join(lines))), pytrace=False)
def test_raiseWhenSshConnectionFails(): json = '{\ "hostname" : "<ip>",\ "username" : "root",\ "password" : "password"\ }' cliProcessingJson, UserObject, CliObject, cli, _ = setupCliProcessingJson(json, "password") when(cli).loginSsh().thenRaise(Exception("Any")) try: cliProcessingJson.execute(UserObject.called, CliObject.called) fail() except: pass
def test_assertion_when_bad_result_detected(self): resultContainBadResult = 0 badResult = "who cares" cli = self.makeCli() when(cli).compareReceivedAgainst(any(),any(), indexOfSuccessfulResult=any()).thenReturn(resultContainBadResult) assertion = assertResultNotEquals(badResult) try: assertion.executeOn(cli) fail() except: pass verify(cli).compareReceivedAgainst([badResult, "$", EOF, TIMEOUT], any(), indexOfSuccessfulResult=any())
def __exit__(self, *exc_info): super(WarningsChecker, self).__exit__(*exc_info) # only check if we're not currently handling an exception if all(a is None for a in exc_info): if self.expected_warning is not None: if not any(issubclass(r.category, self.expected_warning) for r in self): __tracebackhide__ = True from _pytest.runner import fail fail("DID NOT WARN. No warnings of type {0} was emitted. " "The list of emitted warnings is: {1}.".format( self.expected_warning, [each.message for each in self]))
def test_assertion_when_good_results_not_detected(self): resultDoesNotContainGoodResult = 2 goodResult = ["who cares", "I don't"] cli = self.makeCli() when(cli).compareReceivedAgainst(any(),any(), indexOfSuccessfulResult=any()).thenReturn(resultDoesNotContainGoodResult) assertion = assertResultEquals(goodResult) try: assertion.executeOn(cli) fail() except: pass verify(cli).compareReceivedAgainst(goodResult+[EOF, TIMEOUT], 30, indexOfSuccessfulResult=0)
def istrue(self): try: return self._istrue() except Exception: self.exc = sys.exc_info() if isinstance(self.exc[1], SyntaxError): msg = [" " * (self.exc[1].offset + 4) + "^", ] msg.append("SyntaxError: invalid syntax") else: msg = traceback.format_exception_only(*self.exc[:2]) fail("Error evaluating %r expression\n" " %s\n" "%s" % (self.name, self.expr, "\n".join(msg)), pytrace=False)
def _addexcinfo(self, rawexcinfo): # unwrap potential exception info (see twisted trial support below) rawexcinfo = getattr(rawexcinfo, '_rawexcinfo', rawexcinfo) try: excinfo = _pytest._code.ExceptionInfo(rawexcinfo) except TypeError: try: try: l = traceback.format_exception(*rawexcinfo) l.insert(0, "NOTE: Incompatible Exception Representation, " "displaying natively:\n\n") fail("".join(l), pytrace=False) except (fail.Exception, KeyboardInterrupt): raise except: fail("ERROR: Unknown Incompatible Exception " "representation:\n%r" % (rawexcinfo,), pytrace=False) except KeyboardInterrupt: raise except fail.Exception: excinfo = _pytest._code.ExceptionInfo() self.__dict__.setdefault('_excinfo', []).append(excinfo)
def get_sms_via_heroku(client, environment=None): if environment is None: environment = Config.ENVIRONMENT url = 'https://notify-sms-inbox.herokuapp.com/' + environment response = client.get(url) j = json.loads(response.text) x = 0 loop_condition = True while loop_condition: if response.status_code == 200: loop_condition = False if x > 12: loop_condition = False if j['result'] == 'error': sleep(5) x += 1 response = client.get(url) j = json.loads(response.text) try: return j['sms_code'] except KeyError: fail('No sms code delivered')
def fail_fixturefunc(fixturefunc, msg): fs, lineno = getfslineno(fixturefunc) location = "%s:%s" % (fs, lineno + 1) source = _pytest._code.Source(fixturefunc) fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)
def fail_fixturefunc(fixturefunc, msg): fs, lineno = getfslineno(fixturefunc) location = "%s:%s" % (fs, lineno+1) source = _pytest._code.Source(fixturefunc) fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)