def setUp(self) -> None:
     self.gmi = GMI("mock_api_key")
     with open(JSON_TEST_DATA_1) as file:
         self.mock_obj = MockAbstractObject.from_json(
             self.gmi, json.load(file))
     with open(JSON_TEST_DATA_2) as file:
         self.for_overwrite = MockAbstractObject.from_json(
             self.gmi, json.load(file))
Exemplo n.º 2
0
    def check_file(self, name: str, recorded_data: Dict[str, Any]) -> None:
        def mocked_requests_api_call(
            url: str,
            params: Dict[str, str],
            headers: List[str],
            data: Optional[str] = None,
        ) -> MockRequestsResponse:
            if data is None:
                self.assertEqual(params, recorded_data["request"]["args"])
            else:
                self.assertEqual(json.loads(data),
                                 recorded_data["request"]["args"])
            self.assertTrue(url, recorded_data["request"]["url"])
            return MockRequestsResponse(recorded_data["response"])

        name_split = name.split(".")
        module, klass_name = ".".join(name_split[:-1]), name_split[-1]
        klass = getattr(import_module(module), klass_name)
        if recorded_data["request"]["mode"] == "GET":
            patch_func = "get"
        else:
            patch_func = "post"
        with mock.patch("requests." + patch_func,
                        side_effect=mocked_requests_api_call):
            instance = klass(GMI("test_gmi"),
                             **recorded_data["request"]["init"])
            try:
                results = instance.result
            except AttributeError:
                results = None
            if isinstance(results, list):
                for result in results:
                    self.check_types(result)
            elif results is None:
                self.assertEqual(instance.parse(recorded_data["response"]),
                                 None)
            elif type(results) in [bool]:
                pass
            else:
                self.check_types(results)
Exemplo n.º 3
0
 def setUp(self, request_init: MagicMock) -> None:
     self.data = bytes(123)
     self.instance = ImageConvertRequest(GMI("image_test"), self.data)
 def test_sms_create(self):
     with self.assertRaises(ValueError):
         SmsCreateRequest(GMI("test"), duration=50, registration_id="none")
Exemplo n.º 5
0
 def test_disable_sms(self, request_init: MagicMock) -> None:
     request_init.side_effect = ValueError("marker")
     with self.assertRaisesRegex(ValueError, "marker"):
         User(GMI("test")).disable_sms()
def mm_instance(content=None):
    return MockManager(GMI('access_token_here'), content)
Exemplo n.º 7
0
 def test_unblock(self, request_init: MagicMock) -> None:
     request_init.side_effect = ValueError("marker")
     with self.assertRaisesRegex(ValueError, "marker"):
         Block.unblock(GMI("test"), "dummy", "other")
Exemplo n.º 8
0
 def test_get_all(self, request_init: MagicMock) -> None:
     request_init.side_effect = ValueError("marker")
     with self.assertRaisesRegex(ValueError, "marker"):
         Block(GMI("test")).get_all("dummy")
Exemplo n.º 9
0
def get_gmi(access_token: str) -> GMI:
    return GMI(access_token)
Exemplo n.º 10
0
def gmi(monkeypatch):
    from lowerpines.endpoints.bot import Bot
    from lowerpines.endpoints.group import Group, GroupMessagesManager
    from lowerpines.endpoints.message import Message
    from lowerpines.endpoints.user import User

    global_users = {}
    global_bots = {}
    global_groups = {}
    global_messages = defaultdict(list)

    class TestUser(User):
        def save(self):
            global_users[self.gmi.access_token] = self

        def refresh(self):
            if self.gmi.access_token in global_users:
                self._refresh_from_other(global_users[self.gmi.access_token])

    class TestGroup(Group):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.messages = TestGroupMessageManager(self)

        def save(self):
            if not self.group_id:
                self.group_id = str(uuid.uuid4()).replace('-', '')
            global_groups[self.group_id] = self

        def delete(self):
            if self.group_id in global_groups:
                del global_groups[self.group_id]

        def refresh(self):
            pass

        def add_member(self, member):
            self.members.append(member)

        @staticmethod
        def get_all(gmi):
            return global_groups.values()

        @staticmethod
        def get(gmi, group_id):
            return global_groups.get(group_id)

    class TestGroupMessageManager(GroupMessagesManager):
        @property
        def count(self):
            return len(global_messages[self.group.group_id])

        def all(self):
            return global_messages[self.group.group_id]

        def recent(self, count=100):
            return global_messages[self.group.group_id][-count:]

        def before(self, message, count=100):
            group_messages = global_messages[self.group.group_id]
            idx = group_messages.index(message)
            return group_messages[max(idx - count, 0):idx]

        def since(self, message, count=100):
            group_messages = global_messages[self.group.group_id]
            idx = group_messages.index(message)
            return group_messages[idx:min(idx + count, len(group_messages))]

    class TestMessage(Message):
        def save(self):
            if self.message_id:
                from lowerpines.exceptions import InvalidOperationException
                raise InvalidOperationException(
                    "You cannot change a message that has already been sent")
            else:
                self.message_id = str(uuid.uuid4()).replace('-', '')
                global_messages[self.group_id].append(self)

        def refresh(self):
            pass

        def like(self):
            if self.favorited_by is None:
                self.favorited_by = []
            self.favorited_by.append(self.gmi.user.get().user_id)

        def like_as(self, user_id):
            if self.favorited_by is None:
                self.favorited_by = []
            self.favorited_by.append(user_id)

        @classmethod
        def from_json(cls, gmi, json_dict, *args):
            return Message.from_json(gmi, json_dict, *args)

    class TestBot(Bot):
        def save(self):
            if self.bot_id is None:
                self.bot_id = str(uuid.uuid4()).replace('-', '')

            global_bots[self.bot_id] = self

        def delete(self):
            if self.bot_id in global_bots:
                del global_bots[self.bot_id]

        def post(self, text):
            from lowerpines.message import smart_split_complex_message
            text, attachments = smart_split_complex_message(text)
            message = TestMessage(self.gmi,
                                  group_id=self.group_id,
                                  text=text,
                                  attachments=attachments)
            message.favorited_by = []
            message.name = self.name
            message.save()

        @staticmethod
        def get_all(gmi):
            return global_bots.values()

    monkeypatch.setattr('lowerpines.endpoints.user.User', TestUser)
    monkeypatch.setattr('lowerpines.endpoints.group.Group', TestGroup)
    monkeypatch.setattr('lowerpines.endpoints.message.Message', TestMessage)
    monkeypatch.setattr('lowerpines.endpoints.bot.Bot', TestBot)
    monkeypatch.setattr('lowerpines.user.User', TestUser)
    monkeypatch.setattr('lowerpines.group.Group', TestGroup)
    monkeypatch.setattr('lowerpines.bot.Bot', TestBot)

    from lowerpines.gmi import GMI

    return GMI('faketoken')
def mm_instance(content: Any = None):
    return MockManager(GMI("access_token_here"), content)