Exemple #1
0
def test_validate_months_are_corrected():
    query = Query(
        dimensions=["month"],
        start_date=dt.date(2021, 4, 2),
        end_date=dt.date(2022, 3, 31),
    )
    query.validate()
    assert query._start_date == dt.date(2021, 4, 1)
    assert query._end_date == dt.date(2022, 3, 1)
    async def retrieve(
        self,
        *,
        dimensions: t.Collection[str] | None = None,
        filters: dict[str, str] | None = None,
        metrics: t.Collection[str] | None = None,
        sort_options: t.Collection[str] | None = None,
        max_results: int = 0,
        start_date: dt.date | None = None,
        end_date: dt.date | None = None,
        currency: str = "USD",
        start_index: int = 1,
        include_historical_data: bool = False,
        skip_validation: bool = False,
        force_authorisation: bool = False,
        skip_update_check: bool = False,
        skip_refresh_check: bool = False,
        token_path: pathlib.Path | str = ".",
        port: int = 8080,
    ) -> Report:
        """Retrieves a report from the YouTube Analytics API.

        Keyword Args:
            dimensions:
                The dimensions to use in the report. Defaults to
                ``None``. If this is ``None``, no dimensions will be
                used.
            filters:
                The filters to use in the report. Defaults to ``None``.
                If this is ``None``, no filters will be used.
            metrics:
                The metrics to use in the report. Defaults to ``None``.
                If this is ``None``, all available metrics for the
                selected report type will be used.
            sort_options:
                The sort options to use in the report. Defaults to
                ``None``. If this is ``None``, no sort options will be
                used.
            max_results:
                The maximum number of results to include in the report.
                Defaults to ``0``. If this is ``0``, no limit will be
                set on the maximum number of results.
            start_date:
                The date from which to begin pulling data. Defaults to
                ``None``. If this is ``None``, this will be set to 28
                days before the end date.
            end_date:
                The date in which to pull data up to. Defaults to
                ``None``. If this is ``None``, this will be set to the
                current date.

                .. warning::
                    Due to the nature of the YouTube Analytics API, some
                    dates may be missing from the report. analytix does
                    not compensate for this, as the number missing is
                    not consistent.

            currency:
                The currency in which financial data will be displayed.
                Defaults to "USD". This **must** be an ISO 4217 currency
                code (such as USD or GBP).
            start_index:
                The first row of the data to include in the report.
                Defaults to ``1``. This value one-indexed, meaning
                setting this to ``1`` will include all rows, and
                setting it to ``10`` will remove the first nine rows.
            include_historical_data:
                Whether to retrieve data from dates earlier than the
                current channel owner assumed ownership of the channel.
                Defaults to ``False``. You only need to worry about this
                if you are not the original owner of the channel.
            skip_validation:
                Whether to skip the validation process. Defaults to
                ``False``.
            force_authorisation:
                Whether to force the (re)authorisation of the client.
                Defaults to ``False``.
            skip_update_check:
                Whether to skip checking for updates. Defaults to
                ``False``.
            skip_refresh_token:
                Whether to skip token refreshing. Defaults to ``False``.
            token_path:
                The path to the token file or the directory the token
                file is or should be stored in. If this is not provided,
                this defaults to the current directory, and if a
                directory is passed, the file is given the name
                "tokens.json".

                .. versionadded:: 3.3.0
            port:
                The port to use for the authorisation webserver when
                using loopback IP address authorisation. Defaults to
                8080. This is ignored if analytix is configured to use
                manual copy/paste authorisation.

                .. versionadded:: 3.4.0

        Returns:
            An instance for working with retrieved data.
        """

        if not skip_update_check and not self._checked_for_update:
            await self.check_for_updates()

        query = Query(
            dimensions,
            filters,
            metrics,
            sort_options,
            max_results,
            start_date,
            end_date,
            currency,
            start_index,
            include_historical_data,
        )

        if not skip_validation:
            query.validate()
        else:
            _log.warning(
                "Skipping validation -- invalid requests will count toward your quota"
            )

        if not self.authorised or force_authorisation:
            await self.authorise(token_path=token_path,
                                 force=force_authorisation,
                                 port=port)

        if (not skip_refresh_check) and await self.needs_refresh():
            await self.refresh_access_token(port=port)

        assert self._tokens is not None
        headers = {"Authorization": f"Bearer {self._tokens.access_token}"}
        resp = await self._session.get(query.url, headers=headers)
        data = resp.json()
        _log.debug(f"Data retrieved: {data}")

        if next(iter(data)) == "error":
            error = data["error"]
            raise errors.APIError(error["code"], error["message"])

        if not query.rtype:
            query.set_report_type()

        assert query.rtype is not None
        report = Report(data, query.rtype)
        _log.info(f"Created report of shape {report.shape}!")
        return report
Exemple #3
0
def test_validate_start_index():
    query = Query(start_index=0)
    with pytest.raises(InvalidRequest) as exc:
        query.validate()
    assert str(exc.value) == "the start index should be positive"
Exemple #4
0
def test_validate_currency():
    query = Query(currency="LOL")
    with pytest.raises(InvalidRequest) as exc:
        query.validate()
    assert str(exc.value) == "expected a valid ISO 4217 currency code"
Exemple #5
0
def test_validate_end_date_gt_start_date():
    query = Query(end_date=dt.date(2021, 1, 1), start_date=dt.date(2021, 1, 2))
    with pytest.raises(InvalidRequest) as exc:
        query.validate()
    assert str(
        exc.value) == "the start date should be earlier than the end date"
Exemple #6
0
def test_validate_end_date_is_date():
    query = Query(end_date="2021-01-01", start_date=dt.date(2021, 1, 1))
    with pytest.raises(InvalidRequest) as exc:
        query.validate()
    assert str(exc.value) == "expected end date as date object"
Exemple #7
0
def test_validate_start_date_is_date():
    query = Query(start_date="2021-01-01")
    with pytest.raises(InvalidRequest) as exc:
        query.validate()
    assert str(exc.value) == "expected start date as date object"
Exemple #8
0
def test_validate_max_results():
    query = Query(max_results=-1)
    with pytest.raises(InvalidRequest) as exc:
        query.validate()
    assert (str(exc.value) ==
            "the max results should be non-negative (0 for unlimited results)")