Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit fe071f52 authored by Zach Johnson's avatar Zach Johnson
Browse files

add beginings of behavior.py, a fluent behavior composer

Has getting the right cert behavior ever left you frustrated?
Is it too hard to know what a test is exactly doing? Does creating
the right responses ever feel like a game of telephone?

Introducing behavior.py - now you can write tests more naturally
and get context locally in the test on what will happen, instead of
opaque behavior in CertXYZ.

Now basically, the only new principal involved is that instead of
power being generated by the relative motion of conductors and fluxes
it’s produced by the modial interaction of magneto-reluctance and
capacitive diractance. The original behaviors had a base plate of
prefabulated amulite, surmounted by a malleable logarithmic casing
in such a way that the two spurving bearings were in a direct
line with the panametric fan.

behavior.py has now reached a high level of development, and it’s
being successfully used in the operation of milford trenions. It’s
available soon; wherever Rockwell Automation products are sold.

e.g.

self.cert_l2cap.reply_with_unacceptable_parameters()
(when is it going to?, is it always going to? can I make
it do it 2 times and then reply with something else?)

now becomes

when(self.cert_l2cap).config_request(anything())
    .then().reply_with_unacceptable_parameters()

yes, it's longer, but now the exact behavior is clear.

or you could imagine something like:

when(self.cert_l2cap).config_request(L2capMatchers.ConfigRequest(mode=BASIC))
    .then().reply_with_ertm()

Test: cert/run --host
Change-Id: I81133db3174446c0b9380da795dbb0e9f9bcf2a3
parent 99c567d6
Loading
Loading
Loading
Loading
+100 −0
Original line number Original line Diff line number Diff line
#!/usr/bin/env python3
#
#   Copyright 2020 - The Android Open Source Project
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

from abc import ABC, abstractmethod

from cert.truth import assertThat


class IHasBehaviors(ABC):

    @abstractmethod
    def get_behaviors(self):
        pass


def anything():
    return lambda obj: True


def when(has_behaviors):
    assertThat(isinstance(has_behaviors, IHasBehaviors)).isTrue()
    return has_behaviors.get_behaviors()


class SingleArgumentBehavior(object):

    def __init__(self, reply_stage_factory):
        self._reply_stage_factory = reply_stage_factory
        self._instances = []

    def begin(self, matcher):
        return PersistenceStage(self, matcher, self._reply_stage_factory)

    def append(self, behavior_instance):
        self._instances.append(behavior_instance)

    def run(self, obj):
        for instance in self._instances:
            if instance.try_run(obj):
                return


class PersistenceStage(object):

    def __init__(self, behavior, matcher, reply_stage_factory):
        self._behavior = behavior
        self._matcher = matcher
        self._reply_stage_factory = reply_stage_factory

    def then(self, times=1):
        reply_stage = self._reply_stage_factory()
        reply_stage.init(self._behavior, self._matcher, times)
        return reply_stage

    def always(self):
        return self.then(times=-1)


class ReplyStage(object):

    def init(self, behavior, matcher, persistence):
        self._behavior = behavior
        self._matcher = matcher
        self._persistence = persistence

    def _commit(self, fn):
        self._behavior.append(
            BehaviorInstance(self._matcher, self._persistence, fn))


class BehaviorInstance(object):

    def __init__(self, matcher, persistence, fn):
        self._matcher = matcher
        self._persistence = persistence
        self._fn = fn
        self._called_count = 0

    def try_run(self, obj):
        if not self._matcher(obj):
            return False
        if self._persistence >= 0:
            if self._called_count >= self._persistence:
                return False
        self._called_count += 1
        self._fn(obj)
        return True
+122 −0
Original line number Original line Diff line number Diff line
@@ -28,6 +28,11 @@ from bluetooth_packets_python3 import l2cap_packets
from cert.event_stream import EventStream, FilteringEventStream
from cert.event_stream import EventStream, FilteringEventStream
from cert.truth import assertThat
from cert.truth import assertThat
from cert.metadata import metadata
from cert.metadata import metadata
from cert.behavior import when
from cert.behavior import IHasBehaviors
from cert.behavior import anything
from cert.behavior import SingleArgumentBehavior
from cert.behavior import ReplyStage




class BogusProto:
class BogusProto:
@@ -88,6 +93,40 @@ class FetchEvents:
        return None
        return None




class TestBehaviors(object):

    def __init__(self, parent):
        self.test_request_behavior = SingleArgumentBehavior(
            lambda: TestBehaviors.TestRequestReplyStage(parent))

    def test_request(self, matcher):
        return self.test_request_behavior.begin(matcher)

    class TestRequestReplyStage(ReplyStage):

        def __init__(self, parent):
            self._parent = parent

        def increment_count(self):
            self._commit(lambda obj: self._increment_count(obj))
            return self

        def _increment_count(self, obj):
            self._parent.count += 1
            self._parent.captured.append(obj)


class ObjectWithBehaviors(IHasBehaviors):

    def __init__(self):
        self.behaviors = TestBehaviors(self)
        self.count = 0
        self.captured = []

    def get_behaviors(self):
        return self.behaviors


class CertSelfTest(BaseTestClass):
class CertSelfTest(BaseTestClass):


    def setup_test(self):
    def setup_test(self):
@@ -484,3 +523,86 @@ class CertSelfTest(BaseTestClass):
            asserts.assert_equal(e.extras["pts_test_name"], "Hello world")
            asserts.assert_equal(e.extras["pts_test_name"], "Hello world")
        else:
        else:
            asserts.fail("Must throw an exception using @metadata decorator")
            asserts.fail("Must throw an exception using @metadata decorator")

    def test_fluent_behavior_simple(self):
        thing = ObjectWithBehaviors()
        when(thing).test_request(anything()).then().increment_count()

        thing.behaviors.test_request_behavior.run("A")

        assertThat(thing.count).isEqualTo(1)
        assertThat(thing.captured).isEqualTo(["A"])

    def test_fluent_behavior__then_single__captures_one(self):
        thing = ObjectWithBehaviors()
        when(thing).test_request(anything()).then().increment_count()

        thing.behaviors.test_request_behavior.run("A")
        thing.behaviors.test_request_behavior.run("A")
        thing.behaviors.test_request_behavior.run("A")

        assertThat(thing.count).isEqualTo(1)
        assertThat(thing.captured).isEqualTo(["A"])

    def test_fluent_behavior__then_times__captures_all(self):
        thing = ObjectWithBehaviors()
        when(thing).test_request(anything()).then(times=3).increment_count()

        thing.behaviors.test_request_behavior.run("A")
        thing.behaviors.test_request_behavior.run("B")
        thing.behaviors.test_request_behavior.run("C")

        assertThat(thing.count).isEqualTo(3)
        assertThat(thing.captured).isEqualTo(["A", "B", "C"])

    def test_fluent_behavior__always__captures_all(self):
        thing = ObjectWithBehaviors()
        when(thing).test_request(anything()).always().increment_count()

        thing.behaviors.test_request_behavior.run("A")
        thing.behaviors.test_request_behavior.run("B")
        thing.behaviors.test_request_behavior.run("C")

        assertThat(thing.count).isEqualTo(3)
        assertThat(thing.captured).isEqualTo(["A", "B", "C"])

    def test_fluent_behavior__matcher__captures_relevant(self):
        thing = ObjectWithBehaviors()
        when(thing).test_request(
            lambda obj: obj == "B").always().increment_count()

        thing.behaviors.test_request_behavior.run("A")
        thing.behaviors.test_request_behavior.run("B")
        thing.behaviors.test_request_behavior.run("C")

        assertThat(thing.count).isEqualTo(1)
        assertThat(thing.captured).isEqualTo(["B"])

    def test_fluent_behavior__then_repeated__captures_relevant(self):
        thing = ObjectWithBehaviors()
        when(thing).test_request(
            anything()).then().increment_count().increment_count()

        thing.behaviors.test_request_behavior.run("A")
        thing.behaviors.test_request_behavior.run("B")
        thing.behaviors.test_request_behavior.run("A")

        assertThat(thing.count).isEqualTo(2)
        assertThat(thing.captured).isEqualTo(["A", "B"])

    def test_fluent_behavior__fallback__captures_relevant(self):
        thing = ObjectWithBehaviors()
        when(thing).test_request(lambda obj: obj == "B").then(
            times=1).increment_count()
        when(thing).test_request(
            lambda obj: obj == "C").always().increment_count()

        thing.behaviors.test_request_behavior.run("A")
        thing.behaviors.test_request_behavior.run("B")
        thing.behaviors.test_request_behavior.run("A")
        thing.behaviors.test_request_behavior.run("C")
        thing.behaviors.test_request_behavior.run("B")
        thing.behaviors.test_request_behavior.run("C")

        assertThat(thing.count).isEqualTo(3)
        assertThat(thing.captured).isEqualTo(["B", "C", "C"])