def test_shouldCloseAllSubLoggersWhenItIsClosed(): subLogger1 = mock.mock() subLogger2 = mock.mock() subLogger1.expectCalls(mock.call("close", ())) subLogger2.expectCalls(mock.call("close", ())) with TeeLogger(subLogger1, subLogger2): pass subLogger1.checkExpectedCalls() subLogger2.checkExpectedCalls()
def test_shouldPrintLineForEachScheduledRuleButNotScheduleThem(fixture): sub = mock.mock() sub.name = "sub-sched" output = mock.mock() output.expectCallsInAnyOrder( mock.callMatching( "println", lambda line: "first" in line and "sub-sched" in line), mock.callMatching("println", lambda line: "second" in line)) dry = DryScheduler(sub, output) dry.schedule([buildScheduling("first"), buildScheduling("second")]) output.checkExpectedCalls()
def test_shouldReturnTheErrorsOfTheFirstValidatorGroupThatReturnsSome(): rules = [object(), object()] errors1 = ["first error", "foo"] errors2 = ["second error", "bar"] errors3 = ["third error", "quux"] sub0, sub1, sub2, sub3 = mock.mock(), mock.mock(), mock.mock(), mock.mock() sub0.expectCalls(mock.call("validate", (rules, ), ret=[])) sub1.expectCalls(mock.call("validate", (rules, ), ret=errors1)) sub2.expectCalls(mock.call("validate", (rules, ), ret=errors2)) sub3.expectCalls(mock.call("validate", (rules, ), ret=errors3)) validator = ValidatorCollectionValidator([[sub0], [sub2, sub1], [sub3]]) assert set(validator.validate(rules)) == set(errors2 + errors1)
def test_shouldImmediatelyWriteAnyChunkToAllOfItsSubLoggers(): chunk = b"abcdef" subLogger1 = mock.mock() subLogger2 = mock.mock() subLogger1.expectCalls(mock.call("write", (chunk, ))) subLogger2.expectCalls(mock.call("write", (chunk, ))) logger = TeeLogger(subLogger1, subLogger2) logger.write(chunk) subLogger1.checkExpectedCalls() subLogger2.checkExpectedCalls()
def test_shouldNotHaveAttributesThatArentAssignedOrExpected(fixture): mocked = mock.mock() assert not hasattr(mocked, "foo") with pytest.raises(AttributeError): mocked.foo()
def test_shouldReturnALazyRuleForEachFileAndBuildWithTheFactoryWhenLoadIsCalled( fixture): fixture.writeAnyRule("rule-1") fixture.writeAnyRule("rule-2") fileReader = mock.mock() lazyRules = fixture.read(fileReader, loadLazyRules=False, namePrefix="a-") assert lazyRules[0].name.startswith("a-rule-") ruleOpts1, schedOpts1, syncerOpts1, ruleOpts2, schedOpts2, syncerOpts2 = \ object(), object(), object(), object(), object(), object() fileReader.expectCallsInAnyOrder( readCall(paths=[fixture.rulePath("rule-1")], ret=sectionsDict(ruleOpts1, schedOpts1, syncerOpts1)), readCall(paths=[fixture.rulePath("rule-2")], ret=sectionsDict(ruleOpts2, schedOpts2, syncerOpts2))) firstConstructedRule = object() secondConstructedRule = object() fixture.factory.expectCallsInAnyOrder( buildCall(name="a-rule-1", ruleOpts=ruleOpts1, schedOpts=schedOpts1, syncerOpts=syncerOpts1, ret=firstConstructedRule), buildCall(name="a-rule-2", ruleOpts=ruleOpts2, schedOpts=schedOpts2, syncerOpts=syncerOpts2, ret=secondConstructedRule)) assert iterToTest(rule.load() for rule in lazyRules).\ shouldContainInAnyOrder(firstConstructedRule, secondConstructedRule)
def test_shouldReturnFirstConfiguredValueThatIsNotNone(fixture): mocked = mock.mock() mocked.expectCalls(mock.call("foo", ())) mocked.expectCalls(mock.call("foo", (), ret="")) mocked.expectCalls(mock.call("foo", (), ret=5)) assert mocked.foo() == "" mocked.checkExpectedCalls()
def test_shouldCheckOrderOfCalls(fixture): mocked = mock.mock() expectTestCalls(mocked, False) with pytest.raises(AssertionError): mocked.bar() mocked.foo(40) mocked.bar()
def __init__(self): self.moduleLoader = mock.mock() self.loader = PyModuleSchedulerLoader(self.moduleLoader) self.path = "/etc/foo.py" self.validModule = lambda x:x self.validModule.init = lambda *args: None self.validModule.availableOptions = [] self.validModule.availableSharedOptions = []
def test_shouldMakeExpectationsOverrideNormalMethods(fixture): mocked = mock.mock() mocked.foo = lambda arg: None mocked.foo(5) mocked.expectCalls(mock.call("foo", (2, ))) with pytest.raises(AssertionError): mocked.foo(5)
def test_shouldForwardAnyCallsToSubScheduler(fixture): sub = mock.mock() sub.expectCallsInOrder( mock.callMatching("foo", lambda x, y: x == 1 and y == 2, ret=3)) dry = DryScheduler(sub, object()) assert dry.foo(1, 2) == 3 sub.checkExpectedCalls()
def test_shouldCallTheWrappedSchedsExecuteMethodIfItHasOne(): wrappedSched = mock.mock() execEnv, scheduling, returnedObject = object(), object(), object() wrappedSched.expectCalls( mock.call("execute", (execEnv, scheduling), ret=returnedObject)) assert DefaultImplScheduler(wrappedSched).execute(execEnv, scheduling) is \ returnedObject
def test_shouldReturnNameAndBasicInfoOfRulesEvenWithoutBuildingThem(fixture): fixture.writeAnyRule("foo") fixture.writeAnyRule("bar") fixture.writeInstanceFile("@bar") iterToTest(fixture.read(mockedFileReader=mock.mock(), loadLazyRules=False)).shouldContainMatchingInAnyOrder( lambda rule: rule.name == "foo" and not rule.enabled, lambda rule: rule.name == "bar" and rule.enabled)
def test_shouldCallRunSynchronizerWhenExecutedAsADefault(): returnedObject = object() execEnv = mock.mock() execEnv.expectCalls(mock.call("runSynchronizer", (), ret=returnedObject)) schedWithoutExecute = object() scheduler = DefaultImplScheduler(schedWithoutExecute) assert scheduler.execute(execEnv, anyScheduling()) is returnedObject
def test_shouldPassOnAnyGivenKeywordArgsToWriteFuncs(): subLogger = mock.mock() subLogger.expectCalls( mock.callMatching("write", lambda *args, **kwargs: kwargs == dict(Foo="Bar"))) TeeLogger(subLogger).write(b"", Foo="Bar") subLogger.checkExpectedCalls()
def test_shouldAllowExactlyTheExpectedCalls(fixture): mocked = mock.mock() mocked.expectCalls( mock.callMatching("allowed", lambda a, b: [a, b] == [1, 2])) with pytest.raises(AssertionError): mocked.allowed(1, 3) mocked.allowed(1, 2) with pytest.raises(AssertionError): mocked.allowed(1, 2)
def test_shouldBeAbleToAllowAnyNumberOfCallsForSomeExpectations(fixture): mocked = mock.mock() mocked.expectCalls(mock.call("baz", (1, )), mock.call("baz", (), anyNumber=True), mock.call("foo", (), anyNumber=True), inAnyOrder=False) mocked.foo() mocked.baz() mocked.baz(1) mocked.baz() mocked.checkExpectedCalls()
def test_shouldMakeInstanceFileOverrideAllSettingsALastTime(fixture): fixture.writeAnyRule("rule") fixture.writeInstanceFile("ta@ta@rule") reader = mock.mock() reader.expectCallsInAnyOrder(readCall( paths=[fixture.rulePath("rule"), fixture.instancePath("ta@ta@rule")], instanceArgument="ta@ta", ret=sectionsDict())) fixture.factory.expectCallsInAnyOrder(buildCall(name="ta@ta@rule")) fixture.read(reader)
def mockSyncer(name="foo", availableOptions=[], ports=[ port(["file"], isWrittenTo=False), port(["file"], isWrittenTo=True) ]): ret = mock.mock(name) ret.name = name ret.availableOptions = list(availableOptions) ret.ports = ports ret.onePortMustHaveFileProtocol = False return ret
def test_shouldNotScheduleAnythingAndFailIfValidationFails(fixture): sched1, sched2 = mockScheds(2) rule1, rule2 = fixture.ruleWithSched(sched1), fixture.ruleWithSched(sched2) ruleSet = fixture.makeRuleSet(rule1, rule2) validator = mock.mock() validator.expectCalls(mock.call("validate", (ruleSet, ), ret=["raven"])) with pytest.raises(ValidationException) as ex: ruleSet.schedule(validator) assert ex.value.errors == ["raven"]
def getLoggedOutput(self, logInput, *formatArgs, maxVerbosity=10, prefix="sibt", **kwargs): output = mock.mock() ret = [None] def storeResult(string): ret[0] = string return True output.expectCalls(mock.callMatching("println", storeResult)) logger = PrefixingErrorLogger(output, prefix, maxVerbosity) logger.log(logInput, *formatArgs, **kwargs) return ret[0]
def test_shouldBeAbleToSimultaneouslyCheckMultipleGroupsOfExpectations( fixture): mocked = mock.mock() mocked.expectCalls(mock.call("foo", ()), mock.call("bar", ())) mocked.expectCalls(mock.call("bar", ()), mock.call("foo", ()), mock.call("quux", ()), inAnyOrder=True) mocked.foo() mocked.bar() with pytest.raises(AssertionError): mocked.checkExpectedCalls() mocked.quux() mocked.checkExpectedCalls()
def mock(self): mocked = mock.mock() mocked.availableOptions = self.options mocked.availableSharedOptions = self.sharedOptions mocked.name = self.name mocked.init = self.kwParams["initFunc"] mocked.check = self.kwParams["checkFunc"] mocked.run = self.kwParams["scheduleFunc"] if "executeFunc" in self.kwParams: mocked.execute = self.kwParams["executeFunc"] if "nextExecutionTimeFunc" in self.kwParams: mocked.nextExecutionTime = self.kwParams["nextExecutionTimeFunc"] self.path.write("") self.reRegister(mocked) return mocked, self
def test_shouldBeAbleToTestKeywordArguments(fixture): mocked = mock.mock() mocked.expectCallsInAnyOrder( mock.call("foo", (4, ), {"arg": 2}, anyNumber=True), mock.callMatching("bar", lambda *args, **kwargs: args == (4, ) and kwargs == {"arg": 2}, anyNumber=True)) mocked.foo(4, arg=2) with pytest.raises(AssertionError): mocked.foo(4, arg=3) with pytest.raises(AssertionError): mocked.foo(4) mocked.bar(4, arg=2) with pytest.raises(AssertionError): mocked.bar(4, arg=0)
def mockRule(name="foo", options=None, scheduler=None, loc1="/tmp/1", loc2="/tmp/2", writeLocs=[2], schedOpts=dict(), syncerName="foo", syncerCheckErrors=[], syncerOpts=mkSyncerOpts(), nextExecution=None, executing=False, currentExecution=None, lastFinishedExecution=None): ret = mock.mock(name) if options is None: options = dict(LocCheckLevel=LocCheckLevel.Default) ret.options = options ret.name = name ret.schedulerOptions = schedOpts ret.synchronizerOptions = syncerOpts ret.scheduler = scheduler ret.scheduling = object() ret.locs = [parseLocation(str(loc1)), parseLocation(str(loc2))] ret.writeLocs = [parseLocation(str(loc1))] if 1 in writeLocs else [] + \ [parseLocation(str(loc2))] if 2 in writeLocs else [] ret.nonWriteLocs = [parseLocation(str(loc1))] if 1 not in writeLocs else \ [] + [parseLocation(str(loc2))] if 2 not in writeLocs else [] ret.syncerName = syncerName ret.syncerCheckErrors = syncerCheckErrors ret.nextExecution = nextExecution ret.currentExecution = currentExecution ret.executing = executing ret.lastFinishedExecution = lastFinishedExecution return ret
def __init__(self): self.callsMock = mock.mock() self.logger = BufferingLogger()
def __init__(self): self.ruleFactory = mock.mock() self.parser = mock.mock()
def makeSched(i): name = "sched-{0}".format(i + 1) ret = mock.mock(name) ret.name = name return ret
def construct(self, runners=[]): wrapped = mock.mock() return wrapped, HashbangAwareProcessRunner(runners, wrapped)
def __init__(self): self.functions = mock.mock() self.syncer = FunctionModuleSynchronizer(self.functions, "some-synchronizer")