Esempio n. 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)
Esempio n. 2
0
def test_determine_top_videos_playback_detail():
    query = Query(
        dimensions=["video"],
        filters={
            "subscribedStatus": "SUBSCRIBED",
            "youtubeProduct": "CORE"
        },
    )
    assert isinstance(query.determine_report_type(),
                      rt.TopVideosPlaybackDetail)
Esempio n. 3
0
def test_determine_top_videos_youtube_product():
    query = Query(
        dimensions=["video"],
        filters={
            "subscribedStatus": "SUBSCRIBED",
            "youtubeProduct": "CORE"
        },
        metrics=["averageViewPercentage"],
    )
    assert isinstance(query.determine_report_type(),
                      rt.TopVideosYouTubeProduct)
Esempio n. 4
0
async def query() -> Query:
    return Query(
        dimensions=["day", "country"],
        filters={
            "continent": "002",
            "deviceType": "MOBILE"
        },
        metrics=["views", "likes", "comments"],
        sort_options=["shares", "dislikes"],
        start_date=dt.date(2021, 1, 1),
        end_date=dt.date(2021, 12, 31),
    )
Esempio n. 5
0
def test_create_defaults():
    query = Query()
    assert query.dimensions == ()
    assert query.filters == {}
    assert query.metrics == ()
    assert query.sort_options == ()
    assert query.max_results == 0
    assert query._start_date == dt.date.today() - dt.timedelta(days=28)
    assert query._end_date == dt.date.today()
    assert query.currency == "USD"
    assert query.start_index == 1
    assert query._include_historical_data == False
    assert query.rtype is None
Esempio n. 6
0
def test_create_custom():
    query = Query(
        dimensions=["day", "country"],
        filters={"continent": "002"},
        metrics=["views", "likes", "comments"],
        sort_options=["shares", "dislikes"],
        max_results=200,
        start_date=dt.date(2021, 1, 1),
        end_date=dt.date(2021, 12, 31),
        currency="GBP",
        start_index=10,
        include_historical_data=True,
    )
    assert query.dimensions == ["day", "country"]
    assert query.filters == {"continent": "002"}
    assert query.metrics == ["views", "likes", "comments"]
    assert query.sort_options == ["shares", "dislikes"]
    assert query.max_results == 200
    assert query._start_date == dt.date(2021, 1, 1)
    assert query._end_date == dt.date(2021, 12, 31)
    assert query.currency == "GBP"
    assert query.start_index == 10
    assert query._include_historical_data == True
    assert query.rtype is None
Esempio n. 7
0
def test_determine_time_based_activity_2():
    query = Query(dimensions=["month"])
    assert isinstance(query.determine_report_type(), rt.TimeBasedActivity)
Esempio n. 8
0
def test_determine_subscribed_status():
    query = Query(dimensions=["subscribedStatus"])
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsSubscribedStatus)
Esempio n. 9
0
def test_determine_subscribed_status_us():
    query = Query(dimensions=["subscribedStatus"],
                  filters={"province": "US-OH"})
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsSubscribedStatusUS)
Esempio n. 10
0
def test_determine_playback_details_view_percentage_geography_based_3():
    query = Query(dimensions=["country", "youtubeProduct"])
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsViewPercentageGeographyBased)
Esempio n. 11
0
def test_determine_playback_details_live_time_based_4():
    query = Query(filters={"liveOrOnDemand": "LIVE"})
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsLiveTimeBased)
Esempio n. 12
0
def test_determine_basic_user_activity_playlist():
    query = Query(filters={"isCurated": "1"})
    assert isinstance(query.determine_report_type(),
                      rt.BasicUserActivityPlaylist)
Esempio n. 13
0
def test_determine_basic_user_activity():
    query = Query()
    assert isinstance(query.determine_report_type(), rt.BasicUserActivity)
Esempio n. 14
0
def test_determine_playback_details_view_percentage_geography_based_us_4():
    query = Query(dimensions=["province"], filters={"youtubeProduct": "CORE"})
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsViewPercentageGeographyBasedUS)
Esempio n. 15
0
def test_determine_top_videos_regional():
    query = Query(dimensions=["video"])
    assert isinstance(query.determine_report_type(), rt.TopVideosRegional)
Esempio n. 16
0
def test_determine_geography_based_activity_us_playlist():
    query = Query(dimensions=["province"], filters={"isCurated": "1"})
    assert isinstance(query.determine_report_type(),
                      rt.GeographyBasedActivityUSPlaylist)
Esempio n. 17
0
def test_determine_playback_details_view_percentage_geography_based_us_2():
    query = Query(dimensions=["province"],
                  filters={"subscribedStatus": "SUBSCRIBED"})
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsViewPercentageGeographyBasedUS)
Esempio n. 18
0
def test_determine_playback_details_live_geography_based_us_2():
    query = Query(dimensions=["province"], filters={"liveOrOnDemand": "LIVE"})
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsLiveGeographyBasedUS)
Esempio n. 19
0
def test_determine_playback_details_live_geography_based_1():
    query = Query(dimensions=["country", "liveOrOnDemand"])
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsLiveGeographyBased)
Esempio n. 20
0
def test_determine_geography_based_activity():
    query = Query(dimensions=["country"])
    assert isinstance(query.determine_report_type(), rt.GeographyBasedActivity)
Esempio n. 21
0
def test_determine_time_based_activity_playlist_2():
    query = Query(dimensions=["month"], filters={"isCurated": "1"})
    assert isinstance(query.determine_report_type(),
                      rt.TimeBasedActivityPlaylist)
Esempio n. 22
0
def test_determine_top_videos_subscribed():
    query = Query(dimensions=["video"],
                  filters={"subscribedStatus": "SUBSCRIBED"})
    assert isinstance(query.determine_report_type(), rt.TopVideosSubscribed)
Esempio n. 23
0
def test_determine_time_based_activity_us_2():
    query = Query(dimensions=["month"], filters={"province": "US-OH"})
    assert isinstance(query.determine_report_type(), rt.TimeBasedActivityUS)
Esempio n. 24
0
def test_determine_playback_details_view_percentage_time_based_2():
    query = Query(filters={"youtubeProduct": "CORE"})
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsViewPercentageTimeBased)
Esempio n. 25
0
def test_determine_basic_user_activity_us():
    query = Query(filters={"province": "US-OH"})
    assert isinstance(query.determine_report_type(), rt.BasicUserActivityUS)
Esempio n. 26
0
def test_determine_playback_details_live_time_based_3():
    query = Query(dimensions=["liveOrOnDemand"])
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsLiveTimeBased)
Esempio n. 27
0
def test_determine_geography_based_activity_us():
    query = Query(dimensions=["province"])
    assert isinstance(query.determine_report_type(),
                      rt.GeographyBasedActivityUS)
Esempio n. 28
0
def test_determine_playback_details_view_percentage_geography_based_1():
    query = Query(dimensions=["country", "subscribedStatus"])
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsViewPercentageGeographyBased)
Esempio n. 29
0
    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
Esempio n. 30
0
def test_determine_playback_details_view_percentage_time_based_1():
    query = Query(dimensions=["youtubeProduct"])
    assert isinstance(query.determine_report_type(),
                      rt.PlaybackDetailsViewPercentageTimeBased)