Exemplo n.º 1
0
def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the sensor platform."""

    username = config[CONF_USERNAME]
    item = config[CONF_ITEM]
    access_token = config[CONF_ACCESS_TOKEN]
    refresh_token = config[CONF_REFRESH_TOKEN]
    user_id = config[CONF_USER_ID]

    global tgtg_client

    # Log in with tokens
    tgtg_client = TgtgClient(
        access_token=access_token, refresh_token=refresh_token, user_id=user_id
    )

    # If item: isn't defined, use favorites - otherwise use defined items
    if item != [""]:
        for each_item_id in item:
            add_entities([TGTGSensor(each_item_id)])
    else:
        tgtgReply = tgtg_client.get_items()
        for item in tgtgReply:
            add_entities([TGTGSensor(item["item"]["item_id"])])
Exemplo n.º 2
0
def test_get_all_business_success():
    data = [
        {
            "id": "88",
            "created_by": "88",
            "category_id": "1",
            "latitude": "55.65004170",
            "longitude": "12.20162040",
            "business_name": "Asia House - Hedehusene",
            "todays_stock": "6",
            "is_open": "1",
            "img_path": "https://images.tgtg.ninja/user/1468224399_GT8Gn0MCoH_scale.jpg",
            "pickup_day_offset": "0",
            "current_window_pickup_start_utc": "2019-09-22 19:20:00",
            "current_window_pickup_end_utc": "2019-09-22 19:25:00",
        }
    ]
    responses.add(
        responses.GET,
        urljoin(BASE_URL, ALL_BUSINESS_ENDPOINT),
        json={"info": data, "msg": "OK", "status_code": 1},
        status=200,
    )
    client = TgtgClient()
    client.get_all_business()
    assert client.get_all_business() == data
Exemplo n.º 3
0
def test_get_inactive_fail(refresh_tokens_response):
    responses.add(
        responses.POST, urljoin(BASE_URL, INACTIVE_ORDER_ENDPOINT), json={}, status=400
    )
    client = TgtgClient(**tgtg_client_fake_tokens)
    with pytest.raises(TgtgAPIError):
        client.get_inactive()
Exemplo n.º 4
0
def test_get_items_fail():
    responses.add(responses.POST,
                  urljoin(BASE_URL, API_ITEM_ENDPOINT),
                  json={},
                  status=400)
    client = TgtgClient(access_token="an_access_token", user_id=1234)
    with pytest.raises(TgtgAPIError):
        client.get_items()
Exemplo n.º 5
0
def test_get_item_fail(login_response):
    responses.add(responses.POST,
                  urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1",
                  json={},
                  status=400)
    client = TgtgClient(email="*****@*****.**", password="******")
    with pytest.raises(TgtgAPIError):
        client.get_item(1)
Exemplo n.º 6
0
def test_get_item_success():
    responses.add(responses.POST,
                  urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1",
                  json={},
                  status=200)
    client = TgtgClient(access_token="an_access_token", user_id=1234)
    assert client.get_item(1) == {}
    assert len(responses.calls) == 1
Exemplo n.º 7
0
def test_get_item_fail(refresh_tokens_response):
    responses.add(responses.POST,
                  urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1",
                  json={},
                  status=400)
    client = TgtgClient(**tgtg_client_fake_tokens)
    with pytest.raises(TgtgAPIError):
        client.get_item(1)
Exemplo n.º 8
0
def test_get_items_success():
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT),
        json={"items": []},
        status=200,
    )
    client = TgtgClient(access_token="an_access_token", user_id=1234)
    assert client.get_items() == []
Exemplo n.º 9
0
 def test_get_items(self):
     client = TgtgClient(email=os.environ["TGTG_EMAIL"],
                         password=os.environ["TGTG_PASSWORD"])
     data = client.get_items(favorites_only=False,
                             radius=10,
                             latitude=48.126,
                             longitude=-1.723)
     assert len(data) == 20
     assert all(prop in data[0] for prop in GLOBAL_PROPERTIES)
Exemplo n.º 10
0
    def test_get_one_item(self):
        client = TgtgClient(email=os.environ["TGTG_EMAIL"],
                            password=os.environ["TGTG_PASSWORD"])
        item_id = "36684"
        data = client.get_item(item_id)

        assert all(prop in data for prop in GLOBAL_PROPERTIES)
        assert all(prop in data["item"] for prop in ITEM_PROPERTIES)
        assert all(prop in data["store"] for prop in STORE_PROPERTIES)
        assert data["item"]["item_id"] == item_id
Exemplo n.º 11
0
def test_set_favorite():
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1/setFavorite",
        json={},
        status=200,
    )
    client = TgtgClient(access_token="an_access_token", user_id=1234)
    assert client.set_favorite(1, True) is None
    assert len(responses.calls) == 1
Exemplo n.º 12
0
def test_set_favorite_fail(login_response):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1/setFavorite",
        json={},
        status=400,
    )
    client = TgtgClient(email="*****@*****.**", password="******")
    with pytest.raises(TgtgAPIError):
        client.set_favorite(1, True)
Exemplo n.º 13
0
def test_get_items_fail():
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT),
        json={"status": 401, "error": "Unauthorized"},
        status=200,
    )
    client = TgtgClient(access_token="an_access_token", user_id=1234)
    with pytest.raises(TgtgAPIError):
        client.get_items()
Exemplo n.º 14
0
def test_set_favorite_fail(refresh_tokens_response):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1/setFavorite",
        json={},
        status=400,
    )
    client = TgtgClient(**tgtg_client_fake_tokens)
    with pytest.raises(TgtgAPIError):
        client.set_favorite(1, True)
Exemplo n.º 15
0
def test_get_item_success(login_response):
    responses.add(responses.POST,
                  urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1",
                  json={},
                  status=200)
    client = TgtgClient(email="*****@*****.**", password="******")
    assert client.get_item(1) == {}
    assert (len([
        call for call in responses.calls
        if API_ITEM_ENDPOINT in call.request.url
    ]) == 1)
Exemplo n.º 16
0
def test_get_item_success(refresh_tokens_response):
    responses.add(responses.POST,
                  urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1",
                  json={},
                  status=200)
    client = TgtgClient(**tgtg_client_fake_tokens)
    assert client.get_item(1) == {}
    assert (len([
        call for call in responses.calls
        if API_ITEM_ENDPOINT in call.request.url
    ]) == 1)
Exemplo n.º 17
0
    def test_get_items(self):
        passkey = environ.get('REPO_ACCESS_TOKEN')
        username = environ.get("TGTG_USERNAME", None)
        env_file = environ.get('GITHUB_ENV', None)
        timeout = environ.get('TGTG_TIMEOUT', 60)

        if passkey:
            encrypted_access_token = environ.get("TGTG_ACCESS_TOKEN", None)
            encrypted_refresh_token = environ.get("TGTG_REFRESH_TOKEN", None)
            encrypted_user_id = environ.get("TGTG_USER_ID", None)
            access_token = cryptocode.decrypt(
                encrypted_access_token,
                passkey) if encrypted_access_token else None
            refresh_token = cryptocode.decrypt(
                encrypted_refresh_token,
                passkey) if encrypted_refresh_token else None
            user_id = cryptocode.decrypt(
                encrypted_user_id, passkey) if encrypted_user_id else None
        else:
            access_token = environ.get("TGTG_ACCESS_TOKEN", None)
            refresh_token = environ.get("TGTG_REFRESH_TOKEN", None)
            user_id = environ.get("TGTG_USER_ID", None)

        client = TgtgClient(
            email=username,
            timeout=timeout,
            access_token=access_token,
            refresh_token=refresh_token,
            user_id=user_id,
        )

        # get credentials and safe tokens to GITHUB_ENV file
        # this enables github workflow to reuse the access_token on sheduled runs
        # the credentials are encrypted with the REPO_ACCESS_TOKEN
        credentials = client.get_credentials()
        if env_file:
            with open(env_file, "a") as file:
                file.write("TGTG_ACCESS_TOKEN={}\n".format(
                    cryptocode.encrypt(credentials["access_token"], passkey)))
                file.write("TGTG_REFRESH_TOKEN={}\n".format(
                    cryptocode.encrypt(credentials["refresh_token"], passkey)))
                file.write("TGTG_USER_ID={}\n".format(
                    cryptocode.encrypt(credentials["user_id"], passkey)))

        # Tests
        data = client.get_items(favorites_only=True)
        assert len(data) > 0
        for prop in GLOBAL_PROPERTIES:
            assert prop in data[0]
        for prop in ITEM_PROPERTIES:
            assert prop in data[0]["item"]
        for prop in PRICE_PROPERTIES:
            assert prop in data[0]["item"]["price_including_taxes"]
Exemplo n.º 18
0
def test_set_favorite(login_response):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1/setFavorite",
        json={},
        status=200,
    )
    client = TgtgClient(email="*****@*****.**", password="******")
    assert client.set_favorite(1, True) is None
    assert (len([
        call for call in responses.calls
        if API_ITEM_ENDPOINT in call.request.url
    ]) == 1)
Exemplo n.º 19
0
def test_set_favorite(refresh_tokens_response):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT) + "1/setFavorite",
        json={},
        status=200,
    )
    client = TgtgClient(**tgtg_client_fake_tokens)
    assert client.set_favorite(1, True) is None
    assert (len([
        call for call in responses.calls
        if API_ITEM_ENDPOINT in call.request.url
    ]) == 1)
Exemplo n.º 20
0
def test_refresh_token_after_some_time(refresh_tokens_response):
    # login the client for the first time
    client = TgtgClient(**tgtg_client_fake_tokens)
    client.login()
    new_access_token = "new_access_token"
    new_refresh_token = "new_refresh_token"

    responses.replace(
        responses.POST,
        urljoin(BASE_URL, REFRESH_ENDPOINT),
        json={
            "access_token": new_access_token,
            "refresh_token": new_refresh_token
        },
        status=200,
    )

    # token lifetime is ok, no need to refresh
    with freeze_time(datetime.datetime.now() + datetime.timedelta(
            seconds=DEFAULT_ACCESS_TOKEN_LIFETIME)):
        client.login()
        assert client.access_token != new_access_token
        assert client.refresh_token != new_refresh_token

    # token lifetime expired, refresh needed
    with freeze_time(datetime.datetime.now() + datetime.timedelta(
            seconds=DEFAULT_ACCESS_TOKEN_LIFETIME + 1)):
        client.login()
        assert client.access_token == new_access_token
        assert client.refresh_token == new_refresh_token
Exemplo n.º 21
0
    def test_get_items(self):
        username = environ.get("TGTG_USERNAME", None)
        timeout = environ.get("TGTG_TIMEOUT", 60)
        access_token = environ.get("TGTG_ACCESS_TOKEN", None)
        refresh_token = environ.get("TGTG_REFRESH_TOKEN", None)
        user_id = environ.get("TGTG_USER_ID", None)

        client = TgtgClient(
            email=username,
            timeout=timeout,
            access_token=access_token,
            refresh_token=refresh_token,
            user_id=user_id,
        )

        # Tests
        items = client.get_items(favorites_only=True)
        assert len(items) > 0
        item = items[0]
        item_id = item["item"]["item_id"]
        for prop in GLOBAL_PROPERTIES:
            assert prop in item
        for prop in ITEM_PROPERTIES:
            assert prop in item["item"]
        for prop in PRICE_PROPERTIES:
            assert prop in item["item"]["price_including_taxes"]

        client.set_favorite(item_id, False)
        client.set_favorite(item_id, True)

        item = client.get_item(item_id)

        assert item["item"]["item_id"] == item_id
Exemplo n.º 22
0
def test_login_with_tokens():
    responses.add(
        responses.POST,
        urljoin(BASE_URL, REFRESH_ENDPOINT),
        json={
            "access_token": "test",
            "refresh_token": "test_",
        },
        status=200,
    )
    client = TgtgClient(**tgtg_client_fake_tokens)
    client.login()
    assert client.access_token == "test"
    assert client.refresh_token == "test_"
Exemplo n.º 23
0
def test_login_with_email_password_success(remove_auth_env_var):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, LOGIN_ENDPOINT),
        json={
            "access_token": "an_access_token",
            "startup_data": {"user": {"user_id": 1234}},
        },
        status=200,
    )
    client = TgtgClient(email="*****@*****.**", password="******")
    client._login()
    assert client.access_token == "an_access_token"
    assert client.user_id == 1234
Exemplo n.º 24
0
def test_get_items_custom_user_agent():
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT),
        json={"items": []},
        status=200,
    )
    custom_user_agent = "test"
    client = TgtgClient(access_token="an_access_token",
                        user_id=1234,
                        user_agent=custom_user_agent)
    client.get_items()
    assert len(responses.calls) == 1
    assert responses.calls[0].request.headers[
        "user-agent"] == custom_user_agent
Exemplo n.º 25
0
def test_login_with_email_password_success():
    responses.add(
        responses.POST,
        urljoin(BASE_URL, LOGIN_ENDPOINT),
        json={
            "access_token": "an_access_token",
            "user_id": 1234,
            "language": "en-US",
            "status_code": 1,
        },
        status=200,
    )
    client = TgtgClient(email="*****@*****.**", password="******")
    client._login()
    assert client.access_token == "an_access_token"
    assert client.user_id == 1234
Exemplo n.º 26
0
def test_get_items_custom_user_agent(refresh_tokens_response):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT),
        json={"items": []},
        status=200,
    )
    custom_user_agent = "test"
    client = TgtgClient(**tgtg_client_fake_tokens,
                        user_agent=custom_user_agent)
    client.get_items()
    assert (len([
        call for call in responses.calls
        if API_ITEM_ENDPOINT in call.request.url
    ]) == 1)
    for call in responses.calls:
        assert call.request.headers["user-agent"] == custom_user_agent
Exemplo n.º 27
0
def test_get_items_custom_user_agent(login_response):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, API_ITEM_ENDPOINT),
        json={"items": []},
        status=200,
    )
    custom_user_agent = "test"
    client = TgtgClient(email="*****@*****.**",
                        password="******",
                        user_agent=custom_user_agent)
    client.get_items()
    assert (len([
        call for call in responses.calls
        if API_ITEM_ENDPOINT in call.request.url
    ]) == 1)
    assert responses.calls[0].request.headers[
        "user-agent"] == custom_user_agent
Exemplo n.º 28
0
def test_login_with_bad_email_or_password_fail(remove_auth_env_var):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, LOGIN_ENDPOINT),
        json={"errors": [{"code": "FAILED LOGIN"}]},
        status=403,
    )
    with pytest.raises(TgtgLoginError):
        TgtgClient(email="*****@*****.**", password="******")._login()
Exemplo n.º 29
0
 def __init__(self, notifiers: bool = True):
     self.config = Config(config_file) if path.isfile(
         config_file) else Config()
     if self.config.debug:
         # pylint: disable=E1103
         loggers = [
             logging.getLogger(name)
             for name in logging.root.manager.loggerDict
         ]
         # pylint: enable=E1103
         for logger in loggers:
             logger.setLevel(logging.DEBUG)
         log.info("Debugging mode enabled")
     self.metrics = Metrics()
     self.item_ids = self.config.item_ids
     self.amounts = {}
     try:
         self.tgtg_client = TgtgClient(
             email=self.config.tgtg["username"],
             timeout=self.config.tgtg["timeout"],
             access_token_lifetime=self.config.
             tgtg["access_token_lifetime"],
             max_polling_tries=self.config.tgtg["max_polling_tries"],
             polling_wait_time=self.config.tgtg["polling_wait_time"],
             access_token=self.config.tgtg["access_token"],
             refresh_token=self.config.tgtg["refresh_token"],
             user_id=self.config.tgtg["user_id"])
         self.tgtg_client.login()
         self.config.save_tokens(self.tgtg_client.access_token,
                                 self.tgtg_client.refresh_token,
                                 self.tgtg_client.user_id)
     except TgtgAPIError as err:
         raise err
     except Error as err:
         log.error(err)
         raise TGTGConfigurationError() from err
     if notifiers:
         if self.config.metrics:
             self.metrics.enable_metrics()
         self.notifiers = Notifiers(self.config)
         if not self.config.disable_tests:
             log.info("Sending test Notifications ...")
             self.notifiers.send(self._test_item)
Exemplo n.º 30
0
def test_get_inactive_success(refresh_tokens_response):
    responses.add(
        responses.POST,
        urljoin(BASE_URL, INACTIVE_ORDER_ENDPOINT),
        json={"orders": []},
        status=200,
    )
    client = TgtgClient(**tgtg_client_fake_tokens)
    assert client.get_inactive()["orders"] == []
    assert (
        len(
            [
                call
                for call in responses.calls
                if INACTIVE_ORDER_ENDPOINT in call.request.url
            ]
        )
        == 1
    )