From c9ce9962499e22a1e776806d0bb1acc24b1ca434 Mon Sep 17 00:00:00 2001
From: Samive
Date: Wed, 1 Apr 2026 10:32:02 +0800
Subject: [PATCH] initial commit
---
.dockerignore | 14 +
.gitignore | 4 +
Dockerfile | 19 +
README.md | 2533 +----------------
test/__init__.py | 0
test/conftest.py | 94 -
test/helper.py | 384 ---
test/parameters.json | 48 -
test/test_InfoExtractor.py | 2168 --------------
test/test_YoutubeDL.py | 1367 ---------
test/test_YoutubeDLCookieJar.py | 66 -
test/test_aes.py | 163 --
test/test_age_restriction.py | 55 -
test/test_all_urls.py | 122 -
test/test_cache.py | 57 -
test/test_compat.py | 104 -
test/test_config.py | 227 --
test/test_cookies.py | 357 ---
test/test_devalue.py | 239 --
test/test_download.py | 309 --
test/test_downloader_external.py | 139 -
test/test_downloader_http.py | 105 -
test/test_execution.py | 60 -
test/test_http_proxy.py | 378 ---
test/test_jsc/conftest.py | 60 -
test/test_jsc/test_ejs_integration.py | 153 -
test/test_jsc/test_provider.py | 194 --
test/test_jsinterp.py | 576 ----
test/test_netrc.py | 28 -
test/test_networking.py | 2220 ---------------
test/test_networking_utils.py | 207 --
test/test_overwrites.py | 54 -
test/test_plugins.py | 246 --
test/test_post_hooks.py | 70 -
test/test_postprocessors.py | 636 -----
test/test_pot/conftest.py | 71 -
test/test_pot/test_pot_builtin_memorycache.py | 117 -
test/test_pot/test_pot_builtin_utils.py | 52 -
test/test_pot/test_pot_builtin_webpospec.py | 92 -
test/test_pot/test_pot_director.py | 1529 ----------
test/test_pot/test_pot_framework.py | 639 -----
test/test_socks.py | 476 ----
test/test_subtitles.py | 418 ---
test/test_traversal.py | 638 -----
test/test_update.py | 305 --
test/test_utils.py | 2248 ---------------
test/test_verbose_output.py | 75 -
test/test_websockets.py | 517 ----
test/test_youtube_lists.py | 71 -
test/test_youtube_misc.py | 26 -
test/testcert.pem | 52 -
test/testdata/certificate/ca.crt | 10 -
test/testdata/certificate/ca.key | 5 -
test/testdata/certificate/ca.srl | 1 -
test/testdata/certificate/client.crt | 9 -
test/testdata/certificate/client.csr | 7 -
test/testdata/certificate/client.key | 5 -
test/testdata/certificate/clientencrypted.key | 8 -
.../certificate/clientwithencryptedkey.crt | 17 -
test/testdata/certificate/clientwithkey.crt | 14 -
test/testdata/certificate/instructions.md | 19 -
test/testdata/cookies/httponly_cookies.txt | 6 -
test/testdata/cookies/malformed_cookies.txt | 9 -
test/testdata/cookies/session_cookies.txt | 6 -
test/testdata/f4m/custom_base_url.f4m | 10 -
test/testdata/ism/ec-3_test.Manifest | 1 -
test/testdata/ism/sintel.Manifest | 988 -------
test/testdata/m3u8/bipbop_16x9.m3u8 | 38 -
.../m3u8/img_bipbop_adv_example_fmp4.m3u8 | 76 -
test/testdata/mpd/float_duration.mpd | 18 -
test/testdata/mpd/subtitles.mpd | 351 ---
test/testdata/mpd/unfragmented.mpd | 28 -
test/testdata/mpd/urls_only.mpd | 218 --
test/testdata/netrc/netrc | 4 -
test/testdata/netrc/print_netrc.py | 2 -
.../yt_dlp_plugins/extractor/package.py | 6 -
.../yt_dlp_plugins/extractor/normal.py | 10 -
.../yt_dlp_plugins/postprocessor/normal.py | 5 -
.../thumbnails/foo %d bar/placeholder | 0
test/testdata/xspf/foo_xspf.xspf | 34 -
.../yt_dlp_plugins/extractor/_ignore.py | 5 -
.../yt_dlp_plugins/extractor/ignore.py | 13 -
.../yt_dlp_plugins/extractor/normal.py | 11 -
.../yt_dlp_plugins/extractor/override.py | 5 -
.../yt_dlp_plugins/extractor/overridetwo.py | 5 -
.../yt_dlp_plugins/postprocessor/normal.py | 5 -
.../yt_dlp_plugins/extractor/zipped.py | 6 -
.../yt_dlp_plugins/postprocessor/zipped.py | 5 -
web/.dockerignore | 8 +
web/README.md | 24 +
web/backend/main.py | 288 ++
web/backend/requirements.txt | 3 +
web/frontend/app.js | 309 ++
web/frontend/index.html | 135 +
web/frontend/style.css | 380 +++
95 files changed, 1291 insertions(+), 22598 deletions(-)
create mode 100644 .dockerignore
create mode 100644 Dockerfile
delete mode 100644 test/__init__.py
delete mode 100644 test/conftest.py
delete mode 100644 test/helper.py
delete mode 100644 test/parameters.json
delete mode 100644 test/test_InfoExtractor.py
delete mode 100644 test/test_YoutubeDL.py
delete mode 100644 test/test_YoutubeDLCookieJar.py
delete mode 100644 test/test_aes.py
delete mode 100644 test/test_age_restriction.py
delete mode 100644 test/test_all_urls.py
delete mode 100644 test/test_cache.py
delete mode 100644 test/test_compat.py
delete mode 100644 test/test_config.py
delete mode 100644 test/test_cookies.py
delete mode 100644 test/test_devalue.py
delete mode 100755 test/test_download.py
delete mode 100644 test/test_downloader_external.py
delete mode 100644 test/test_downloader_http.py
delete mode 100644 test/test_execution.py
delete mode 100644 test/test_http_proxy.py
delete mode 100644 test/test_jsc/conftest.py
delete mode 100644 test/test_jsc/test_ejs_integration.py
delete mode 100644 test/test_jsc/test_provider.py
delete mode 100644 test/test_jsinterp.py
delete mode 100644 test/test_netrc.py
delete mode 100644 test/test_networking.py
delete mode 100644 test/test_networking_utils.py
delete mode 100644 test/test_overwrites.py
delete mode 100644 test/test_plugins.py
delete mode 100644 test/test_post_hooks.py
delete mode 100644 test/test_postprocessors.py
delete mode 100644 test/test_pot/conftest.py
delete mode 100644 test/test_pot/test_pot_builtin_memorycache.py
delete mode 100644 test/test_pot/test_pot_builtin_utils.py
delete mode 100644 test/test_pot/test_pot_builtin_webpospec.py
delete mode 100644 test/test_pot/test_pot_director.py
delete mode 100644 test/test_pot/test_pot_framework.py
delete mode 100644 test/test_socks.py
delete mode 100644 test/test_subtitles.py
delete mode 100644 test/test_traversal.py
delete mode 100644 test/test_update.py
delete mode 100644 test/test_utils.py
delete mode 100644 test/test_verbose_output.py
delete mode 100644 test/test_websockets.py
delete mode 100644 test/test_youtube_lists.py
delete mode 100644 test/test_youtube_misc.py
delete mode 100644 test/testcert.pem
delete mode 100644 test/testdata/certificate/ca.crt
delete mode 100644 test/testdata/certificate/ca.key
delete mode 100644 test/testdata/certificate/ca.srl
delete mode 100644 test/testdata/certificate/client.crt
delete mode 100644 test/testdata/certificate/client.csr
delete mode 100644 test/testdata/certificate/client.key
delete mode 100644 test/testdata/certificate/clientencrypted.key
delete mode 100644 test/testdata/certificate/clientwithencryptedkey.crt
delete mode 100644 test/testdata/certificate/clientwithkey.crt
delete mode 100644 test/testdata/certificate/instructions.md
delete mode 100644 test/testdata/cookies/httponly_cookies.txt
delete mode 100644 test/testdata/cookies/malformed_cookies.txt
delete mode 100644 test/testdata/cookies/session_cookies.txt
delete mode 100644 test/testdata/f4m/custom_base_url.f4m
delete mode 100644 test/testdata/ism/ec-3_test.Manifest
delete mode 100644 test/testdata/ism/sintel.Manifest
delete mode 100644 test/testdata/m3u8/bipbop_16x9.m3u8
delete mode 100644 test/testdata/m3u8/img_bipbop_adv_example_fmp4.m3u8
delete mode 100644 test/testdata/mpd/float_duration.mpd
delete mode 100644 test/testdata/mpd/subtitles.mpd
delete mode 100644 test/testdata/mpd/unfragmented.mpd
delete mode 100644 test/testdata/mpd/urls_only.mpd
delete mode 100644 test/testdata/netrc/netrc
delete mode 100644 test/testdata/netrc/print_netrc.py
delete mode 100644 test/testdata/plugin_packages/testpackage/yt_dlp_plugins/extractor/package.py
delete mode 100644 test/testdata/reload_plugins/yt_dlp_plugins/extractor/normal.py
delete mode 100644 test/testdata/reload_plugins/yt_dlp_plugins/postprocessor/normal.py
delete mode 100644 test/testdata/thumbnails/foo %d bar/placeholder
delete mode 100644 test/testdata/xspf/foo_xspf.xspf
delete mode 100644 test/testdata/yt_dlp_plugins/extractor/_ignore.py
delete mode 100644 test/testdata/yt_dlp_plugins/extractor/ignore.py
delete mode 100644 test/testdata/yt_dlp_plugins/extractor/normal.py
delete mode 100644 test/testdata/yt_dlp_plugins/extractor/override.py
delete mode 100644 test/testdata/yt_dlp_plugins/extractor/overridetwo.py
delete mode 100644 test/testdata/yt_dlp_plugins/postprocessor/normal.py
delete mode 100644 test/testdata/zipped_plugins/yt_dlp_plugins/extractor/zipped.py
delete mode 100644 test/testdata/zipped_plugins/yt_dlp_plugins/postprocessor/zipped.py
create mode 100644 web/.dockerignore
create mode 100644 web/README.md
create mode 100644 web/backend/main.py
create mode 100644 web/backend/requirements.txt
create mode 100644 web/frontend/app.js
create mode 100644 web/frontend/index.html
create mode 100644 web/frontend/style.css
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 000000000..de223390c
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,14 @@
+web/backend/downloads/
+web/backend/cookies.txt
+web/.dockerignore
+.venv/
+.git/
+__pycache__/
+*.pyc
+*.pyo
+*.egg-info/
+test/
+bundle/
+devscripts/
+*.md
+!README.md
diff --git a/.gitignore b/.gitignore
index afc9dc9c9..0faf54aba 100644
--- a/.gitignore
+++ b/.gitignore
@@ -134,3 +134,7 @@ yt-dlp-plugins
# Packages
yt_dlp_ejs/
+
+# yt-dlp web UI
+web/backend/cookies.txt
+web/backend/downloads/
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 000000000..f95a93a2c
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,19 @@
+FROM python:3.12-slim
+
+# Install ffmpeg for merging video+audio streams
+RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+
+# Install Python dependencies
+RUN pip install --no-cache-dir yt-dlp fastapi "uvicorn[standard]" httpx
+
+# Copy web app
+COPY web/backend ./web/backend
+COPY web/frontend ./web/frontend
+
+RUN mkdir -p /app/web/backend/downloads
+
+EXPOSE 8000
+
+CMD ["python", "-m", "uvicorn", "web.backend.main:app", "--host", "0.0.0.0", "--port", "8000"]
diff --git a/README.md b/README.md
index 915f40a38..d2b1fbcda 100644
--- a/README.md
+++ b/README.md
@@ -1,2493 +1,174 @@
-
-
+# yt-dlp Web UI
-[](#readme)
+A beautiful, self-hosted web application for downloading YouTube (and 1000+ other sites) videos — powered by [yt-dlp](https://github.com/yt-dlp/yt-dlp).
-[](#installation "Installation")
-[](https://pypi.org/project/yt-dlp "PyPI")
-[](Maintainers.md#maintainers "Donate")
-[](https://discord.gg/H5MNcFW63r "Discord")
-[](supportedsites.md "Supported Sites")
-[](LICENSE "License")
-[](https://github.com/yt-dlp/yt-dlp/actions "CI Status")
-[](https://github.com/yt-dlp/yt-dlp/commits "Commit History")
-[](https://github.com/yt-dlp/yt-dlp/pulse/monthly "Last activity")
+
+
+
-
-
+---
-yt-dlp is a feature-rich command-line audio/video downloader with support for [thousands of sites](supportedsites.md). The project is a fork of [youtube-dl](https://github.com/ytdl-org/youtube-dl) based on the now inactive [youtube-dlc](https://github.com/blackjack4494/yt-dlc).
+## Features
-
+- Paste any YouTube (or supported site) URL and fetch video info instantly
+- View thumbnail, title, uploader, duration, views, likes, and upload date
+- Select from all available formats grouped by quality (Video+Audio, Video only, Audio only)
+- Highest quality format pre-selected automatically
+- Live download progress with percentage, speed, and ETA
+- Cancel download at any time
+- Clean dark UI with animated progress bar
-
-* [INSTALLATION](#installation)
- * [Detailed instructions](https://github.com/yt-dlp/yt-dlp/wiki/Installation)
- * [Release Files](#release-files)
- * [Update](#update)
- * [Dependencies](#dependencies)
- * [Compile](#compile)
-* [USAGE AND OPTIONS](#usage-and-options)
- * [General Options](#general-options)
- * [Network Options](#network-options)
- * [Geo-restriction](#geo-restriction)
- * [Video Selection](#video-selection)
- * [Download Options](#download-options)
- * [Filesystem Options](#filesystem-options)
- * [Thumbnail Options](#thumbnail-options)
- * [Internet Shortcut Options](#internet-shortcut-options)
- * [Verbosity and Simulation Options](#verbosity-and-simulation-options)
- * [Workarounds](#workarounds)
- * [Video Format Options](#video-format-options)
- * [Subtitle Options](#subtitle-options)
- * [Authentication Options](#authentication-options)
- * [Post-processing Options](#post-processing-options)
- * [SponsorBlock Options](#sponsorblock-options)
- * [Extractor Options](#extractor-options)
- * [Preset Aliases](#preset-aliases)
-* [CONFIGURATION](#configuration)
- * [Configuration file encoding](#configuration-file-encoding)
- * [Authentication with netrc](#authentication-with-netrc)
- * [Notes about environment variables](#notes-about-environment-variables)
-* [OUTPUT TEMPLATE](#output-template)
- * [Output template examples](#output-template-examples)
-* [FORMAT SELECTION](#format-selection)
- * [Filtering Formats](#filtering-formats)
- * [Sorting Formats](#sorting-formats)
- * [Format Selection examples](#format-selection-examples)
-* [MODIFYING METADATA](#modifying-metadata)
- * [Modifying metadata examples](#modifying-metadata-examples)
-* [EXTRACTOR ARGUMENTS](#extractor-arguments)
-* [PLUGINS](#plugins)
- * [Installing Plugins](#installing-plugins)
- * [Developing Plugins](#developing-plugins)
-* [EMBEDDING YT-DLP](#embedding-yt-dlp)
- * [Embedding examples](#embedding-examples)
-* [CHANGES FROM YOUTUBE-DL](#changes-from-youtube-dl)
- * [New features](#new-features)
- * [Differences in default behavior](#differences-in-default-behavior)
- * [Deprecated options](#deprecated-options)
-* [CONTRIBUTING](CONTRIBUTING.md#contributing-to-yt-dlp)
- * [Opening an Issue](CONTRIBUTING.md#opening-an-issue)
- * [Developer Instructions](CONTRIBUTING.md#developer-instructions)
-* [WIKI](https://github.com/yt-dlp/yt-dlp/wiki)
- * [FAQ](https://github.com/yt-dlp/yt-dlp/wiki/FAQ)
-
+---
+## Quick Start with Docker
-# INSTALLATION
-
-
-[](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe)
-[](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp)
-[](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos)
-[](https://pypi.org/project/yt-dlp)
-[](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.tar.gz)
-[](#release-files)
-[](https://github.com/yt-dlp/yt-dlp/releases)
-
-
-You can install yt-dlp using [the binaries](#release-files), [pip](https://pypi.org/project/yt-dlp) or one using a third-party package manager. See [the wiki](https://github.com/yt-dlp/yt-dlp/wiki/Installation) for detailed instructions
-
-
-
-## RELEASE FILES
-
-#### Recommended
-
-File|Description
-:---|:---
-[yt-dlp](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp)|Platform-independent [zipimport](https://docs.python.org/3/library/zipimport.html) binary. Needs Python (recommended for **Linux/BSD**)
-[yt-dlp.exe](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe)|Windows (Win8+) standalone x64 binary (recommended for **Windows**)
-[yt-dlp_macos](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos)|Universal MacOS (10.15+) standalone executable (recommended for **MacOS**)
-
-#### Alternatives
-
-File|Description
-:---|:---
-[yt-dlp_linux](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux)|Linux (glibc 2.17+) standalone x86_64 binary
-[yt-dlp_linux.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux.zip)|Unpackaged Linux (glibc 2.17+) x86_64 executable (no auto-update)
-[yt-dlp_linux_aarch64](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_aarch64)|Linux (glibc 2.17+) standalone aarch64 binary
-[yt-dlp_linux_aarch64.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_aarch64.zip)|Unpackaged Linux (glibc 2.17+) aarch64 executable (no auto-update)
-[yt-dlp_linux_armv7l.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_armv7l.zip)|Unpackaged Linux (glibc 2.31+) armv7l executable (no auto-update)
-[yt-dlp_musllinux](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_musllinux)|Linux (musl 1.2+) standalone x86_64 binary
-[yt-dlp_musllinux.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_musllinux.zip)|Unpackaged Linux (musl 1.2+) x86_64 executable (no auto-update)
-[yt-dlp_musllinux_aarch64](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_musllinux_aarch64)|Linux (musl 1.2+) standalone aarch64 binary
-[yt-dlp_musllinux_aarch64.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_musllinux_aarch64.zip)|Unpackaged Linux (musl 1.2+) aarch64 executable (no auto-update)
-[yt-dlp_x86.exe](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_x86.exe)|Windows (Win8+) standalone x86 (32-bit) binary
-[yt-dlp_win_x86.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_win_x86.zip)|Unpackaged Windows (Win8+) x86 (32-bit) executable (no auto-update)
-[yt-dlp_arm64.exe](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_arm64.exe)|Windows (Win10+) standalone ARM64 binary
-[yt-dlp_win_arm64.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_win_arm64.zip)|Unpackaged Windows (Win10+) ARM64 executable (no auto-update)
-[yt-dlp_win.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_win.zip)|Unpackaged Windows (Win8+) x64 executable (no auto-update)
-[yt-dlp_macos.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos.zip)|Unpackaged MacOS (10.15+) executable (no auto-update)
-
-#### Misc
-
-File|Description
-:---|:---
-[yt-dlp.tar.gz](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.tar.gz)|Source tarball
-[SHA2-512SUMS](https://github.com/yt-dlp/yt-dlp/releases/latest/download/SHA2-512SUMS)|GNU-style SHA512 sums
-[SHA2-512SUMS.sig](https://github.com/yt-dlp/yt-dlp/releases/latest/download/SHA2-512SUMS.sig)|GPG signature file for SHA512 sums
-[SHA2-256SUMS](https://github.com/yt-dlp/yt-dlp/releases/latest/download/SHA2-256SUMS)|GNU-style SHA256 sums
-[SHA2-256SUMS.sig](https://github.com/yt-dlp/yt-dlp/releases/latest/download/SHA2-256SUMS.sig)|GPG signature file for SHA256 sums
-
-The public key that can be used to verify the GPG signatures is [available here](https://github.com/yt-dlp/yt-dlp/blob/master/public.key)
-Example usage:
-```
-curl -L https://github.com/yt-dlp/yt-dlp/raw/master/public.key | gpg --import
-gpg --verify SHA2-256SUMS.sig SHA2-256SUMS
-gpg --verify SHA2-512SUMS.sig SHA2-512SUMS
-```
-
-#### Licensing
-
-While yt-dlp is licensed under the [Unlicense](LICENSE), many of the release files contain code from other projects with different licenses.
-
-Most notably, the PyInstaller-bundled executables include GPLv3+ licensed code, and as such the combined work is licensed under [GPLv3+](https://www.gnu.org/licenses/gpl-3.0.html).
-
-The zipimport Unix executable (`yt-dlp`) contains [ISC](https://github.com/meriyah/meriyah/blob/main/LICENSE.md) licensed code from [`meriyah`](https://github.com/meriyah/meriyah) and [MIT](https://github.com/davidbonnet/astring/blob/main/LICENSE) licensed code from [`astring`](https://github.com/davidbonnet/astring).
-
-See [THIRD_PARTY_LICENSES.txt](THIRD_PARTY_LICENSES.txt) for more details.
-
-The git repository, the source tarball (`yt-dlp.tar.gz`), the PyPI source distribution and the PyPI built distribution (wheel) only contain code licensed under the [Unlicense](LICENSE).
-
-
-
-**Note**: The manpages, shell completion (autocomplete) files etc. are available inside the [source tarball](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.tar.gz)
-
-
-## UPDATE
-You can use `yt-dlp -U` to update if you are using the [release binaries](#release-files)
-
-If you [installed with pip](https://github.com/yt-dlp/yt-dlp/wiki/Installation#with-pip), simply re-run the same command that was used to install the program
-
-For other third-party package managers, see [the wiki](https://github.com/yt-dlp/yt-dlp/wiki/Installation#third-party-package-managers) or refer to their documentation
-
-
-
-There are currently three release channels for binaries: `stable`, `nightly` and `master`.
-
-* `stable` is the default channel, and many of its changes have been tested by users of the `nightly` and `master` channels.
-* The `nightly` channel has releases scheduled to build every day around midnight UTC, for a snapshot of the project's new patches and changes. This is the **recommended channel for regular users** of yt-dlp. The `nightly` releases are available from [yt-dlp/yt-dlp-nightly-builds](https://github.com/yt-dlp/yt-dlp-nightly-builds/releases) or as development releases of the `yt-dlp` PyPI package (which can be installed with pip's `--pre` flag).
-* The `master` channel features releases that are built after each push to the master branch, and these will have the very latest fixes and additions, but may also be more prone to regressions. They are available from [yt-dlp/yt-dlp-master-builds](https://github.com/yt-dlp/yt-dlp-master-builds/releases).
-
-When using `--update`/`-U`, a release binary will only update to its current channel.
-`--update-to CHANNEL` can be used to switch to a different channel when a newer version is available. `--update-to [CHANNEL@]TAG` can also be used to upgrade or downgrade to specific tags from a channel.
-
-You may also use `--update-to ` (`/`) to update to a channel on a completely different repository. Be careful with what repository you are updating to though, there is no verification done for binaries from different repositories.
-
-Example usage:
-
-* `yt-dlp --update-to master` switch to the `master` channel and update to its latest release
-* `yt-dlp --update-to stable@2023.07.06` upgrade/downgrade to release to `stable` channel tag `2023.07.06`
-* `yt-dlp --update-to 2023.10.07` upgrade/downgrade to tag `2023.10.07` if it exists on the current channel
-* `yt-dlp --update-to example/yt-dlp@2023.09.24` upgrade/downgrade to the release from the `example/yt-dlp` repository, tag `2023.09.24`
-
-**Important**: Any user experiencing an issue with the `stable` release should install or update to the `nightly` release before submitting a bug report:
-```
-# To update to nightly from stable executable/binary:
-yt-dlp --update-to nightly
-
-# To install nightly with pip:
-python -m pip install -U --pre "yt-dlp[default]"
-```
-
-When running a yt-dlp version that is older than 90 days, you will see a warning message suggesting to update to the latest version.
-You can suppress this warning by adding `--no-update` to your command or configuration file.
-
-## DEPENDENCIES
-Python versions 3.10+ (CPython) and 3.11+ (PyPy) are supported. Other versions and implementations may or may not work correctly.
-
-
-
-While all the other dependencies are optional, `ffmpeg`, `ffprobe`, `yt-dlp-ejs` and a supported JavaScript runtime/engine are highly recommended
-
-### Strongly recommended
-
-* [**ffmpeg** and **ffprobe**](https://www.ffmpeg.org) - Required for [merging separate video and audio files](#format-selection), as well as for various [post-processing](#post-processing-options) tasks. License [depends on the build](https://www.ffmpeg.org/legal.html)
-
- There are bugs in ffmpeg that cause various issues when used alongside yt-dlp. Since ffmpeg is such an important dependency, we provide [custom builds](https://github.com/yt-dlp/FFmpeg-Builds#ffmpeg-static-auto-builds) with patches for some of these issues at [yt-dlp/FFmpeg-Builds](https://github.com/yt-dlp/FFmpeg-Builds). See [the readme](https://github.com/yt-dlp/FFmpeg-Builds#patches-applied) for details on the specific issues solved by these builds
-
- **Important**: What you need is ffmpeg *binary*, **NOT** [the Python package of the same name](https://pypi.org/project/ffmpeg)
-
-* [**yt-dlp-ejs**](https://github.com/yt-dlp/ejs) - Required for full YouTube support. Licensed under [Unlicense](https://github.com/yt-dlp/ejs/blob/main/LICENSE), bundles [MIT](https://github.com/davidbonnet/astring/blob/main/LICENSE) and [ISC](https://github.com/meriyah/meriyah/blob/main/LICENSE.md) components.
-
- A JavaScript runtime/engine like [**deno**](https://deno.land) (recommended), [**node.js**](https://nodejs.org), [**bun**](https://bun.sh), or [**QuickJS**](https://bellard.org/quickjs/) is also required to run yt-dlp-ejs. See [the wiki](https://github.com/yt-dlp/yt-dlp/wiki/EJS).
-
-### Networking
-* [**certifi**](https://github.com/certifi/python-certifi)\* - Provides Mozilla's root certificate bundle. Licensed under [MPLv2](https://github.com/certifi/python-certifi/blob/master/LICENSE)
-* [**brotli**](https://github.com/google/brotli)\* or [**brotlicffi**](https://github.com/python-hyper/brotlicffi) - [Brotli](https://en.wikipedia.org/wiki/Brotli) content encoding support. Both licensed under MIT [1](https://github.com/google/brotli/blob/master/LICENSE) [2](https://github.com/python-hyper/brotlicffi/blob/master/LICENSE)
-* [**websockets**](https://github.com/aaugustin/websockets)\* - For downloading over websocket. Licensed under [BSD-3-Clause](https://github.com/aaugustin/websockets/blob/main/LICENSE)
-* [**requests**](https://github.com/psf/requests)\* - HTTP library. For HTTPS proxy and persistent connections support. Licensed under [Apache-2.0](https://github.com/psf/requests/blob/main/LICENSE)
-
-#### Impersonation
-
-The following provide support for impersonating browser requests. This may be required for some sites that employ TLS fingerprinting.
-
-* [**curl_cffi**](https://github.com/lexiforest/curl_cffi) (recommended) - Python binding for [curl-impersonate](https://github.com/lexiforest/curl-impersonate). Provides impersonation targets for Chrome, Edge and Safari. Licensed under [MIT](https://github.com/lexiforest/curl_cffi/blob/main/LICENSE)
- * Can be installed with the `curl-cffi` extra, e.g. `pip install "yt-dlp[default,curl-cffi]"`
- * Currently included in most builds *except* `yt-dlp` (Unix zipimport binary), `yt-dlp_x86` (Windows 32-bit) and `yt-dlp_musllinux_aarch64`
-
-
-### Metadata
-
-* [**mutagen**](https://github.com/quodlibet/mutagen)\* - For `--embed-thumbnail` in certain formats. Licensed under [GPLv2+](https://github.com/quodlibet/mutagen/blob/master/COPYING)
-* [**AtomicParsley**](https://github.com/wez/atomicparsley) - For `--embed-thumbnail` in `mp4`/`m4a` files when `mutagen`/`ffmpeg` cannot. Licensed under [GPLv2+](https://github.com/wez/atomicparsley/blob/master/COPYING)
-* [**xattr**](https://github.com/xattr/xattr), [**pyxattr**](https://github.com/iustin/pyxattr) or [**setfattr**](http://savannah.nongnu.org/projects/attr) - For writing xattr metadata (`--xattrs`) on **Mac** and **BSD**. Licensed under [MIT](https://github.com/xattr/xattr/blob/master/LICENSE.txt), [LGPL2.1](https://github.com/iustin/pyxattr/blob/master/COPYING) and [GPLv2+](http://git.savannah.nongnu.org/cgit/attr.git/tree/doc/COPYING) respectively
-
-### Misc
-
-* [**pycryptodomex**](https://github.com/Legrandin/pycryptodome)\* - For decrypting AES-128 HLS streams and various other data. Licensed under [BSD-2-Clause](https://github.com/Legrandin/pycryptodome/blob/master/LICENSE.rst)
-* [**phantomjs**](https://github.com/ariya/phantomjs) - Used in some extractors where JavaScript needs to be run. No longer used for YouTube. To be deprecated in the near future. Licensed under [BSD-3-Clause](https://github.com/ariya/phantomjs/blob/master/LICENSE.BSD)
-* [**secretstorage**](https://github.com/mitya57/secretstorage)\* - For `--cookies-from-browser` to access the **Gnome** keyring while decrypting cookies of **Chromium**-based browsers on **Linux**. Licensed under [BSD-3-Clause](https://github.com/mitya57/secretstorage/blob/master/LICENSE)
-* Any external downloader that you want to use with `--downloader`
-
-### Deprecated
-
-* [**rtmpdump**](http://rtmpdump.mplayerhq.hu) - For downloading `rtmp` streams. ffmpeg can be used instead with `--downloader ffmpeg`. Licensed under [GPLv2+](http://rtmpdump.mplayerhq.hu)
-* [**mplayer**](http://mplayerhq.hu/design7/info.html) or [**mpv**](https://mpv.io) - For downloading `rstp`/`mms` streams. ffmpeg can be used instead with `--downloader ffmpeg`. Licensed under [GPLv2+](https://github.com/mpv-player/mpv/blob/master/Copyright)
-
-To use or redistribute the dependencies, you must agree to their respective licensing terms.
-
-The standalone release binaries are built with the Python interpreter and the packages marked with **\*** included.
-
-If you do not have the necessary dependencies for a task you are attempting, yt-dlp will warn you. All the currently available dependencies are visible at the top of the `--verbose` output
-
-
-## COMPILE
-
-### Standalone PyInstaller Builds
-To build the standalone executable, you must have Python and `pyinstaller` (plus any of yt-dlp's [optional dependencies](#dependencies) if needed). The executable will be built for the same CPU architecture as the Python used.
-
-You can run the following commands:
-
-```
-python devscripts/install_deps.py --include-group pyinstaller
-python devscripts/make_lazy_extractors.py
-python -m bundle.pyinstaller
-```
-
-On some systems, you may need to use `py` or `python3` instead of `python`.
-
-`python -m bundle.pyinstaller` accepts any arguments that can be passed to `pyinstaller`, such as `--onefile/-F` or `--onedir/-D`, which is further [documented here](https://pyinstaller.org/en/stable/usage.html#what-to-generate).
-
-**Note**: Pyinstaller versions below 4.4 [do not support](https://github.com/pyinstaller/pyinstaller#requirements-and-tested-platforms) Python installed from the Windows store without using a virtual environment.
-
-**Important**: Running `pyinstaller` directly **instead of** using `python -m bundle.pyinstaller` is **not** officially supported. This may or may not work correctly.
-
-### Platform-independent Binary (UNIX)
-You will need the build tools `python` (3.10+), `zip`, `make` (GNU), `pandoc`\* and `pytest`\*.
-
-After installing these, simply run `make`.
-
-You can also run `make yt-dlp` instead to compile only the binary without updating any of the additional files. (The build tools marked with **\*** are not needed for this)
-
-### Related scripts
-
-* **`devscripts/install_deps.py`** - Install dependencies for yt-dlp.
-* **`devscripts/update-version.py`** - Update the version number based on the current date.
-* **`devscripts/set-variant.py`** - Set the build variant of the executable.
-* **`devscripts/make_changelog.py`** - Create a markdown changelog using short commit messages and update `CONTRIBUTORS` file.
-* **`devscripts/make_lazy_extractors.py`** - Create lazy extractors. Running this before building the binaries (any variant) will improve their startup performance. Set the environment variable `YTDLP_NO_LAZY_EXTRACTORS` to something nonempty to forcefully disable lazy extractor loading.
-
-Note: See their `--help` for more info.
-
-### Forking the project
-If you fork the project on GitHub, you can run your fork's [build workflow](.github/workflows/build.yml) to automatically build the selected version(s) as artifacts. Alternatively, you can run the [release workflow](.github/workflows/release.yml) or enable the [nightly workflow](.github/workflows/release-nightly.yml) to create full (pre-)releases.
-
-# USAGE AND OPTIONS
-
-
- yt-dlp [OPTIONS] [--] URL [URL...]
-
-Tip: Use `CTRL`+`F` (or `Command`+`F`) to search by keywords
-
-
-
-## General Options:
- -h, --help Print this help text and exit
- --version Print program version and exit
- -U, --update Update this program to the latest version
- --no-update Do not check for updates (default)
- --update-to [CHANNEL]@[TAG] Upgrade/downgrade to a specific version.
- CHANNEL can be a repository as well. CHANNEL
- and TAG default to "stable" and "latest"
- respectively if omitted; See "UPDATE" for
- details. Supported channels: stable,
- nightly, master
- -i, --ignore-errors Ignore download and postprocessing errors.
- The download will be considered successful
- even if the postprocessing fails
- --no-abort-on-error Continue with next video on download errors;
- e.g. to skip unavailable videos in a
- playlist (default)
- --abort-on-error Abort downloading of further videos if an
- error occurs (Alias: --no-ignore-errors)
- --list-extractors List all supported extractors and exit
- --extractor-descriptions Output descriptions of all supported
- extractors and exit
- --use-extractors NAMES Extractor names to use separated by commas.
- You can also use regexes, "all", "default"
- and "end" (end URL matching); e.g. --ies
- "holodex.*,end,youtube". Prefix the name
- with a "-" to exclude it, e.g. --ies
- default,-generic. Use --list-extractors for
- a list of extractor names. (Alias: --ies)
- --default-search PREFIX Use this prefix for unqualified URLs. E.g.
- "gvsearch2:python" downloads two videos from
- google videos for the search term "python".
- Use the value "auto" to let yt-dlp guess
- ("auto_warning" to emit a warning when
- guessing). "error" just throws an error. The
- default value "fixup_error" repairs broken
- URLs, but emits an error if this is not
- possible instead of searching
- --ignore-config Don't load any more configuration files
- except those given to --config-locations.
- For backward compatibility, if this option
- is found inside the system configuration
- file, the user configuration is not loaded.
- (Alias: --no-config)
- --no-config-locations Do not load any custom configuration files
- (default). When given inside a configuration
- file, ignore all previous --config-locations
- defined in the current file
- --config-locations PATH Location of the main configuration file;
- either the path to the config or its
- containing directory ("-" for stdin). Can be
- used multiple times and inside other
- configuration files
- --plugin-dirs DIR Path to an additional directory to search
- for plugins. This option can be used
- multiple times to add multiple directories.
- Use "default" to search the default plugin
- directories (default)
- --no-plugin-dirs Clear plugin directories to search,
- including defaults and those provided by
- previous --plugin-dirs
- --js-runtimes RUNTIME[:PATH] Additional JavaScript runtime to enable,
- with an optional location for the runtime
- (either the path to the binary or its
- containing directory). This option can be
- used multiple times to enable multiple
- runtimes. Supported runtimes are (in order
- of priority, from highest to lowest): deno,
- node, quickjs, bun. Only "deno" is enabled
- by default. The highest priority runtime
- that is both enabled and available will be
- used. In order to use a lower priority
- runtime when "deno" is available, --no-js-
- runtimes needs to be passed before enabling
- other runtimes
- --no-js-runtimes Clear JavaScript runtimes to enable,
- including defaults and those provided by
- previous --js-runtimes
- --remote-components COMPONENT Remote components to allow yt-dlp to fetch
- when required. This option is currently not
- needed if you are using an official
- executable or have the requisite version of
- the yt-dlp-ejs package installed. You can
- use this option multiple times to allow
- multiple components. Supported values:
- ejs:npm (external JavaScript components from
- npm), ejs:github (external JavaScript
- components from yt-dlp-ejs GitHub). By
- default, no remote components are allowed
- --no-remote-components Disallow fetching of all remote components,
- including any previously allowed by
- --remote-components or defaults.
- --flat-playlist Do not extract a playlist's URL result
- entries; some entry metadata may be missing
- and downloading may be bypassed
- --no-flat-playlist Fully extract the videos of a playlist
- (default)
- --live-from-start Download livestreams from the start.
- Currently experimental and only supported
- for YouTube, Twitch, and TVer
- --no-live-from-start Download livestreams from the current time
- (default)
- --wait-for-video MIN[-MAX] Wait for scheduled streams to become
- available. Pass the minimum number of
- seconds (or range) to wait between retries
- --no-wait-for-video Do not wait for scheduled streams (default)
- --mark-watched Mark videos watched (even with --simulate)
- --no-mark-watched Do not mark videos watched (default)
- --color [STREAM:]POLICY Whether to emit color codes in output,
- optionally prefixed by the STREAM (stdout or
- stderr) to apply the setting to. Can be one
- of "always", "auto" (default), "never", or
- "no_color" (use non color terminal
- sequences). Use "auto-tty" or "no_color-tty"
- to decide based on terminal support only.
- Can be used multiple times
- --compat-options OPTS Options that can help keep compatibility
- with youtube-dl or youtube-dlc
- configurations by reverting some of the
- changes made in yt-dlp. See "Differences in
- default behavior" for details
- --alias ALIASES OPTIONS Create aliases for an option string. Unless
- an alias starts with a dash "-", it is
- prefixed with "--". Arguments are parsed
- according to the Python string formatting
- mini-language. E.g. --alias get-audio,-X "-S
- aext:{0},abr -x --audio-format {0}" creates
- options "--get-audio" and "-X" that takes an
- argument (ARG0) and expands to "-S
- aext:ARG0,abr -x --audio-format ARG0". All
- defined aliases are listed in the --help
- output. Alias options can trigger more
- aliases; so be careful to avoid defining
- recursive options. As a safety measure, each
- alias may be triggered a maximum of 100
- times. This option can be used multiple times
- -t, --preset-alias PRESET Applies a predefined set of options. e.g.
- --preset-alias mp3. The following presets
- are available: mp3, aac, mp4, mkv, sleep.
- See the "Preset Aliases" section at the end
- for more info. This option can be used
- multiple times
-
-## Network Options:
- --proxy URL Use the specified HTTP/HTTPS/SOCKS proxy. To
- enable SOCKS proxy, specify a proper scheme,
- e.g. socks5://user:pass@127.0.0.1:1080/.
- Pass in an empty string (--proxy "") for
- direct connection
- --socket-timeout SECONDS Time to wait before giving up, in seconds
- --source-address IP Client-side IP address to bind to
- --impersonate CLIENT[:OS] Client to impersonate for requests. E.g.
- chrome, chrome-110, chrome:windows-10. Pass
- --impersonate="" to impersonate any client.
- Note that forcing impersonation for all
- requests may have a detrimental impact on
- download speed and stability
- --list-impersonate-targets List available clients to impersonate.
- -4, --force-ipv4 Make all connections via IPv4
- -6, --force-ipv6 Make all connections via IPv6
- --enable-file-urls Enable file:// URLs. This is disabled by
- default for security reasons.
-
-## Geo-restriction:
- --geo-verification-proxy URL Use this proxy to verify the IP address for
- some geo-restricted sites. The default proxy
- specified by --proxy (or none, if the option
- is not present) is used for the actual
- downloading
- --xff VALUE How to fake X-Forwarded-For HTTP header to
- try bypassing geographic restriction. One of
- "default" (only when known to be useful),
- "never", an IP block in CIDR notation, or a
- two-letter ISO 3166-2 country code
-
-## Video Selection:
- -I, --playlist-items ITEM_SPEC Comma-separated playlist_index of the items
- to download. You can specify a range using
- "[START]:[STOP][:STEP]". For backward
- compatibility, START-STOP is also supported.
- Use negative indices to count from the right
- and negative STEP to download in reverse
- order. E.g. "-I 1:3,7,-5::2" used on a
- playlist of size 15 will download the items
- at index 1,2,3,7,11,13,15
- --min-filesize SIZE Abort download if filesize is smaller than
- SIZE, e.g. 50k or 44.6M
- --max-filesize SIZE Abort download if filesize is larger than
- SIZE, e.g. 50k or 44.6M
- --date DATE Download only videos uploaded on this date.
- The date can be "YYYYMMDD" or in the format
- [now|today|yesterday][-N[day|week|month|year]].
- E.g. "--date today-2weeks" downloads only
- videos uploaded on the same day two weeks ago
- --datebefore DATE Download only videos uploaded on or before
- this date. The date formats accepted are the
- same as --date
- --dateafter DATE Download only videos uploaded on or after
- this date. The date formats accepted are the
- same as --date
- --match-filters FILTER Generic video filter. Any "OUTPUT TEMPLATE"
- field can be compared with a number or a
- string using the operators defined in
- "Filtering Formats". You can also simply
- specify a field to match if the field is
- present, use "!field" to check if the field
- is not present, and "&" to check multiple
- conditions. Use a "\" to escape "&" or
- quotes if needed. If used multiple times,
- the filter matches if at least one of the
- conditions is met. E.g. --match-filters
- !is_live --match-filters "like_count>?100 &
- description~='(?i)\bcats \& dogs\b'" matches
- only videos that are not live OR those that
- have a like count more than 100 (or the like
- field is not available) and also has a
- description that contains the phrase "cats &
- dogs" (caseless). Use "--match-filters -" to
- interactively ask whether to download each
- video
- --no-match-filters Do not use any --match-filters (default)
- --break-match-filters FILTER Same as "--match-filters" but stops the
- download process when a video is rejected
- --no-break-match-filters Do not use any --break-match-filters (default)
- --no-playlist Download only the video, if the URL refers
- to a video and a playlist
- --yes-playlist Download the playlist, if the URL refers to
- a video and a playlist
- --age-limit YEARS Download only videos suitable for the given
- age
- --download-archive FILE Download only videos not listed in the
- archive file. Record the IDs of all
- downloaded videos in it
- --no-download-archive Do not use archive file (default)
- --max-downloads NUMBER Abort after downloading NUMBER files
- --break-on-existing Stop the download process when encountering
- a file that is in the archive supplied with
- the --download-archive option
- --no-break-on-existing Do not stop the download process when
- encountering a file that is in the archive
- (default)
- --break-per-input Alters --max-downloads, --break-on-existing,
- --break-match-filters, and autonumber to
- reset per input URL
- --no-break-per-input --break-on-existing and similar options
- terminates the entire download queue
- --skip-playlist-after-errors N Number of allowed failures until the rest of
- the playlist is skipped
-
-## Download Options:
- -N, --concurrent-fragments N Number of fragments of a dash/hlsnative
- video that should be downloaded concurrently
- (default is 1)
- -r, --limit-rate RATE Maximum download rate in bytes per second,
- e.g. 50K or 4.2M
- --throttled-rate RATE Minimum download rate in bytes per second
- below which throttling is assumed and the
- video data is re-extracted, e.g. 100K
- -R, --retries RETRIES Number of retries (default is 10), or
- "infinite"
- --file-access-retries RETRIES Number of times to retry on file access
- error (default is 3), or "infinite"
- --fragment-retries RETRIES Number of retries for a fragment (default is
- 10), or "infinite" (DASH, hlsnative and ISM)
- --retry-sleep [TYPE:]EXPR Time to sleep between retries in seconds
- (optionally) prefixed by the type of retry
- (http (default), fragment, file_access,
- extractor) to apply the sleep to. EXPR can
- be a number, linear=START[:END[:STEP=1]] or
- exp=START[:END[:BASE=2]]. This option can be
- used multiple times to set the sleep for the
- different retry types, e.g. --retry-sleep
- linear=1::2 --retry-sleep fragment:exp=1:20
- --skip-unavailable-fragments Skip unavailable fragments for DASH,
- hlsnative and ISM downloads (default)
- (Alias: --no-abort-on-unavailable-fragments)
- --abort-on-unavailable-fragments
- Abort download if a fragment is unavailable
- (Alias: --no-skip-unavailable-fragments)
- --keep-fragments Keep downloaded fragments on disk after
- downloading is finished
- --no-keep-fragments Delete downloaded fragments after
- downloading is finished (default)
- --buffer-size SIZE Size of download buffer, e.g. 1024 or 16K
- (default is 1024)
- --resize-buffer The buffer size is automatically resized
- from an initial value of --buffer-size
- (default)
- --no-resize-buffer Do not automatically adjust the buffer size
- --http-chunk-size SIZE Size of a chunk for chunk-based HTTP
- downloading, e.g. 10485760 or 10M (default
- is disabled). May be useful for bypassing
- bandwidth throttling imposed by a webserver
- (experimental)
- --playlist-random Download playlist videos in random order
- --lazy-playlist Process entries in the playlist as they are
- received. This disables n_entries,
- --playlist-random and --playlist-reverse
- --no-lazy-playlist Process videos in the playlist only after
- the entire playlist is parsed (default)
- --hls-use-mpegts Use the mpegts container for HLS videos;
- allowing some players to play the video
- while downloading, and reducing the chance
- of file corruption if download is
- interrupted. This is enabled by default for
- live streams
- --no-hls-use-mpegts Do not use the mpegts container for HLS
- videos. This is default when not downloading
- live streams
- --download-sections REGEX Download only chapters that match the
- regular expression. A "*" prefix denotes
- time-range instead of chapter. Negative
- timestamps are calculated from the end.
- "*from-url" can be used to download between
- the "start_time" and "end_time" extracted
- from the URL. Needs ffmpeg. This option can
- be used multiple times to download multiple
- sections, e.g. --download-sections
- "*10:15-inf" --download-sections "intro"
- --downloader [PROTO:]NAME Name or path of the external downloader to
- use (optionally) prefixed by the protocols
- (http, ftp, m3u8, dash, rstp, rtmp, mms) to
- use it for. Currently supports native,
- aria2c, axel, curl, ffmpeg, httpie, wget.
- You can use this option multiple times to
- set different downloaders for different
- protocols. E.g. --downloader aria2c
- --downloader "dash,m3u8:native" will use
- aria2c for http/ftp downloads, and the
- native downloader for dash/m3u8 downloads
- (Alias: --external-downloader)
- --downloader-args NAME:ARGS Give these arguments to the external
- downloader. Specify the downloader name and
- the arguments separated by a colon ":". For
- ffmpeg, arguments can be passed to different
- positions using the same syntax as
- --postprocessor-args. You can use this
- option multiple times to give different
- arguments to different downloaders (Alias:
- --external-downloader-args)
-
-## Filesystem Options:
- -a, --batch-file FILE File containing URLs to download ("-" for
- stdin), one URL per line. Lines starting
- with "#", ";" or "]" are considered as
- comments and ignored
- --no-batch-file Do not read URLs from batch file (default)
- -P, --paths [TYPES:]PATH The paths where the files should be
- downloaded. Specify the type of file and the
- path separated by a colon ":". All the same
- TYPES as --output are supported.
- Additionally, you can also provide "home"
- (default) and "temp" paths. All intermediary
- files are first downloaded to the temp path
- and then the final files are moved over to
- the home path after download is finished.
- This option is ignored if --output is an
- absolute path
- -o, --output [TYPES:]TEMPLATE Output filename template; see "OUTPUT
- TEMPLATE" for details
- --output-na-placeholder TEXT Placeholder for unavailable fields in
- --output (default: "NA")
- --restrict-filenames Restrict filenames to only ASCII characters,
- and avoid "&" and spaces in filenames
- --no-restrict-filenames Allow Unicode characters, "&" and spaces in
- filenames (default)
- --windows-filenames Force filenames to be Windows-compatible
- --no-windows-filenames Sanitize filenames only minimally
- --trim-filenames LENGTH Limit the filename length (excluding
- extension) to the specified number of
- characters
- -w, --no-overwrites Do not overwrite any files
- --force-overwrites Overwrite all video and metadata files. This
- option includes --no-continue
- --no-force-overwrites Do not overwrite the video, but overwrite
- related files (default)
- -c, --continue Resume partially downloaded files/fragments
- (default)
- --no-continue Do not resume partially downloaded
- fragments. If the file is not fragmented,
- restart download of the entire file
- --part Use .part files instead of writing directly
- into output file (default)
- --no-part Do not use .part files - write directly into
- output file
- --mtime Use the Last-modified header to set the file
- modification time
- --no-mtime Do not use the Last-modified header to set
- the file modification time (default)
- --write-description Write video description to a .description file
- --no-write-description Do not write video description (default)
- --write-info-json Write video metadata to a .info.json file
- (this may contain personal information)
- --no-write-info-json Do not write video metadata (default)
- --write-playlist-metafiles Write playlist metadata in addition to the
- video metadata when using --write-info-json,
- --write-description etc. (default)
- --no-write-playlist-metafiles Do not write playlist metadata when using
- --write-info-json, --write-description etc.
- --clean-info-json Remove some internal metadata such as
- filenames from the infojson (default)
- --no-clean-info-json Write all fields to the infojson
- --write-comments Retrieve video comments to be placed in the
- infojson. The comments are fetched even
- without this option if the extraction is
- known to be quick (Alias: --get-comments)
- --no-write-comments Do not retrieve video comments unless the
- extraction is known to be quick (Alias:
- --no-get-comments)
- --load-info-json FILE JSON file containing the video information
- (created with the "--write-info-json" option)
- --cookies FILE Netscape formatted file to read cookies from
- and dump cookie jar in
- --no-cookies Do not read/dump cookies from/to file
- (default)
- --cookies-from-browser BROWSER[+KEYRING][:PROFILE][::CONTAINER]
- The name of the browser to load cookies
- from. Currently supported browsers are:
- brave, chrome, chromium, edge, firefox,
- opera, safari, vivaldi, whale. Optionally,
- the KEYRING used for decrypting Chromium
- cookies on Linux, the name/path of the
- PROFILE to load cookies from, and the
- CONTAINER name (if Firefox) ("none" for no
- container) can be given with their
- respective separators. By default, all
- containers of the most recently accessed
- profile are used. Currently supported
- keyrings are: basictext, gnomekeyring,
- kwallet, kwallet5, kwallet6
- --no-cookies-from-browser Do not load cookies from browser (default)
- --cache-dir DIR Location in the filesystem where yt-dlp can
- store some downloaded information (such as
- client ids and signatures) permanently. By
- default ${XDG_CACHE_HOME}/yt-dlp
- --no-cache-dir Disable filesystem caching
- --rm-cache-dir Delete all filesystem cache files
-
-## Thumbnail Options:
- --write-thumbnail Write thumbnail image to disk
- --no-write-thumbnail Do not write thumbnail image to disk (default)
- --write-all-thumbnails Write all thumbnail image formats to disk
- --list-thumbnails List available thumbnails of each video.
- Simulate unless --no-simulate is used
-
-## Internet Shortcut Options:
- --write-link Write an internet shortcut file, depending
- on the current platform (.url, .webloc or
- .desktop). The URL may be cached by the OS
- --write-url-link Write a .url Windows internet shortcut. The
- OS caches the URL based on the file path
- --write-webloc-link Write a .webloc macOS internet shortcut
- --write-desktop-link Write a .desktop Linux internet shortcut
-
-## Verbosity and Simulation Options:
- -q, --quiet Activate quiet mode. If used with --verbose,
- print the log to stderr
- --no-quiet Deactivate quiet mode. (Default)
- --no-warnings Ignore warnings
- -s, --simulate Do not download the video and do not write
- anything to disk
- --no-simulate Download the video even if printing/listing
- options are used
- --ignore-no-formats-error Ignore "No video formats" error. Useful for
- extracting metadata even if the videos are
- not actually available for download
- (experimental)
- --no-ignore-no-formats-error Throw error when no downloadable video
- formats are found (default)
- --skip-download Do not download the video but write all
- related files (Alias: --no-download)
- -O, --print [WHEN:]TEMPLATE Field name or output template to print to
- screen, optionally prefixed with when to
- print it, separated by a ":". Supported
- values of "WHEN" are the same as that of
- --use-postprocessor (default: video).
- Implies --quiet. Implies --simulate unless
- --no-simulate or later stages of WHEN are
- used. This option can be used multiple times
- --print-to-file [WHEN:]TEMPLATE FILE
- Append given template to the file. The
- values of WHEN and TEMPLATE are the same as
- that of --print. FILE uses the same syntax
- as the output template. This option can be
- used multiple times
- -j, --dump-json Quiet, but print JSON information for each
- video. Simulate unless --no-simulate is
- used. See "OUTPUT TEMPLATE" for a
- description of available keys
- -J, --dump-single-json Quiet, but print JSON information for each
- URL or infojson passed. Simulate unless
- --no-simulate is used. If the URL refers to
- a playlist, the whole playlist information
- is dumped in a single line
- --force-write-archive Force download archive entries to be written
- as far as no errors occur, even if -s or
- another simulation option is used (Alias:
- --force-download-archive)
- --newline Output progress bar as new lines
- --no-progress Do not print progress bar
- --progress Show progress bar, even if in quiet mode
- --console-title Display progress in console titlebar
- --progress-template [TYPES:]TEMPLATE
- Template for progress outputs, optionally
- prefixed with one of "download:" (default),
- "download-title:" (the console title),
- "postprocess:", or "postprocess-title:".
- The video's fields are accessible under the
- "info" key and the progress attributes are
- accessible under "progress" key. E.g.
- --console-title --progress-template
- "download-title:%(info.id)s-%(progress.eta)s"
- --progress-delta SECONDS Time between progress output (default: 0)
- -v, --verbose Print various debugging information
- --dump-pages Print downloaded pages encoded using base64
- to debug problems (very verbose)
- --write-pages Write downloaded intermediary pages to files
- in the current directory to debug problems
- --print-traffic Display sent and read HTTP traffic
-
-## Workarounds:
- --encoding ENCODING Force the specified encoding (experimental)
- --legacy-server-connect Explicitly allow HTTPS connection to servers
- that do not support RFC 5746 secure
- renegotiation
- --no-check-certificates Suppress HTTPS certificate validation
- --prefer-insecure Use an unencrypted connection to retrieve
- information about the video (Currently
- supported only for YouTube)
- --add-headers FIELD:VALUE Specify a custom HTTP header and its value,
- separated by a colon ":". You can use this
- option multiple times
- --bidi-workaround Work around terminals that lack
- bidirectional text support. Requires bidiv
- or fribidi executable in PATH
- --sleep-requests SECONDS Number of seconds to sleep between requests
- during data extraction
- --sleep-interval SECONDS Number of seconds to sleep before each
- download. This is the minimum time to sleep
- when used along with --max-sleep-interval
- (Alias: --min-sleep-interval)
- --max-sleep-interval SECONDS Maximum number of seconds to sleep. Can only
- be used along with --min-sleep-interval
- --sleep-subtitles SECONDS Number of seconds to sleep before each
- subtitle download
-
-## Video Format Options:
- -f, --format FORMAT Video format code, see "FORMAT SELECTION"
- for more details
- -S, --format-sort SORTORDER Sort the formats by the fields given, see
- "Sorting Formats" for more details
- --format-sort-reset Disregard previous user specified sort order
- and reset to the default
- --format-sort-force Force user specified sort order to have
- precedence over all fields, see "Sorting
- Formats" for more details (Alias: --S-force)
- --no-format-sort-force Some fields have precedence over the user
- specified sort order (default)
- --video-multistreams Allow multiple video streams to be merged
- into a single file
- --no-video-multistreams Only one video stream is downloaded for each
- output file (default)
- --audio-multistreams Allow multiple audio streams to be merged
- into a single file
- --no-audio-multistreams Only one audio stream is downloaded for each
- output file (default)
- --prefer-free-formats Prefer video formats with free containers
- over non-free ones of the same quality. Use
- with "-S ext" to strictly prefer free
- containers irrespective of quality
- --no-prefer-free-formats Don't give any special preference to free
- containers (default)
- --check-formats Make sure formats are selected only from
- those that are actually downloadable
- --check-all-formats Check all formats for whether they are
- actually downloadable
- --no-check-formats Do not check that the formats are actually
- downloadable
- -F, --list-formats List available formats of each video.
- Simulate unless --no-simulate is used
- --merge-output-format FORMAT Containers that may be used when merging
- formats, separated by "/", e.g. "mp4/mkv".
- Ignored if no merge is required. (currently
- supported: avi, flv, mkv, mov, mp4, webm)
-
-## Subtitle Options:
- --write-subs Write subtitle file
- --no-write-subs Do not write subtitle file (default)
- --write-auto-subs Write automatically generated subtitle file
- (Alias: --write-automatic-subs)
- --no-write-auto-subs Do not write auto-generated subtitles
- (default) (Alias: --no-write-automatic-subs)
- --list-subs List available subtitles of each video.
- Simulate unless --no-simulate is used
- --sub-format FORMAT Subtitle format; accepts formats preference
- separated by "/", e.g. "srt" or "ass/srt/best"
- --sub-langs LANGS Languages of the subtitles to download (can
- be regex) or "all" separated by commas, e.g.
- --sub-langs "en.*,ja" (where "en.*" is a
- regex pattern that matches "en" followed by
- 0 or more of any character). You can prefix
- the language code with a "-" to exclude it
- from the requested languages, e.g. --sub-
- langs all,-live_chat. Use --list-subs for a
- list of available language tags
-
-## Authentication Options:
- -u, --username USERNAME Login with this account ID
- -p, --password PASSWORD Account password. If this option is left
- out, yt-dlp will ask interactively
- -2, --twofactor TWOFACTOR Two-factor authentication code
- -n, --netrc Use .netrc authentication data
- --netrc-location PATH Location of .netrc authentication data;
- either the path or its containing directory.
- Defaults to ~/.netrc
- --netrc-cmd NETRC_CMD Command to execute to get the credentials
- for an extractor.
- --video-password PASSWORD Video-specific password
- --ap-mso MSO Adobe Pass multiple-system operator (TV
- provider) identifier, use --ap-list-mso for
- a list of available MSOs
- --ap-username USERNAME Multiple-system operator account login
- --ap-password PASSWORD Multiple-system operator account password.
- If this option is left out, yt-dlp will ask
- interactively
- --ap-list-mso List all supported multiple-system operators
- --client-certificate CERTFILE Path to client certificate file in PEM
- format. May include the private key
- --client-certificate-key KEYFILE
- Path to private key file for client
- certificate
- --client-certificate-password PASSWORD
- Password for client certificate private key,
- if encrypted. If not provided, and the key
- is encrypted, yt-dlp will ask interactively
-
-## Post-Processing Options:
- -x, --extract-audio Convert video files to audio-only files
- (requires ffmpeg and ffprobe)
- --audio-format FORMAT Format to convert the audio to when -x is
- used. (currently supported: best (default),
- aac, alac, flac, m4a, mp3, opus, vorbis,
- wav). You can specify multiple rules using
- similar syntax as --remux-video
- --audio-quality QUALITY Specify ffmpeg audio quality to use when
- converting the audio with -x. Insert a value
- between 0 (best) and 10 (worst) for VBR or a
- specific bitrate like 128K (default 5)
- --remux-video FORMAT Remux the video into another container if
- necessary (currently supported: avi, flv,
- gif, mkv, mov, mp4, webm, aac, aiff, alac,
- flac, m4a, mka, mp3, ogg, opus, vorbis,
- wav). If the target container does not
- support the video/audio codec, remuxing will
- fail. You can specify multiple rules; e.g.
- "aac>m4a/mov>mp4/mkv" will remux aac to m4a,
- mov to mp4 and anything else to mkv
- --recode-video FORMAT Re-encode the video into another format if
- necessary. The syntax and supported formats
- are the same as --remux-video
- --postprocessor-args NAME:ARGS Give these arguments to the postprocessors.
- Specify the postprocessor/executable name
- and the arguments separated by a colon ":"
- to give the argument to the specified
- postprocessor/executable. Supported PP are:
- Merger, ModifyChapters, SplitChapters,
- ExtractAudio, VideoRemuxer, VideoConvertor,
- Metadata, EmbedSubtitle, EmbedThumbnail,
- SubtitlesConvertor, ThumbnailsConvertor,
- FixupStretched, FixupM4a, FixupM3u8,
- FixupTimestamp and FixupDuration. The
- supported executables are: AtomicParsley,
- FFmpeg and FFprobe. You can also specify
- "PP+EXE:ARGS" to give the arguments to the
- specified executable only when being used by
- the specified postprocessor. Additionally,
- for ffmpeg/ffprobe, "_i"/"_o" can be
- appended to the prefix optionally followed
- by a number to pass the argument before the
- specified input/output file, e.g. --ppa
- "Merger+ffmpeg_i1:-v quiet". You can use
- this option multiple times to give different
- arguments to different postprocessors.
- (Alias: --ppa)
- -k, --keep-video Keep the intermediate video file on disk
- after post-processing
- --no-keep-video Delete the intermediate video file after
- post-processing (default)
- --post-overwrites Overwrite post-processed files (default)
- --no-post-overwrites Do not overwrite post-processed files
- --embed-subs Embed subtitles in the video (only for mp4,
- webm and mkv videos)
- --no-embed-subs Do not embed subtitles (default)
- --embed-thumbnail Embed thumbnail in the video as cover art
- --no-embed-thumbnail Do not embed thumbnail (default)
- --embed-metadata Embed metadata to the video file. Also
- embeds chapters/infojson if present unless
- --no-embed-chapters/--no-embed-info-json are
- used (Alias: --add-metadata)
- --no-embed-metadata Do not add metadata to file (default)
- (Alias: --no-add-metadata)
- --embed-chapters Add chapter markers to the video file
- (Alias: --add-chapters)
- --no-embed-chapters Do not add chapter markers (default) (Alias:
- --no-add-chapters)
- --embed-info-json Embed the infojson as an attachment to
- mkv/mka video files
- --no-embed-info-json Do not embed the infojson as an attachment
- to the video file
- --parse-metadata [WHEN:]FROM:TO
- Parse additional metadata like title/artist
- from other fields; see "MODIFYING METADATA"
- for details. Supported values of "WHEN" are
- the same as that of --use-postprocessor
- (default: pre_process)
- --replace-in-metadata [WHEN:]FIELDS REGEX REPLACE
- Replace text in a metadata field using the
- given regex. This option can be used
- multiple times. Supported values of "WHEN"
- are the same as that of --use-postprocessor
- (default: pre_process)
- --xattrs Write metadata to the video file's xattrs
- (using Dublin Core and XDG standards)
- --concat-playlist POLICY Concatenate videos in a playlist. One of
- "never", "always", or "multi_video"
- (default; only when the videos form a single
- show). All the video files must have the
- same codecs and number of streams to be
- concatenable. The "pl_video:" prefix can be
- used with "--paths" and "--output" to set
- the output filename for the concatenated
- files. See "OUTPUT TEMPLATE" for details
- --fixup POLICY Automatically correct known faults of the
- file. One of never (do nothing), warn (only
- emit a warning), detect_or_warn (the
- default; fix the file if we can, warn
- otherwise), force (try fixing even if the
- file already exists)
- --ffmpeg-location PATH Location of the ffmpeg binary; either the
- path to the binary or its containing directory
- --exec [WHEN:]CMD Execute a command, optionally prefixed with
- when to execute it, separated by a ":".
- Supported values of "WHEN" are the same as
- that of --use-postprocessor (default:
- after_move). The same syntax as the output
- template can be used to pass any field as
- arguments to the command. If no fields are
- passed, %(filepath,_filename|)q is appended
- to the end of the command. This option can
- be used multiple times
- --no-exec Remove any previously defined --exec
- --convert-subs FORMAT Convert the subtitles to another format
- (currently supported: ass, lrc, srt, vtt).
- Use "--convert-subs none" to disable
- conversion (default) (Alias: --convert-
- subtitles)
- --convert-thumbnails FORMAT Convert the thumbnails to another format
- (currently supported: jpg, png, webp). You
- can specify multiple rules using similar
- syntax as "--remux-video". Use "--convert-
- thumbnails none" to disable conversion
- (default)
- --split-chapters Split video into multiple files based on
- internal chapters. The "chapter:" prefix can
- be used with "--paths" and "--output" to set
- the output filename for the split files. See
- "OUTPUT TEMPLATE" for details
- --no-split-chapters Do not split video based on chapters (default)
- --remove-chapters REGEX Remove chapters whose title matches the
- given regular expression. The syntax is the
- same as --download-sections. This option can
- be used multiple times
- --no-remove-chapters Do not remove any chapters from the file
- (default)
- --force-keyframes-at-cuts Force keyframes at cuts when
- downloading/splitting/removing sections.
- This is slow due to needing a re-encode, but
- the resulting video may have fewer artifacts
- around the cuts
- --no-force-keyframes-at-cuts Do not force keyframes around the chapters
- when cutting/splitting (default)
- --use-postprocessor NAME[:ARGS]
- The (case-sensitive) name of plugin
- postprocessors to be enabled, and
- (optionally) arguments to be passed to it,
- separated by a colon ":". ARGS are a
- semicolon ";" delimited list of NAME=VALUE.
- The "when" argument determines when the
- postprocessor is invoked. It can be one of
- "pre_process" (after video extraction),
- "after_filter" (after video passes filter),
- "video" (after --format; before
- --print/--output), "before_dl" (before each
- video download), "post_process" (after each
- video download; default), "after_move"
- (after moving the video file to its final
- location), "after_video" (after downloading
- and processing all formats of a video), or
- "playlist" (at end of playlist). This option
- can be used multiple times to add different
- postprocessors
-
-## SponsorBlock Options:
-Make chapter entries for, or remove various segments (sponsor,
- introductions, etc.) from downloaded YouTube videos using the
- [SponsorBlock API](https://sponsor.ajay.app)
-
- --sponsorblock-mark CATS SponsorBlock categories to create chapters
- for, separated by commas. Available
- categories are sponsor, intro, outro,
- selfpromo, preview, filler, interaction,
- music_offtopic, hook, poi_highlight,
- chapter, all and default (=all). You can
- prefix the category with a "-" to exclude
- it. See [1] for descriptions of the
- categories. E.g. --sponsorblock-mark
- all,-preview
- [1] https://wiki.sponsor.ajay.app/w/Segment_Categories
- --sponsorblock-remove CATS SponsorBlock categories to be removed from
- the video file, separated by commas. If a
- category is present in both mark and remove,
- remove takes precedence. The syntax and
- available categories are the same as for
- --sponsorblock-mark except that "default"
- refers to "all,-filler" and poi_highlight,
- chapter are not available
- --sponsorblock-chapter-title TEMPLATE
- An output template for the title of the
- SponsorBlock chapters created by
- --sponsorblock-mark. The only available
- fields are start_time, end_time, category,
- categories, name, category_names. Defaults
- to "[SponsorBlock]: %(category_names)l"
- --no-sponsorblock Disable both --sponsorblock-mark and
- --sponsorblock-remove
- --sponsorblock-api URL SponsorBlock API location, defaults to
- https://sponsor.ajay.app
-
-## Extractor Options:
- --extractor-retries RETRIES Number of retries for known extractor errors
- (default is 3), or "infinite"
- --allow-dynamic-mpd Process dynamic DASH manifests (default)
- (Alias: --no-ignore-dynamic-mpd)
- --ignore-dynamic-mpd Do not process dynamic DASH manifests
- (Alias: --no-allow-dynamic-mpd)
- --hls-split-discontinuity Split HLS playlists to different formats at
- discontinuities such as ad breaks
- --no-hls-split-discontinuity Do not split HLS playlists into different
- formats at discontinuities such as ad breaks
- (default)
- --extractor-args IE_KEY:ARGS Pass ARGS arguments to the IE_KEY extractor.
- See "EXTRACTOR ARGUMENTS" for details. You
- can use this option multiple times to give
- arguments for different extractors
-
-## Preset Aliases:
-Predefined aliases for convenience and ease of use. Note that future
- versions of yt-dlp may add or adjust presets, but the existing preset
- names will not be changed or removed
-
- -t mp3 -f 'ba[acodec^=mp3]/ba/b' -x --audio-format
- mp3
-
- -t aac -f
- 'ba[acodec^=aac]/ba[acodec^=mp4a.40.]/ba/b'
- -x --audio-format aac
-
- -t mp4 --merge-output-format mp4 --remux-video mp4
- -S vcodec:h264,lang,quality,res,fps,hdr:12,a
- codec:aac
-
- -t mkv --merge-output-format mkv --remux-video mkv
-
- -t sleep --sleep-subtitles 5 --sleep-requests 0.75
- --sleep-interval 10 --max-sleep-interval 20
-
-# CONFIGURATION
-
-You can configure yt-dlp by placing any supported command line option in a configuration file. The configuration is loaded from the following locations:
-
-1. **Main Configuration**:
- * The file given to `--config-locations`
-1. **Portable Configuration**: (Recommended for portable installations)
- * If using a binary, `yt-dlp.conf` in the same directory as the binary
- * If running from source-code, `yt-dlp.conf` in the parent directory of `yt_dlp`
-1. **Home Configuration**:
- * `yt-dlp.conf` in the home path given to `-P`
- * If `-P` is not given, the current directory is searched
-1. **User Configuration**:
- * `${XDG_CONFIG_HOME}/yt-dlp.conf`
- * `${XDG_CONFIG_HOME}/yt-dlp/config` (recommended on Linux/macOS)
- * `${XDG_CONFIG_HOME}/yt-dlp/config.txt`
- * `${APPDATA}/yt-dlp.conf`
- * `${APPDATA}/yt-dlp/config` (recommended on Windows)
- * `${APPDATA}/yt-dlp/config.txt`
- * `~/yt-dlp.conf`
- * `~/yt-dlp.conf.txt`
- * `~/.yt-dlp/config`
- * `~/.yt-dlp/config.txt`
-
- See also: [Notes about environment variables](#notes-about-environment-variables)
-1. **System Configuration**:
- * `/etc/yt-dlp.conf`
- * `/etc/yt-dlp/config`
- * `/etc/yt-dlp/config.txt`
-
-E.g. with the following configuration file, yt-dlp will always extract the audio, copy the mtime, use a proxy and save all videos under `YouTube` directory in your home directory:
-```
-# Lines starting with # are comments
-
-# Always extract audio
--x
-
-# Copy the mtime
---mtime
-
-# Use this proxy
---proxy 127.0.0.1:3128
-
-# Save all videos under YouTube directory in your home directory
--o ~/YouTube/%(title)s.%(ext)s
-```
-
-**Note**: Options in a configuration file are just the same options aka switches used in regular command line calls; thus there **must be no whitespace** after `-` or `--`, e.g. `-o` or `--proxy` but not `- o` or `-- proxy`. They must also be quoted when necessary, as if it were a UNIX shell.
-
-You can use `--ignore-config` if you want to disable all configuration files for a particular yt-dlp run. If `--ignore-config` is found inside any configuration file, no further configuration will be loaded. For example, having the option in the portable configuration file prevents loading of home, user, and system configurations. Additionally, (for backward compatibility) if `--ignore-config` is found inside the system configuration file, the user configuration is not loaded.
-
-### Configuration file encoding
-
-The configuration files are decoded according to the UTF BOM if present, and in the encoding from system locale otherwise.
-
-If you want your file to be decoded differently, add `# coding: ENCODING` to the beginning of the file (e.g. `# coding: shift-jis`). There must be no characters before that, even spaces or BOM.
-
-### Authentication with netrc
-
-You may also want to configure automatic credentials storage for extractors that support authentication (by providing login and password with `--username` and `--password`) in order not to pass credentials as command line arguments on every yt-dlp execution and prevent tracking plain text passwords in the shell command history. You can achieve this using a [`.netrc` file](https://stackoverflow.com/tags/.netrc/info) on a per-extractor basis. For that, you will need to create a `.netrc` file in `--netrc-location` and restrict permissions to read/write by only you:
-```
-touch ${HOME}/.netrc
-chmod a-rwx,u+rw ${HOME}/.netrc
-```
-After that, you can add credentials for an extractor in the following format, where *extractor* is the name of the extractor in lowercase:
-```
-machine login password
-```
-E.g.
-```
-machine youtube login myaccount@gmail.com password my_youtube_password
-machine twitch login my_twitch_account_name password my_twitch_password
-```
-To activate authentication with the `.netrc` file you should pass `--netrc` to yt-dlp or place it in the [configuration file](#configuration).
-
-The default location of the .netrc file is `~` (see below).
-
-As an alternative to using the `.netrc` file, which has the disadvantage of keeping your passwords in a plain text file, you can configure a custom shell command to provide the credentials for an extractor. This is done by providing the `--netrc-cmd` parameter, it shall output the credentials in the netrc format and return `0` on success, other values will be treated as an error. `{}` in the command will be replaced by the name of the extractor to make it possible to select the credentials for the right extractor.
-
-E.g. To use an encrypted `.netrc` file stored as `.authinfo.gpg`
-```
-yt-dlp --netrc-cmd 'gpg --decrypt ~/.authinfo.gpg' 'https://www.youtube.com/watch?v=BaW_jenozKc'
-```
-
-
-### Notes about environment variables
-* Environment variables are normally specified as `${VARIABLE}`/`$VARIABLE` on UNIX and `%VARIABLE%` on Windows; but is always shown as `${VARIABLE}` in this documentation
-* yt-dlp also allows using UNIX-style variables on Windows for path-like options; e.g. `--output`, `--config-locations`
-* If unset, `${XDG_CONFIG_HOME}` defaults to `~/.config` and `${XDG_CACHE_HOME}` to `~/.cache`
-* On Windows, `~` points to `${HOME}` if present; or, `${USERPROFILE}` or `${HOMEDRIVE}${HOMEPATH}` otherwise
-* On Windows, `${USERPROFILE}` generally points to `C:\Users\` and `${APPDATA}` to `${USERPROFILE}\AppData\Roaming`
-
-# OUTPUT TEMPLATE
-
-The `-o` option is used to indicate a template for the output file names while `-P` option is used to specify the path each type of file should be saved to.
-
-
-**tl;dr:** [navigate me to examples](#output-template-examples).
-
-
-The simplest usage of `-o` is not to set any template arguments when downloading a single file, like in `yt-dlp -o funny_video.flv "https://some/video"` (hard-coding file extension like this is _not_ recommended and could break some post-processing).
-
-It may however also contain special sequences that will be replaced when downloading each video. The special sequences may be formatted according to [Python string formatting operations](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting), e.g. `%(NAME)s` or `%(NAME)05d`. To clarify, that is a percent symbol followed by a name in parentheses, followed by formatting operations.
-
-The field names themselves (the part inside the parenthesis) can also have some special formatting:
-
-1. **Object traversal**: The dictionaries and lists available in metadata can be traversed by using a dot `.` separator; e.g. `%(tags.0)s`, `%(subtitles.en.-1.ext)s`. You can do Python slicing with colon `:`; E.g. `%(id.3:7)s`, `%(id.6:2:-1)s`, `%(formats.:.format_id)s`. Curly braces `{}` can be used to build dictionaries with only specific keys; e.g. `%(formats.:.{format_id,height})#j`. An empty field name `%()s` refers to the entire infodict; e.g. `%(.{id,title})s`. Note that all the fields that become available using this method are not listed below. Use `-j` to see such fields
-
-1. **Arithmetic**: Simple arithmetic can be done on numeric fields using `+`, `-` and `*`. E.g. `%(playlist_index+10)03d`, `%(n_entries+1-playlist_index)d`
-
-1. **Date/time Formatting**: Date/time fields can be formatted according to [strftime formatting](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes) by specifying it separated from the field name using a `>`. E.g. `%(duration>%H-%M-%S)s`, `%(upload_date>%Y-%m-%d)s`, `%(epoch-3600>%H-%M-%S)s`
-
-1. **Alternatives**: Alternate fields can be specified separated with a `,`. E.g. `%(release_date>%Y,upload_date>%Y|Unknown)s`
-
-1. **Replacement**: A replacement value can be specified using a `&` separator according to the [`str.format` mini-language](https://docs.python.org/3/library/string.html#format-specification-mini-language). If the field is *not* empty, this replacement value will be used instead of the actual field content. This is done after alternate fields are considered; thus the replacement is used if *any* of the alternative fields is *not* empty. E.g. `%(chapters&has chapters|no chapters)s`, `%(title&TITLE={:>20}|NO TITLE)s`
-
-1. **Default**: A literal default value can be specified for when the field is empty using a `|` separator. This overrides `--output-na-placeholder`. E.g. `%(uploader|Unknown)s`
-
-1. **More Conversions**: In addition to the normal format types `diouxXeEfFgGcrs`, yt-dlp additionally supports converting to `B` = **B**ytes, `j` = **j**son (flag `#` for pretty-printing, `+` for Unicode), `h` = HTML escaping, `l` = a comma-separated **l**ist (flag `#` for `\n` newline-separated), `q` = a string **q**uoted for the terminal (flag `#` to split a list into different arguments), `D` = add **D**ecimal suffixes (e.g. 10M) (flag `#` to use 1024 as factor), and `S` = **S**anitize as filename (flag `#` for restricted)
-
-1. **Unicode normalization**: The format type `U` can be used for NFC [Unicode normalization](https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize). The alternate form flag (`#`) changes the normalization to NFD and the conversion flag `+` can be used for NFKC/NFKD compatibility equivalence normalization. E.g. `%(title)+.100U` is NFKC
-
-To summarize, the general syntax for a field is:
-```
-%(name[.keys][addition][>strf][,alternate][&replacement][|default])[flags][width][.precision][length]type
-```
-
-Additionally, you can set different output templates for the various metadata files separately from the general output template by specifying the type of file followed by the template separated by a colon `:`. The different file types supported are `subtitle`, `thumbnail`, `description`, `annotation` (deprecated), `infojson`, `link`, `pl_thumbnail`, `pl_description`, `pl_infojson`, `chapter`, `pl_video`. E.g. `-o "%(title)s.%(ext)s" -o "thumbnail:%(title)s\%(title)s.%(ext)s"` will put the thumbnails in a folder with the same name as the video. If any of the templates is empty, that type of file will not be written. E.g. `--write-thumbnail -o "thumbnail:"` will write thumbnails only for playlists and not for video.
-
-
-
-**Note**: Due to post-processing (i.e. merging etc.), the actual output filename might differ. Use `--print after_move:filepath` to get the name after all post-processing is complete.
-
-The available fields are:
-
- - `id` (string): Video identifier
- - `title` (string): Video title
- - `fulltitle` (string): Video title ignoring live timestamp and generic title
- - `ext` (string): Video filename extension
- - `alt_title` (string): A secondary title of the video
- - `description` (string): The description of the video
- - `display_id` (string): An alternative identifier for the video
- - `uploader` (string): Full name of the video uploader
- - `uploader_id` (string): Nickname or id of the video uploader
- - `uploader_url` (string): URL to the video uploader's profile
- - `license` (string): License name the video is licensed under
- - `creators` (list): The creators of the video
- - `creator` (string): The creators of the video; comma-separated
- - `timestamp` (numeric): UNIX timestamp of the moment the video became available
- - `upload_date` (string): Video upload date in UTC (YYYYMMDD)
- - `release_timestamp` (numeric): UNIX timestamp of the moment the video was released
- - `release_date` (string): The date (YYYYMMDD) when the video was released in UTC
- - `release_year` (numeric): Year (YYYY) when the video or album was released
- - `modified_timestamp` (numeric): UNIX timestamp of the moment the video was last modified
- - `modified_date` (string): The date (YYYYMMDD) when the video was last modified in UTC
- - `channel` (string): Full name of the channel the video is uploaded on
- - `channel_id` (string): Id of the channel
- - `channel_url` (string): URL of the channel
- - `channel_follower_count` (numeric): Number of followers of the channel
- - `channel_is_verified` (boolean): Whether the channel is verified on the platform
- - `location` (string): Physical location where the video was filmed
- - `duration` (numeric): Length of the video in seconds
- - `duration_string` (string): Length of the video (HH:mm:ss)
- - `view_count` (numeric): How many users have watched the video on the platform
- - `concurrent_view_count` (numeric): How many users are currently watching the video on the platform.
- - `like_count` (numeric): Number of positive ratings of the video
- - `dislike_count` (numeric): Number of negative ratings of the video
- - `repost_count` (numeric): Number of reposts of the video
- - `average_rating` (numeric): Average rating given by users, the scale used depends on the webpage
- - `comment_count` (numeric): Number of comments on the video (For some extractors, comments are only downloaded at the end, and so this field cannot be used)
- - `save_count` (numeric): Number of times the video has been saved or bookmarked
- - `age_limit` (numeric): Age restriction for the video (years)
- - `live_status` (string): One of "not_live", "is_live", "is_upcoming", "was_live", "post_live" (was live, but VOD is not yet processed)
- - `is_live` (boolean): Whether this video is a live stream or a fixed-length video
- - `was_live` (boolean): Whether this video was originally a live stream
- - `playable_in_embed` (string): Whether this video is allowed to play in embedded players on other sites
- - `availability` (string): Whether the video is "private", "premium_only", "subscriber_only", "needs_auth", "unlisted" or "public"
- - `media_type` (string): The type of media as classified by the site, e.g. "episode", "clip", "trailer"
- - `start_time` (numeric): Time in seconds where the reproduction should start, as specified in the URL
- - `end_time` (numeric): Time in seconds where the reproduction should end, as specified in the URL
- - `extractor` (string): Name of the extractor
- - `extractor_key` (string): Key name of the extractor
- - `epoch` (numeric): Unix epoch of when the information extraction was completed
- - `autonumber` (numeric): Number that will be increased with each download, starting at `--autonumber-start`, padded with leading zeros to 5 digits
- - `video_autonumber` (numeric): Number that will be increased with each video
- - `n_entries` (numeric): Total number of extracted items in the playlist
- - `playlist_id` (string): Identifier of the playlist that contains the video
- - `playlist_title` (string): Name of the playlist that contains the video
- - `playlist` (string): `playlist_title` if available or else `playlist_id`
- - `playlist_count` (numeric): Total number of items in the playlist. May not be known if entire playlist is not extracted
- - `playlist_index` (numeric): Index of the video in the playlist padded with leading zeros according the final index
- - `playlist_autonumber` (numeric): Position of the video in the playlist download queue padded with leading zeros according to the total length of the playlist
- - `playlist_uploader` (string): Full name of the playlist uploader
- - `playlist_uploader_id` (string): Nickname or id of the playlist uploader
- - `playlist_channel` (string): Display name of the channel that uploaded the playlist
- - `playlist_channel_id` (string): Identifier of the channel that uploaded the playlist
- - `playlist_webpage_url` (string): URL of the playlist webpage
- - `webpage_url` (string): A URL to the video webpage which, if given to yt-dlp, should yield the same result again
- - `webpage_url_basename` (string): The basename of the webpage URL
- - `webpage_url_domain` (string): The domain of the webpage URL
- - `original_url` (string): The URL given by the user (or the same as `webpage_url` for playlist entries)
- - `categories` (list): List of categories the video belongs to
- - `tags` (list): List of tags assigned to the video
- - `cast` (list): List of cast members
-
-All the fields in [Filtering Formats](#filtering-formats) can also be used
-
-Available for the video that belongs to some logical chapter or section:
-
- - `chapter` (string): Name or title of the chapter the video belongs to
- - `chapter_number` (numeric): Number of the chapter the video belongs to
- - `chapter_id` (string): Id of the chapter the video belongs to
-
-Available for the video that is an episode of some series or program:
-
- - `series` (string): Title of the series or program the video episode belongs to
- - `series_id` (string): Id of the series or program the video episode belongs to
- - `season` (string): Title of the season the video episode belongs to
- - `season_number` (numeric): Number of the season the video episode belongs to
- - `season_id` (string): Id of the season the video episode belongs to
- - `episode` (string): Title of the video episode
- - `episode_number` (numeric): Number of the video episode within a season
- - `episode_id` (string): Id of the video episode
-
-Available for the media that is a track or a part of a music album:
-
- - `track` (string): Title of the track
- - `track_number` (numeric): Number of the track within an album or a disc
- - `track_id` (string): Id of the track
- - `artists` (list): Artist(s) of the track
- - `artist` (string): Artist(s) of the track; comma-separated
- - `genres` (list): Genre(s) of the track
- - `genre` (string): Genre(s) of the track; comma-separated
- - `composers` (list): Composer(s) of the piece
- - `composer` (string): Composer(s) of the piece; comma-separated
- - `album` (string): Title of the album the track belongs to
- - `album_type` (string): Type of the album
- - `album_artists` (list): All artists appeared on the album
- - `album_artist` (string): All artists appeared on the album; comma-separated
- - `disc_number` (numeric): Number of the disc or other physical medium the track belongs to
-
-Available only when using `--download-sections` and for `chapter:` prefix when using `--split-chapters` for videos with internal chapters:
-
- - `section_title` (string): Title of the chapter
- - `section_number` (numeric): Number of the chapter within the file
- - `section_start` (numeric): Start time of the chapter in seconds
- - `section_end` (numeric): End time of the chapter in seconds
-
-Available only when used in `--print`:
-
- - `urls` (string): The URLs of all requested formats, one in each line
- - `filename` (string): Name of the video file. Note that the [actual filename may differ](#outtmpl-postprocess-note)
- - `formats_table` (table): The video format table as printed by `--list-formats`
- - `thumbnails_table` (table): The thumbnail format table as printed by `--list-thumbnails`
- - `subtitles_table` (table): The subtitle format table as printed by `--list-subs`
- - `automatic_captions_table` (table): The automatic subtitle format table as printed by `--list-subs`
-
- Available only after the video is downloaded (`post_process`/`after_move`):
-
- - `filepath`: Actual path of downloaded video file
-
-Available only in `--sponsorblock-chapter-title`:
-
- - `start_time` (numeric): Start time of the chapter in seconds
- - `end_time` (numeric): End time of the chapter in seconds
- - `categories` (list): The [SponsorBlock categories](https://wiki.sponsor.ajay.app/w/Types#Category) the chapter belongs to
- - `category` (string): The smallest SponsorBlock category the chapter belongs to
- - `category_names` (list): Friendly names of the categories
- - `name` (string): Friendly name of the smallest category
- - `type` (string): The [SponsorBlock action type](https://wiki.sponsor.ajay.app/w/Types#Action_Type) of the chapter
-
-Each aforementioned sequence when referenced in an output template will be replaced by the actual value corresponding to the sequence name. E.g. for `-o %(title)s-%(id)s.%(ext)s` and an mp4 video with title `yt-dlp test video` and id `BaW_jenozKc`, this will result in a `yt-dlp test video-BaW_jenozKc.mp4` file created in the current directory.
-
-**Note**: Some of the sequences are not guaranteed to be present, since they depend on the metadata obtained by a particular extractor. Such sequences will be replaced with placeholder value provided with `--output-na-placeholder` (`NA` by default).
-
-**Tip**: Look at the `-j` output to identify which fields are available for the particular URL
-
-For numeric sequences, you can use [numeric related formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting); e.g. `%(view_count)05d` will result in a string with view count padded with zeros up to 5 characters, like in `00042`.
-
-Output templates can also contain arbitrary hierarchical path, e.g. `-o "%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s"` which will result in downloading each video in a directory corresponding to this path template. Any missing directory will be automatically created for you.
-
-To use percent literals in an output template use `%%`. To output to stdout use `-o -`.
-
-The current default template is `%(title)s [%(id)s].%(ext)s`.
-
-In some cases, you don't want special characters such as 中, spaces, or &, such as when transferring the downloaded filename to a Windows system or the filename through an 8bit-unsafe channel. In these cases, add the `--restrict-filenames` flag to get a shorter title.
-
-#### Output template examples
+### Pull and run from Docker Hub
```bash
-$ yt-dlp --print filename -o "test video.%(ext)s" BaW_jenozKc
-test video.webm # Literal name with correct extension
-
-$ yt-dlp --print filename -o "%(title)s.%(ext)s" BaW_jenozKc
-youtube-dl test video ''_ä↭𝕐.webm # All kinds of weird characters
-
-$ yt-dlp --print filename -o "%(title)s.%(ext)s" BaW_jenozKc --restrict-filenames
-youtube-dl_test_video_.webm # Restricted file name
-
-# Download YouTube playlist videos in separate directory indexed by video order in a playlist
-$ yt-dlp -o "%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s" "https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re"
-
-# Download YouTube playlist videos in separate directories according to their uploaded year
-$ yt-dlp -o "%(upload_date>%Y)s/%(title)s.%(ext)s" "https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re"
-
-# Prefix playlist index with " - " separator, but only if it is available
-$ yt-dlp -o "%(playlist_index&{} - |)s%(title)s.%(ext)s" BaW_jenozKc "https://www.youtube.com/user/TheLinuxFoundation/playlists"
-
-# Download all playlists of YouTube channel/user keeping each playlist in separate directory:
-$ yt-dlp -o "%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s" "https://www.youtube.com/user/TheLinuxFoundation/playlists"
-
-# Download Udemy course keeping each chapter in separate directory under MyVideos directory in your home
-$ yt-dlp -u user -p password -P "~/MyVideos" -o "%(playlist)s/%(chapter_number)s - %(chapter)s/%(title)s.%(ext)s" "https://www.udemy.com/java-tutorial"
-
-# Download entire series season keeping each series and each season in separate directory under C:/MyVideos
-$ yt-dlp -P "C:/MyVideos" -o "%(series)s/%(season_number)s - %(season)s/%(episode_number)s - %(episode)s.%(ext)s" "https://videomore.ru/kino_v_detalayah/5_sezon/367617"
-
-# Download video as "C:\MyVideos\uploader\title.ext", subtitles as "C:\MyVideos\subs\uploader\title.ext"
-# and put all temporary files in "C:\MyVideos\tmp"
-$ yt-dlp -P "C:/MyVideos" -P "temp:tmp" -P "subtitle:subs" -o "%(uploader)s/%(title)s.%(ext)s" BaW_jenozKc --write-subs
-
-# Download video as "C:\MyVideos\uploader\title.ext" and subtitles as "C:\MyVideos\uploader\subs\title.ext"
-$ yt-dlp -P "C:/MyVideos" -o "%(uploader)s/%(title)s.%(ext)s" -o "subtitle:%(uploader)s/subs/%(title)s.%(ext)s" BaW_jenozKc --write-subs
-
-# Stream the video being downloaded to stdout
-$ yt-dlp -o - BaW_jenozKc
+docker pull samive/yt-dlp-web:latest
+docker run -d -p 8000:8000 --name yt-dlp-web samive/yt-dlp-web:latest
```
-# FORMAT SELECTION
+Then open **http://localhost:8000** in your browser.
-By default, yt-dlp tries to download the best available quality if you **don't** pass any options.
-This is generally equivalent to using `-f bestvideo*+bestaudio/best`. However, if multiple audiostreams is enabled (`--audio-multistreams`), the default format changes to `-f bestvideo+bestaudio/best`. Similarly, if ffmpeg is unavailable, or if you use yt-dlp to stream to `stdout` (`-o -`), the default becomes `-f best/bestvideo+bestaudio`.
-
-**Deprecation warning**: Latest versions of yt-dlp can stream multiple formats to the stdout simultaneously using ffmpeg. So, in future versions, the default for this will be set to `-f bv*+ba/b` similar to normal downloads. If you want to preserve the `-f b/bv+ba` setting, it is recommended to explicitly specify it in the configuration options.
-
-The general syntax for format selection is `-f FORMAT` (or `--format FORMAT`) where `FORMAT` is a *selector expression*, i.e. an expression that describes format or formats you would like to download.
-
-
-**tl;dr:** [navigate me to examples](#format-selection-examples).
-
-
-The simplest case is requesting a specific format; e.g. with `-f 22` you can download the format with format code equal to 22. You can get the list of available format codes for particular video using `--list-formats` or `-F`. Note that these format codes are extractor specific.
-
-You can also use a file extension (currently `3gp`, `aac`, `flv`, `m4a`, `mp3`, `mp4`, `ogg`, `wav`, `webm` are supported) to download the best quality format of a particular file extension served as a single file, e.g. `-f webm` will download the best quality format with the `webm` extension served as a single file.
-
-You can use `-f -` to interactively provide the format selector *for each video*
-
-You can also use special names to select particular edge case formats:
-
- - `all`: Select **all formats** separately
- - `mergeall`: Select and **merge all formats** (Must be used with `--audio-multistreams`, `--video-multistreams` or both)
- - `b*`, `best*`: Select the best quality format that **contains either** a video or an audio or both (i.e.; `vcodec!=none or acodec!=none`)
- - `b`, `best`: Select the best quality format that **contains both** video and audio. Equivalent to `best*[vcodec!=none][acodec!=none]`
- - `bv`, `bestvideo`: Select the best quality **video-only** format. Equivalent to `best*[acodec=none]`
- - `bv*`, `bestvideo*`: Select the best quality format that **contains video**. It may also contain audio. Equivalent to `best*[vcodec!=none]`
- - `ba`, `bestaudio`: Select the best quality **audio-only** format. Equivalent to `best*[vcodec=none]`
- - `ba*`, `bestaudio*`: Select the best quality format that **contains audio**. It may also contain video. Equivalent to `best*[acodec!=none]` ([Do not use!](https://github.com/yt-dlp/yt-dlp/issues/979#issuecomment-919629354))
- - `w*`, `worst*`: Select the worst quality format that contains either a video or an audio
- - `w`, `worst`: Select the worst quality format that contains both video and audio. Equivalent to `worst*[vcodec!=none][acodec!=none]`
- - `wv`, `worstvideo`: Select the worst quality video-only format. Equivalent to `worst*[acodec=none]`
- - `wv*`, `worstvideo*`: Select the worst quality format that contains video. It may also contain audio. Equivalent to `worst*[vcodec!=none]`
- - `wa`, `worstaudio`: Select the worst quality audio-only format. Equivalent to `worst*[vcodec=none]`
- - `wa*`, `worstaudio*`: Select the worst quality format that contains audio. It may also contain video. Equivalent to `worst*[acodec!=none]`
-
-For example, to download the worst quality video-only format you can use `-f worstvideo`. It is, however, recommended not to use `worst` and related options. When your format selector is `worst`, the format which is worst in all respects is selected. Most of the time, what you actually want is the video with the smallest filesize instead. So it is generally better to use `-S +size` or more rigorously, `-S +size,+br,+res,+fps` instead of `-f worst`. See [Sorting Formats](#sorting-formats) for more details.
-
-You can select the n'th best format of a type by using `best.`. For example, `best.2` will select the 2nd best combined format. Similarly, `bv*.3` will select the 3rd best format that contains a video stream.
-
-If you want to download multiple videos, and they don't have the same formats available, you can specify the order of preference using slashes. Note that formats on the left hand side are preferred; e.g. `-f 22/17/18` will download format 22 if it's available, otherwise it will download format 17 if it's available, otherwise it will download format 18 if it's available, otherwise it will complain that no suitable formats are available for download.
-
-If you want to download several formats of the same video use a comma as a separator, e.g. `-f 22,17,18` will download all these three formats, of course if they are available. Or a more sophisticated example combined with the precedence feature: `-f 136/137/mp4/bestvideo,140/m4a/bestaudio`.
-
-You can merge the video and audio of multiple formats into a single file using `-f ++...` (requires ffmpeg installed); e.g. `-f bestvideo+bestaudio` will download the best video-only format, the best audio-only format and mux them together with ffmpeg.
-
-**Deprecation warning**: Since the *below* described behavior is complex and counter-intuitive, this will be removed and multistreams will be enabled by default in the future. A new operator will be instead added to limit formats to single audio/video
-
-Unless `--video-multistreams` is used, all formats with a video stream except the first one are ignored. Similarly, unless `--audio-multistreams` is used, all formats with an audio stream except the first one are ignored. E.g. `-f bestvideo+best+bestaudio --video-multistreams --audio-multistreams` will download and merge all 3 given formats. The resulting file will have 2 video streams and 2 audio streams. But `-f bestvideo+best+bestaudio --no-video-multistreams` will download and merge only `bestvideo` and `bestaudio`. `best` is ignored since another format containing a video stream (`bestvideo`) has already been selected. The order of the formats is therefore important. `-f best+bestaudio --no-audio-multistreams` will download only `best` while `-f bestaudio+best --no-audio-multistreams` will ignore `best` and download only `bestaudio`.
-
-## Filtering Formats
-
-You can also filter the video formats by putting a condition in brackets, as in `-f "best[height=720]"` (or `-f "[filesize>10M]"` since filters without a selector are interpreted as `best`).
-
-The following numeric meta fields can be used with comparisons `<`, `<=`, `>`, `>=`, `=` (equals), `!=` (not equals):
-
- - `filesize`: The number of bytes, if known in advance
- - `filesize_approx`: An estimate for the number of bytes
- - `width`: Width of the video, if known
- - `height`: Height of the video, if known
- - `aspect_ratio`: Aspect ratio of the video, if known
- - `tbr`: Average bitrate of audio and video in [kbps](## "1000 bits/sec")
- - `abr`: Average audio bitrate in [kbps](## "1000 bits/sec")
- - `vbr`: Average video bitrate in [kbps](## "1000 bits/sec")
- - `asr`: Audio sampling rate in Hertz
- - `fps`: Frame rate
- - `audio_channels`: The number of audio channels
- - `stretched_ratio`: `width:height` of the video's pixels, if not square
-
-Also filtering work for comparisons `=` (equals), `^=` (starts with), `$=` (ends with), `*=` (contains), `~=` (matches regex) and following string meta fields:
-
- - `url`: Video URL
- - `ext`: File extension
- - `acodec`: Name of the audio codec in use
- - `vcodec`: Name of the video codec in use
- - `container`: Name of the container format
- - `protocol`: The protocol that will be used for the actual download, lower-case (`http`, `https`, `rtsp`, `rtmp`, `rtmpe`, `mms`, `f4m`, `ism`, `http_dash_segments`, `m3u8`, or `m3u8_native`)
- - `language`: Language code
- - `dynamic_range`: The dynamic range of the video
- - `format_id`: A short description of the format
- - `format`: A human-readable description of the format
- - `format_note`: Additional info about the format
- - `resolution`: Textual description of width and height
-
-Any string comparison may be prefixed with negation `!` in order to produce an opposite comparison, e.g. `!*=` (does not contain). The comparand of a string comparison needs to be quoted with either double or single quotes if it contains spaces or special characters other than `._-`.
-
-**Note**: None of the aforementioned meta fields are guaranteed to be present since this solely depends on the metadata obtained by the particular extractor, i.e. the metadata offered by the website. Any other field made available by the extractor can also be used for filtering.
-
-Formats for which the value is not known are excluded unless you put a question mark (`?`) after the operator. You can combine format filters, so `-f "bv[height<=?720][tbr>500]"` selects up to 720p videos (or videos where the height is not known) with a bitrate of at least 500 kbps. You can also use the filters with `all` to download all formats that satisfy the filter, e.g. `-f "all[vcodec=none]"` selects all audio-only formats.
-
-Format selectors can also be grouped using parentheses; e.g. `-f "(mp4,webm)[height<480]"` will download the best pre-merged mp4 and webm formats with a height lower than 480.
-
-## Sorting Formats
-
-You can change the criteria for being considered the `best` by using `-S` (`--format-sort`). The general format for this is `--format-sort field1,field2...`.
-
-The available fields are:
-
- - `hasvid`: Gives priority to formats that have a video stream
- - `hasaud`: Gives priority to formats that have an audio stream
- - `ie_pref`: The format preference
- - `lang`: The language preference as determined by the extractor (e.g. original language preferred over audio description)
- - `quality`: The quality of the format
- - `source`: The preference of the source
- - `proto`: Protocol used for download (`https`/`ftps` > `http`/`ftp` > `m3u8_native`/`m3u8` > `http_dash_segments`> `websocket_frag` > `mms`/`rtsp` > `f4f`/`f4m`)
- - `vcodec`: Video Codec (`av01` > `vp9.2` > `vp9` > `h265` > `h264` > `vp8` > `h263` > `theora` > other)
- - `acodec`: Audio Codec (`flac`/`alac` > `wav`/`aiff` > `opus` > `vorbis` > `aac` > `mp4a` > `mp3` > `ac4` > `eac3` > `ac3` > `dts` > other)
- - `codec`: Equivalent to `vcodec,acodec`
- - `vext`: Video Extension (`mp4` > `mov` > `webm` > `flv` > other). If `--prefer-free-formats` is used, `webm` is preferred.
- - `aext`: Audio Extension (`m4a` > `aac` > `mp3` > `ogg` > `opus` > `webm` > other). If `--prefer-free-formats` is used, the order changes to `ogg` > `opus` > `webm` > `mp3` > `m4a` > `aac`
- - `ext`: Equivalent to `vext,aext`
- - `filesize`: Exact filesize, if known in advance
- - `fs_approx`: Approximate filesize
- - `size`: Exact filesize if available, otherwise approximate filesize
- - `height`: Height of video
- - `width`: Width of video
- - `res`: Video resolution, calculated as the smallest dimension.
- - `fps`: Framerate of video
- - `hdr`: The dynamic range of the video (`DV` > `HDR12` > `HDR10+` > `HDR10` > `HLG` > `SDR`)
- - `channels`: The number of audio channels
- - `tbr`: Total average bitrate in [kbps](## "1000 bits/sec")
- - `vbr`: Average video bitrate in [kbps](## "1000 bits/sec")
- - `abr`: Average audio bitrate in [kbps](## "1000 bits/sec")
- - `br`: Average bitrate in [kbps](## "1000 bits/sec"), `tbr`/`vbr`/`abr`
- - `asr`: Audio sample rate in Hz
-
-**Deprecation warning**: Many of these fields have (currently undocumented) aliases, that may be removed in a future version. It is recommended to use only the documented field names.
-
-All fields, unless specified otherwise, are sorted in descending order. To reverse this, prefix the field with a `+`. E.g. `+res` prefers format with the smallest resolution. Additionally, you can suffix a preferred value for the fields, separated by a `:`. E.g. `res:720` prefers larger videos, but no larger than 720p and the smallest video if there are no videos less than 720p. For `codec` and `ext`, you can provide two preferred values, the first for video and the second for audio. E.g. `+codec:avc:m4a` (equivalent to `+vcodec:avc,+acodec:m4a`) sets the video codec preference to `h264` > `h265` > `vp9` > `vp9.2` > `av01` > `vp8` > `h263` > `theora` and audio codec preference to `mp4a` > `aac` > `vorbis` > `opus` > `mp3` > `ac3` > `dts`. You can also make the sorting prefer the nearest values to the provided by using `~` as the delimiter. E.g. `filesize~1G` prefers the format with filesize closest to 1 GiB.
-
-The fields `hasvid` and `ie_pref` are always given highest priority in sorting, irrespective of the user-defined order. This behavior can be changed by using `--format-sort-force`. Apart from these, the default order used is: `lang,quality,res,fps,hdr:12,vcodec,channels,acodec,size,br,asr,proto,ext,hasaud,source,id`. The extractors may override this default order, but they cannot override the user-provided order.
-
-Note that the default for hdr is `hdr:12`; i.e. Dolby Vision is not preferred. This choice was made since DV formats are not yet fully compatible with most devices. This may be changed in the future.
-
-If your format selector is `worst`, the last item is selected after sorting. This means it will select the format that is worst in all respects. Most of the time, what you actually want is the video with the smallest filesize instead. So it is generally better to use `-f best -S +size,+br,+res,+fps`.
-
-If you use the `-S`/`--format-sort` option multiple times, each subsequent sorting argument will be prepended to the previous one, and only the highest priority entry of any duplicated field will be preserved. E.g. `-S proto -S res` is equivalent to `-S res,proto`, and `-S res:720,fps -S vcodec,res:1080` is equivalent to `-S vcodec,res:1080,fps`. You can use `--format-sort-reset` to disregard any previously passed `-S`/`--format-sort` arguments and reset to the default order.
-
-**Tip**: You can use the `-v -F` to see how the formats have been sorted (worst to best).
-
-## Format Selection examples
+### Persist downloads to your machine
```bash
-# Download and merge the best video-only format and the best audio-only format,
-# or download the best combined format if video-only format is not available
-$ yt-dlp -f "bv+ba/b"
-
-# Download best format that contains video,
-# and if it doesn't already have an audio stream, merge it with best audio-only format
-$ yt-dlp -f "bv*+ba/b"
-
-# Same as above
-$ yt-dlp
-
-# Download the best video-only format and the best audio-only format without merging them
-# For this case, an output template should be used since
-# by default, bestvideo and bestaudio will have the same file name.
-$ yt-dlp -f "bv,ba" -o "%(title)s.f%(format_id)s.%(ext)s"
-
-# Download and merge the best format that has a video stream,
-# and all audio-only formats into one file
-$ yt-dlp -f "bv*+mergeall[vcodec=none]" --audio-multistreams
-
-# Download and merge the best format that has a video stream,
-# and the best 2 audio-only formats into one file
-$ yt-dlp -f "bv*+ba+ba.2" --audio-multistreams
-
-
-# The following examples show the old method (without -S) of format selection
-# and how to use -S to achieve a similar but (generally) better result
-
-# Download the worst video available (old method)
-$ yt-dlp -f "wv*+wa/w"
-
-# Download the best video available but with the smallest resolution
-$ yt-dlp -S "+res"
-
-# Download the smallest video available
-$ yt-dlp -S "+size,+br"
-
-
-
-# Download the best mp4 video available, or the best video if no mp4 available
-$ yt-dlp -f "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4] / bv*+ba/b"
-
-# Download the best video with the best extension
-# (For video, mp4 > mov > webm > flv. For audio, m4a > aac > mp3 ...)
-$ yt-dlp -S "ext"
-
-
-
-# Download the best video available but no better than 480p,
-# or the worst video if there is no video under 480p
-$ yt-dlp -f "bv*[height<=480]+ba/b[height<=480] / wv*+ba/w"
-
-# Download the best video available with the largest height but no better than 480p,
-# or the best video with the smallest resolution if there is no video under 480p
-$ yt-dlp -S "height:480"
-
-# Download the best video available with the largest resolution but no better than 480p,
-# or the best video with the smallest resolution if there is no video under 480p
-# Resolution is determined by using the smallest dimension.
-# So this works correctly for vertical videos as well
-$ yt-dlp -S "res:480"
-
-
-
-# Download the best video (that also has audio) but no bigger than 50 MB,
-# or the worst video (that also has audio) if there is no video under 50 MB
-$ yt-dlp -f "b[filesize<50M] / w"
-
-# Download the largest video (that also has audio) but no bigger than 50 MB,
-# or the smallest video (that also has audio) if there is no video under 50 MB
-$ yt-dlp -f "b" -S "filesize:50M"
-
-# Download the best video (that also has audio) that is closest in size to 50 MB
-$ yt-dlp -f "b" -S "filesize~50M"
-
-
-
-# Download best video available via direct link over HTTP/HTTPS protocol,
-# or the best video available via any protocol if there is no such video
-$ yt-dlp -f "(bv*+ba/b)[protocol^=http][protocol!*=dash] / (bv*+ba/b)"
-
-# Download best video available via the best protocol
-# (https/ftps > http/ftp > m3u8_native > m3u8 > http_dash_segments ...)
-$ yt-dlp -S "proto"
-
-
-
-# Download the best video with either h264 or h265 codec,
-# or the best video if there is no such video
-$ yt-dlp -f "(bv*[vcodec~='^((he|a)vc|h26[45])']+ba) / (bv*+ba/b)"
-
-# Download the best video with best codec no better than h264,
-# or the best video with worst codec if there is no such video
-$ yt-dlp -S "codec:h264"
-
-# Download the best video with worst codec no worse than h264,
-# or the best video with best codec if there is no such video
-$ yt-dlp -S "+codec:h264"
-
-
-
-# More complex examples
-
-# Download the best video no better than 720p preferring framerate greater than 30,
-# or the worst video (still preferring framerate greater than 30) if there is no such video
-$ yt-dlp -f "((bv*[fps>30]/bv*)[height<=720]/(wv*[fps>30]/wv*)) + ba / (b[fps>30]/b)[height<=720]/(w[fps>30]/w)"
-
-# Download the video with the largest resolution no better than 720p,
-# or the video with the smallest resolution available if there is no such video,
-# preferring larger framerate for formats with the same resolution
-$ yt-dlp -S "res:720,fps"
-
-
-
-# Download the video with smallest resolution no worse than 480p,
-# or the video with the largest resolution available if there is no such video,
-# preferring better codec and then larger total bitrate for the same resolution
-$ yt-dlp -S "+res:480,codec,br"
+docker run -d \
+ -p 8000:8000 \
+ -v $(pwd)/downloads:/app/web/backend/downloads \
+ --name yt-dlp-web \
+ samive/yt-dlp-web:latest
```
-# MODIFYING METADATA
-
-The metadata obtained by the extractors can be modified by using `--parse-metadata` and `--replace-in-metadata`
-
-`--replace-in-metadata FIELDS REGEX REPLACE` is used to replace text in any metadata field using [Python regular expression](https://docs.python.org/3/library/re.html#regular-expression-syntax). [Backreferences](https://docs.python.org/3/library/re.html?highlight=backreferences#re.sub) can be used in the replace string for advanced use.
-
-The general syntax of `--parse-metadata FROM:TO` is to give the name of a field or an [output template](#output-template) to extract data from, and the format to interpret it as, separated by a colon `:`. Either a [Python regular expression](https://docs.python.org/3/library/re.html#regular-expression-syntax) with named capture groups, a single field name, or a similar syntax to the [output template](#output-template) (only `%(field)s` formatting is supported) can be used for `TO`. The option can be used multiple times to parse and modify various fields.
-
-Note that these options preserve their relative order, allowing replacements to be made in parsed fields and vice versa. Also, any field thus created can be used in the [output template](#output-template) and will also affect the media file's metadata added when using `--embed-metadata`.
-
-This option also has a few special uses:
-
-* You can download an additional URL based on the metadata of the currently downloaded video. To do this, set the field `additional_urls` to the URL that you want to download. E.g. `--parse-metadata "description:(?Phttps?://www\.vimeo\.com/\d+)"` will download the first vimeo video found in the description
-
-* You can use this to change the metadata that is embedded in the media file. To do this, set the value of the corresponding field with a `meta_` prefix. For example, any value you set to `meta_description` field will be added to the `description` field in the file - you can use this to set a different "description" and "synopsis". To modify the metadata of individual streams, use the `meta_` prefix (e.g. `meta1_language`). Any value set to the `meta_` field will overwrite all default values.
-
-**Note**: Metadata modification happens before format selection, post-extraction and other post-processing operations. Some fields may be added or changed during these steps, overriding your changes.
-
-For reference, these are the fields yt-dlp adds by default to the file metadata:
-
-Metadata fields | From
-:--------------------------|:------------------------------------------------
-`title` | `track` or `title`
-`date` | `upload_date`
-`description`, `synopsis` | `description`
-`purl`, `comment` | `webpage_url`
-`track` | `track_number`
-`artist` | `artist`, `artists`, `creator`, `creators`, `uploader` or `uploader_id`
-`composer` | `composer` or `composers`
-`genre` | `genre`, `genres`, `categories` or `tags`
-`album` | `album` or `series`
-`album_artist` | `album_artist` or `album_artists`
-`disc` | `disc_number`
-`show` | `series`
-`season_number` | `season_number`
-`episode_id` | `episode` or `episode_id`
-`episode_sort` | `episode_number`
-`language` of each stream | the format's `language`
-
-**Note**: The file format may not support some of these fields
-
-
-## Modifying metadata examples
+### Stop / remove the container
```bash
-# Interpret the title as "Artist - Title"
-$ yt-dlp --parse-metadata "title:%(artist)s - %(title)s"
-
-# Regex example
-$ yt-dlp --parse-metadata "description:Artist - (?P.+)"
-
-# Copy the episode field to the title field (with FROM and TO as single fields)
-$ yt-dlp --parse-metadata "episode:title"
-
-# Set title as "Series name S01E05"
-$ yt-dlp --parse-metadata "%(series)s S%(season_number)02dE%(episode_number)02d:%(title)s"
-
-# Prioritize uploader as the "artist" field in video metadata
-$ yt-dlp --parse-metadata "%(uploader|)s:%(meta_artist)s" --embed-metadata
-
-# Set "comment" field in video metadata using description instead of webpage_url,
-# handling multiple lines correctly
-$ yt-dlp --parse-metadata "description:(?s)(?P.+)" --embed-metadata
-
-# Do not set any "synopsis" in the video metadata
-$ yt-dlp --parse-metadata ":(?P)"
-
-# Remove "formats" field from the infojson by setting it to an empty string
-$ yt-dlp --parse-metadata "video::(?P)" --write-info-json
-
-# Replace all spaces and "_" in title and uploader with a `-`
-$ yt-dlp --replace-in-metadata "title,uploader" "[ _]" "-"
-
+docker stop yt-dlp-web
+docker rm yt-dlp-web
```
-# EXTRACTOR ARGUMENTS
+---
-Some extractors accept additional arguments which can be passed using `--extractor-args KEY:ARGS`. `ARGS` is a `;` (semicolon) separated string of `ARG=VAL1,VAL2`. E.g. `--extractor-args "youtube:player-client=tv,mweb;formats=incomplete" --extractor-args "twitter:api=syndication"`
+## Build from Source
-Note: In CLI, `ARG` can use `-` instead of `_`; e.g. `youtube:player-client"` becomes `youtube:player_client"`
+### Prerequisites
-The following extractors use this feature:
+- [Docker](https://docs.docker.com/get-docker/) installed
-#### youtube
-* `lang`: Prefer translated metadata (`title`, `description` etc) of this language code (case-sensitive). By default, the video primary language metadata is preferred, with a fallback to `en` translated. See [youtube/_base.py](https://github.com/yt-dlp/yt-dlp/blob/415b4c9f955b1a0391204bd24a7132590e7b3bdb/yt_dlp/extractor/youtube/_base.py#L402-L409) for the list of supported content language codes
-* `skip`: One or more of `hls`, `dash` or `translated_subs` to skip extraction of the m3u8 manifests, dash manifests and [auto-translated subtitles](https://github.com/yt-dlp/yt-dlp/issues/4090#issuecomment-1158102032) respectively
-* `player_client`: Clients to extract video data from. The currently available clients are `web`, `web_safari`, `web_embedded`, `web_music`, `web_creator`, `mweb`, `ios`, `android`, `android_vr`, `tv`, `tv_downgraded`, and `tv_simply`. By default, `android_vr,web_safari` is used. If no JavaScript runtime/engine is available, then only `android_vr` is used. If logged-in cookies are passed to yt-dlp, then `tv_downgraded,web_safari` is used for free accounts and `tv_downgraded,web_creator` is used for premium accounts. The `web_music` client is added for `music.youtube.com` URLs when logged-in cookies are used. The `web_embedded` client is added for age-restricted videos but only successfully works around the age-restriction sometimes (e.g. if the video is embeddable), and may be added as a fallback if `android_vr` is unable to access a video. The `web_creator` client is added for age-restricted videos if account age-verification is required. Some clients, such as `web_creator` and `web_music`, require a `po_token` for their formats to be downloadable. Some clients, such as `web_creator`, will only work with authentication. Not all clients support authentication via cookies. You can use `default` for the default clients, or you can use `all` for all clients (not recommended). You can prefix a client with `-` to exclude it, e.g. `youtube:player_client=default,-web_safari`
-* `player_skip`: Skip some network requests that are generally needed for robust extraction. One or more of `configs` (skip client configs), `webpage` (skip initial webpage), `js` (skip js player), `initial_data` (skip initial data/next ep request). While these options can help reduce the number of requests needed or avoid some rate-limiting, they could cause issues such as missing formats or metadata. See [#860](https://github.com/yt-dlp/yt-dlp/pull/860) and [#12826](https://github.com/yt-dlp/yt-dlp/issues/12826) for more details
-* `webpage_skip`: Skip extraction of embedded webpage data. One or both of `player_response`, `initial_data`. These options are for testing purposes and don't skip any network requests. Neither is skipped by default; however, if a `player_js_version` value other than `actual` is used, then `webpage_skip=player_response` is implied
-* `webpage_client`: Client to use for the video webpage request. One of `web` or `web_safari` (default)
-* `player_params`: YouTube player parameters to use for player requests. Will overwrite any default ones set by yt-dlp.
-* `player_js_variant`: The player javascript variant to use for n/sig deciphering. The known variants are: `main`, `tcc`, `tce`, `es5`, `es6`, `es6_tcc`, `es6_tce`, `tv`, `tv_es6`, `phone`, `house`. The default is `main`, and the others are for debugging purposes. You can use `actual` to go with what is prescribed by the site
-* `player_js_version`: The player javascript version to use for n/sig deciphering, in the format of `signature_timestamp@hash` (e.g. `20348@0004de42`). The default is to use what is prescribed by the site, and can be selected with `actual`. Using any other value will imply `webpage_skip=player_response`
-* `comment_sort`: `top` or `new` (default) - choose comment sorting mode (on YouTube's side)
-* `max_comments`: Limit the amount of comments to gather. Comma-separated list of integers representing `max-comments,max-parents,max-replies,max-replies-per-thread,max-depth`. Default is `all,all,all,all,all`
- * A `max-depth` value of `1` will discard all replies, regardless of the `max-replies` or `max-replies-per-thread` values given
- * E.g. `all,all,1000,10,2` will get a maximum of 1000 replies total, with up to 10 replies per thread, and only 2 levels of depth (i.e. top-level comments plus their immediate replies). `1000,all,100` will get a maximum of 1000 comments, with a maximum of 100 replies total
-* `formats`: Change the types of formats to return. `dashy` (convert HTTP to DASH), `duplicate` (identical content but different URLs or protocol; includes `dashy`), `incomplete` (cannot be downloaded completely - live dash, live adaptive https, and post-live m3u8), `missing_pot` (include formats that require a PO Token but are missing one)
-* `innertube_host`: Innertube API host to use for all API requests; e.g. `studio.youtube.com`, `youtubei.googleapis.com`. Note that cookies exported from one subdomain will not work on others
-* `innertube_key`: Innertube API key to use for all API requests. By default, no API key is used
-* `raise_incomplete_data`: `Incomplete Data Received` raises an error instead of reporting a warning
-* `data_sync_id`: Overrides the account Data Sync ID used in Innertube API requests. This may be needed if you are using an account with `youtube:player_skip=webpage,configs` or `youtubetab:skip=webpage`
-* `visitor_data`: Overrides the Visitor Data used in Innertube API requests. This should be used with `player_skip=webpage,configs` and without cookies. Note: this may have adverse effects if used improperly. If a session from a browser is wanted, you should pass cookies instead (which contain the Visitor ID)
-* `po_token`: Proof of Origin (PO) Token(s) to use. Comma-separated list of PO Tokens in the format `CLIENT.CONTEXT+PO_TOKEN`, e.g. `youtube:po_token=web.gvs+XXX,web.player=XXX,web_safari.gvs+YYY`. Context can be any of `gvs` (Google Video Server URLs), `player` (Innertube player request) or `subs` (Subtitles)
-* `pot_trace`: Enable debug logging for PO Token fetching. Either `true` or `false` (default)
-* `fetch_pot`: Policy to use for fetching a PO Token from providers. One of `always` (always try fetch a PO Token regardless if the client requires one for the given context), `never` (never fetch a PO Token), or `auto` (default; only fetch a PO Token if the client requires one for the given context)
-* `jsc_trace`: Enable debug logging for JS Challenge fetching. Either `true` or `false` (default)
-* `use_ad_playback_context`: Skip preroll ads to eliminate the mandatory wait period before download. Do NOT use this when passing premium account cookies to yt-dlp, as it will result in a loss of premium formats. Only effective with the `mweb` and `web_music` player clients. Either `true` or `false` (default)
+### Build the image
-#### youtube-ejs
-* `jitless`: Run supported Javascript engines in JIT-less mode. Supported runtimes are `deno`, `node` and `bun`. Provides better security at the cost of performance/speed. Do note that `node` and `bun` are still considered insecure. Either `true` or `false` (default)
-
-#### youtubepot-webpo
-* `bind_to_visitor_id`: Whether to use the Visitor ID instead of Visitor Data for caching WebPO tokens. Either `true` (default) or `false`
-
-#### youtubetab (YouTube playlists, channels, feeds, etc.)
-* `skip`: One or more of `webpage` (skip initial webpage download), `authcheck` (allow the download of playlists requiring authentication when no initial webpage is downloaded. This may cause unwanted behavior, see [#1122](https://github.com/yt-dlp/yt-dlp/pull/1122) for more details)
-* `approximate_date`: Extract approximate `upload_date` and `timestamp` in flat-playlist. This may cause date-based filters to be slightly off
-
-#### generic
-* `fragment_query`: Passthrough any query in mpd/m3u8 manifest URLs to their fragments if no value is provided, or else apply the query string given as `fragment_query=VALUE`. Note that if the stream has an HLS AES-128 key, then the query parameters will be passed to the key URI as well, unless the `key_query` extractor-arg is passed, or unless an external key URI is provided via the `hls_key` extractor-arg. Does not apply to ffmpeg
-* `variant_query`: Passthrough the master m3u8 URL query to its variant playlist URLs if no value is provided, or else apply the query string given as `variant_query=VALUE`
-* `key_query`: Passthrough the master m3u8 URL query to its HLS AES-128 decryption key URI if no value is provided, or else apply the query string given as `key_query=VALUE`. Note that this will have no effect if the key URI is provided via the `hls_key` extractor-arg. Does not apply to ffmpeg
-* `hls_key`: An HLS AES-128 key URI *or* key (as hex), and optionally the IV (as hex), in the form of `(URI|KEY)[,IV]`; e.g. `generic:hls_key=ABCDEF1234567980,0xFEDCBA0987654321`. Passing any of these values will force usage of the native HLS downloader and override the corresponding values found in the m3u8 playlist
-* `is_live`: Bypass live HLS detection and manually set `live_status` - a value of `false` will set `not_live`, any other value (or no value) will set `is_live`
-* `impersonate`: Target(s) to try and impersonate with the initial webpage request; e.g. `generic:impersonate=safari,chrome-110`. Use `generic:impersonate` to impersonate any available target, and use `generic:impersonate=false` to disable impersonation (default)
-
-#### vikichannel
-* `video_types`: Types of videos to download - one or more of `episodes`, `movies`, `clips`, `trailers`
-
-#### youtubewebarchive
-* `check_all`: Try to check more at the cost of more requests. One or more of `thumbnails`, `captures`
-
-#### gamejolt
-* `comment_sort`: `hot` (default), `you` (cookies needed), `top`, `new` - choose comment sorting mode (on GameJolt's side)
-
-#### hotstar
-* `res`: resolution to ignore - one or more of `sd`, `hd`, `fhd`
-* `vcodec`: vcodec to ignore - one or more of `h264`, `h265`, `dvh265`
-* `dr`: dynamic range to ignore - one or more of `sdr`, `hdr10`, `dv`
-
-#### instagram
-* `app_id`: The value of the `X-IG-App-ID` header used for API requests. Default is the web app ID, `936619743392459`
-
-#### niconicochannelplus
-* `max_comments`: Maximum number of comments to extract - default is `120`
-
-#### tiktok
-* `api_hostname`: Hostname to use for mobile API calls, e.g. `api22-normal-c-alisg.tiktokv.com`
-* `app_name`: Default app name to use with mobile API calls, e.g. `trill`
-* `app_version`: Default app version to use with mobile API calls - should be set along with `manifest_app_version`, e.g. `34.1.2`
-* `manifest_app_version`: Default numeric app version to use with mobile API calls, e.g. `2023401020`
-* `aid`: Default app ID to use with mobile API calls, e.g. `1180`
-* `app_info`: Enable mobile API extraction with one or more app info strings in the format of `/[app_name]/[app_version]/[manifest_app_version]/[aid]`, where `iid` is the unique app install ID. `iid` is the only required value; all other values and their `/` separators can be omitted, e.g. `tiktok:app_info=1234567890123456789` or `tiktok:app_info=123,456/trill///1180,789//34.0.1/340001`
-* `device_id`: Enable mobile API extraction with a genuine device ID to be used with mobile API calls. Default is a random 19-digit string
-
-#### rokfinchannel
-* `tab`: Which tab to download - one of `new`, `top`, `videos`, `podcasts`, `streams`, `stacks`
-
-#### twitter
-* `api`: Select one of `graphql` (default), `legacy` or `syndication` as the API for tweet extraction. Has no effect if logged in
-
-#### stacommu, wrestleuniverse
-* `device_id`: UUID value assigned by the website and used to enforce device limits for paid livestream content. Can be found in browser local storage
-
-#### twitch
-* `client_id`: Client ID value to be sent with GraphQL requests, e.g. `twitch:client_id=kimne78kx3ncx6brgo4mv6wki5h1ko`
-
-#### nhkradirulive (NHK らじる★らじる LIVE)
-* `area`: Which regional variation to extract. Valid areas are: `sapporo`, `sendai`, `tokyo`, `nagoya`, `osaka`, `hiroshima`, `matsuyama`, `fukuoka`. Defaults to `tokyo`
-
-#### nflplusreplay
-* `type`: Type(s) of game replays to extract. Valid types are: `full_game`, `full_game_spanish`, `condensed_game` and `all_22`. You can use `all` to extract all available replay types, which is the default
-
-#### jiocinema
-* `refresh_token`: The `refreshToken` UUID from browser local storage can be passed to extend the life of your login session when logging in with `token` as username and the `accessToken` from browser local storage as password
-
-#### jiosaavn
-* `bitrate`: Audio bitrates to request. One or more of `16`, `32`, `64`, `128`, `320`. Default is `128,320`
-
-#### afreecatvlive
-* `cdn`: One or more CDN IDs to use with the API call for stream URLs, e.g. `gcp_cdn`, `gs_cdn_pc_app`, `gs_cdn_mobile_web`, `gs_cdn_pc_web`
-
-#### soundcloud
-* `formats`: Formats to request from the API. Requested values should be in the format of `{protocol}_{codec}`, e.g. `hls_opus,http_aac`. The `*` character functions as a wildcard, e.g. `*_mp3`, and can be passed by itself to request all formats. Known protocols include `http`, `hls` and `hls-aes`; known codecs include `aac`, `opus` and `mp3`. Original `download` formats are always extracted. Default is `http_aac,hls_aac,http_opus,hls_opus,http_mp3,hls_mp3`
-
-#### orfon (orf:on)
-* `prefer_segments_playlist`: Prefer a playlist of program segments instead of a single complete video when available. If individual segments are desired, use `--concat-playlist never --extractor-args "orfon:prefer_segments_playlist"`
-
-#### bilibili
-* `prefer_multi_flv`: Prefer extracting flv formats over mp4 for older videos that still provide legacy formats
-
-#### sonylivseries
-* `sort_order`: Episode sort order for series extraction - one of `asc` (ascending, oldest first) or `desc` (descending, newest first). Default is `asc`
-
-#### tver
-* `backend`: Backend API to use for extraction - one of `streaks` (default) or `brightcove` (deprecated)
-
-#### vimeo
-* `client`: Client to extract video data from. The currently available clients are `android`, `ios`, `macos` and `web`. Only one client can be used. The `macos` client is used by default, but the `web` client is used when logged-in. The `web` client only works with account cookies or login credentials. The `android` and `ios` clients only work with previously cached OAuth tokens
-* `original_format_policy`: Policy for when to try extracting original formats. One of `always`, `never`, or `auto`. The default `auto` policy tries to avoid exceeding the web client's API rate-limit by only making an extra request when Vimeo publicizes the video's downloadability
-
-**Note**: These options may be changed/removed in the future without concern for backward compatibility
-
-
-
-
-# PLUGINS
-
-Note that **all** plugins are imported even if not invoked, and that **there are no checks** performed on plugin code. **Use plugins at your own risk and only if you trust the code!**
-
-Plugins can be of ``s `extractor` or `postprocessor`.
-- Extractor plugins do not need to be enabled from the CLI and are automatically invoked when the input URL is suitable for it.
-- Extractor plugins take priority over built-in extractors.
-- Postprocessor plugins can be invoked using `--use-postprocessor NAME`.
-
-
-Plugins are loaded from the namespace packages `yt_dlp_plugins.extractor` and `yt_dlp_plugins.postprocessor`.
-
-In other words, the file structure on the disk looks something like:
-
- yt_dlp_plugins/
- extractor/
- myplugin.py
- postprocessor/
- myplugin.py
-
-yt-dlp looks for these `yt_dlp_plugins` namespace folders in many locations (see below) and loads in plugins from **all** of them.
-Set the environment variable `YTDLP_NO_PLUGINS` to something nonempty to disable loading plugins entirely.
-
-See the [wiki for some known plugins](https://github.com/yt-dlp/yt-dlp/wiki/Plugins)
-
-## Installing Plugins
-
-Plugins can be installed using various methods and locations.
-
-1. **Configuration directories**:
- Plugin packages (containing a `yt_dlp_plugins` namespace folder) can be dropped into the following standard [configuration locations](#configuration):
- * **User Plugins**
- * `${XDG_CONFIG_HOME}/yt-dlp/plugins//yt_dlp_plugins/` (recommended on Linux/macOS)
- * `${XDG_CONFIG_HOME}/yt-dlp-plugins//yt_dlp_plugins/`
- * `${APPDATA}/yt-dlp/plugins//yt_dlp_plugins/` (recommended on Windows)
- * `${APPDATA}/yt-dlp-plugins//yt_dlp_plugins/`
- * `~/.yt-dlp/plugins//yt_dlp_plugins/`
- * `~/yt-dlp-plugins//yt_dlp_plugins/`
- * **System Plugins**
- * `/etc/yt-dlp/plugins//yt_dlp_plugins/`
- * `/etc/yt-dlp-plugins//yt_dlp_plugins/`
-2. **Executable location**: Plugin packages can similarly be installed in a `yt-dlp-plugins` directory under the executable location (recommended for portable installations):
- * Binary: where `/yt-dlp.exe`, `/yt-dlp-plugins//yt_dlp_plugins/`
- * Source: where `/yt_dlp/__main__.py`, `/yt-dlp-plugins//yt_dlp_plugins/`
-
-3. **pip and other locations in `PYTHONPATH`**
- * Plugin packages can be installed and managed using `pip`. See [yt-dlp-sample-plugins](https://github.com/yt-dlp/yt-dlp-sample-plugins) for an example.
- * Note: plugin files between plugin packages installed with pip must have unique filenames.
- * Any path in `PYTHONPATH` is searched in for the `yt_dlp_plugins` namespace folder.
- * Note: This does not apply for Pyinstaller builds.
-
-
-`.zip`, `.egg` and `.whl` archives containing a `yt_dlp_plugins` namespace folder in their root are also supported as plugin packages.
-
-* e.g. `${XDG_CONFIG_HOME}/yt-dlp/plugins/mypluginpkg.zip` where `mypluginpkg.zip` contains `yt_dlp_plugins//myplugin.py`
-
-Run yt-dlp with `--verbose` to check if the plugin has been loaded.
-
-## Developing Plugins
-
-See the [yt-dlp-sample-plugins](https://github.com/yt-dlp/yt-dlp-sample-plugins) repo for a template plugin package and the [Plugin Development](https://github.com/yt-dlp/yt-dlp/wiki/Plugin-Development) section of the wiki for a plugin development guide.
-
-All public classes with a name ending in `IE`/`PP` are imported from each file for extractors and postprocessors respectively. This respects underscore prefix (e.g. `_MyBasePluginIE` is private) and `__all__`. Modules can similarly be excluded by prefixing the module name with an underscore (e.g. `_myplugin.py`).
-
-To replace an existing extractor with a subclass of one, set the `plugin_name` class keyword argument (e.g. `class MyPluginIE(ABuiltInIE, plugin_name='myplugin')` will replace `ABuiltInIE` with `MyPluginIE`). Since the extractor replaces the parent, you should exclude the subclass extractor from being imported separately by making it private using one of the methods described above.
-
-If you are a plugin author, add [yt-dlp-plugins](https://github.com/topics/yt-dlp-plugins) as a topic to your repository for discoverability.
-
-See the [Developer Instructions](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) on how to write and test an extractor.
-
-# EMBEDDING YT-DLP
-
-yt-dlp makes the best effort to be a good command-line program, and thus should be callable from any programming language.
-
-Your program should avoid parsing the normal stdout since they may change in future versions. Instead, they should use options such as `-J`, `--print`, `--progress-template`, `--exec` etc to create console output that you can reliably reproduce and parse.
-
-From a Python program, you can embed yt-dlp in a more powerful fashion, like this:
-
-```python
-from yt_dlp import YoutubeDL
-
-URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']
-with YoutubeDL() as ydl:
- ydl.download(URLS)
+```bash
+git clone https://github.com/YOUR_GITHUB_USERNAME/yt-dlp-web.git
+cd yt-dlp-web
+docker build -t yt-dlp-web .
```
-Most likely, you'll want to use various options. For a list of options available, have a look at [`yt_dlp/YoutubeDL.py`](yt_dlp/YoutubeDL.py#L183) or `help(yt_dlp.YoutubeDL)` in a Python shell. If you are already familiar with the CLI, you can use [`devscripts/cli_to_api.py`](https://github.com/yt-dlp/yt-dlp/blob/master/devscripts/cli_to_api.py) to translate any CLI switches to `YoutubeDL` params.
+### Run the image
-**Tip**: If you are porting your code from youtube-dl to yt-dlp, one important point to look out for is that we do not guarantee the return value of `YoutubeDL.extract_info` to be json serializable, or even be a dictionary. It will be dictionary-like, but if you want to ensure it is a serializable dictionary, pass it through `YoutubeDL.sanitize_info` as shown in the [example below](#extracting-information)
-
-## Embedding examples
-
-#### Extracting information
-
-```python
-import json
-import yt_dlp
-
-URL = 'https://www.youtube.com/watch?v=BaW_jenozKc'
-
-# ℹ️ See help(yt_dlp.YoutubeDL) for a list of available options and public functions
-ydl_opts = {}
-with yt_dlp.YoutubeDL(ydl_opts) as ydl:
- info = ydl.extract_info(URL, download=False)
-
- # ℹ️ ydl.sanitize_info makes the info json-serializable
- print(json.dumps(ydl.sanitize_info(info)))
-```
-#### Download using an info-json
-
-```python
-import yt_dlp
-
-INFO_FILE = 'path/to/video.info.json'
-
-with yt_dlp.YoutubeDL() as ydl:
- error_code = ydl.download_with_info_file(INFO_FILE)
-
-print('Some videos failed to download' if error_code
- else 'All videos successfully downloaded')
+```bash
+docker run -d -p 8000:8000 --name yt-dlp-web yt-dlp-web
```
-#### Extract audio
+Open **http://localhost:8000**.
-```python
-import yt_dlp
+---
-URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']
+## Run without Docker (Development)
-ydl_opts = {
- 'format': 'm4a/bestaudio/best',
- # ℹ️ See help(yt_dlp.postprocessor) for a list of available Postprocessors and their arguments
- 'postprocessors': [{ # Extract audio using ffmpeg
- 'key': 'FFmpegExtractAudio',
- 'preferredcodec': 'm4a',
- }]
-}
+### Prerequisites
-with yt_dlp.YoutubeDL(ydl_opts) as ydl:
- error_code = ydl.download(URLS)
+- Python 3.10+
+- ffmpeg installed and on PATH ([download](https://ffmpeg.org/download.html))
+
+### Setup
+
+```bash
+# Install yt-dlp from source
+pip install -e ".[default]"
+
+# Install backend dependencies
+pip install fastapi "uvicorn[standard]" httpx
+
+# Start the server
+python -m uvicorn web.backend.main:app --reload --port 8000
```
-#### Filter videos
+Open **http://localhost:8000**.
-```python
-import yt_dlp
+---
-URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']
+## Usage Guide
-def longer_than_a_minute(info, *, incomplete):
- """Download only videos longer than a minute (or with unknown duration)"""
- duration = info.get('duration')
- if duration and duration < 60:
- return 'The video is too short'
+1. **Paste a URL** — Paste any YouTube (or supported site) link into the input field and click **Fetch**
+2. **Review video info** — Thumbnail, title, uploader, duration, views, likes, and upload date are shown
+3. **Select a format** — Choose from the dropdown (highest quality is pre-selected)
+4. **Download** — Click the **Download** button and watch the live progress bar
+5. **Cancel** — Click **Cancel** at any time to stop the download
-ydl_opts = {
- 'match_filter': longer_than_a_minute,
-}
+### YouTube authentication (optional)
-with yt_dlp.YoutubeDL(ydl_opts) as ydl:
- error_code = ydl.download(URLS)
+Some videos require sign-in. Export your cookies using the [Get cookies.txt LOCALLY](https://chrome.google.com/webstore/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc) browser extension and mount them:
+
+```bash
+docker run -d \
+ -p 8000:8000 \
+ -v $(pwd)/cookies.txt:/app/web/backend/cookies.txt:ro \
+ --name yt-dlp-web \
+ samive/yt-dlp-web:latest
```
-#### Adding logger and progress hook
+> **Note:** Using cookies with Chrome on Windows may cause issues due to DPAPI encryption. Firefox or Edge cookies work more reliably.
-```python
-import yt_dlp
+---
-URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']
+## Publish to Docker Hub
-class MyLogger:
- def debug(self, msg):
- # For compatibility with youtube-dl, both debug and info are passed into debug
- # You can distinguish them by the prefix '[debug] '
- if msg.startswith('[debug] '):
- pass
- else:
- self.info(msg)
+### 1. Create a Docker Hub account
- def info(self, msg):
- pass
+Sign up at [hub.docker.com](https://hub.docker.com) and create a public repository named `yt-dlp-web`.
- def warning(self, msg):
- pass
+### 2. Log in from terminal
- def error(self, msg):
- print(msg)
-
-
-# ℹ️ See "progress_hooks" in help(yt_dlp.YoutubeDL)
-def my_hook(d):
- if d['status'] == 'finished':
- print('Done downloading, now post-processing ...')
-
-
-ydl_opts = {
- 'logger': MyLogger(),
- 'progress_hooks': [my_hook],
-}
-
-with yt_dlp.YoutubeDL(ydl_opts) as ydl:
- ydl.download(URLS)
+```bash
+docker login
```
-#### Add a custom PostProcessor
+### 3. Build and tag the image
-```python
-import yt_dlp
-
-URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']
-
-# ℹ️ See help(yt_dlp.postprocessor.PostProcessor)
-class MyCustomPP(yt_dlp.postprocessor.PostProcessor):
- def run(self, info):
- self.to_screen('Doing stuff')
- return [], info
-
-
-with yt_dlp.YoutubeDL() as ydl:
- # ℹ️ "when" can take any value in yt_dlp.utils.POSTPROCESS_WHEN
- ydl.add_post_processor(MyCustomPP(), when='pre_process')
- ydl.download(URLS)
+```bash
+docker build -t samive/yt-dlp-web:latest .
```
+### 4. Push to Docker Hub
-#### Use a custom format selector
-
-```python
-import yt_dlp
-
-URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']
-
-def format_selector(ctx):
- """ Select the best video and the best audio that won't result in an mkv.
- NOTE: This is just an example and does not handle all cases """
-
- # formats are already sorted worst to best
- formats = ctx.get('formats')[::-1]
-
- # acodec='none' means there is no audio
- best_video = next(f for f in formats
- if f['vcodec'] != 'none' and f['acodec'] == 'none')
-
- # find compatible audio extension
- audio_ext = {'mp4': 'm4a', 'webm': 'webm'}[best_video['ext']]
- # vcodec='none' means there is no video
- best_audio = next(f for f in formats if (
- f['acodec'] != 'none' and f['vcodec'] == 'none' and f['ext'] == audio_ext))
-
- # These are the minimum required fields for a merged format
- yield {
- 'format_id': f'{best_video["format_id"]}+{best_audio["format_id"]}',
- 'ext': best_video['ext'],
- 'requested_formats': [best_video, best_audio],
- # Must be + separated list of protocols
- 'protocol': f'{best_video["protocol"]}+{best_audio["protocol"]}'
- }
-
-
-ydl_opts = {
- 'format': format_selector,
-}
-
-with yt_dlp.YoutubeDL(ydl_opts) as ydl:
- ydl.download(URLS)
+```bash
+docker push samive/yt-dlp-web:latest
```
+### 5. (Optional) Tag a version
-# CHANGES FROM YOUTUBE-DL
+```bash
+docker tag samive/yt-dlp-web:latest samive/yt-dlp-web:1.0.0
+docker push samive/yt-dlp-web:1.0.0
+```
-### New features
+Anyone can now pull and run your image with:
-* Forked from [**yt-dlc@f9401f2**](https://github.com/blackjack4494/yt-dlc/commit/f9401f2a91987068139c5f757b12fc711d4c0cee) and merged with [**youtube-dl@a08f2b7**](https://github.com/ytdl-org/youtube-dl/commit/a08f2b7e4567cdc50c0614ee0a4ffdff49b8b6e6) ([exceptions](https://github.com/yt-dlp/yt-dlp/issues/21))
+```bash
+docker pull samive/yt-dlp-web:latest
+```
-* **[SponsorBlock Integration](#sponsorblock-options)**: You can mark/remove sponsor sections in YouTube videos by utilizing the [SponsorBlock](https://sponsor.ajay.app) API
+---
-* **[Format Sorting](#sorting-formats)**: The default format sorting options have been changed so that higher resolution and better codecs will be now preferred instead of simply using larger bitrate. Furthermore, you can now specify the sort order using `-S`. This allows for much easier format selection than what is possible by simply using `--format` ([examples](#format-selection-examples))
+## Tech Stack
-* **Merged with animelover1984/youtube-dl**: You get most of the features and improvements from [animelover1984/youtube-dl](https://github.com/animelover1984/youtube-dl) including `--write-comments`, `BiliBiliSearch`, `BilibiliChannel`, Embedding thumbnail in mp4/ogg/opus, playlist infojson etc. See [#31](https://github.com/yt-dlp/yt-dlp/pull/31) for details.
+- **Backend** — Python, [FastAPI](https://fastapi.tiangolo.com/), [yt-dlp](https://github.com/yt-dlp/yt-dlp)
+- **Frontend** — Vanilla HTML/CSS/JS (no framework)
+- **Container** — Docker with ffmpeg
-* **YouTube improvements**:
- * Supports Clips, Stories (`ytstories:`), Search (including filters)**\***, YouTube Music Search, Channel-specific search, Search prefix (`ytsearch:`)**\***, Mixes, and Feeds (`:ytfav`, `:ytwatchlater`, `:ytsubs`, `:ythistory`, `:ytrec`, `:ytnotif`)
- * Fix for [n-sig based throttling](https://github.com/ytdl-org/youtube-dl/issues/29326) **\***
- * Download livestreams from the start using `--live-from-start` (*experimental*)
- * Channel URLs download all uploads of the channel, including shorts and live
+---
-* **Cookies from browser**: Cookies can be automatically extracted from all major web browsers using `--cookies-from-browser BROWSER[+KEYRING][:PROFILE][::CONTAINER]`
+## License
-* **Download time range**: Videos can be downloaded partially based on either timestamps or chapters using `--download-sections`
-
-* **Split video by chapters**: Videos can be split into multiple files based on chapters using `--split-chapters`
-
-* **Multi-threaded fragment downloads**: Download multiple fragments of m3u8/mpd videos in parallel. Use `--concurrent-fragments` (`-N`) option to set the number of threads used
-
-* **Aria2c with HLS/DASH**: You can use `aria2c` as the external downloader for DASH(mpd) and HLS(m3u8) formats
-
-* **New and fixed extractors**: Many new extractors have been added and a lot of existing ones have been fixed. See the [changelog](Changelog.md) or the [list of supported sites](supportedsites.md)
-
-* **New MSOs**: Philo, Spectrum, SlingTV, Cablevision, RCN etc.
-
-* **Subtitle extraction from manifests**: Subtitles can be extracted from streaming media manifests. See [commit/be6202f](https://github.com/yt-dlp/yt-dlp/commit/be6202f12b97858b9d716e608394b51065d0419f) for details
-
-* **Multiple paths and output templates**: You can give different [output templates](#output-template) and download paths for different types of files. You can also set a temporary path where intermediary files are downloaded to using `--paths` (`-P`)
-
-* **Portable Configuration**: Configuration files are automatically loaded from the home and root directories. See [CONFIGURATION](#configuration) for details
-
-* **Output template improvements**: Output templates can now have date-time formatting, numeric offsets, object traversal etc. See [output template](#output-template) for details. Even more advanced operations can also be done with the help of `--parse-metadata` and `--replace-in-metadata`
-
-* **Other new options**: Many new options have been added such as `--alias`, `--print`, `--concat-playlist`, `--wait-for-video`, `--retry-sleep`, `--sleep-requests`, `--convert-thumbnails`, `--force-download-archive`, `--force-overwrites`, `--break-match-filters` etc
-
-* **Improvements**: Regex and other operators in `--format`/`--match-filters`, multiple `--postprocessor-args` and `--downloader-args`, faster archive checking, more [format selection options](#format-selection), merge multi-video/audio, multiple `--config-locations`, `--exec` at different stages, etc
-
-* **Plugins**: Extractors and PostProcessors can be loaded from an external file. See [plugins](#plugins) for details
-
-* **Self updater**: The releases can be updated using `yt-dlp -U`, and downgraded using `--update-to` if required
-
-* **Automated builds**: [Nightly/master builds](#update-channels) can be used with `--update-to nightly` and `--update-to master`
-
-See [changelog](Changelog.md) or [commits](https://github.com/yt-dlp/yt-dlp/commits) for the full list of changes
-
-Features marked with a **\*** have been back-ported to youtube-dl
-
-### Differences in default behavior
-
-Some of yt-dlp's default options are different from that of youtube-dl and youtube-dlc:
-
-* yt-dlp supports only [Python 3.10+](## "Windows 8"), and will remove support for more versions as they [become EOL](https://devguide.python.org/versions/#python-release-cycle); while [youtube-dl still supports Python 2.6+ and 3.2+](https://github.com/ytdl-org/youtube-dl/issues/30568#issue-1118238743)
-* The options `--auto-number` (`-A`), `--title` (`-t`) and `--literal` (`-l`), no longer work. See [removed options](#Removed) for details
-* `avconv` is not supported as an alternative to `ffmpeg`
-* yt-dlp stores config files in slightly different locations to youtube-dl. See [CONFIGURATION](#configuration) for a list of correct locations
-* The default [output template](#output-template) is `%(title)s [%(id)s].%(ext)s`. There is no real reason for this change. This was changed before yt-dlp was ever made public and now there are no plans to change it back to `%(title)s-%(id)s.%(ext)s`. Instead, you may use `--compat-options filename`
-* The default [format sorting](#sorting-formats) is different from youtube-dl and prefers higher resolution and better codecs rather than higher bitrates. You can use the `--format-sort` option to change this to any order you prefer, or use `--compat-options format-sort` to use youtube-dl's sorting order. Older versions of yt-dlp preferred VP9 due to its broader compatibility; you can use `--compat-options prefer-vp9-sort` to revert to that format sorting preference. These two compat options cannot be used together
-* The default format selector is `bv*+ba/b`. This means that if a combined video + audio format that is better than the best video-only format is found, the former will be preferred. Use `-f bv+ba/b` or `--compat-options format-spec` to revert this
-* Unlike youtube-dlc, yt-dlp does not allow merging multiple audio/video streams into one file by default (since this conflicts with the use of `-f bv*+ba`). If needed, this feature must be enabled using `--audio-multistreams` and `--video-multistreams`. You can also use `--compat-options multistreams` to enable both
-* `--no-abort-on-error` is enabled by default. Use `--abort-on-error` or `--compat-options abort-on-error` to abort on errors instead
-* When writing metadata files such as thumbnails, description or infojson, the same information (if available) is also written for playlists. Use `--no-write-playlist-metafiles` or `--compat-options no-playlist-metafiles` to not write these files
-* `--add-metadata` attaches the `infojson` to `mkv` files in addition to writing the metadata when used with `--write-info-json`. Use `--no-embed-info-json` or `--compat-options no-attach-info-json` to revert this
-* Some metadata are embedded into different fields when using `--add-metadata` as compared to youtube-dl. Most notably, `comment` field contains the `webpage_url` and `synopsis` contains the `description`. You can [use `--parse-metadata`](#modifying-metadata) to modify this to your liking or use `--compat-options embed-metadata` to revert this
-* `playlist_index` behaves differently when used with options like `--playlist-reverse` and `--playlist-items`. See [#302](https://github.com/yt-dlp/yt-dlp/issues/302) for details. You can use `--compat-options playlist-index` if you want to keep the earlier behavior
-* The output of `-F` is listed in a new format. Use `--compat-options list-formats` to revert this
-* Live chats (if available) are considered as subtitles. Use `--sub-langs all,-live_chat` to download all subtitles except live chat. You can also use `--compat-options no-live-chat` to prevent any live chat/danmaku from downloading
-* YouTube channel URLs download all uploads of the channel. To download only the videos in a specific tab, pass the tab's URL. If the channel does not show the requested tab, an error will be raised. Also, `/live` URLs raise an error if there are no live videos instead of silently downloading the entire channel. You may use `--compat-options no-youtube-channel-redirect` to revert all these redirections
-* Unavailable videos are also listed for YouTube playlists. Use `--compat-options no-youtube-unavailable-videos` to remove this
-* The upload dates extracted from YouTube are in UTC.
-* If `ffmpeg` is used as the downloader, the downloading and merging of formats happen in a single step when possible. Use `--compat-options no-direct-merge` to revert this
-* Thumbnail embedding in `mp4` is done with mutagen if possible. Use `--compat-options embed-thumbnail-atomicparsley` to force the use of AtomicParsley instead
-* Some internal metadata such as filenames are removed by default from the infojson. Use `--no-clean-infojson` or `--compat-options no-clean-infojson` to revert this
-* When `--embed-subs` and `--write-subs` are used together, the subtitles are written to disk and also embedded in the media file. You can use just `--embed-subs` to embed the subs and automatically delete the separate file. See [#630 (comment)](https://github.com/yt-dlp/yt-dlp/issues/630#issuecomment-893659460) for more info. `--compat-options no-keep-subs` can be used to revert this
-* `certifi` will be used for SSL root certificates, if installed. If you want to use system certificates (e.g. self-signed), use `--compat-options no-certifi`
-* yt-dlp's sanitization of invalid characters in filenames is different/smarter than in youtube-dl. You can use `--compat-options filename-sanitization` to revert to youtube-dl's behavior
-* ~~yt-dlp tries to parse the external downloader outputs into the standard progress output if possible (Currently implemented: [aria2c](https://github.com/yt-dlp/yt-dlp/issues/5931)). You can use `--compat-options no-external-downloader-progress` to get the downloader output as-is~~
-* yt-dlp versions between 2021.09.01 and 2023.01.02 applies `--match-filters` to nested playlists. This was an unintentional side-effect of [8f18ac](https://github.com/yt-dlp/yt-dlp/commit/8f18aca8717bb0dd49054555af8d386e5eda3a88) and is fixed in [d7b460](https://github.com/yt-dlp/yt-dlp/commit/d7b460d0e5fc710950582baed2e3fc616ed98a80). Use `--compat-options playlist-match-filter` to revert this
-* yt-dlp versions between 2021.11.10 and 2023.06.21 estimated `filesize_approx` values for fragmented/manifest formats. This was added for convenience in [f2fe69](https://github.com/yt-dlp/yt-dlp/commit/f2fe69c7b0d208bdb1f6292b4ae92bc1e1a7444a), but was reverted in [0dff8e](https://github.com/yt-dlp/yt-dlp/commit/0dff8e4d1e6e9fb938f4256ea9af7d81f42fd54f) due to the potentially extreme inaccuracy of the estimated values. Use `--compat-options manifest-filesize-approx` to keep extracting the estimated values
-* yt-dlp uses modern http client backends such as `requests`. Use `--compat-options prefer-legacy-http-handler` to prefer the legacy http handler (`urllib`) to be used for standard http requests.
-* The sub-modules `swfinterp`, `casefold` are removed.
-* Passing `--simulate` (or calling `extract_info` with `download=False`) no longer alters the default format selection. See [#9843](https://github.com/yt-dlp/yt-dlp/issues/9843) for details.
-* yt-dlp no longer applies the server modified time to downloaded files by default. Use `--mtime` or `--compat-options mtime-by-default` to revert this.
-
-For convenience, there are some compat option aliases available to use:
-
-* `--compat-options all`: Use all compat options (**Do NOT use this!**)
-* `--compat-options youtube-dl`: Same as `--compat-options all,-multistreams,-playlist-match-filter,-manifest-filesize-approx,-allow-unsafe-ext,-prefer-vp9-sort`
-* `--compat-options youtube-dlc`: Same as `--compat-options all,-no-live-chat,-no-youtube-channel-redirect,-playlist-match-filter,-manifest-filesize-approx,-allow-unsafe-ext,-prefer-vp9-sort`
-* `--compat-options 2021`: Same as `--compat-options 2022,no-certifi,filename-sanitization`
-* `--compat-options 2022`: Same as `--compat-options 2023,playlist-match-filter,no-external-downloader-progress,prefer-legacy-http-handler,manifest-filesize-approx`
-* `--compat-options 2023`: Same as `--compat-options 2024,prefer-vp9-sort`
-* `--compat-options 2024`: Same as `--compat-options 2025,mtime-by-default`
-* `--compat-options 2025`: Currently does nothing. Use this to enable all future compat options
-
-Using one of the yearly compat option aliases will pin yt-dlp's default behavior to what it was at the *end* of that calendar year.
-
-The following compat options restore vulnerable behavior from before security patches:
-
-* `--compat-options allow-unsafe-ext`: Allow files with any extension (including unsafe ones) to be downloaded ([GHSA-79w7-vh3h-8g4j]())
-
- > :warning: Only use if a valid file download is rejected because its extension is detected as uncommon
- >
- > **This option can enable remote code execution! Consider [opening an issue]() instead!**
-
-### Deprecated options
-
-These are all the deprecated options and the current alternative to achieve the same effect
-
-#### Almost redundant options
-While these options are almost the same as their new counterparts, there are some differences that prevents them being redundant
-
- -j, --dump-json --print "%()j"
- -F, --list-formats --print formats_table
- --list-thumbnails --print thumbnails_table --print playlist:thumbnails_table
- --list-subs --print automatic_captions_table --print subtitles_table
-
-#### Redundant options
-While these options are redundant, they are still expected to be used due to their ease of use
-
- --get-description --print description
- --get-duration --print duration_string
- --get-filename --print filename
- --get-format --print format
- --get-id --print id
- --get-thumbnail --print thumbnail
- -e, --get-title --print title
- -g, --get-url --print urls
- --match-title REGEX --match-filters "title ~= (?i)REGEX"
- --reject-title REGEX --match-filters "title !~= (?i)REGEX"
- --min-views COUNT --match-filters "view_count >=? COUNT"
- --max-views COUNT --match-filters "view_count <=? COUNT"
- --break-on-reject Use --break-match-filters
- --user-agent UA --add-headers "User-Agent:UA"
- --referer URL --add-headers "Referer:URL"
- --playlist-start NUMBER -I NUMBER:
- --playlist-end NUMBER -I :NUMBER
- --playlist-reverse -I ::-1
- --no-playlist-reverse Default
- --no-colors --color no_color
-
-#### Not recommended
-While these options still work, their use is not recommended since there are other alternatives to achieve the same
-
- --force-generic-extractor --ies generic,default
- --exec-before-download CMD --exec "before_dl:CMD"
- --no-exec-before-download --no-exec
- --all-formats -f all
- --all-subs --sub-langs all --write-subs
- --print-json -j --no-simulate
- --autonumber-size NUMBER Use string formatting, e.g. %(autonumber)03d
- --autonumber-start NUMBER Use internal field formatting like %(autonumber+NUMBER)s
- --id -o "%(id)s.%(ext)s"
- --metadata-from-title FORMAT --parse-metadata "%(title)s:FORMAT"
- --hls-prefer-native --downloader "m3u8:native"
- --hls-prefer-ffmpeg --downloader "m3u8:ffmpeg"
- --list-formats-old --compat-options list-formats (Alias: --no-list-formats-as-table)
- --list-formats-as-table --compat-options -list-formats [Default]
- --geo-bypass --xff "default"
- --no-geo-bypass --xff "never"
- --geo-bypass-country CODE --xff CODE
- --geo-bypass-ip-block IP_BLOCK --xff IP_BLOCK
-
-#### Developer options
-These options are not intended to be used by the end-user
-
- --test Download only part of video for testing extractors
- --load-pages Load pages dumped by --write-pages
- --allow-unplayable-formats List unplayable formats also
- --no-allow-unplayable-formats Default
-
-#### Old aliases
-These are aliases that are no longer documented for various reasons
-
- --clean-infojson --clean-info-json
- --force-write-download-archive --force-write-archive
- --no-clean-infojson --no-clean-info-json
- --no-split-tracks --no-split-chapters
- --no-write-srt --no-write-subs
- --prefer-unsecure --prefer-insecure
- --rate-limit RATE --limit-rate RATE
- --split-tracks --split-chapters
- --srt-lang LANGS --sub-langs LANGS
- --trim-file-names LENGTH --trim-filenames LENGTH
- --write-srt --write-subs
- --yes-overwrites --force-overwrites
-
-#### Sponskrub Options
-Support for [SponSkrub](https://github.com/faissaloo/SponSkrub) has been removed in favor of the `--sponsorblock` options
-
- --sponskrub --sponsorblock-mark all
- --no-sponskrub --no-sponsorblock
- --sponskrub-cut --sponsorblock-remove all
- --no-sponskrub-cut --sponsorblock-remove -all
- --sponskrub-force Not applicable
- --no-sponskrub-force Not applicable
- --sponskrub-location Not applicable
- --sponskrub-args Not applicable
-
-#### No longer supported
-These options may no longer work as intended
-
- --prefer-avconv avconv is not officially supported by yt-dlp (Alias: --no-prefer-ffmpeg)
- --prefer-ffmpeg Default (Alias: --no-prefer-avconv)
- -C, --call-home Not implemented
- --no-call-home Default
- --include-ads No longer supported
- --no-include-ads Default
- --write-annotations No supported site has annotations now
- --no-write-annotations Default
- --avconv-location Removed alias for --ffmpeg-location
- --cn-verification-proxy URL Removed alias for --geo-verification-proxy URL
- --dump-headers Removed alias for --print-traffic
- --dump-intermediate-pages Removed alias for --dump-pages
- --youtube-skip-dash-manifest Removed alias for --extractor-args "youtube:skip=dash" (Alias: --no-youtube-include-dash-manifest)
- --youtube-skip-hls-manifest Removed alias for --extractor-args "youtube:skip=hls" (Alias: --no-youtube-include-hls-manifest)
- --youtube-include-dash-manifest Default (Alias: --no-youtube-skip-dash-manifest)
- --youtube-include-hls-manifest Default (Alias: --no-youtube-skip-hls-manifest)
- --youtube-print-sig-code Removed testing functionality
- --dump-user-agent No longer supported
- --xattr-set-filesize No longer supported
- --compat-options seperate-video-versions No longer needed
- --compat-options no-youtube-prefer-utc-upload-date No longer supported
-
-#### Removed
-These options were deprecated since 2014 and have now been entirely removed
-
- -A, --auto-number -o "%(autonumber)s-%(id)s.%(ext)s"
- -t, -l, --title, --literal -o "%(title)s-%(id)s.%(ext)s"
-
-
-# CONTRIBUTING
-See [CONTRIBUTING.md](CONTRIBUTING.md#contributing-to-yt-dlp) for instructions on [Opening an Issue](CONTRIBUTING.md#opening-an-issue) and [Contributing code to the project](CONTRIBUTING.md#developer-instructions)
-
-# WIKI
-See the [Wiki](https://github.com/yt-dlp/yt-dlp/wiki) for more information
+This project uses yt-dlp which is licensed under [The Unlicense](LICENSE).
diff --git a/test/__init__.py b/test/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/test/conftest.py b/test/conftest.py
deleted file mode 100644
index 9d3198619..000000000
--- a/test/conftest.py
+++ /dev/null
@@ -1,94 +0,0 @@
-import inspect
-
-import pytest
-
-from yt_dlp.networking import RequestHandler
-from yt_dlp.networking.common import _REQUEST_HANDLERS
-from yt_dlp.utils._utils import _YDLLogger as FakeLogger
-
-
-@pytest.fixture
-def handler(request):
- RH_KEY = getattr(request, 'param', None)
- if not RH_KEY:
- return
- if inspect.isclass(RH_KEY) and issubclass(RH_KEY, RequestHandler):
- handler = RH_KEY
- elif RH_KEY in _REQUEST_HANDLERS:
- handler = _REQUEST_HANDLERS[RH_KEY]
- else:
- pytest.skip(f'{RH_KEY} request handler is not available')
-
- class HandlerWrapper(handler):
- RH_KEY = handler.RH_KEY
-
- def __init__(self, **kwargs):
- super().__init__(logger=FakeLogger, **kwargs)
-
- return HandlerWrapper
-
-
-@pytest.fixture(autouse=True)
-def skip_handler(request, handler):
- """usage: pytest.mark.skip_handler('my_handler', 'reason')"""
- for marker in request.node.iter_markers('skip_handler'):
- if marker.args[0] == handler.RH_KEY:
- pytest.skip(marker.args[1] if len(marker.args) > 1 else '')
-
-
-@pytest.fixture(autouse=True)
-def skip_handler_if(request, handler):
- """usage: pytest.mark.skip_handler_if('my_handler', lambda request: True, 'reason')"""
- for marker in request.node.iter_markers('skip_handler_if'):
- if marker.args[0] == handler.RH_KEY and marker.args[1](request):
- pytest.skip(marker.args[2] if len(marker.args) > 2 else '')
-
-
-@pytest.fixture(autouse=True)
-def skip_handlers_if(request, handler):
- """usage: pytest.mark.skip_handlers_if(lambda request, handler: True, 'reason')"""
- for marker in request.node.iter_markers('skip_handlers_if'):
- if handler and marker.args[0](request, handler):
- pytest.skip(marker.args[1] if len(marker.args) > 1 else '')
-
-
-@pytest.fixture(autouse=True)
-def handler_flaky(request, handler):
- """Mark a certain handler as being flaky.
-
- This will skip the test if pytest does not get run using `--allow-flaky`
-
- usage:
- pytest.mark.handler_flaky('my_handler', os.name != 'nt', reason='reason')
- """
- for marker in request.node.iter_markers(handler_flaky.__name__):
- if (
- marker.args[0] == handler.RH_KEY
- and (not marker.args[1:] or any(marker.args[1:]))
- and request.config.getoption('disallow_flaky')
- ):
- reason = marker.kwargs.get('reason')
- pytest.skip(f'flaky: {reason}' if reason else 'flaky')
-
-
-def pytest_addoption(parser, pluginmanager):
- parser.addoption(
- '--disallow-flaky',
- action='store_true',
- help='disallow flaky tests from running.',
- )
-
-
-def pytest_configure(config):
- config.addinivalue_line(
- 'markers', 'skip_handler(handler): skip test for the given handler',
- )
- config.addinivalue_line(
- 'markers', 'skip_handler_if(handler): skip test for the given handler if condition is true',
- )
- config.addinivalue_line(
- 'markers', 'skip_handlers_if(handler): skip test for handlers when the condition is true',
- )
- config.addinivalue_line(
- 'markers', 'handler_flaky(handler): mark handler as flaky if condition is true',
- )
diff --git a/test/helper.py b/test/helper.py
deleted file mode 100644
index 4f65a09d1..000000000
--- a/test/helper.py
+++ /dev/null
@@ -1,384 +0,0 @@
-import errno
-import hashlib
-import json
-import os.path
-import re
-import ssl
-import sys
-import types
-
-import yt_dlp.extractor
-from yt_dlp import YoutubeDL
-from yt_dlp.utils import preferredencoding, try_call, write_string, find_available_port
-
-if 'pytest' in sys.modules:
- import pytest
- is_download_test = pytest.mark.download
-else:
- def is_download_test(test_class):
- return test_class
-
-
-def get_params(override=None):
- PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
- 'parameters.json')
- LOCAL_PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
- 'local_parameters.json')
- with open(PARAMETERS_FILE, encoding='utf-8') as pf:
- parameters = json.load(pf)
- if os.path.exists(LOCAL_PARAMETERS_FILE):
- with open(LOCAL_PARAMETERS_FILE, encoding='utf-8') as pf:
- parameters.update(json.load(pf))
- if override:
- parameters.update(override)
- return parameters
-
-
-def try_rm(filename):
- """ Remove a file if it exists """
- try:
- os.remove(filename)
- except OSError as ose:
- if ose.errno != errno.ENOENT:
- raise
-
-
-def report_warning(message, *args, **kwargs):
- """
- Print the message to stderr, it will be prefixed with 'WARNING:'
- If stderr is a tty file the 'WARNING:' will be colored
- """
- if sys.stderr.isatty() and os.name != 'nt':
- _msg_header = '\033[0;33mWARNING:\033[0m'
- else:
- _msg_header = 'WARNING:'
- output = f'{_msg_header} {message}\n'
- if 'b' in getattr(sys.stderr, 'mode', ''):
- output = output.encode(preferredencoding())
- sys.stderr.write(output)
-
-
-class FakeYDL(YoutubeDL):
- def __init__(self, override=None):
- # Different instances of the downloader can't share the same dictionary
- # some test set the "sublang" parameter, which would break the md5 checks.
- params = get_params(override=override)
- super().__init__(params, auto_init=False)
- self.result = []
-
- def to_screen(self, s, *args, **kwargs):
- print(s)
-
- def trouble(self, s, *args, **kwargs):
- raise Exception(s)
-
- def download(self, x):
- self.result.append(x)
-
- def expect_warning(self, regex):
- # Silence an expected warning matching a regex
- old_report_warning = self.report_warning
-
- def report_warning(self, message, *args, **kwargs):
- if re.match(regex, message):
- return
- old_report_warning(message, *args, **kwargs)
- self.report_warning = types.MethodType(report_warning, self)
-
-
-def gettestcases(include_onlymatching=False):
- for ie in yt_dlp.extractor.gen_extractors():
- yield from ie.get_testcases(include_onlymatching)
-
-
-def getwebpagetestcases():
- for ie in yt_dlp.extractor.gen_extractors():
- for tc in ie.get_webpage_testcases():
- tc.setdefault('add_ie', []).append('Generic')
- yield tc
-
-
-md5 = lambda s: hashlib.md5(s.encode()).hexdigest()
-
-
-def _iter_differences(got, expected, field):
- if isinstance(expected, str):
- op, _, val = expected.partition(':')
- if op in ('mincount', 'maxcount', 'count'):
- if not isinstance(got, (list, dict)):
- yield field, f'expected either {list.__name__} or {dict.__name__}, got {type(got).__name__}'
- return
-
- expected_num = int(val)
- got_num = len(got)
- if op == 'mincount':
- if got_num < expected_num:
- yield field, f'expected at least {val} items, got {got_num}'
- return
-
- if op == 'maxcount':
- if got_num > expected_num:
- yield field, f'expected at most {val} items, got {got_num}'
- return
-
- assert op == 'count'
- if got_num != expected_num:
- yield field, f'expected exactly {val} items, got {got_num}'
- return
-
- if not isinstance(got, str):
- yield field, f'expected {str.__name__}, got {type(got).__name__}'
- return
-
- if op == 're':
- if not re.match(val, got):
- yield field, f'should match {val!r}, got {got!r}'
- return
-
- if op == 'startswith':
- if not got.startswith(val):
- yield field, f'should start with {val!r}, got {got!r}'
- return
-
- if op == 'contains':
- if not val.startswith(got):
- yield field, f'should contain {val!r}, got {got!r}'
- return
-
- if op == 'md5':
- hash_val = md5(got)
- if hash_val != val:
- yield field, f'expected hash {val}, got {hash_val}'
- return
-
- if got != expected:
- yield field, f'expected {expected!r}, got {got!r}'
- return
-
- if isinstance(expected, dict) and isinstance(got, dict):
- for key, expected_val in expected.items():
- if key not in got:
- yield field, f'missing key: {key!r}'
- continue
-
- field_name = key if field is None else f'{field}.{key}'
- yield from _iter_differences(got[key], expected_val, field_name)
- return
-
- if isinstance(expected, type):
- if not isinstance(got, expected):
- yield field, f'expected {expected.__name__}, got {type(got).__name__}'
- return
-
- if isinstance(expected, list) and isinstance(got, list):
- # TODO: clever diffing algorithm lmao
- if len(expected) != len(got):
- yield field, f'expected length of {len(expected)}, got {len(got)}'
- return
-
- for index, (got_val, expected_val) in enumerate(zip(got, expected, strict=True)):
- field_name = str(index) if field is None else f'{field}.{index}'
- yield from _iter_differences(got_val, expected_val, field_name)
- return
-
- if got != expected:
- yield field, f'expected {expected!r}, got {got!r}'
-
-
-def _expect_value(message, got, expected, field):
- mismatches = list(_iter_differences(got, expected, field))
- if not mismatches:
- return
-
- fields = [field for field, _ in mismatches if field is not None]
- return ''.join((
- message, f' ({", ".join(fields)})' if fields else '',
- *(f'\n\t{field}: {message}' for field, message in mismatches)))
-
-
-def expect_value(self, got, expected, field):
- if message := _expect_value('values differ', got, expected, field):
- self.fail(message)
-
-
-def expect_dict(self, got_dict, expected_dict):
- if message := _expect_value('dictionaries differ', got_dict, expected_dict, None):
- self.fail(message)
-
-
-def sanitize_got_info_dict(got_dict):
- IGNORED_FIELDS = (
- *YoutubeDL._format_fields,
-
- # Lists
- 'formats', 'thumbnails', 'subtitles', 'automatic_captions', 'comments', 'entries',
-
- # Auto-generated
- 'autonumber', 'playlist', 'format_index', 'video_ext', 'audio_ext', 'duration_string', 'epoch', 'n_entries',
- 'fulltitle', 'extractor', 'extractor_key', 'filename', 'filepath', 'infojson_filename', 'original_url',
-
- # Only live_status needs to be checked
- 'is_live', 'was_live',
- )
-
- IGNORED_PREFIXES = ('', 'playlist', 'requested', 'webpage')
-
- def sanitize(key, value):
- if isinstance(value, str) and len(value) > 100 and key != 'thumbnail':
- return f'md5:{md5(value)}'
- elif isinstance(value, list) and len(value) > 10:
- return f'count:{len(value)}'
- elif key.endswith('_count') and isinstance(value, int):
- return int
- return value
-
- test_info_dict = {
- key: sanitize(key, value) for key, value in got_dict.items()
- if value is not None and key not in IGNORED_FIELDS and (
- not any(key.startswith(f'{prefix}_') for prefix in IGNORED_PREFIXES)
- or key == '_old_archive_ids')
- }
-
- # display_id may be generated from id
- if test_info_dict.get('display_id') == test_info_dict.get('id'):
- test_info_dict.pop('display_id')
-
- # Remove deprecated fields
- for old in YoutubeDL._deprecated_multivalue_fields:
- test_info_dict.pop(old, None)
-
- # release_year may be generated from release_date
- if try_call(lambda: test_info_dict['release_year'] == int(test_info_dict['release_date'][:4])):
- test_info_dict.pop('release_year')
-
- # Check url for flat entries
- if got_dict.get('_type', 'video') != 'video' and got_dict.get('url'):
- test_info_dict['url'] = got_dict['url']
-
- return test_info_dict
-
-
-def expect_info_dict(self, got_dict, expected_dict):
- ALLOWED_KEYS_SORT_ORDER = (
- # NB: Keep in sync with the docstring of extractor/common.py
- 'ie_key', 'url', 'id', 'ext', 'direct', 'display_id', 'title', 'alt_title', 'description', 'media_type',
- 'uploader', 'uploader_id', 'uploader_url', 'channel', 'channel_id', 'channel_url', 'channel_is_verified',
- 'channel_follower_count', 'comment_count', 'view_count', 'concurrent_view_count', 'save_count',
- 'like_count', 'dislike_count', 'repost_count', 'average_rating', 'age_limit', 'duration', 'thumbnail', 'heatmap',
- 'chapters', 'chapter', 'chapter_number', 'chapter_id', 'start_time', 'end_time', 'section_start', 'section_end',
- 'categories', 'tags', 'cast', 'composers', 'artists', 'album_artists', 'creators', 'genres',
- 'track', 'track_number', 'track_id', 'album', 'album_type', 'disc_number',
- 'series', 'series_id', 'season', 'season_number', 'season_id', 'episode', 'episode_number', 'episode_id',
- 'timestamp', 'upload_date', 'release_timestamp', 'release_date', 'release_year', 'modified_timestamp', 'modified_date',
- 'playable_in_embed', 'availability', 'live_status', 'location', 'license', '_old_archive_ids',
- )
-
- expect_dict(self, got_dict, expected_dict)
- # Check for the presence of mandatory fields
- if got_dict.get('_type') not in ('playlist', 'multi_video'):
- mandatory_fields = ['id', 'title']
- if expected_dict.get('ext'):
- mandatory_fields.extend(('url', 'ext'))
- for key in mandatory_fields:
- self.assertTrue(got_dict.get(key), f'Missing mandatory field {key}')
- # Check for mandatory fields that are automatically set by YoutubeDL
- if got_dict.get('_type', 'video') == 'video':
- for key in ['webpage_url', 'extractor', 'extractor_key']:
- self.assertTrue(got_dict.get(key), f'Missing field: {key}')
-
- test_info_dict = sanitize_got_info_dict(got_dict)
-
- # Check for invalid/misspelled field names being returned by the extractor
- invalid_keys = sorted(test_info_dict.keys() - ALLOWED_KEYS_SORT_ORDER)
- self.assertFalse(invalid_keys, f'Invalid fields returned by the extractor: {", ".join(invalid_keys)}')
-
- missing_keys = sorted(
- test_info_dict.keys() - expected_dict.keys(),
- key=ALLOWED_KEYS_SORT_ORDER.index)
- if missing_keys:
- def _repr(v):
- if isinstance(v, str):
- return "'{}'".format(v.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n'))
- elif isinstance(v, type):
- return v.__name__
- else:
- return repr(v)
- info_dict_str = ''.join(
- f' {_repr(k)}: {_repr(v)},\n'
- for k, v in test_info_dict.items() if k not in missing_keys)
- if info_dict_str:
- info_dict_str += '\n'
- info_dict_str += ''.join(
- f' {_repr(k)}: {_repr(test_info_dict[k])},\n'
- for k in missing_keys)
- info_dict_str = '\n\'info_dict\': {\n' + info_dict_str + '},\n'
- write_string(info_dict_str.replace('\n', '\n '), out=sys.stderr)
- self.assertFalse(
- missing_keys,
- 'Missing keys in test definition: {}'.format(', '.join(sorted(missing_keys))))
-
-
-def assertRegexpMatches(self, text, regexp, msg=None):
- if hasattr(self, 'assertRegexp'):
- return self.assertRegexp(text, regexp, msg)
- else:
- m = re.match(regexp, text)
- if not m:
- note = f'Regexp didn\'t match: {regexp!r} not found'
- if len(text) < 1000:
- note += f' in {text!r}'
- if msg is None:
- msg = note
- else:
- msg = note + ', ' + msg
- self.assertTrue(m, msg)
-
-
-def assertGreaterEqual(self, got, expected, msg=None):
- if not (got >= expected):
- if msg is None:
- msg = f'{got!r} not greater than or equal to {expected!r}'
- self.assertTrue(got >= expected, msg)
-
-
-def assertLessEqual(self, got, expected, msg=None):
- if not (got <= expected):
- if msg is None:
- msg = f'{got!r} not less than or equal to {expected!r}'
- self.assertTrue(got <= expected, msg)
-
-
-def assertEqual(self, got, expected, msg=None):
- if got != expected:
- if msg is None:
- msg = f'{got!r} not equal to {expected!r}'
- self.assertTrue(got == expected, msg)
-
-
-def expect_warnings(ydl, warnings_re):
- real_warning = ydl.report_warning
-
- def _report_warning(w, *args, **kwargs):
- if not any(re.search(w_re, w) for w_re in warnings_re):
- real_warning(w, *args, **kwargs)
-
- ydl.report_warning = _report_warning
-
-
-def http_server_port(httpd):
- if os.name == 'java' and isinstance(httpd.socket, ssl.SSLSocket):
- # In Jython SSLSocket is not a subclass of socket.socket
- sock = httpd.socket.sock
- else:
- sock = httpd.socket
- return sock.getsockname()[1]
-
-
-def verify_address_availability(address):
- if find_available_port(address) is None:
- pytest.skip(f'Unable to bind to source address {address} (address may not exist)')
-
-
-def validate_and_send(rh, req):
- rh.validate(req)
- return rh.send(req)
diff --git a/test/parameters.json b/test/parameters.json
deleted file mode 100644
index d08748a50..000000000
--- a/test/parameters.json
+++ /dev/null
@@ -1,48 +0,0 @@
-{
- "check_formats": false,
- "consoletitle": false,
- "continuedl": true,
- "forcedescription": false,
- "forcefilename": false,
- "forceformat": false,
- "forcethumbnail": false,
- "forcetitle": false,
- "forceurl": false,
- "force_write_download_archive": false,
- "format": "b/bv",
- "ignoreerrors": false,
- "listformats": null,
- "logtostderr": false,
- "matchtitle": null,
- "max_downloads": null,
- "overwrites": null,
- "nopart": false,
- "noprogress": false,
- "outtmpl": "%(id)s.%(ext)s",
- "password": null,
- "playliststart": 1,
- "prefer_free_formats": false,
- "quiet": false,
- "ratelimit": null,
- "rejecttitle": null,
- "retries": 10,
- "simulate": false,
- "subtitleslang": null,
- "subtitlesformat": "best",
- "test": true,
- "updatetime": true,
- "usenetrc": false,
- "username": null,
- "verbose": true,
- "writedescription": false,
- "writeinfojson": true,
- "writelink": false,
- "writeurllink": false,
- "writewebloclink": false,
- "writedesktoplink": false,
- "writesubtitles": false,
- "allsubtitles": false,
- "listsubtitles": false,
- "fixup": "never",
- "allow_playlist_files": false
-}
diff --git a/test/test_InfoExtractor.py b/test/test_InfoExtractor.py
deleted file mode 100644
index f66fdbf8d..000000000
--- a/test/test_InfoExtractor.py
+++ /dev/null
@@ -1,2168 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import http.server
-import threading
-
-from test.helper import FakeYDL, expect_dict, expect_value, http_server_port
-from yt_dlp.compat import compat_etree_fromstring
-from yt_dlp.extractor import YoutubeIE, get_info_extractor
-from yt_dlp.extractor.common import InfoExtractor
-from yt_dlp.utils import (
- ExtractorError,
- RegexNotFoundError,
- encode_data_uri,
- strip_jsonp,
-)
-
-TEAPOT_RESPONSE_STATUS = 418
-TEAPOT_RESPONSE_BODY = "418 I'm a teapot "
-
-
-class InfoExtractorTestRequestHandler(http.server.BaseHTTPRequestHandler):
- def log_message(self, format, *args):
- pass
-
- def do_GET(self):
- if self.path == '/teapot':
- self.send_response(TEAPOT_RESPONSE_STATUS)
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.end_headers()
- self.wfile.write(TEAPOT_RESPONSE_BODY.encode())
- elif self.path == '/fake.m3u8':
- self.send_response(200)
- self.send_header('Content-Length', '1024')
- self.end_headers()
- self.wfile.write(1024 * b'\x00')
- elif self.path == '/bipbop.m3u8':
- with open('test/testdata/m3u8/bipbop_16x9.m3u8', 'rb') as f:
- data = f.read()
- self.send_response(200)
- self.send_header('Content-Length', str(len(data)))
- self.end_headers()
- self.wfile.write(data)
- else:
- assert False
-
-
-class DummyIE(InfoExtractor):
- def _sort_formats(self, formats, field_preference=[]):
- self._downloader.sort_formats(
- {'formats': formats, '_format_sort_fields': field_preference})
-
-
-class TestInfoExtractor(unittest.TestCase):
- def setUp(self):
- self.ie = DummyIE(FakeYDL())
-
- def test_ie_key(self):
- self.assertEqual(get_info_extractor(YoutubeIE.ie_key()), YoutubeIE)
-
- def test_get_netrc_login_info(self):
- for params in [
- {'usenetrc': True, 'netrc_location': './test/testdata/netrc/netrc'},
- {'netrc_cmd': f'{sys.executable} ./test/testdata/netrc/print_netrc.py'},
- ]:
- ie = DummyIE(FakeYDL(params))
- self.assertEqual(ie._get_netrc_login_info(netrc_machine='normal_use'), ('user', 'pass'))
- self.assertEqual(ie._get_netrc_login_info(netrc_machine='empty_user'), ('', 'pass'))
- self.assertEqual(ie._get_netrc_login_info(netrc_machine='empty_pass'), ('user', ''))
- self.assertEqual(ie._get_netrc_login_info(netrc_machine='both_empty'), ('', ''))
- self.assertEqual(ie._get_netrc_login_info(netrc_machine='nonexistent'), (None, None))
- with self.assertRaises(ExtractorError):
- ie._get_netrc_login_info(netrc_machine=';echo rce')
-
- def test_html_search_regex(self):
- html = 'Watch this video
'
- search = lambda re, *args: self.ie._html_search_regex(re, html, *args)
- self.assertEqual(search(r'(.+?)
', 'foo'), 'Watch this video')
-
- def test_opengraph(self):
- ie = self.ie
- html = '''
-
-
-
-
-
-
-
-
-
- '''
- self.assertEqual(ie._og_search_title(html), 'Foo')
- self.assertEqual(ie._og_search_description(html), 'Some video\'s description ')
- self.assertEqual(ie._og_search_thumbnail(html), 'http://domain.com/pic.jpg?key1=val1&key2=val2')
- self.assertEqual(ie._og_search_video_url(html, default=None), None)
- self.assertEqual(ie._og_search_property('foobar', html), 'Foo')
- self.assertEqual(ie._og_search_property('test1', html), 'foo > < bar')
- self.assertEqual(ie._og_search_property('test2', html), 'foo >//< bar')
- self.assertEqual(ie._og_search_property('test3', html), 'Ill-formatted opengraph')
- self.assertEqual(ie._og_search_property(('test0', 'test1'), html), 'foo > < bar')
- self.assertRaises(RegexNotFoundError, ie._og_search_property, 'test0', html, None, fatal=True)
- self.assertRaises(RegexNotFoundError, ie._og_search_property, ('test0', 'test00'), html, None, fatal=True)
- self.assertEqual(ie._og_search_property('test4', html), 'unquoted-value')
-
- def test_html_search_meta(self):
- ie = self.ie
- html = '''
-
-
-
-
-
-
- '''
-
- self.assertEqual(ie._html_search_meta('a', html), '1')
- self.assertEqual(ie._html_search_meta('b', html), '2')
- self.assertEqual(ie._html_search_meta('c', html), '3')
- self.assertEqual(ie._html_search_meta('d', html), '4')
- self.assertEqual(ie._html_search_meta('e', html), '5')
- self.assertEqual(ie._html_search_meta('f', html), '6')
- self.assertEqual(ie._html_search_meta(('a', 'b', 'c'), html), '1')
- self.assertEqual(ie._html_search_meta(('c', 'b', 'a'), html), '3')
- self.assertEqual(ie._html_search_meta(('z', 'x', 'c'), html), '3')
- self.assertRaises(RegexNotFoundError, ie._html_search_meta, 'z', html, None, fatal=True)
- self.assertRaises(RegexNotFoundError, ie._html_search_meta, ('z', 'x'), html, None, fatal=True)
-
- def test_search_json_ld_realworld(self):
- _TESTS = [
- # https://github.com/ytdl-org/youtube-dl/issues/23306
- (
- r'''''',
- {
- 'title': '1 On 1 With Kleio',
- 'description': 'Kleio Valentien',
- 'url': 'https://gvideo.eporner.com/xN49A1cT3eB/xN49A1cT3eB.mp4',
- 'timestamp': 1449347075,
- 'duration': 743.0,
- 'view_count': 1120958,
- 'width': 1920,
- 'height': 1080,
- },
- {},
- ),
- (
- r'''''',
- {
- 'timestamp': 1636523400,
- 'title': 'md5:91fe569e952e4d146485740ae927662b',
- },
- {'expected_type': 'NewsArticle'},
- ),
- (
- r'''
- ''',
- {
- 'chapters': [
- {'title': 'Explosie Turnhout', 'start_time': 70, 'end_time': 440},
- {'title': 'Jaarwisseling', 'start_time': 440, 'end_time': 1179},
- {'title': 'Natuurbranden Colorado', 'start_time': 1179, 'end_time': 1263},
- {'title': 'Klimaatverandering', 'start_time': 1263, 'end_time': 1367},
- {'title': 'Zacht weer', 'start_time': 1367, 'end_time': 1383},
- {'title': 'Financiële balans', 'start_time': 1383, 'end_time': 1484},
- {'title': 'Club Brugge', 'start_time': 1484, 'end_time': 1575},
- {'title': 'Mentale gezondheid bij topsporters', 'start_time': 1575, 'end_time': 1728},
- {'title': 'Olympische Winterspelen', 'start_time': 1728, 'end_time': 1873},
- {'title': 'Sober oudjaar in Nederland', 'start_time': 1873, 'end_time': 2079.23},
- ],
- 'title': 'Het journaal - Aflevering 365 (Seizoen 2021)',
- }, {},
- ),
- (
- # test multiple thumbnails in a list
- r'''
-''',
- {
- 'thumbnails': [{'url': 'https://www.rainews.it/cropgd/640x360/dl/img/2021/12/30/1640886376927_GettyImages.jpg'}],
- },
- {},
- ),
- (
- # test single thumbnail
- r'''
-''',
- {
- 'thumbnails': [{'url': 'https://www.rainews.it/cropgd/640x360/dl/img/2021/12/30/1640886376927_GettyImages.jpg'}],
- },
- {},
- ),
- (
- # test thumbnail_url key without URL scheme
- r'''
-''',
- {
- 'thumbnails': [{'url': 'https://www.nobelprize.org/images/12693-landscape-medium-gallery.jpg'}],
- },
- {},
- ),
- ]
- for html, expected_dict, search_json_ld_kwargs in _TESTS:
- expect_dict(
- self,
- self.ie._search_json_ld(html, None, **search_json_ld_kwargs),
- expected_dict,
- )
-
- def test_download_json(self):
- uri = encode_data_uri(b'{"foo": "blah"}', 'application/json')
- self.assertEqual(self.ie._download_json(uri, None), {'foo': 'blah'})
- uri = encode_data_uri(b'callback({"foo": "blah"})', 'application/javascript')
- self.assertEqual(self.ie._download_json(uri, None, transform_source=strip_jsonp), {'foo': 'blah'})
- uri = encode_data_uri(b'{"foo": invalid}', 'application/json')
- self.assertRaises(ExtractorError, self.ie._download_json, uri, None)
- self.assertEqual(self.ie._download_json(uri, None, fatal=False), None)
-
- def test_parse_html5_media_entries(self):
- # inline video tag
- expect_dict(
- self,
- self.ie._parse_html5_media_entries(
- 'https://127.0.0.1/video.html',
- r' ', None)[0],
- {
- 'formats': [{
- 'url': 'https://127.0.0.1/vid.mp4',
- }],
- })
-
- # from https://www.r18.com/
- # with kpbs in label
- expect_dict(
- self,
- self.ie._parse_html5_media_entries(
- 'https://www.r18.com/',
- r'''
-
-
-
-
- Your browser does not support the video tag.
-
- ''', None)[0],
- {
- 'formats': [{
- 'url': 'https://awscc3001.r18.com/litevideo/freepv/m/mgm/mgmr105/mgmr105_sm_w.mp4',
- 'ext': 'mp4',
- 'format_id': '300kbps',
- 'height': 240,
- 'tbr': 300,
- }, {
- 'url': 'https://awscc3001.r18.com/litevideo/freepv/m/mgm/mgmr105/mgmr105_dm_w.mp4',
- 'ext': 'mp4',
- 'format_id': '1000kbps',
- 'height': 480,
- 'tbr': 1000,
- }, {
- 'url': 'https://awscc3001.r18.com/litevideo/freepv/m/mgm/mgmr105/mgmr105_dmb_w.mp4',
- 'ext': 'mp4',
- 'format_id': '1500kbps',
- 'height': 740,
- 'tbr': 1500,
- }],
- 'thumbnail': '//pics.r18.com/digital/amateur/mgmr105/mgmr105jp.jpg',
- })
-
- # from https://www.csfd.cz/
- # with width and height
- expect_dict(
- self,
- self.ie._parse_html5_media_entries(
- 'https://www.csfd.cz/',
- r'''
-
-
-
-
-
-
-
-
-
- ''', None)[0],
- {
- 'formats': [{
- 'url': 'https://video.csfd.cz/files/videos/157/750/157750813/163327358_eac647.mp4',
- 'ext': 'mp4',
- 'width': 640,
- 'height': 360,
- }, {
- 'url': 'https://video.csfd.cz/files/videos/157/750/157750813/163327360_3d2646.mp4',
- 'ext': 'mp4',
- 'width': 1280,
- 'height': 720,
- }, {
- 'url': 'https://video.csfd.cz/files/videos/157/750/157750813/163327356_91f258.mp4',
- 'ext': 'mp4',
- 'width': 1920,
- 'height': 1080,
- }, {
- 'url': 'https://video.csfd.cz/files/videos/157/750/157750813/163327359_962b4a.webm',
- 'ext': 'webm',
- 'width': 640,
- 'height': 360,
- }, {
- 'url': 'https://video.csfd.cz/files/videos/157/750/157750813/163327361_6feee0.webm',
- 'ext': 'webm',
- 'width': 1280,
- 'height': 720,
- }, {
- 'url': 'https://video.csfd.cz/files/videos/157/750/157750813/163327357_8ab472.webm',
- 'ext': 'webm',
- 'width': 1920,
- 'height': 1080,
- }],
- 'subtitles': {
- 'cs': [{'url': 'https://video.csfd.cz/files/subtitles/163/344/163344115_4c388b.srt'}],
- },
- 'thumbnail': 'https://img.csfd.cz/files/images/film/video/preview/163/344/163344118_748d20.png?h360',
- })
-
- # from https://tamasha.com/v/Kkdjw
- # with height in label
- expect_dict(
- self,
- self.ie._parse_html5_media_entries(
- 'https://tamasha.com/v/Kkdjw',
- r'''
-
-
-
-
-
- ''', None)[0],
- {
- 'formats': [{
- 'url': 'https://s-v2.tamasha.com/statics/videos_file/19/8f/Kkdjw_198feff8577d0057536e905cce1fb61438dd64e0_n_240.mp4',
- }, {
- 'url': 'https://s-v2.tamasha.com/statics/videos_file/19/8f/Kkdjw_198feff8577d0057536e905cce1fb61438dd64e0_n_240.mp4',
- 'ext': 'mp4',
- 'format_id': '240p',
- 'height': 240,
- }, {
- 'url': 'https://s-v2.tamasha.com/statics/videos_file/20/00/Kkdjw_200041c66f657fc967db464d156eafbc1ed9fe6f_n_144.mp4',
- 'ext': 'mp4',
- 'format_id': '144p',
- 'height': 144,
- }],
- })
-
- # from https://www.directvnow.com
- # with data-src
- expect_dict(
- self,
- self.ie._parse_html5_media_entries(
- 'https://www.directvnow.com',
- r'''
-
- ''', None)[0],
- {
- 'formats': [{
- 'ext': 'mp4',
- 'url': 'https://cdn.directv.com/content/dam/dtv/prod/website_directvnow-international/videos/DTVN_hdr_HBO_v3.mp4',
- }],
- })
-
- # from https://www.directvnow.com
- # with data-src
- expect_dict(
- self,
- self.ie._parse_html5_media_entries(
- 'https://www.directvnow.com',
- r'''
-
- ''', None)[0],
- {
- 'formats': [{
- 'url': 'https://cdn.directv.com/content/dam/dtv/prod/website_directvnow-international/videos/DTVN_hdr_HBO_v3.mp4',
- 'ext': 'mp4',
- }],
- })
-
- # from https://www.klarna.com/uk/
- # with data-video-src
- expect_dict(
- self,
- self.ie._parse_html5_media_entries(
- 'https://www.directvnow.com',
- r'''
-
-
-
- ''', None)[0],
- {
- 'formats': [{
- 'url': 'https://www.klarna.com/uk/wp-content/uploads/sites/11/2019/01/KL062_Smooth3_0_DogWalking_5s_920x080_.mp4',
- 'ext': 'mp4',
- }],
- })
-
- # from https://0000.studio/
- # with type attribute but without extension in URL
- expect_dict(
- self,
- self.ie._parse_html5_media_entries(
- 'https://0000.studio',
- r'''
-
-
- ''', None)[0],
- {
- 'formats': [{
- 'url': 'https://d1ggyt9m8pwf3g.cloudfront.net/protected/ap-northeast-1:1864af40-28d5-492b-b739-b32314b1a527/archive/clip/838db6a7-8973-4cd6-840d-8517e4093c92',
- 'ext': 'mp4',
- }],
- })
-
- def test_extract_jwplayer_data_realworld(self):
- # from http://www.suffolk.edu/sjc/
- expect_dict(
- self,
- self.ie._extract_jwplayer_data(r'''
-
- ''', None, require_title=False),
- {
- 'id': 'XEgvuql4',
- 'formats': [{
- 'url': 'rtmp://192.138.214.154/live/sjclive',
- 'ext': 'flv',
- }],
- })
-
- # from https://www.pornoxo.com/videos/7564/striptease-from-sexy-secretary/
- expect_dict(
- self,
- self.ie._extract_jwplayer_data(r'''
-
- ''', 'dummy', require_title=False),
- {
- 'thumbnail': 'https://t03.vipstreamservice.com/thumbs/pxo-full/2009-12/14/a4b2157147afe5efa93ce1978e0265289c193874e02597.flv-full-13.jpg',
- 'formats': [{
- 'url': 'https://cdn.pornoxo.com/key=MF+oEbaxqTKb50P-w9G3nA,end=1489689259,ip=104.199.146.27/ip=104.199.146.27/speed=6573765/buffer=3.0/2009-12/4b2157147afe5efa93ce1978e0265289c193874e02597.flv',
- 'ext': 'flv',
- }],
- })
-
- # from http://www.indiedb.com/games/king-machine/videos
- expect_dict(
- self,
- self.ie._extract_jwplayer_data(r'''
-
- ''', 'dummy'),
- {
- 'title': 'king machine trailer 1',
- 'thumbnail': 'http://media.indiedb.com/cache/images/games/1/50/49678/thumb_620x2000/king-machine-trailer.mp4.jpg',
- 'formats': [{
- 'url': 'http://cdn.dbolical.com/cache/videos/games/1/50/49678/encode_mp4/king-machine-trailer.mp4',
- 'height': 360,
- 'ext': 'mp4',
- }, {
- 'url': 'http://cdn.dbolical.com/cache/videos/games/1/50/49678/encode720p_mp4/king-machine-trailer.mp4',
- 'height': 720,
- 'ext': 'mp4',
- }],
- })
-
- def test_parse_m3u8_formats(self):
- _TEST_CASES = [
- (
- # https://github.com/ytdl-org/youtube-dl/issues/11995
- # http://teamcoco.com/video/clueless-gamer-super-bowl-for-honor
- 'img_bipbop_adv_example_fmp4',
- 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- [{
- # 60kbps (bitrate not provided in m3u8); sorted as worst because it's grouped with lowest bitrate video track
- 'format_id': 'aud1-English',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/a1/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'language': 'en',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'audio_ext': 'mp4',
- 'source_preference': 0,
- }, {
- # 192kbps (bitrate not provided in m3u8)
- 'format_id': 'aud3-English',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/a3/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'language': 'en',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'audio_ext': 'mp4',
- 'source_preference': 1,
- }, {
- # 384kbps (bitrate not provided in m3u8); sorted as best because it's grouped with the highest bitrate video track
- 'format_id': 'aud2-English',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/a2/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'language': 'en',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'audio_ext': 'mp4',
- 'source_preference': 2,
- }, {
- 'format_id': '530',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v2/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 480,
- 'height': 270,
- 'vcodec': 'avc1.640015',
- }, {
- 'format_id': '561',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v2/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 480,
- 'height': 270,
- 'vcodec': 'avc1.640015',
- }, {
- 'format_id': '753',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v2/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 480,
- 'height': 270,
- 'vcodec': 'avc1.640015',
- }, {
- 'format_id': '895',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v3/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 640,
- 'height': 360,
- 'vcodec': 'avc1.64001e',
- }, {
- 'format_id': '926',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v3/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 640,
- 'height': 360,
- 'vcodec': 'avc1.64001e',
- }, {
- 'format_id': '1118',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v3/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 640,
- 'height': 360,
- 'vcodec': 'avc1.64001e',
- }, {
- 'format_id': '1265',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v4/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 768,
- 'height': 432,
- 'vcodec': 'avc1.64001e',
- }, {
- 'format_id': '1295',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v4/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 768,
- 'height': 432,
- 'vcodec': 'avc1.64001e',
- }, {
- 'format_id': '1487',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v4/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 768,
- 'height': 432,
- 'vcodec': 'avc1.64001e',
- }, {
- 'format_id': '2168',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v5/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 960,
- 'height': 540,
- 'vcodec': 'avc1.640020',
- }, {
- 'format_id': '2198',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v5/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 960,
- 'height': 540,
- 'vcodec': 'avc1.640020',
- }, {
- 'format_id': '2390',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v5/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 960,
- 'height': 540,
- 'vcodec': 'avc1.640020',
- }, {
- 'format_id': '3168',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v6/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1280,
- 'height': 720,
- 'vcodec': 'avc1.640020',
- }, {
- 'format_id': '3199',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v6/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1280,
- 'height': 720,
- 'vcodec': 'avc1.640020',
- }, {
- 'format_id': '3391',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v6/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1280,
- 'height': 720,
- 'vcodec': 'avc1.640020',
- }, {
- 'format_id': '4670',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v7/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }, {
- 'format_id': '4701',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v7/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }, {
- 'format_id': '4893',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v7/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }, {
- 'format_id': '6170',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v8/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }, {
- 'format_id': '6200',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v8/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }, {
- 'format_id': '6392',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v8/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }, {
- 'format_id': '7968',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v9/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }, {
- 'format_id': '7998',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v9/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }, {
- 'format_id': '8190',
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v9/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.64002a',
- }],
- {},
- ),
- (
- 'bipbop_16x9',
- 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8',
- [{
- 'format_id': 'bipbop_audio-BipBop Audio 2',
- 'format_index': None,
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/alternate_audio_aac/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8',
- 'language': 'eng',
- 'ext': 'mp4',
- 'protocol': 'm3u8_native',
- 'preference': None,
- 'quality': None,
- 'vcodec': 'none',
- 'audio_ext': 'mp4',
- 'video_ext': 'none',
- }, {
- 'format_id': '41',
- 'format_index': None,
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/gear0/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8',
- 'tbr': 41.457,
- 'ext': 'mp4',
- 'fps': None,
- 'protocol': 'm3u8_native',
- 'preference': None,
- 'quality': None,
- 'vcodec': 'none',
- 'acodec': 'mp4a.40.2',
- 'audio_ext': 'mp4',
- 'video_ext': 'none',
- 'abr': 41.457,
- }, {
- 'format_id': '263',
- 'format_index': None,
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/gear1/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8',
- 'tbr': 263.851,
- 'ext': 'mp4',
- 'fps': None,
- 'protocol': 'm3u8_native',
- 'preference': None,
- 'quality': None,
- 'width': 416,
- 'height': 234,
- 'vcodec': 'avc1.4d400d',
- 'acodec': 'mp4a.40.2',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- }, {
- 'format_id': '577',
- 'format_index': None,
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/gear2/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8',
- 'tbr': 577.61,
- 'ext': 'mp4',
- 'fps': None,
- 'protocol': 'm3u8_native',
- 'preference': None,
- 'quality': None,
- 'width': 640,
- 'height': 360,
- 'vcodec': 'avc1.4d401e',
- 'acodec': 'mp4a.40.2',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- }, {
- 'format_id': '915',
- 'format_index': None,
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/gear3/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8',
- 'tbr': 915.905,
- 'ext': 'mp4',
- 'fps': None,
- 'protocol': 'm3u8_native',
- 'preference': None,
- 'quality': None,
- 'width': 960,
- 'height': 540,
- 'vcodec': 'avc1.4d401f',
- 'acodec': 'mp4a.40.2',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- }, {
- 'format_id': '1030',
- 'format_index': None,
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/gear4/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8',
- 'tbr': 1030.138,
- 'ext': 'mp4',
- 'fps': None,
- 'protocol': 'm3u8_native',
- 'preference': None,
- 'quality': None,
- 'width': 1280,
- 'height': 720,
- 'vcodec': 'avc1.4d401f',
- 'acodec': 'mp4a.40.2',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- }, {
- 'format_id': '1924',
- 'format_index': None,
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/gear5/prog_index.m3u8',
- 'manifest_url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8',
- 'tbr': 1924.009,
- 'ext': 'mp4',
- 'fps': None,
- 'protocol': 'm3u8_native',
- 'preference': None,
- 'quality': None,
- 'width': 1920,
- 'height': 1080,
- 'vcodec': 'avc1.4d401f',
- 'acodec': 'mp4a.40.2',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- }],
- {
- 'en': [{
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/subtitles/eng/prog_index.m3u8',
- 'ext': 'vtt',
- 'protocol': 'm3u8_native',
- }, {
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/subtitles/eng_forced/prog_index.m3u8',
- 'ext': 'vtt',
- 'protocol': 'm3u8_native',
- }],
- 'fr': [{
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/subtitles/fra/prog_index.m3u8',
- 'ext': 'vtt',
- 'protocol': 'm3u8_native',
- }, {
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/subtitles/fra_forced/prog_index.m3u8',
- 'ext': 'vtt',
- 'protocol': 'm3u8_native',
- }],
- 'es': [{
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/subtitles/spa/prog_index.m3u8',
- 'ext': 'vtt',
- 'protocol': 'm3u8_native',
- }, {
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/subtitles/spa_forced/prog_index.m3u8',
- 'ext': 'vtt',
- 'protocol': 'm3u8_native',
- }],
- 'ja': [{
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/subtitles/jpn/prog_index.m3u8',
- 'ext': 'vtt',
- 'protocol': 'm3u8_native',
- }, {
- 'url': 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/subtitles/jpn_forced/prog_index.m3u8',
- 'ext': 'vtt',
- 'protocol': 'm3u8_native',
- }],
- },
- ),
- ]
-
- for m3u8_file, m3u8_url, expected_formats, expected_subs in _TEST_CASES:
- with open(f'./test/testdata/m3u8/{m3u8_file}.m3u8', encoding='utf-8') as f:
- formats, subs = self.ie._parse_m3u8_formats_and_subtitles(
- f.read(), m3u8_url, ext='mp4')
- self.ie._sort_formats(formats)
- expect_value(self, formats, expected_formats, None)
- expect_value(self, subs, expected_subs, None)
-
- def test_parse_mpd_formats(self):
- _TEST_CASES = [
- (
- # https://github.com/ytdl-org/youtube-dl/issues/13919
- # Also tests duplicate representation ids, see
- # https://github.com/ytdl-org/youtube-dl/issues/15111
- 'float_duration',
- 'http://unknown/manifest.mpd', # mpd_url
- None, # mpd_base_url
- [{
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'm4a',
- 'format_id': '318597',
- 'format_note': 'DASH audio',
- 'protocol': 'http_dash_segments',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'none',
- 'tbr': 61.587,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': '318597',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'none',
- 'vcodec': 'avc1.42001f',
- 'tbr': 318.597,
- 'width': 340,
- 'height': 192,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': '638590',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'none',
- 'vcodec': 'avc1.42001f',
- 'tbr': 638.59,
- 'width': 512,
- 'height': 288,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': '1022565',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'none',
- 'vcodec': 'avc1.4d001f',
- 'tbr': 1022.565,
- 'width': 688,
- 'height': 384,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': '2046506',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'none',
- 'vcodec': 'avc1.4d001f',
- 'tbr': 2046.506,
- 'width': 1024,
- 'height': 576,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': '3998017',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'none',
- 'vcodec': 'avc1.640029',
- 'tbr': 3998.017,
- 'width': 1280,
- 'height': 720,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': '5997485',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'none',
- 'vcodec': 'avc1.640032',
- 'tbr': 5997.485,
- 'width': 1920,
- 'height': 1080,
- }],
- {},
- ), (
- # https://github.com/ytdl-org/youtube-dl/pull/14844
- 'urls_only',
- 'http://unknown/manifest.mpd', # mpd_url
- None, # mpd_base_url
- [{
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': 'h264_aac_144p_m4s',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'avc3.42c01e',
- 'tbr': 200,
- 'width': 256,
- 'height': 144,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': 'h264_aac_240p_m4s',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'avc3.42c01e',
- 'tbr': 400,
- 'width': 424,
- 'height': 240,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': 'h264_aac_360p_m4s',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'avc3.42c01e',
- 'tbr': 800,
- 'width': 640,
- 'height': 360,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': 'h264_aac_480p_m4s',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'avc3.42c01e',
- 'tbr': 1200,
- 'width': 856,
- 'height': 480,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': 'h264_aac_576p_m4s',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'avc3.42c01e',
- 'tbr': 1600,
- 'width': 1024,
- 'height': 576,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': 'h264_aac_720p_m4s',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'avc3.42c01e',
- 'tbr': 2400,
- 'width': 1280,
- 'height': 720,
- }, {
- 'manifest_url': 'http://unknown/manifest.mpd',
- 'ext': 'mp4',
- 'format_id': 'h264_aac_1080p_m4s',
- 'format_note': 'DASH video',
- 'protocol': 'http_dash_segments',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'avc3.42c01e',
- 'tbr': 4400,
- 'width': 1920,
- 'height': 1080,
- }],
- {},
- ), (
- # https://github.com/ytdl-org/youtube-dl/issues/20346
- # Media considered unfragmented even though it contains
- # Initialization tag
- 'unfragmented',
- 'https://v.redd.it/hw1x7rcg7zl21/DASHPlaylist.mpd', # mpd_url
- 'https://v.redd.it/hw1x7rcg7zl21', # mpd_base_url
- [{
- 'url': 'https://v.redd.it/hw1x7rcg7zl21/audio',
- 'manifest_url': 'https://v.redd.it/hw1x7rcg7zl21/DASHPlaylist.mpd',
- 'ext': 'm4a',
- 'format_id': 'AUDIO-1',
- 'format_note': 'DASH audio',
- 'container': 'm4a_dash',
- 'acodec': 'mp4a.40.2',
- 'vcodec': 'none',
- 'tbr': 129.87,
- 'asr': 48000,
-
- }, {
- 'url': 'https://v.redd.it/hw1x7rcg7zl21/DASH_240',
- 'manifest_url': 'https://v.redd.it/hw1x7rcg7zl21/DASHPlaylist.mpd',
- 'ext': 'mp4',
- 'format_id': 'VIDEO-2',
- 'format_note': 'DASH video',
- 'container': 'mp4_dash',
- 'acodec': 'none',
- 'vcodec': 'avc1.4d401e',
- 'tbr': 608.0,
- 'width': 240,
- 'height': 240,
- 'fps': 30,
- }, {
- 'url': 'https://v.redd.it/hw1x7rcg7zl21/DASH_360',
- 'manifest_url': 'https://v.redd.it/hw1x7rcg7zl21/DASHPlaylist.mpd',
- 'ext': 'mp4',
- 'format_id': 'VIDEO-1',
- 'format_note': 'DASH video',
- 'container': 'mp4_dash',
- 'acodec': 'none',
- 'vcodec': 'avc1.4d401e',
- 'tbr': 804.261,
- 'width': 360,
- 'height': 360,
- 'fps': 30,
- }],
- {},
- ), (
- 'subtitles',
- 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/',
- [{
- 'format_id': 'audio=128001',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'ext': 'm4a',
- 'tbr': 128.001,
- 'asr': 48000,
- 'format_note': 'DASH audio',
- 'container': 'm4a_dash',
- 'vcodec': 'none',
- 'acodec': 'mp4a.40.2',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'fragment_base_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/dash/',
- 'protocol': 'http_dash_segments',
- 'audio_ext': 'm4a',
- 'video_ext': 'none',
- 'abr': 128.001,
- }, {
- 'format_id': 'video=100000',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'ext': 'mp4',
- 'width': 336,
- 'height': 144,
- 'tbr': 100,
- 'format_note': 'DASH video',
- 'container': 'mp4_dash',
- 'vcodec': 'avc1.4D401F',
- 'acodec': 'none',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'fragment_base_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/dash/',
- 'protocol': 'http_dash_segments',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- 'vbr': 100,
- }, {
- 'format_id': 'video=326000',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'ext': 'mp4',
- 'width': 562,
- 'height': 240,
- 'tbr': 326,
- 'format_note': 'DASH video',
- 'container': 'mp4_dash',
- 'vcodec': 'avc1.4D401F',
- 'acodec': 'none',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'fragment_base_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/dash/',
- 'protocol': 'http_dash_segments',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- 'vbr': 326,
- }, {
- 'format_id': 'video=698000',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'ext': 'mp4',
- 'width': 844,
- 'height': 360,
- 'tbr': 698,
- 'format_note': 'DASH video',
- 'container': 'mp4_dash',
- 'vcodec': 'avc1.4D401F',
- 'acodec': 'none',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'fragment_base_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/dash/',
- 'protocol': 'http_dash_segments',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- 'vbr': 698,
- }, {
- 'format_id': 'video=1493000',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'ext': 'mp4',
- 'width': 1126,
- 'height': 480,
- 'tbr': 1493,
- 'format_note': 'DASH video',
- 'container': 'mp4_dash',
- 'vcodec': 'avc1.4D401F',
- 'acodec': 'none',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'fragment_base_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/dash/',
- 'protocol': 'http_dash_segments',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- 'vbr': 1493,
- }, {
- 'format_id': 'video=4482000',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'ext': 'mp4',
- 'width': 1688,
- 'height': 720,
- 'tbr': 4482,
- 'format_note': 'DASH video',
- 'container': 'mp4_dash',
- 'vcodec': 'avc1.4D401F',
- 'acodec': 'none',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'fragment_base_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/dash/',
- 'protocol': 'http_dash_segments',
- 'video_ext': 'mp4',
- 'audio_ext': 'none',
- 'vbr': 4482,
- }],
- {
- 'en': [
- {
- 'ext': 'mp4',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/manifest.mpd',
- 'fragment_base_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/dash/',
- 'protocol': 'http_dash_segments',
- },
- ],
- },
- ),
- ]
-
- for mpd_file, mpd_url, mpd_base_url, expected_formats, expected_subtitles in _TEST_CASES:
- with open(f'./test/testdata/mpd/{mpd_file}.mpd', encoding='utf-8') as f:
- formats, subtitles = self.ie._parse_mpd_formats_and_subtitles(
- compat_etree_fromstring(f.read().encode()),
- mpd_base_url=mpd_base_url, mpd_url=mpd_url)
- self.ie._sort_formats(formats)
- expect_value(self, formats, expected_formats, None)
- expect_value(self, subtitles, expected_subtitles, None)
-
- def test_parse_ism_formats(self):
- _TEST_CASES = [
- (
- 'sintel',
- 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- [{
- 'format_id': 'audio-128',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'ext': 'isma',
- 'tbr': 128,
- 'asr': 48000,
- 'vcodec': 'none',
- 'acodec': 'AACL',
- 'protocol': 'ism',
- 'audio_channels': 2,
- '_download_params': {
- 'stream_type': 'audio',
- 'duration': 8880746666,
- 'timescale': 10000000,
- 'width': 0,
- 'height': 0,
- 'fourcc': 'AACL',
- 'codec_private_data': '1190',
- 'sampling_rate': 48000,
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video-100',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'ext': 'ismv',
- 'width': 336,
- 'height': 144,
- 'tbr': 100,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 8880746666,
- 'timescale': 10000000,
- 'width': 336,
- 'height': 144,
- 'fourcc': 'AVC1',
- 'codec_private_data': '00000001674D401FDA0544EFFC2D002CBC40000003004000000C03C60CA80000000168EF32C8',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video-326',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'ext': 'ismv',
- 'width': 562,
- 'height': 240,
- 'tbr': 326,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 8880746666,
- 'timescale': 10000000,
- 'width': 562,
- 'height': 240,
- 'fourcc': 'AVC1',
- 'codec_private_data': '00000001674D401FDA0241FE23FFC3BC83BA44000003000400000300C03C60CA800000000168EF32C8',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video-698',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'ext': 'ismv',
- 'width': 844,
- 'height': 360,
- 'tbr': 698,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 8880746666,
- 'timescale': 10000000,
- 'width': 844,
- 'height': 360,
- 'fourcc': 'AVC1',
- 'codec_private_data': '00000001674D401FDA0350BFB97FF06AF06AD1000003000100000300300F1832A00000000168EF32C8',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video-1493',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'ext': 'ismv',
- 'width': 1126,
- 'height': 480,
- 'tbr': 1493,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 8880746666,
- 'timescale': 10000000,
- 'width': 1126,
- 'height': 480,
- 'fourcc': 'AVC1',
- 'codec_private_data': '00000001674D401FDA011C3DE6FFF0D890D871000003000100000300300F1832A00000000168EF32C8',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video-4482',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'ext': 'ismv',
- 'width': 1688,
- 'height': 720,
- 'tbr': 4482,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 8880746666,
- 'timescale': 10000000,
- 'width': 1688,
- 'height': 720,
- 'fourcc': 'AVC1',
- 'codec_private_data': '00000001674D401FDA01A816F97FFC1ABC1AB440000003004000000C03C60CA80000000168EF32C8',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }],
- {
- 'eng': [
- {
- 'ext': 'ismt',
- 'protocol': 'ism',
- 'url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- 'manifest_url': 'https://sdn-global-streaming-cache-3qsdn.akamaized.net/stream/3144/files/17/07/672975/3144-kZT4LWMQw6Rh7Kpd.ism/Manifest',
- '_download_params': {
- 'stream_type': 'text',
- 'duration': 8880746666,
- 'timescale': 10000000,
- 'fourcc': 'TTML',
- 'codec_private_data': '',
- },
- },
- ],
- },
- ),
- (
- 'ec-3_test',
- 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- [{
- 'format_id': 'audio_deu-127',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'isma',
- 'tbr': 127,
- 'asr': 48000,
- 'vcodec': 'none',
- 'acodec': 'AACL',
- 'protocol': 'ism',
- 'language': 'deu',
- 'audio_channels': 2,
- '_download_params': {
- 'stream_type': 'audio',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 0,
- 'height': 0,
- 'fourcc': 'AACL',
- 'language': 'deu',
- 'codec_private_data': '1190',
- 'sampling_rate': 48000,
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'audio_deu_1-224',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'isma',
- 'tbr': 224,
- 'asr': 48000,
- 'vcodec': 'none',
- 'acodec': 'EC-3',
- 'protocol': 'ism',
- 'language': 'deu',
- 'audio_channels': 6,
- '_download_params': {
- 'stream_type': 'audio',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 0,
- 'height': 0,
- 'fourcc': 'EC-3',
- 'language': 'deu',
- 'codec_private_data': '00063F000000AF87FBA7022DFB42A4D405CD93843BDD0700200F00',
- 'sampling_rate': 48000,
- 'channels': 6,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video_deu-23',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'ismv',
- 'width': 384,
- 'height': 216,
- 'tbr': 23,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- 'language': 'deu',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 384,
- 'height': 216,
- 'fourcc': 'AVC1',
- 'language': 'deu',
- 'codec_private_data': '000000016742C00CDB06077E5C05A808080A00000300020000030009C0C02EE0177CC6300F142AE00000000168CA8DC8',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video_deu-403',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'ismv',
- 'width': 400,
- 'height': 224,
- 'tbr': 403,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- 'language': 'deu',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 400,
- 'height': 224,
- 'fourcc': 'AVC1',
- 'language': 'deu',
- 'codec_private_data': '00000001674D4014E98323B602D4040405000003000100000300320F1429380000000168EAECF2',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video_deu-680',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'ismv',
- 'width': 640,
- 'height': 360,
- 'tbr': 680,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- 'language': 'deu',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 640,
- 'height': 360,
- 'fourcc': 'AVC1',
- 'language': 'deu',
- 'codec_private_data': '00000001674D401EE981405FF2E02D4040405000000300100000030320F162D3800000000168EAECF2',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video_deu-1253',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'ismv',
- 'width': 640,
- 'height': 360,
- 'tbr': 1253,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- 'vbr': 1253,
- 'language': 'deu',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 640,
- 'height': 360,
- 'fourcc': 'AVC1',
- 'language': 'deu',
- 'codec_private_data': '00000001674D401EE981405FF2E02D4040405000000300100000030320F162D3800000000168EAECF2',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video_deu-2121',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'ismv',
- 'width': 768,
- 'height': 432,
- 'tbr': 2121,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- 'language': 'deu',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 768,
- 'height': 432,
- 'fourcc': 'AVC1',
- 'language': 'deu',
- 'codec_private_data': '00000001674D401EECA0601BD80B50101014000003000400000300C83C58B6580000000168E93B3C80',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video_deu-3275',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'ismv',
- 'width': 1280,
- 'height': 720,
- 'tbr': 3275,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- 'language': 'deu',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 1280,
- 'height': 720,
- 'fourcc': 'AVC1',
- 'language': 'deu',
- 'codec_private_data': '00000001674D4020ECA02802DD80B501010140000003004000000C83C60C65800000000168E93B3C80',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video_deu-5300',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'ismv',
- 'width': 1920,
- 'height': 1080,
- 'tbr': 5300,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- 'language': 'deu',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 1920,
- 'height': 1080,
- 'fourcc': 'AVC1',
- 'language': 'deu',
- 'codec_private_data': '00000001674D4028ECA03C0113F2E02D4040405000000300100000030320F18319600000000168E93B3C80',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }, {
- 'format_id': 'video_deu-8079',
- 'url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'manifest_url': 'https://smstr01.dmm.t-online.de/smooth24/smoothstream_m1/streaming/sony/9221438342941275747/636887760842957027/25_km_h-Trailer-9221571562372022953_deu_20_1300k_HD_H_264_ISMV.ism/Manifest',
- 'ext': 'ismv',
- 'width': 1920,
- 'height': 1080,
- 'tbr': 8079,
- 'vcodec': 'AVC1',
- 'acodec': 'none',
- 'protocol': 'ism',
- 'language': 'deu',
- '_download_params': {
- 'stream_type': 'video',
- 'duration': 370000000,
- 'timescale': 10000000,
- 'width': 1920,
- 'height': 1080,
- 'fourcc': 'AVC1',
- 'language': 'deu',
- 'codec_private_data': '00000001674D4028ECA03C0113F2E02D4040405000000300100000030320F18319600000000168E93B3C80',
- 'channels': 2,
- 'bits_per_sample': 16,
- 'nal_unit_length_field': 4,
- },
- }],
- {},
- ),
- ]
-
- for ism_file, ism_url, expected_formats, expected_subtitles in _TEST_CASES:
- with open(f'./test/testdata/ism/{ism_file}.Manifest', encoding='utf-8') as f:
- formats, subtitles = self.ie._parse_ism_formats_and_subtitles(
- compat_etree_fromstring(f.read().encode()), ism_url=ism_url)
- self.ie._sort_formats(formats)
- expect_value(self, formats, expected_formats, None)
- expect_value(self, subtitles, expected_subtitles, None)
-
- def test_parse_f4m_formats(self):
- _TEST_CASES = [
- (
- # https://github.com/ytdl-org/youtube-dl/issues/14660
- 'custom_base_url',
- 'http://api.new.livestream.com/accounts/6115179/events/6764928/videos/144884262.f4m',
- [{
- 'manifest_url': 'http://api.new.livestream.com/accounts/6115179/events/6764928/videos/144884262.f4m',
- 'ext': 'flv',
- 'format_id': '2148',
- 'protocol': 'f4m',
- 'tbr': 2148,
- 'width': 1280,
- 'height': 720,
- }],
- ),
- ]
-
- for f4m_file, f4m_url, expected_formats in _TEST_CASES:
- with open(f'./test/testdata/f4m/{f4m_file}.f4m', encoding='utf-8') as f:
- formats = self.ie._parse_f4m_formats(
- compat_etree_fromstring(f.read().encode()),
- f4m_url, None)
- self.ie._sort_formats(formats)
- expect_value(self, formats, expected_formats, None)
-
- def test_parse_xspf(self):
- _TEST_CASES = [
- (
- 'foo_xspf',
- 'https://example.org/src/foo_xspf.xspf',
- [{
- 'id': 'foo_xspf',
- 'title': 'Pandemonium',
- 'description': 'Visit http://bigbrother404.bandcamp.com',
- 'duration': 202.416,
- 'formats': [{
- 'manifest_url': 'https://example.org/src/foo_xspf.xspf',
- 'url': 'https://example.org/src/cd1/track%201.mp3',
- }],
- }, {
- 'id': 'foo_xspf',
- 'title': 'Final Cartridge (Nichico Twelve Remix)',
- 'description': 'Visit http://bigbrother404.bandcamp.com',
- 'duration': 255.857,
- 'formats': [{
- 'manifest_url': 'https://example.org/src/foo_xspf.xspf',
- 'url': 'https://example.org/%E3%83%88%E3%83%A9%E3%83%83%E3%82%AF%E3%80%80%EF%BC%92.mp3',
- }],
- }, {
- 'id': 'foo_xspf',
- 'title': 'Rebuilding Nightingale',
- 'description': 'Visit http://bigbrother404.bandcamp.com',
- 'duration': 287.915,
- 'formats': [{
- 'manifest_url': 'https://example.org/src/foo_xspf.xspf',
- 'url': 'https://example.org/src/track3.mp3',
- }, {
- 'manifest_url': 'https://example.org/src/foo_xspf.xspf',
- 'url': 'https://example.com/track3.mp3',
- }],
- }],
- ),
- ]
-
- for xspf_file, xspf_url, expected_entries in _TEST_CASES:
- with open(f'./test/testdata/xspf/{xspf_file}.xspf', encoding='utf-8') as f:
- entries = self.ie._parse_xspf(
- compat_etree_fromstring(f.read().encode()),
- xspf_file, xspf_url=xspf_url, xspf_base_url=xspf_url)
- expect_value(self, entries, expected_entries, None)
- for i in range(len(entries)):
- expect_dict(self, entries[i], expected_entries[i])
-
- def test_response_with_expected_status_returns_content(self):
- # Checks for mitigations against the effects of
- # that affect Python 3.4.1+, which
- # manifest as `_download_webpage`, `_download_xml`, `_download_json`,
- # or the underlying `_download_webpage_handle` returning no content
- # when a response matches `expected_status`.
-
- httpd = http.server.HTTPServer(
- ('127.0.0.1', 0), InfoExtractorTestRequestHandler)
- port = http_server_port(httpd)
- server_thread = threading.Thread(target=httpd.serve_forever)
- server_thread.daemon = True
- server_thread.start()
-
- content, _ = self.ie._download_webpage_handle(
- f'http://127.0.0.1:{port}/teapot', None,
- expected_status=TEAPOT_RESPONSE_STATUS)
- self.assertEqual(content, TEAPOT_RESPONSE_BODY)
-
- def test_search_nextjs_data(self):
- data = ''
- self.assertEqual(self.ie._search_nextjs_data(data, None), {'props': {}})
- self.assertEqual(self.ie._search_nextjs_data('', None, fatal=False), {})
- self.assertEqual(self.ie._search_nextjs_data('', None, default=None), None)
- self.assertEqual(self.ie._search_nextjs_data('', None, default={}), {})
- with self.assertWarns(DeprecationWarning):
- self.assertEqual(self.ie._search_nextjs_data('', None, default='{}'), {})
-
- def test_search_nextjs_v13_data(self):
- HTML = R'''
-
-
-
-
-
-
-
- '''
- EXPECTED = {
- '18': {
- 'foo': 'bar',
- },
- '16': {
- 'meta': {
- 'dateCreated': 1730489700,
- 'uuid': '40cac41d-8d29-4ef5-aa11-75047b9f0907',
- },
- },
- '19': {
- 'duplicated_field_name': {'x': 1},
- },
- '20': {
- 'duplicated_field_name': {'y': 2},
- },
- }
- self.assertEqual(self.ie._search_nextjs_v13_data(HTML, None), EXPECTED)
- self.assertEqual(self.ie._search_nextjs_v13_data('', None, fatal=False), {})
- self.assertEqual(self.ie._search_nextjs_v13_data(None, None, fatal=False), {})
-
- def test_search_nuxt_json(self):
- HTML_TMPL = ''
- VALID_DATA = '''
- ["ShallowReactive",1],
- {"data":2,"state":21,"once":25,"_errors":28,"_server_errors":30},
- ["ShallowReactive",3],
- {"$abcdef123456":4},
- {"podcast":5,"activeEpisodeData":7},
- {"podcast":6,"seasons":14},
- {"title":10,"id":11},
- ["Reactive",8],
- {"episode":9,"creators":18,"empty_list":20},
- {"title":12,"id":13,"refs":34,"empty_refs":35},
- "Series Title",
- "podcast-id-01",
- "Episode Title",
- "episode-id-99",
- [15,16,17],
- 1,
- 2,
- 3,
- [19],
- "Podcast Creator",
- [],
- {"$ssite-config":22},
- {"env":23,"name":24,"map":26,"numbers":14},
- "production",
- "podcast-website",
- ["Set"],
- ["Reactive",27],
- ["Map"],
- ["ShallowReactive",29],
- {},
- ["NuxtError",31],
- {"status":32,"message":33},
- 503,
- "Service Unavailable",
- [36,37],
- [38,39],
- ["Ref",40],
- ["ShallowRef",41],
- ["EmptyRef",42],
- ["EmptyShallowRef",43],
- "ref",
- "shallow_ref",
- "{\\"ref\\":1}",
- "{\\"shallow_ref\\":2}"
- '''
- PAYLOAD = {
- 'data': {
- '$abcdef123456': {
- 'podcast': {
- 'podcast': {
- 'title': 'Series Title',
- 'id': 'podcast-id-01',
- },
- 'seasons': [1, 2, 3],
- },
- 'activeEpisodeData': {
- 'episode': {
- 'title': 'Episode Title',
- 'id': 'episode-id-99',
- 'refs': ['ref', 'shallow_ref'],
- 'empty_refs': [{'ref': 1}, {'shallow_ref': 2}],
- },
- 'creators': ['Podcast Creator'],
- 'empty_list': [],
- },
- },
- },
- 'state': {
- '$ssite-config': {
- 'env': 'production',
- 'name': 'podcast-website',
- 'map': [],
- 'numbers': [1, 2, 3],
- },
- },
- 'once': [],
- '_errors': {},
- '_server_errors': {
- 'status': 503,
- 'message': 'Service Unavailable',
- },
- }
- PARTIALLY_INVALID = [(
- '''
- {"data":1},
- {"invalid_raw_list":2},
- [15,16,17]
- ''',
- {'data': {'invalid_raw_list': [None, None, None]}},
- ), (
- '''
- {"data":1},
- ["EmptyRef",2],
- "not valid JSON"
- ''',
- {'data': None},
- ), (
- '''
- {"data":1},
- ["EmptyShallowRef",2],
- "not valid JSON"
- ''',
- {'data': None},
- )]
- INVALID = [
- '''
- []
- ''',
- '''
- ["unsupported",1],
- {"data":2},
- {}
- ''',
- ]
- DEFAULT = object()
-
- self.assertEqual(self.ie._search_nuxt_json(HTML_TMPL.format(VALID_DATA), None), PAYLOAD)
- self.assertEqual(self.ie._search_nuxt_json('', None, fatal=False), {})
- self.assertIs(self.ie._search_nuxt_json('', None, default=DEFAULT), DEFAULT)
-
- for data, expected in PARTIALLY_INVALID:
- self.assertEqual(
- self.ie._search_nuxt_json(HTML_TMPL.format(data), None, fatal=False), expected)
-
- for data in INVALID:
- self.assertIs(
- self.ie._search_nuxt_json(HTML_TMPL.format(data), None, default=DEFAULT), DEFAULT)
-
-
-class TestInfoExtractorNetwork(unittest.TestCase):
- def setUp(self, /):
- self.httpd = http.server.HTTPServer(
- ('127.0.0.1', 0), InfoExtractorTestRequestHandler)
- self.port = http_server_port(self.httpd)
-
- self.server_thread = threading.Thread(target=self.httpd.serve_forever)
- self.server_thread.daemon = True
- self.server_thread.start()
-
- self.called = False
-
- def require_warning(*args, **kwargs):
- self.called = True
-
- self.ydl = FakeYDL()
- self.ydl.report_warning = require_warning
- self.ie = DummyIE(self.ydl)
-
- def tearDown(self, /):
- self.ydl.close()
- self.httpd.shutdown()
- self.httpd.server_close()
- self.server_thread.join(1)
-
- def test_extract_m3u8_formats(self):
- formats, subtitles = self.ie._extract_m3u8_formats_and_subtitles(
- f'http://127.0.0.1:{self.port}/bipbop.m3u8', None, fatal=False)
- self.assertFalse(self.called)
- self.assertTrue(formats)
- self.assertTrue(subtitles)
-
- def test_extract_m3u8_formats_warning(self):
- formats, subtitles = self.ie._extract_m3u8_formats_and_subtitles(
- f'http://127.0.0.1:{self.port}/fake.m3u8', None, fatal=False)
- self.assertTrue(self.called, 'Warning was not issued for binary m3u8 file')
- self.assertFalse(formats)
- self.assertFalse(subtitles)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_YoutubeDL.py b/test/test_YoutubeDL.py
deleted file mode 100644
index 2705accb7..000000000
--- a/test/test_YoutubeDL.py
+++ /dev/null
@@ -1,1367 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-from unittest.mock import patch
-
-from yt_dlp.globals import all_plugins_loaded
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import contextlib
-import copy
-import json
-
-from test.helper import FakeYDL, assertRegexpMatches, try_rm
-from yt_dlp import YoutubeDL
-from yt_dlp.extractor.common import InfoExtractor
-from yt_dlp.postprocessor.common import PostProcessor
-from yt_dlp.utils import (
- ExtractorError,
- LazyList,
- OnDemandPagedList,
- int_or_none,
- match_filter_func,
-)
-from yt_dlp.utils.traversal import traverse_obj
-
-TEST_URL = 'http://localhost/sample.mp4'
-
-
-class YDL(FakeYDL):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.downloaded_info_dicts = []
- self.msgs = []
-
- def process_info(self, info_dict):
- self.downloaded_info_dicts.append(info_dict.copy())
-
- def to_screen(self, msg, *args, **kwargs):
- self.msgs.append(msg)
-
- def dl(self, *args, **kwargs):
- assert False, 'Downloader must not be invoked for test_YoutubeDL'
-
-
-def _make_result(formats, **kwargs):
- res = {
- 'formats': formats,
- 'id': 'testid',
- 'title': 'testttitle',
- 'extractor': 'testex',
- 'extractor_key': 'TestEx',
- 'webpage_url': 'http://example.com/watch?v=shenanigans',
- }
- res.update(**kwargs)
- return res
-
-
-class TestFormatSelection(unittest.TestCase):
- def test_prefer_free_formats(self):
- # Same resolution => download webm
- ydl = YDL()
- ydl.params['prefer_free_formats'] = True
- formats = [
- {'ext': 'webm', 'height': 460, 'url': TEST_URL},
- {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
- ydl.sort_formats(info_dict)
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['ext'], 'webm')
-
- # Different resolution => download best quality (mp4)
- ydl = YDL()
- ydl.params['prefer_free_formats'] = True
- formats = [
- {'ext': 'webm', 'height': 720, 'url': TEST_URL},
- {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
- ]
- info_dict['formats'] = formats
- ydl.sort_formats(info_dict)
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['ext'], 'mp4')
-
- # No prefer_free_formats => prefer mp4 and webm
- ydl = YDL()
- ydl.params['prefer_free_formats'] = False
- formats = [
- {'ext': 'webm', 'height': 720, 'url': TEST_URL},
- {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
- {'ext': 'flv', 'height': 720, 'url': TEST_URL},
- ]
- info_dict['formats'] = formats
- ydl.sort_formats(info_dict)
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['ext'], 'mp4')
-
- ydl = YDL()
- ydl.params['prefer_free_formats'] = False
- formats = [
- {'ext': 'flv', 'height': 720, 'url': TEST_URL},
- {'ext': 'webm', 'height': 720, 'url': TEST_URL},
- ]
- info_dict['formats'] = formats
- ydl.sort_formats(info_dict)
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['ext'], 'webm')
-
- def test_format_selection(self):
- formats = [
- {'format_id': '35', 'ext': 'mp4', 'preference': 0, 'url': TEST_URL},
- {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
- {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
- {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
- {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- def test(inp, *expected, multi=False):
- ydl = YDL({
- 'format': inp,
- 'allow_multiple_video_streams': multi,
- 'allow_multiple_audio_streams': multi,
- })
- ydl.process_ie_result(info_dict.copy())
- downloaded = [x['format_id'] for x in ydl.downloaded_info_dicts]
- self.assertEqual(downloaded, list(expected))
-
- test('20/47', '47')
- test('20/71/worst', '35')
- test(None, '2')
- test('webm/mp4', '47')
- test('3gp/40/mp4', '35')
- test('example-with-dashes', 'example-with-dashes')
- test('all', '2', '47', '45', 'example-with-dashes', '35')
- test('mergeall', '2+47+45+example-with-dashes+35', multi=True)
- # See: https://github.com/yt-dlp/yt-dlp/pulls/8797
- test('7_a/worst', '35')
-
- def test_format_selection_audio(self):
- formats = [
- {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
- {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
- {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
- {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- ydl = YDL({'format': 'bestaudio'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'audio-high')
-
- ydl = YDL({'format': 'worstaudio'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'audio-low')
-
- formats = [
- {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
- {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- ydl = YDL({'format': 'bestaudio/worstaudio/best'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'vid-high')
-
- def test_format_selection_audio_exts(self):
- formats = [
- {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
- {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
- {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
- {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
- {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
- ]
-
- info_dict = _make_result(formats)
- ydl = YDL({'format': 'best', 'format_sort': ['abr', 'ext']})
- ydl.sort_formats(info_dict)
- ydl.process_ie_result(copy.deepcopy(info_dict))
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'aac-64')
-
- ydl = YDL({'format': 'mp3'})
- ydl.sort_formats(info_dict)
- ydl.process_ie_result(copy.deepcopy(info_dict))
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'mp3-64')
-
- ydl = YDL({'prefer_free_formats': True, 'format_sort': ['abr', 'ext']})
- ydl.sort_formats(info_dict)
- ydl.process_ie_result(copy.deepcopy(info_dict))
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'ogg-64')
-
- def test_format_selection_video(self):
- formats = [
- {'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': TEST_URL},
- {'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': TEST_URL},
- {'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- ydl = YDL({'format': 'bestvideo'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'dash-video-high')
-
- ydl = YDL({'format': 'worstvideo'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'dash-video-low')
-
- ydl = YDL({'format': 'bestvideo[format_id^=dash][format_id$=low]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'dash-video-low')
-
- formats = [
- {'format_id': 'vid-vcodec-dot', 'ext': 'mp4', 'preference': 1, 'vcodec': 'avc1.123456', 'acodec': 'none', 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- ydl = YDL({'format': 'bestvideo[vcodec=avc1.123456]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'vid-vcodec-dot')
-
- def test_format_selection_by_vcodec_sort(self):
- formats = [
- {'format_id': 'av1-format', 'ext': 'mp4', 'vcodec': 'av1', 'acodec': 'none', 'url': TEST_URL},
- {'format_id': 'vp9-hdr-format', 'ext': 'mp4', 'vcodec': 'vp09.02.50.10.01.09.18.09.00', 'acodec': 'none', 'url': TEST_URL},
- {'format_id': 'vp9-sdr-format', 'ext': 'mp4', 'vcodec': 'vp09.00.50.08', 'acodec': 'none', 'url': TEST_URL},
- {'format_id': 'h265-format', 'ext': 'mp4', 'vcodec': 'h265', 'acodec': 'none', 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- ydl = YDL({'format': 'bestvideo', 'format_sort': ['vcodec:vp9.2']})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'vp9-hdr-format')
-
- ydl = YDL({'format': 'bestvideo', 'format_sort': ['vcodec:vp9']})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'vp9-sdr-format')
-
- ydl = YDL({'format': 'bestvideo', 'format_sort': ['+vcodec:vp9.2']})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'vp9-hdr-format')
-
- ydl = YDL({'format': 'bestvideo', 'format_sort': ['+vcodec:vp9']})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'vp9-sdr-format')
-
- def test_format_selection_string_ops(self):
- formats = [
- {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL},
- {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- # equals (=)
- ydl = YDL({'format': '[format_id=abc-cba]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'abc-cba')
-
- # does not equal (!=)
- ydl = YDL({'format': '[format_id!=abc-cba]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'zxc-cxz')
-
- ydl = YDL({'format': '[format_id!=abc-cba][format_id!=zxc-cxz]'})
- self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
-
- # starts with (^=)
- ydl = YDL({'format': '[format_id^=abc]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'abc-cba')
-
- # does not start with (!^=)
- ydl = YDL({'format': '[format_id!^=abc]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'zxc-cxz')
-
- ydl = YDL({'format': '[format_id!^=abc][format_id!^=zxc]'})
- self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
-
- # ends with ($=)
- ydl = YDL({'format': '[format_id$=cba]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'abc-cba')
-
- # does not end with (!$=)
- ydl = YDL({'format': '[format_id!$=cba]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'zxc-cxz')
-
- ydl = YDL({'format': '[format_id!$=cba][format_id!$=cxz]'})
- self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
-
- # contains (*=)
- ydl = YDL({'format': '[format_id*=bc-cb]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'abc-cba')
-
- # does not contain (!*=)
- ydl = YDL({'format': '[format_id!*=bc-cb]'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'zxc-cxz')
-
- ydl = YDL({'format': '[format_id!*=abc][format_id!*=zxc]'})
- self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
-
- ydl = YDL({'format': '[format_id!*=-]'})
- self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
-
- def test_audio_only_extractor_format_selection(self):
- # For extractors with incomplete formats (all formats are audio-only or
- # video-only) best and worst should fallback to corresponding best/worst
- # video-only or audio-only formats (as per
- # https://github.com/ytdl-org/youtube-dl/pull/5556)
- formats = [
- {'format_id': 'low', 'ext': 'mp3', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
- {'format_id': 'high', 'ext': 'mp3', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- ydl = YDL({'format': 'best'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'high')
-
- ydl = YDL({'format': 'worst'})
- ydl.process_ie_result(info_dict.copy())
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'low')
-
- def test_format_not_available(self):
- formats = [
- {'format_id': 'regular', 'ext': 'mp4', 'height': 360, 'url': TEST_URL},
- {'format_id': 'video', 'ext': 'mp4', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- # This must fail since complete video-audio format does not match filter
- # and extractor does not provide incomplete only formats (i.e. only
- # video-only or audio-only).
- ydl = YDL({'format': 'best[height>360]'})
- self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
-
- def test_format_selection_issue_10083(self):
- # See https://github.com/ytdl-org/youtube-dl/issues/10083
- formats = [
- {'format_id': 'regular', 'height': 360, 'url': TEST_URL},
- {'format_id': 'video', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
- {'format_id': 'audio', 'vcodec': 'none', 'url': TEST_URL},
- ]
- info_dict = _make_result(formats)
-
- ydl = YDL({'format': 'best[height>360]/bestvideo[height>360]+bestaudio'})
- ydl.process_ie_result(info_dict.copy())
- self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'video+audio')
-
- def test_invalid_format_specs(self):
- def assert_syntax_error(format_spec):
- self.assertRaises(SyntaxError, YDL, {'format': format_spec})
-
- assert_syntax_error('bestvideo,,best')
- assert_syntax_error('+bestaudio')
- assert_syntax_error('bestvideo+')
- assert_syntax_error('/')
- assert_syntax_error('[720450]'})
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'B')
-
- ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'C')
-
- ydl = YDL({'format': '[filesize>?1]'})
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'G')
-
- ydl = YDL({'format': '[filesize<1M]'})
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'E')
-
- ydl = YDL({'format': '[filesize<1MiB]'})
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'G')
-
- ydl = YDL({'format': 'all[width>=400][width<=600]'})
- ydl.process_ie_result(info_dict)
- downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
- self.assertEqual(downloaded_ids, ['D', 'C', 'B'])
-
- ydl = YDL({'format': 'best[height<40]'})
- with contextlib.suppress(ExtractorError):
- ydl.process_ie_result(info_dict)
- self.assertEqual(ydl.downloaded_info_dicts, [])
-
- ydl = YDL({'format': 'best[aspect_ratio=1]'})
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'A')
-
- ydl = YDL({'format': 'all[aspect_ratio > 1.00]'})
- ydl.process_ie_result(info_dict)
- downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
- self.assertEqual(downloaded_ids, ['D', 'C', 'B'])
-
- ydl = YDL({'format': 'all[aspect_ratio < 1.00]'})
- ydl.process_ie_result(info_dict)
- downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
- self.assertEqual(downloaded_ids, ['E'])
-
- ydl = YDL({'format': 'best[aspect_ratio=1.5]'})
- ydl.process_ie_result(info_dict)
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['format_id'], 'C')
-
- ydl = YDL({'format': 'all[aspect_ratio!=1]'})
- ydl.process_ie_result(info_dict)
- downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
- self.assertEqual(downloaded_ids, ['E', 'D', 'C', 'B'])
-
- @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.available', False)
- def test_default_format_spec_without_ffmpeg(self):
- ydl = YDL({})
- self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
-
- ydl = YDL({'simulate': True})
- self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
-
- ydl = YDL({})
- self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
-
- ydl = YDL({'simulate': True})
- self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
-
- ydl = YDL({'outtmpl': '-'})
- self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
-
- ydl = YDL({})
- self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
- self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
-
- @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.available', True)
- @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.can_merge', lambda _: True)
- def test_default_format_spec_with_ffmpeg(self):
- ydl = YDL({})
- self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
-
- ydl = YDL({'simulate': True})
- self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
-
- ydl = YDL({})
- self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
-
- ydl = YDL({'simulate': True})
- self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
-
- ydl = YDL({'outtmpl': '-'})
- self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
-
- ydl = YDL({})
- self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
- self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
-
-
-class TestYoutubeDL(unittest.TestCase):
- def test_subtitles(self):
- def s_formats(lang, autocaption=False):
- return [{
- 'ext': ext,
- 'url': f'http://localhost/video.{lang}.{ext}',
- '_auto': autocaption,
- } for ext in ['vtt', 'srt', 'ass']]
- subtitles = {l: s_formats(l) for l in ['en', 'fr', 'es']}
- auto_captions = {l: s_formats(l, True) for l in ['it', 'pt', 'es']}
- info_dict = {
- 'id': 'test',
- 'title': 'Test',
- 'url': 'http://localhost/video.mp4',
- 'subtitles': subtitles,
- 'automatic_captions': auto_captions,
- 'extractor': 'TEST',
- 'webpage_url': 'http://example.com/watch?v=shenanigans',
- }
-
- def get_info(params={}):
- params.setdefault('simulate', True)
- ydl = YDL(params)
- ydl.report_warning = lambda *args, **kargs: None
- return ydl.process_video_result(info_dict, download=False)
-
- result = get_info()
- self.assertFalse(result.get('requested_subtitles'))
- self.assertEqual(result['subtitles'], subtitles)
- self.assertEqual(result['automatic_captions'], auto_captions)
-
- result = get_info({'writesubtitles': True})
- subs = result['requested_subtitles']
- self.assertTrue(subs)
- self.assertEqual(set(subs.keys()), {'en'})
- self.assertTrue(subs['en'].get('data') is None)
- self.assertEqual(subs['en']['ext'], 'ass')
-
- result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
- subs = result['requested_subtitles']
- self.assertEqual(subs['en']['ext'], 'srt')
-
- result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
- subs = result['requested_subtitles']
- self.assertTrue(subs)
- self.assertEqual(set(subs.keys()), {'es', 'fr'})
-
- result = get_info({'writesubtitles': True, 'subtitleslangs': ['all', '-en']})
- subs = result['requested_subtitles']
- self.assertTrue(subs)
- self.assertEqual(set(subs.keys()), {'es', 'fr'})
-
- result = get_info({'writesubtitles': True, 'subtitleslangs': ['en', 'fr', '-en']})
- subs = result['requested_subtitles']
- self.assertTrue(subs)
- self.assertEqual(set(subs.keys()), {'fr'})
-
- result = get_info({'writesubtitles': True, 'subtitleslangs': ['-en', 'en']})
- subs = result['requested_subtitles']
- self.assertTrue(subs)
- self.assertEqual(set(subs.keys()), {'en'})
-
- result = get_info({'writesubtitles': True, 'subtitleslangs': ['e.+']})
- subs = result['requested_subtitles']
- self.assertTrue(subs)
- self.assertEqual(set(subs.keys()), {'es', 'en'})
-
- result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
- subs = result['requested_subtitles']
- self.assertTrue(subs)
- self.assertEqual(set(subs.keys()), {'es', 'pt'})
- self.assertFalse(subs['es']['_auto'])
- self.assertTrue(subs['pt']['_auto'])
-
- result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
- subs = result['requested_subtitles']
- self.assertTrue(subs)
- self.assertEqual(set(subs.keys()), {'es', 'pt'})
- self.assertTrue(subs['es']['_auto'])
- self.assertTrue(subs['pt']['_auto'])
-
- def test_add_extra_info(self):
- test_dict = {
- 'extractor': 'Foo',
- }
- extra_info = {
- 'extractor': 'Bar',
- 'playlist': 'funny videos',
- }
- YDL.add_extra_info(test_dict, extra_info)
- self.assertEqual(test_dict['extractor'], 'Foo')
- self.assertEqual(test_dict['playlist'], 'funny videos')
-
- outtmpl_info = {
- 'id': '1234',
- 'ext': 'mp4',
- 'width': None,
- 'height': 1080,
- 'filesize': 1024,
- 'title1': '$PATH',
- 'title2': '%PATH%',
- 'title3': 'foo/bar\\test',
- 'title4': 'foo "bar" test',
- 'title5': 'áéí 𝐀',
- 'timestamp': 1618488000,
- 'duration': 100000,
- 'playlist_index': 1,
- 'playlist_autonumber': 2,
- '__last_playlist_index': 100,
- 'n_entries': 10,
- 'formats': [
- {'id': 'id 1', 'height': 1080, 'width': 1920},
- {'id': 'id 2', 'height': 720},
- {'id': 'id 3'},
- ],
- }
-
- def test_prepare_outtmpl_and_filename(self):
- def test(tmpl, expected, *, info=None, **params):
- params['outtmpl'] = tmpl
- ydl = FakeYDL(params)
- ydl._num_downloads = 1
- self.assertEqual(ydl.validate_outtmpl(tmpl), None)
-
- out = ydl.evaluate_outtmpl(tmpl, info or self.outtmpl_info)
- fname = ydl.prepare_filename(info or self.outtmpl_info)
-
- if not isinstance(expected, (list, tuple)):
- expected = (expected, expected)
- for (name, got), expect in zip((('outtmpl', out), ('filename', fname)), expected, strict=True):
- if callable(expect):
- self.assertTrue(expect(got), f'Wrong {name} from {tmpl}')
- elif expect is not None:
- self.assertEqual(got, expect, f'Wrong {name} from {tmpl}')
-
- # Side-effects
- original_infodict = dict(self.outtmpl_info)
- test('foo.bar', 'foo.bar')
- original_infodict['epoch'] = self.outtmpl_info.get('epoch')
- self.assertTrue(isinstance(original_infodict['epoch'], int))
- test('%(epoch)d', int_or_none)
- self.assertEqual(original_infodict, self.outtmpl_info)
-
- # Auto-generated fields
- test('%(id)s.%(ext)s', '1234.mp4')
- test('%(duration_string)s', ('27:46:40', '27-46-40'))
- test('%(resolution)s', '1080p')
- test('%(playlist_index|)s', '001')
- test('%(playlist_index&{}!)s', '1!')
- test('%(playlist_autonumber)s', '02')
- test('%(autonumber)s', '00001')
- test('%(autonumber+2)03d', '005', autonumber_start=3)
- test('%(autonumber)s', '001', autonumber_size=3)
-
- # Escaping %
- test('%', '%')
- test('%%', '%')
- test('%%%%', '%%')
- test('%s', '%s')
- test('%%%s', '%%s')
- test('%d', '%d')
- test('%abc%', '%abc%')
- test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
- test('%%%(height)s', '%1080')
- test('%(width)06d.%(ext)s', 'NA.mp4')
- test('%(width)06d.%%(ext)s', 'NA.%(ext)s')
- test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
-
- # Sanitization options
- test('%(title3)s', (None, 'foo⧸bar⧹test'))
- test('%(title5)s', (None, 'aei_A'), restrictfilenames=True)
- test('%(title3)s', (None, 'foo_bar_test'), windowsfilenames=False, restrictfilenames=True)
- if sys.platform != 'win32':
- test('%(title3)s', (None, 'foo⧸bar\\test'), windowsfilenames=False)
-
- # ID sanitization
- test('%(id)s', '_abcd', info={'id': '_abcd'})
- test('%(some_id)s', '_abcd', info={'some_id': '_abcd'})
- test('%(formats.0.id)s', '_abcd', info={'formats': [{'id': '_abcd'}]})
- test('%(id)s', '-abcd', info={'id': '-abcd'})
- test('%(id)s', '.abcd', info={'id': '.abcd'})
- test('%(id)s', 'ab__cd', info={'id': 'ab__cd'})
- test('%(id)s', ('ab:cd', 'ab:cd'), info={'id': 'ab:cd'})
- test('%(id.0)s', '-', info={'id': '--'})
-
- # Invalid templates
- self.assertTrue(isinstance(YoutubeDL.validate_outtmpl('%(title)'), ValueError))
- test('%(invalid@tmpl|def)s', 'none', outtmpl_na_placeholder='none')
- test('%(..)s', 'NA')
- test('%(formats.{id)s', 'NA')
-
- # Entire info_dict
- def expect_same_infodict(out):
- got_dict = json.loads(out)
- for info_field, expected in self.outtmpl_info.items():
- self.assertEqual(got_dict.get(info_field), expected, info_field)
- return True
-
- test('%()j', (expect_same_infodict, None))
-
- # NA placeholder
- NA_TEST_OUTTMPL = '%(uploader_date)s-%(width)d-%(x|def)s-%(id)s.%(ext)s'
- test(NA_TEST_OUTTMPL, 'NA-NA-def-1234.mp4')
- test(NA_TEST_OUTTMPL, 'none-none-def-1234.mp4', outtmpl_na_placeholder='none')
- test(NA_TEST_OUTTMPL, '--def-1234.mp4', outtmpl_na_placeholder='')
- test('%(non_existent.0)s', 'NA')
-
- # String formatting
- FMT_TEST_OUTTMPL = '%%(height)%s.%%(ext)s'
- test(FMT_TEST_OUTTMPL % 's', '1080.mp4')
- test(FMT_TEST_OUTTMPL % 'd', '1080.mp4')
- test(FMT_TEST_OUTTMPL % '6d', ' 1080.mp4')
- test(FMT_TEST_OUTTMPL % '-6d', '1080 .mp4')
- test(FMT_TEST_OUTTMPL % '06d', '001080.mp4')
- test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
- test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
- test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
- test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
- test(FMT_TEST_OUTTMPL % ' 0 6d', ' 01080.mp4')
-
- # Type casting
- test('%(id)d', '1234')
- test('%(height)c', '1')
- test('%(ext)c', 'm')
- test('%(id)d %(id)r', "1234 '1234'")
- test('%(id)r %(height)r', "'1234' 1080")
- test('%(title5)a %(height)a', (R"'\xe1\xe9\xed \U0001d400' 1080", None))
- test('%(ext)s-%(ext|def)d', 'mp4-def')
- test('%(width|0)04d', '0')
- test('a%(width|b)d', 'ab', outtmpl_na_placeholder='none')
-
- FORMATS = self.outtmpl_info['formats']
-
- # Custom type casting
- test('%(formats.:.id)l', 'id 1, id 2, id 3')
- test('%(formats.:.id)#l', ('id 1\nid 2\nid 3', 'id 1 id 2 id 3'))
- test('%(ext)l', 'mp4')
- test('%(formats.:.id) 18l', ' id 1, id 2, id 3')
- test('%(formats)j', (json.dumps(FORMATS), None))
- test('%(formats)#j', (
- json.dumps(FORMATS, indent=4),
- json.dumps(FORMATS, indent=4).replace(':', ':').replace('"', '"').replace('\n', ' '),
- ))
- test('%(title5).3B', 'á')
- test('%(title5)U', 'áéí 𝐀')
- test('%(title5)#U', 'a\u0301e\u0301i\u0301 𝐀')
- test('%(title5)+U', 'áéí A')
- test('%(title5)+#U', 'a\u0301e\u0301i\u0301 A')
- test('%(height)D', '1k')
- test('%(filesize)#D', '1Ki')
- test('%(height)5.2D', ' 1.08k')
- test('%(title4)#S', 'foo_bar_test')
- test('%(title4).10S', ('foo "bar" ', 'foo "bar"' + ('#' if os.name == 'nt' else ' ')))
- if os.name == 'nt':
- test('%(title4)q', ('"foo ""bar"" test"', None))
- test('%(formats.:.id)#q', ('"id 1" "id 2" "id 3"', None))
- test('%(formats.0.id)#q', ('"id 1"', None))
- else:
- test('%(title4)q', ('\'foo "bar" test\'', '\'foo "bar" test\''))
- test('%(formats.:.id)#q', "'id 1' 'id 2' 'id 3'")
- test('%(formats.0.id)#q', "'id 1'")
-
- # Internal formatting
- test('%(timestamp-1000>%H-%M-%S)s', '11-43-20')
- test('%(title|%)s %(title|%%)s', '% %%')
- test('%(id+1-height+3)05d', '00158')
- test('%(width+100)05d', 'NA')
- test('%(filesize*8)d', '8192')
- test('%(formats.0) 15s', ('% 15s' % FORMATS[0], None))
- test('%(formats.0)r', (repr(FORMATS[0]), None))
- test('%(height.0)03d', '001')
- test('%(-height.0)04d', '-001')
- test('%(formats.-1.id)s', FORMATS[-1]['id'])
- test('%(formats.0.id.-1)d', FORMATS[0]['id'][-1])
- test('%(formats.3)s', 'NA')
- test('%(formats.:2:-1)r', repr(FORMATS[:2:-1]))
- test('%(formats.0.id.-1+id)f', '1235.000000')
- test('%(formats.0.id.-1+formats.1.id.-1)d', '3')
- out = json.dumps([{'id': f['id'], 'height.:2': str(f['height'])[:2]}
- if 'height' in f else {'id': f['id']}
- for f in FORMATS])
- test('%(formats.:.{id,height.:2})j', (out, None))
- test('%(formats.:.{id,height}.id)l', ', '.join(f['id'] for f in FORMATS))
- test('%(.{id,title})j', ('{"id": "1234"}', '{"id": "1234"}'))
-
- # Alternates
- test('%(title,id)s', '1234')
- test('%(width-100,height+20|def)d', '1100')
- test('%(width-100,height+width|def)s', 'def')
- test('%(timestamp-x>%H\\,%M\\,%S,timestamp>%H\\,%M\\,%S)s', '12,00,00')
-
- # Replacement
- test('%(id&foo)s.bar', 'foo.bar')
- test('%(title&foo)s.bar', 'NA.bar')
- test('%(title&foo|baz)s.bar', 'baz.bar')
- test('%(x,id&foo|baz)s.bar', 'foo.bar')
- test('%(x,title&foo|baz)s.bar', 'baz.bar')
- test('%(id&a\nb|)s', ('a\nb', 'a b'))
- test('%(id&hi {:>10} {}|)s', 'hi 1234 1234')
- test(R'%(id&{0} {}|)s', 'NA')
- test(R'%(id&{0.1}|)s', 'NA')
- test('%(height&{:,d})S', '1,080')
-
- # Laziness
- def gen():
- yield from range(5)
- raise self.assertTrue(False, 'LazyList should not be evaluated till here')
- test('%(key.4)s', '4', info={'key': LazyList(gen())})
-
- # Empty filename
- test('%(foo|)s-%(bar|)s.%(ext)s', '-.mp4')
- # test('%(foo|)s.%(ext)s', ('.mp4', '_.mp4')) # FIXME: ?
- # test('%(foo|)s', ('', '_')) # FIXME: ?
-
- # Environment variable expansion for prepare_filename
- os.environ['__yt_dlp_var'] = 'expanded'
- envvar = '%__yt_dlp_var%' if os.name == 'nt' else '$__yt_dlp_var'
- test(envvar, (envvar, 'expanded'))
- if os.name == 'nt':
- test('%s%', ('%s%', '%s%'))
- os.environ['s'] = 'expanded'
- test('%s%', ('%s%', 'expanded')) # %s% should be expanded before escaping %s
- os.environ['(test)s'] = 'expanded'
- test('%(test)s%', ('NA%', 'expanded')) # Environment should take priority over template
-
- # Path expansion and escaping
- test('Hello %(title1)s', 'Hello $PATH')
- test('Hello %(title2)s', 'Hello %PATH%')
- test('%(title3)s', ('foo/bar\\test', 'foo⧸bar⧹test'))
- test('folder/%(title3)s', ('folder/foo/bar\\test', f'folder{os.path.sep}foo⧸bar⧹test'))
-
- def test_format_note(self):
- ydl = YoutubeDL()
- self.assertEqual(ydl._format_note({}), '')
- assertRegexpMatches(self, ydl._format_note({
- 'vbr': 10,
- }), r'^\s*10k$')
- assertRegexpMatches(self, ydl._format_note({
- 'fps': 30,
- }), r'^30fps$')
-
- def test_postprocessors(self):
- filename = 'post-processor-testfile.mp4'
- audiofile = filename + '.mp3'
-
- class SimplePP(PostProcessor):
- def run(self, info):
- with open(audiofile, 'w') as f:
- f.write('EXAMPLE')
- return [info['filepath']], info
-
- def run_pp(params, pp):
- with open(filename, 'w') as f:
- f.write('EXAMPLE')
- ydl = YoutubeDL(params)
- ydl.add_post_processor(pp())
- ydl.post_process(filename, {'filepath': filename})
-
- run_pp({'keepvideo': True}, SimplePP)
- self.assertTrue(os.path.exists(filename), f'{filename} doesn\'t exist')
- self.assertTrue(os.path.exists(audiofile), f'{audiofile} doesn\'t exist')
- os.unlink(filename)
- os.unlink(audiofile)
-
- run_pp({'keepvideo': False}, SimplePP)
- self.assertFalse(os.path.exists(filename), f'{filename} exists')
- self.assertTrue(os.path.exists(audiofile), f'{audiofile} doesn\'t exist')
- os.unlink(audiofile)
-
- class ModifierPP(PostProcessor):
- def run(self, info):
- with open(info['filepath'], 'w') as f:
- f.write('MODIFIED')
- return [], info
-
- run_pp({'keepvideo': False}, ModifierPP)
- self.assertTrue(os.path.exists(filename), f'{filename} doesn\'t exist')
- os.unlink(filename)
-
- def test_match_filter(self):
- first = {
- 'id': '1',
- 'url': TEST_URL,
- 'title': 'one',
- 'extractor': 'TEST',
- 'duration': 30,
- 'filesize': 10 * 1024,
- 'playlist_id': '42',
- 'uploader': '變態妍字幕版 太妍 тест',
- 'creator': "тест ' 123 ' тест--",
- 'webpage_url': 'http://example.com/watch?v=shenanigans',
- }
- second = {
- 'id': '2',
- 'url': TEST_URL,
- 'title': 'two',
- 'extractor': 'TEST',
- 'duration': 10,
- 'description': 'foo',
- 'filesize': 5 * 1024,
- 'playlist_id': '43',
- 'uploader': 'тест 123',
- 'webpage_url': 'http://example.com/watch?v=SHENANIGANS',
- }
- videos = [first, second]
-
- def get_videos(filter_=None):
- ydl = YDL({'match_filter': filter_, 'simulate': True})
- for v in videos:
- ydl.process_ie_result(v.copy(), download=True)
- return [v['id'] for v in ydl.downloaded_info_dicts]
-
- res = get_videos()
- self.assertEqual(res, ['1', '2'])
-
- def f(v, incomplete):
- if v['id'] == '1':
- return None
- else:
- return 'Video id is not 1'
- res = get_videos(f)
- self.assertEqual(res, ['1'])
-
- f = match_filter_func('duration < 30')
- res = get_videos(f)
- self.assertEqual(res, ['2'])
-
- f = match_filter_func('description = foo')
- res = get_videos(f)
- self.assertEqual(res, ['2'])
-
- f = match_filter_func('description =? foo')
- res = get_videos(f)
- self.assertEqual(res, ['1', '2'])
-
- f = match_filter_func('filesize > 5KiB')
- res = get_videos(f)
- self.assertEqual(res, ['1'])
-
- f = match_filter_func('playlist_id = 42')
- res = get_videos(f)
- self.assertEqual(res, ['1'])
-
- f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
- res = get_videos(f)
- self.assertEqual(res, ['1'])
-
- f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
- res = get_videos(f)
- self.assertEqual(res, ['2'])
-
- f = match_filter_func('creator = "тест \' 123 \' тест--"')
- res = get_videos(f)
- self.assertEqual(res, ['1'])
-
- f = match_filter_func("creator = 'тест \\' 123 \\' тест--'")
- res = get_videos(f)
- self.assertEqual(res, ['1'])
-
- f = match_filter_func(r"creator = 'тест \' 123 \' тест--' & duration > 30")
- res = get_videos(f)
- self.assertEqual(res, [])
-
- def test_playlist_items_selection(self):
- INDICES, PAGE_SIZE = list(range(1, 11)), 3
-
- def entry(i, evaluated):
- evaluated.append(i)
- return {
- 'id': str(i),
- 'title': str(i),
- 'url': TEST_URL,
- }
-
- def pagedlist_entries(evaluated):
- def page_func(n):
- start = PAGE_SIZE * n
- for i in INDICES[start: start + PAGE_SIZE]:
- yield entry(i, evaluated)
- return OnDemandPagedList(page_func, PAGE_SIZE)
-
- def page_num(i):
- return (i + PAGE_SIZE - 1) // PAGE_SIZE
-
- def generator_entries(evaluated):
- for i in INDICES:
- yield entry(i, evaluated)
-
- def list_entries(evaluated):
- return list(generator_entries(evaluated))
-
- def lazylist_entries(evaluated):
- return LazyList(generator_entries(evaluated))
-
- def get_downloaded_info_dicts(params, entries):
- ydl = YDL(params)
- ydl.process_ie_result({
- '_type': 'playlist',
- 'id': 'test',
- 'extractor': 'test:playlist',
- 'extractor_key': 'test:playlist',
- 'webpage_url': 'http://example.com',
- 'entries': entries,
- })
- return ydl.downloaded_info_dicts
-
- def test_selection(params, expected_ids, evaluate_all=False):
- expected_ids = list(expected_ids)
- if evaluate_all:
- generator_eval = pagedlist_eval = INDICES
- elif not expected_ids:
- generator_eval = pagedlist_eval = []
- else:
- generator_eval = INDICES[0: max(expected_ids)]
- pagedlist_eval = INDICES[PAGE_SIZE * page_num(min(expected_ids)) - PAGE_SIZE:
- PAGE_SIZE * page_num(max(expected_ids))]
-
- for name, func, expected_eval in (
- ('list', list_entries, INDICES),
- ('Generator', generator_entries, generator_eval),
- # ('LazyList', lazylist_entries, generator_eval), # Generator and LazyList follow the exact same code path
- ('PagedList', pagedlist_entries, pagedlist_eval),
- ):
- evaluated = []
- entries = func(evaluated)
- results = [(v['playlist_autonumber'] - 1, (int(v['id']), v['playlist_index']))
- for v in get_downloaded_info_dicts(params, entries)]
- self.assertEqual(results, list(enumerate(zip(expected_ids, expected_ids, strict=True))), f'Entries of {name} for {params}')
- self.assertEqual(sorted(evaluated), expected_eval, f'Evaluation of {name} for {params}')
-
- test_selection({}, INDICES)
- test_selection({'playlistend': 20}, INDICES, True)
- test_selection({'playlistend': 2}, INDICES[:2])
- test_selection({'playliststart': 11}, [], True)
- test_selection({'playliststart': 2}, INDICES[1:])
- test_selection({'playlist_items': '2-4'}, INDICES[1:4])
- test_selection({'playlist_items': '2,4'}, [2, 4])
- test_selection({'playlist_items': '20'}, [], True)
- test_selection({'playlist_items': '0'}, [])
-
- # Tests for https://github.com/ytdl-org/youtube-dl/issues/10591
- test_selection({'playlist_items': '2-4,3-4,3'}, [2, 3, 4])
- test_selection({'playlist_items': '4,2'}, [4, 2])
-
- # Tests for https://github.com/yt-dlp/yt-dlp/issues/720
- # https://github.com/yt-dlp/yt-dlp/issues/302
- test_selection({'playlistreverse': True}, INDICES[::-1])
- test_selection({'playliststart': 2, 'playlistreverse': True}, INDICES[:0:-1])
- test_selection({'playlist_items': '2,4', 'playlistreverse': True}, [4, 2])
- test_selection({'playlist_items': '4,2'}, [4, 2])
-
- # Tests for --playlist-items start:end:step
- test_selection({'playlist_items': ':'}, INDICES, True)
- test_selection({'playlist_items': '::1'}, INDICES, True)
- test_selection({'playlist_items': '::-1'}, INDICES[::-1], True)
- test_selection({'playlist_items': ':6'}, INDICES[:6])
- test_selection({'playlist_items': ':-6'}, INDICES[:-5], True)
- test_selection({'playlist_items': '-1:6:-2'}, INDICES[:4:-2], True)
- test_selection({'playlist_items': '9:-6:-2'}, INDICES[8:3:-2], True)
-
- test_selection({'playlist_items': '1:inf:2'}, INDICES[::2], True)
- test_selection({'playlist_items': '-2:inf'}, INDICES[-2:], True)
- test_selection({'playlist_items': ':inf:-1'}, [], True)
- test_selection({'playlist_items': '0-2:2'}, [2])
- test_selection({'playlist_items': '1-:2'}, INDICES[::2], True)
- test_selection({'playlist_items': '0--2:2'}, INDICES[1:-1:2], True)
-
- test_selection({'playlist_items': '10::3'}, [10], True)
- test_selection({'playlist_items': '-1::3'}, [10], True)
- test_selection({'playlist_items': '11::3'}, [], True)
- test_selection({'playlist_items': '-15::2'}, INDICES[1::2], True)
- test_selection({'playlist_items': '-15::15'}, [], True)
-
- def test_do_not_override_ie_key_in_url_transparent(self):
- ydl = YDL()
-
- class Foo1IE(InfoExtractor):
- _VALID_URL = r'foo1:'
-
- def _real_extract(self, url):
- return {
- '_type': 'url_transparent',
- 'url': 'foo2:',
- 'ie_key': 'Foo2',
- 'title': 'foo1 title',
- 'id': 'foo1_id',
- }
-
- class Foo2IE(InfoExtractor):
- _VALID_URL = r'foo2:'
-
- def _real_extract(self, url):
- return {
- '_type': 'url',
- 'url': 'foo3:',
- 'ie_key': 'Foo3',
- }
-
- class Foo3IE(InfoExtractor):
- _VALID_URL = r'foo3:'
-
- def _real_extract(self, url):
- return _make_result([{'url': TEST_URL}], title='foo3 title')
-
- ydl.add_info_extractor(Foo1IE(ydl))
- ydl.add_info_extractor(Foo2IE(ydl))
- ydl.add_info_extractor(Foo3IE(ydl))
- ydl.extract_info('foo1:')
- downloaded = ydl.downloaded_info_dicts[0]
- self.assertEqual(downloaded['url'], TEST_URL)
- self.assertEqual(downloaded['title'], 'foo1 title')
- self.assertEqual(downloaded['id'], 'testid')
- self.assertEqual(downloaded['extractor'], 'testex')
- self.assertEqual(downloaded['extractor_key'], 'TestEx')
-
- # Test case for https://github.com/ytdl-org/youtube-dl/issues/27064
- def test_ignoreerrors_for_playlist_with_url_transparent_iterable_entries(self):
-
- class _YDL(YDL):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
-
- def trouble(self, s, tb=None):
- pass
-
- ydl = _YDL({
- 'format': 'extra',
- 'ignoreerrors': True,
- })
-
- class VideoIE(InfoExtractor):
- _VALID_URL = r'video:(?P\d+)'
-
- def _real_extract(self, url):
- video_id = self._match_id(url)
- formats = [{
- 'format_id': 'default',
- 'url': 'url:',
- }]
- if video_id == '0':
- raise ExtractorError('foo')
- if video_id == '2':
- formats.append({
- 'format_id': 'extra',
- 'url': TEST_URL,
- })
- return {
- 'id': video_id,
- 'title': f'Video {video_id}',
- 'formats': formats,
- }
-
- class PlaylistIE(InfoExtractor):
- _VALID_URL = r'playlist:'
-
- def _entries(self):
- for n in range(3):
- video_id = str(n)
- yield {
- '_type': 'url_transparent',
- 'ie_key': VideoIE.ie_key(),
- 'id': video_id,
- 'url': f'video:{video_id}',
- 'title': f'Video Transparent {video_id}',
- }
-
- def _real_extract(self, url):
- return self.playlist_result(self._entries())
-
- ydl.add_info_extractor(VideoIE(ydl))
- ydl.add_info_extractor(PlaylistIE(ydl))
- info = ydl.extract_info('playlist:')
- entries = info['entries']
- self.assertEqual(len(entries), 3)
- self.assertTrue(entries[0] is None)
- self.assertTrue(entries[1] is None)
- self.assertEqual(len(ydl.downloaded_info_dicts), 1)
- downloaded = ydl.downloaded_info_dicts[0]
- entries[2].pop('requested_downloads', None)
- self.assertEqual(entries[2], downloaded)
- self.assertEqual(downloaded['url'], TEST_URL)
- self.assertEqual(downloaded['title'], 'Video Transparent 2')
- self.assertEqual(downloaded['id'], '2')
- self.assertEqual(downloaded['extractor'], 'Video')
- self.assertEqual(downloaded['extractor_key'], 'Video')
-
- def test_header_cookies(self):
- from http.cookiejar import Cookie
-
- ydl = FakeYDL()
- ydl.report_warning = lambda *_, **__: None
-
- def cookie(name, value, version=None, domain='', path='', secure=False, expires=None):
- return Cookie(
- version or 0, name, value, None, False,
- domain, bool(domain), bool(domain), path, bool(path),
- secure, expires, False, None, None, rest={})
-
- _test_url = 'https://yt.dlp/test'
-
- def test(encoded_cookies, cookies, *, headers=False, round_trip=None, error_re=None):
- def _test():
- ydl.cookiejar.clear()
- ydl._load_cookies(encoded_cookies, autoscope=headers)
- if headers:
- ydl._apply_header_cookies(_test_url)
- data = {'url': _test_url}
- ydl._calc_headers(data)
- self.assertCountEqual(
- map(vars, ydl.cookiejar), map(vars, cookies),
- 'Extracted cookiejar.Cookie is not the same')
- if not headers:
- self.assertEqual(
- data.get('cookies'), round_trip or encoded_cookies,
- 'Cookie is not the same as round trip')
- ydl.__dict__['_YoutubeDL__header_cookies'] = []
-
- with self.subTest(msg=encoded_cookies):
- if not error_re:
- _test()
- return
- with self.assertRaisesRegex(Exception, error_re):
- _test()
-
- test('test=value; Domain=.yt.dlp', [cookie('test', 'value', domain='.yt.dlp')])
- test('test=value', [cookie('test', 'value')], error_re=r'Unscoped cookies are not allowed')
- test('cookie1=value1; Domain=.yt.dlp; Path=/test; cookie2=value2; Domain=.yt.dlp; Path=/', [
- cookie('cookie1', 'value1', domain='.yt.dlp', path='/test'),
- cookie('cookie2', 'value2', domain='.yt.dlp', path='/')])
- test('test=value; Domain=.yt.dlp; Path=/test; Secure; Expires=9999999999', [
- cookie('test', 'value', domain='.yt.dlp', path='/test', secure=True, expires=9999999999)])
- test('test="value; "; path=/test; domain=.yt.dlp', [
- cookie('test', 'value; ', domain='.yt.dlp', path='/test')],
- round_trip='test="value\\073 "; Domain=.yt.dlp; Path=/test')
- test('name=; Domain=.yt.dlp', [cookie('name', '', domain='.yt.dlp')],
- round_trip='name=""; Domain=.yt.dlp')
-
- test('test=value', [cookie('test', 'value', domain='.yt.dlp')], headers=True)
- test('cookie1=value; Domain=.yt.dlp; cookie2=value', [], headers=True, error_re=r'Invalid syntax')
- ydl.deprecated_feature = ydl.report_error
- test('test=value', [], headers=True, error_re=r'Passing cookies as a header is a potential security risk')
-
- def test_infojson_cookies(self):
- TEST_FILE = 'test_infojson_cookies.info.json'
- TEST_URL = 'https://example.com/example.mp4'
- COOKIES = 'a=b; Domain=.example.com; c=d; Domain=.example.com'
- COOKIE_HEADER = {'Cookie': 'a=b; c=d'}
-
- ydl = FakeYDL()
- ydl.process_info = lambda x: ydl._write_info_json('test', x, TEST_FILE)
-
- def make_info(info_header_cookies=False, fmts_header_cookies=False, cookies_field=False):
- fmt = {'url': TEST_URL}
- if fmts_header_cookies:
- fmt['http_headers'] = COOKIE_HEADER
- if cookies_field:
- fmt['cookies'] = COOKIES
- return _make_result([fmt], http_headers=COOKIE_HEADER if info_header_cookies else None)
-
- def test(initial_info, note):
- result = {}
- result['processed'] = ydl.process_ie_result(initial_info)
- self.assertTrue(ydl.cookiejar.get_cookies_for_url(TEST_URL),
- msg=f'No cookies set in cookiejar after initial process when {note}')
- ydl.cookiejar.clear()
- with open(TEST_FILE) as infojson:
- result['loaded'] = ydl.sanitize_info(json.load(infojson), True)
- result['final'] = ydl.process_ie_result(result['loaded'].copy(), download=False)
- self.assertTrue(ydl.cookiejar.get_cookies_for_url(TEST_URL),
- msg=f'No cookies set in cookiejar after final process when {note}')
- ydl.cookiejar.clear()
- for key in ('processed', 'loaded', 'final'):
- info = result[key]
- self.assertIsNone(
- traverse_obj(info, ((None, ('formats', 0)), 'http_headers', 'Cookie'), casesense=False, get_all=False),
- msg=f'Cookie header not removed in {key} result when {note}')
- self.assertEqual(
- traverse_obj(info, ((None, ('formats', 0)), 'cookies'), get_all=False), COOKIES,
- msg=f'No cookies field found in {key} result when {note}')
-
- test({'url': TEST_URL, 'http_headers': COOKIE_HEADER, 'id': '1', 'title': 'x'}, 'no formats field')
- test(make_info(info_header_cookies=True), 'info_dict header cokies')
- test(make_info(fmts_header_cookies=True), 'format header cookies')
- test(make_info(info_header_cookies=True, fmts_header_cookies=True), 'info_dict and format header cookies')
- test(make_info(info_header_cookies=True, fmts_header_cookies=True, cookies_field=True), 'all cookies fields')
- test(make_info(cookies_field=True), 'cookies format field')
- test({'url': TEST_URL, 'cookies': COOKIES, 'id': '1', 'title': 'x'}, 'info_dict cookies field only')
-
- try_rm(TEST_FILE)
-
- def test_add_headers_cookie(self):
- def check_for_cookie_header(result):
- return traverse_obj(result, ((None, ('formats', 0)), 'http_headers', 'Cookie'), casesense=False, get_all=False)
-
- ydl = FakeYDL({'http_headers': {'Cookie': 'a=b'}})
- ydl._apply_header_cookies(_make_result([])['webpage_url']) # Scope to input webpage URL: .example.com
-
- fmt = {'url': 'https://example.com/video.mp4'}
- result = ydl.process_ie_result(_make_result([fmt]), download=False)
- self.assertIsNone(check_for_cookie_header(result), msg='http_headers cookies in result info_dict')
- self.assertEqual(result.get('cookies'), 'a=b; Domain=.example.com', msg='No cookies were set in cookies field')
- self.assertIn('a=b', ydl.cookiejar.get_cookie_header(fmt['url']), msg='No cookies were set in cookiejar')
-
- fmt = {'url': 'https://wrong.com/video.mp4'}
- result = ydl.process_ie_result(_make_result([fmt]), download=False)
- self.assertIsNone(check_for_cookie_header(result), msg='http_headers cookies for wrong domain')
- self.assertFalse(result.get('cookies'), msg='Cookies set in cookies field for wrong domain')
- self.assertFalse(ydl.cookiejar.get_cookie_header(fmt['url']), msg='Cookies set in cookiejar for wrong domain')
-
- def test_load_plugins_compat(self):
- # Should try to reload plugins if they haven't already been loaded
- all_plugins_loaded.value = False
- FakeYDL().close()
- assert all_plugins_loaded.value
-
- def test_close_hooks(self):
- # Should call all registered close hooks on close
- close_hook_called = False
- close_hook_two_called = False
-
- def close_hook():
- nonlocal close_hook_called
- close_hook_called = True
-
- def close_hook_two():
- nonlocal close_hook_two_called
- close_hook_two_called = True
-
- ydl = FakeYDL()
- ydl.add_close_hook(close_hook)
- ydl.add_close_hook(close_hook_two)
-
- ydl.close()
- self.assertTrue(close_hook_called, 'Close hook was not called')
- self.assertTrue(close_hook_two_called, 'Close hook two was not called')
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_YoutubeDLCookieJar.py b/test/test_YoutubeDLCookieJar.py
deleted file mode 100644
index fdb9baee5..000000000
--- a/test/test_YoutubeDLCookieJar.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import re
-import tempfile
-
-from yt_dlp.cookies import YoutubeDLCookieJar
-
-
-class TestYoutubeDLCookieJar(unittest.TestCase):
- def test_keep_session_cookies(self):
- cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/session_cookies.txt')
- cookiejar.load()
- tf = tempfile.NamedTemporaryFile(delete=False)
- try:
- cookiejar.save(filename=tf.name)
- temp = tf.read().decode()
- self.assertTrue(re.search(
- r'www\.foobar\.foobar\s+FALSE\s+/\s+TRUE\s+0\s+YoutubeDLExpiresEmpty\s+YoutubeDLExpiresEmptyValue', temp))
- self.assertTrue(re.search(
- r'www\.foobar\.foobar\s+FALSE\s+/\s+TRUE\s+0\s+YoutubeDLExpires0\s+YoutubeDLExpires0Value', temp))
- finally:
- tf.close()
- os.remove(tf.name)
-
- def test_strip_httponly_prefix(self):
- cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/httponly_cookies.txt')
- cookiejar.load()
-
- def assert_cookie_has_value(key):
- self.assertEqual(cookiejar._cookies['www.foobar.foobar']['/'][key].value, key + '_VALUE')
-
- assert_cookie_has_value('HTTPONLY_COOKIE')
- assert_cookie_has_value('JS_ACCESSIBLE_COOKIE')
-
- def test_malformed_cookies(self):
- cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/malformed_cookies.txt')
- cookiejar.load()
- # Cookies should be empty since all malformed cookie file entries
- # will be ignored
- self.assertFalse(cookiejar._cookies)
-
- def test_get_cookie_header(self):
- cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/httponly_cookies.txt')
- cookiejar.load()
- header = cookiejar.get_cookie_header('https://www.foobar.foobar')
- self.assertIn('HTTPONLY_COOKIE', header)
-
- def test_get_cookies_for_url(self):
- cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/session_cookies.txt')
- cookiejar.load()
- cookies = cookiejar.get_cookies_for_url('https://www.foobar.foobar/')
- self.assertEqual(len(cookies), 2)
- cookies = cookiejar.get_cookies_for_url('https://foobar.foobar/')
- self.assertFalse(cookies)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_aes.py b/test/test_aes.py
deleted file mode 100644
index 9cd9189bc..000000000
--- a/test/test_aes.py
+++ /dev/null
@@ -1,163 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import base64
-
-from yt_dlp.aes import (
- aes_cbc_decrypt,
- aes_cbc_decrypt_bytes,
- aes_cbc_encrypt,
- aes_ctr_decrypt,
- aes_ctr_encrypt,
- aes_decrypt,
- aes_decrypt_text,
- aes_ecb_decrypt,
- aes_ecb_encrypt,
- aes_encrypt,
- aes_gcm_decrypt_and_verify,
- aes_gcm_decrypt_and_verify_bytes,
- key_expansion,
- pad_block,
-)
-from yt_dlp.dependencies import Cryptodome
-
-# the encrypted data can be generate with 'devscripts/generate_aes_testdata.py'
-
-
-class TestAES(unittest.TestCase):
- def setUp(self):
- self.key = self.iv = [0x20, 0x15] + 14 * [0]
- self.secret_msg = b'Secret message goes here'
-
- def test_encrypt(self):
- msg = b'message'
- key = list(range(16))
- encrypted = aes_encrypt(list(msg), key)
- decrypted = bytes(aes_decrypt(encrypted, key))
- self.assertEqual(decrypted, msg)
-
- def test_cbc_decrypt(self):
- data = b'\x97\x92+\xe5\x0b\xc3\x18\x91ky9m&\xb3\xb5@\xe6\x27\xc2\x96.\xc8u\x88\xab9-[\x9e|\xf1\xcd'
- decrypted = bytes(aes_cbc_decrypt(list(data), self.key, self.iv))
- self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg)
- if Cryptodome.AES:
- decrypted = aes_cbc_decrypt_bytes(data, bytes(self.key), bytes(self.iv))
- self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg)
-
- def test_cbc_encrypt(self):
- data = list(self.secret_msg)
- encrypted = bytes(aes_cbc_encrypt(data, self.key, self.iv))
- self.assertEqual(
- encrypted,
- b'\x97\x92+\xe5\x0b\xc3\x18\x91ky9m&\xb3\xb5@\xe6\'\xc2\x96.\xc8u\x88\xab9-[\x9e|\xf1\xcd')
-
- def test_ctr_decrypt(self):
- data = list(b'\x03\xc7\xdd\xd4\x8e\xb3\xbc\x1a*O\xdc1\x12+8Aio\xd1z\xb5#\xaf\x08')
- decrypted = bytes(aes_ctr_decrypt(data, self.key, self.iv))
- self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg)
-
- def test_ctr_encrypt(self):
- data = list(self.secret_msg)
- encrypted = bytes(aes_ctr_encrypt(data, self.key, self.iv))
- self.assertEqual(
- encrypted,
- b'\x03\xc7\xdd\xd4\x8e\xb3\xbc\x1a*O\xdc1\x12+8Aio\xd1z\xb5#\xaf\x08')
-
- def test_gcm_decrypt(self):
- data = b'\x159Y\xcf5eud\x90\x9c\x85&]\x14\x1d\x0f.\x08\xb4T\xe4/\x17\xbd'
- authentication_tag = b'\xe8&I\x80rI\x07\x9d}YWuU@:e'
-
- decrypted = bytes(aes_gcm_decrypt_and_verify(
- list(data), self.key, list(authentication_tag), self.iv[:12]))
- self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg)
- if Cryptodome.AES:
- decrypted = aes_gcm_decrypt_and_verify_bytes(
- data, bytes(self.key), authentication_tag, bytes(self.iv[:12]))
- self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg)
-
- def test_gcm_aligned_decrypt(self):
- data = b'\x159Y\xcf5eud\x90\x9c\x85&]\x14\x1d\x0f'
- authentication_tag = b'\x08\xb1\x9d!&\x98\xd0\xeaRq\x90\xe6;\xb5]\xd8'
-
- decrypted = bytes(aes_gcm_decrypt_and_verify(
- list(data), self.key, list(authentication_tag), self.iv[:12]))
- self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg[:16])
- if Cryptodome.AES:
- decrypted = aes_gcm_decrypt_and_verify_bytes(
- data, bytes(self.key), authentication_tag, bytes(self.iv[:12]))
- self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg[:16])
-
- def test_decrypt_text(self):
- password = bytes(self.key).decode()
- encrypted = base64.b64encode(
- bytes(self.iv[:8])
- + b'\x17\x15\x93\xab\x8d\x80V\xcdV\xe0\t\xcdo\xc2\xa5\xd8ksM\r\xe27N\xae',
- ).decode()
- decrypted = (aes_decrypt_text(encrypted, password, 16))
- self.assertEqual(decrypted, self.secret_msg)
-
- password = bytes(self.key).decode()
- encrypted = base64.b64encode(
- bytes(self.iv[:8])
- + b'\x0b\xe6\xa4\xd9z\x0e\xb8\xb9\xd0\xd4i_\x85\x1d\x99\x98_\xe5\x80\xe7.\xbf\xa5\x83',
- ).decode()
- decrypted = (aes_decrypt_text(encrypted, password, 32))
- self.assertEqual(decrypted, self.secret_msg)
-
- def test_ecb_encrypt(self):
- data = list(self.secret_msg)
- encrypted = bytes(aes_ecb_encrypt(data, self.key))
- self.assertEqual(
- encrypted,
- b'\xaa\x86]\x81\x97>\x02\x92\x9d\x1bR[[L/u\xd3&\xd1(h\xde{\x81\x94\xba\x02\xae\xbd\xa6\xd0:')
-
- def test_ecb_decrypt(self):
- data = list(b'\xaa\x86]\x81\x97>\x02\x92\x9d\x1bR[[L/u\xd3&\xd1(h\xde{\x81\x94\xba\x02\xae\xbd\xa6\xd0:')
- decrypted = bytes(aes_ecb_decrypt(data, self.key, self.iv))
- self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg)
-
- def test_key_expansion(self):
- key = '4f6bdaa39e2f8cb07f5e722d9edef314'
-
- self.assertEqual(key_expansion(list(bytearray.fromhex(key))), [
- 0x4F, 0x6B, 0xDA, 0xA3, 0x9E, 0x2F, 0x8C, 0xB0, 0x7F, 0x5E, 0x72, 0x2D, 0x9E, 0xDE, 0xF3, 0x14,
- 0x53, 0x66, 0x20, 0xA8, 0xCD, 0x49, 0xAC, 0x18, 0xB2, 0x17, 0xDE, 0x35, 0x2C, 0xC9, 0x2D, 0x21,
- 0x8C, 0xBE, 0xDD, 0xD9, 0x41, 0xF7, 0x71, 0xC1, 0xF3, 0xE0, 0xAF, 0xF4, 0xDF, 0x29, 0x82, 0xD5,
- 0x2D, 0xAD, 0xDE, 0x47, 0x6C, 0x5A, 0xAF, 0x86, 0x9F, 0xBA, 0x00, 0x72, 0x40, 0x93, 0x82, 0xA7,
- 0xF9, 0xBE, 0x82, 0x4E, 0x95, 0xE4, 0x2D, 0xC8, 0x0A, 0x5E, 0x2D, 0xBA, 0x4A, 0xCD, 0xAF, 0x1D,
- 0x54, 0xC7, 0x26, 0x98, 0xC1, 0x23, 0x0B, 0x50, 0xCB, 0x7D, 0x26, 0xEA, 0x81, 0xB0, 0x89, 0xF7,
- 0x93, 0x60, 0x4E, 0x94, 0x52, 0x43, 0x45, 0xC4, 0x99, 0x3E, 0x63, 0x2E, 0x18, 0x8E, 0xEA, 0xD9,
- 0xCA, 0xE7, 0x7B, 0x39, 0x98, 0xA4, 0x3E, 0xFD, 0x01, 0x9A, 0x5D, 0xD3, 0x19, 0x14, 0xB7, 0x0A,
- 0xB0, 0x4E, 0x1C, 0xED, 0x28, 0xEA, 0x22, 0x10, 0x29, 0x70, 0x7F, 0xC3, 0x30, 0x64, 0xC8, 0xC9,
- 0xE8, 0xA6, 0xC1, 0xE9, 0xC0, 0x4C, 0xE3, 0xF9, 0xE9, 0x3C, 0x9C, 0x3A, 0xD9, 0x58, 0x54, 0xF3,
- 0xB4, 0x86, 0xCC, 0xDC, 0x74, 0xCA, 0x2F, 0x25, 0x9D, 0xF6, 0xB3, 0x1F, 0x44, 0xAE, 0xE7, 0xEC])
-
- def test_pad_block(self):
- block = [0x21, 0xA0, 0x43, 0xFF]
-
- self.assertEqual(pad_block(block, 'pkcs7'),
- [*block, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C])
-
- self.assertEqual(pad_block(block, 'iso7816'),
- [*block, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
-
- self.assertEqual(pad_block(block, 'whitespace'),
- [*block, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20])
-
- self.assertEqual(pad_block(block, 'zero'),
- [*block, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
-
- block = list(range(16))
- for mode in ('pkcs7', 'iso7816', 'whitespace', 'zero'):
- self.assertEqual(pad_block(block, mode), block, mode)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_age_restriction.py b/test/test_age_restriction.py
deleted file mode 100644
index 68107590e..000000000
--- a/test/test_age_restriction.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-from test.helper import is_download_test, try_rm
-from yt_dlp import YoutubeDL
-from yt_dlp.utils import DownloadError
-
-
-def _download_restricted(url, filename, age):
- """ Returns true if the file has been downloaded """
-
- params = {
- 'age_limit': age,
- 'skip_download': True,
- 'writeinfojson': True,
- 'outtmpl': '%(id)s.%(ext)s',
- }
- ydl = YoutubeDL(params)
- ydl.add_default_info_extractors()
- json_filename = os.path.splitext(filename)[0] + '.info.json'
- try_rm(json_filename)
- try:
- ydl.download([url])
- except DownloadError:
- pass
- else:
- return os.path.exists(json_filename)
- finally:
- try_rm(json_filename)
-
-
-@is_download_test
-class TestAgeRestriction(unittest.TestCase):
- def _assert_restricted(self, url, filename, age, old_age=None):
- self.assertTrue(_download_restricted(url, filename, old_age))
- self.assertFalse(_download_restricted(url, filename, age))
-
- def test_youtube(self):
- self._assert_restricted('HtVdAasjOgU', 'HtVdAasjOgU.mp4', 10)
-
- def test_youporn(self):
- self._assert_restricted(
- 'https://www.youporn.com/watch/16715086/sex-ed-in-detention-18-asmr/',
- '16715086.mp4', 2, old_age=25)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_all_urls.py b/test/test_all_urls.py
deleted file mode 100644
index 848c96ff0..000000000
--- a/test/test_all_urls.py
+++ /dev/null
@@ -1,122 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import collections
-
-from test.helper import gettestcases
-from yt_dlp.extractor import FacebookIE, YoutubeIE, gen_extractors
-
-
-class TestAllURLsMatching(unittest.TestCase):
- def setUp(self):
- self.ies = gen_extractors()
-
- def matching_ies(self, url):
- return [ie.IE_NAME for ie in self.ies if ie.suitable(url) and ie.IE_NAME != 'generic']
-
- def assertMatch(self, url, ie_list):
- self.assertEqual(self.matching_ies(url), ie_list)
-
- def test_youtube_playlist_matching(self):
- assertPlaylist = lambda url: self.assertMatch(url, ['youtube:playlist'])
- assertTab = lambda url: self.assertMatch(url, ['youtube:tab'])
- assertPlaylist('ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8')
- assertPlaylist('UUBABnxM4Ar9ten8Mdjj1j0Q') # 585
- assertPlaylist('PL63F0C78739B09958')
- assertTab('https://www.youtube.com/AsapSCIENCE')
- assertTab('https://www.youtube.com/embedded')
- assertTab('https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q')
- assertTab('https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC')
- assertTab('https://www.youtube.com/watch?v=AV6J6_AeFEQ&playnext=1&list=PL4023E734DA416012') # 668
- self.assertFalse('youtube:playlist' in self.matching_ies('PLtS2H6bU1M'))
- # Top tracks
- assertTab('https://www.youtube.com/playlist?list=MCUS.20142101')
-
- def test_youtube_matching(self):
- self.assertTrue(YoutubeIE.suitable('PLtS2H6bU1M'))
- self.assertFalse(YoutubeIE.suitable('https://www.youtube.com/watch?v=AV6J6_AeFEQ&playnext=1&list=PL4023E734DA416012')) # 668
- self.assertMatch('http://youtu.be/BaW_jenozKc', ['youtube'])
- # self.assertMatch('http://www.youtube.com/v/BaW_jenozKc', ['youtube']) # /v/ is no longer valid
- self.assertMatch('https://youtube.googleapis.com/v/BaW_jenozKc', ['youtube'])
- self.assertMatch('http://www.cleanvideosearch.com/media/action/yt/watch?videoId=8v_4O44sfjM', ['youtube'])
-
- def test_youtube_channel_matching(self):
- assertChannel = lambda url: self.assertMatch(url, ['youtube:tab'])
- assertChannel('https://www.youtube.com/channel/HCtnHdj3df7iM')
- assertChannel('https://www.youtube.com/channel/HCtnHdj3df7iM?feature=gb_ch_rec')
- assertChannel('https://www.youtube.com/channel/HCtnHdj3df7iM/videos')
-
- def test_youtube_user_matching(self):
- self.assertMatch('http://www.youtube.com/NASAgovVideo/videos', ['youtube:tab'])
-
- def test_youtube_feeds(self):
- self.assertMatch('https://www.youtube.com/feed/library', ['youtube:tab'])
- self.assertMatch('https://www.youtube.com/feed/history', ['youtube:tab'])
- self.assertMatch('https://www.youtube.com/feed/watch_later', ['youtube:tab'])
- self.assertMatch('https://www.youtube.com/feed/subscriptions', ['youtube:tab'])
-
- def test_youtube_search_matching(self):
- self.assertMatch('http://www.youtube.com/results?search_query=making+mustard', ['youtube:search_url'])
- self.assertMatch('https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video', ['youtube:search_url'])
-
- def test_facebook_matching(self):
- self.assertTrue(FacebookIE.suitable('https://www.facebook.com/Shiniknoh#!/photo.php?v=10153317450565268'))
- self.assertTrue(FacebookIE.suitable('https://www.facebook.com/cindyweather?fref=ts#!/photo.php?v=10152183998945793'))
-
- def test_no_duplicates(self):
- ies = gen_extractors()
- for tc in gettestcases(include_onlymatching=True):
- url = tc['url']
- for ie in ies:
- if type(ie).__name__ in ('GenericIE', tc['name'] + 'IE'):
- self.assertTrue(ie.suitable(url), f'{type(ie).__name__} should match URL {url!r}')
- else:
- self.assertFalse(
- ie.suitable(url),
- f'{type(ie).__name__} should not match URL {url!r} . That URL belongs to {tc["name"]}.')
-
- def test_keywords(self):
- self.assertMatch(':ytsubs', ['youtube:subscriptions'])
- self.assertMatch(':ytsubscriptions', ['youtube:subscriptions'])
- self.assertMatch(':ythistory', ['youtube:history'])
-
- def test_vimeo_matching(self):
- self.assertMatch('https://vimeo.com/channels/tributes', ['vimeo:channel'])
- self.assertMatch('https://vimeo.com/channels/31259', ['vimeo:channel'])
- self.assertMatch('https://vimeo.com/channels/31259/53576664', ['vimeo'])
- self.assertMatch('https://vimeo.com/user7108434', ['vimeo:user'])
- self.assertMatch('https://vimeo.com/user7108434/videos', ['vimeo:user'])
- self.assertMatch('https://vimeo.com/user21297594/review/75524534/3c257a1b5d', ['vimeo:review'])
-
- # https://github.com/ytdl-org/youtube-dl/issues/1930
- def test_soundcloud_not_matching_sets(self):
- self.assertMatch('http://soundcloud.com/floex/sets/gone-ep', ['soundcloud:set'])
-
- def test_tumblr(self):
- self.assertMatch('http://tatianamaslanydaily.tumblr.com/post/54196191430/orphan-black-dvd-extra-behind-the-scenes', ['Tumblr'])
- self.assertMatch('http://tatianamaslanydaily.tumblr.com/post/54196191430', ['Tumblr'])
-
- def test_pbs(self):
- # https://github.com/ytdl-org/youtube-dl/issues/2350
- self.assertMatch('http://video.pbs.org/viralplayer/2365173446/', ['pbs'])
- self.assertMatch('http://video.pbs.org/widget/partnerplayer/980042464/', ['pbs'])
-
- def test_no_duplicated_ie_names(self):
- name_accu = collections.defaultdict(list)
- for ie in self.ies:
- name_accu[ie.IE_NAME.lower()].append(type(ie).__name__)
- for (ie_name, ie_list) in name_accu.items():
- self.assertEqual(
- len(ie_list), 1,
- f'Multiple extractors with the same IE_NAME "{ie_name}" ({", ".join(ie_list)})')
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_cache.py b/test/test_cache.py
deleted file mode 100644
index ce1624b68..000000000
--- a/test/test_cache.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import shutil
-
-from test.helper import FakeYDL
-from yt_dlp.cache import Cache
-
-
-def _is_empty(d):
- return not bool(os.listdir(d))
-
-
-def _mkdir(d):
- if not os.path.exists(d):
- os.mkdir(d)
-
-
-class TestCache(unittest.TestCase):
- def setUp(self):
- TEST_DIR = os.path.dirname(os.path.abspath(__file__))
- TESTDATA_DIR = os.path.join(TEST_DIR, 'testdata')
- _mkdir(TESTDATA_DIR)
- self.test_dir = os.path.join(TESTDATA_DIR, 'cache_test')
- self.tearDown()
-
- def tearDown(self):
- if os.path.exists(self.test_dir):
- shutil.rmtree(self.test_dir)
-
- def test_cache(self):
- ydl = FakeYDL({
- 'cachedir': self.test_dir,
- })
- c = Cache(ydl)
- obj = {'x': 1, 'y': ['ä', '\\a', True]}
- self.assertEqual(c.load('test_cache', 'k.'), None)
- c.store('test_cache', 'k.', obj)
- self.assertEqual(c.load('test_cache', 'k2'), None)
- self.assertFalse(_is_empty(self.test_dir))
- self.assertEqual(c.load('test_cache', 'k.'), obj)
- self.assertEqual(c.load('test_cache', 'y'), None)
- self.assertEqual(c.load('test_cache2', 'k.'), None)
- c.remove()
- self.assertFalse(os.path.exists(self.test_dir))
- self.assertEqual(c.load('test_cache', 'k.'), None)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_compat.py b/test/test_compat.py
deleted file mode 100644
index 6cc27d487..000000000
--- a/test/test_compat.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import datetime as dt
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import struct
-
-from yt_dlp import compat
-from yt_dlp.compat import urllib # isort: split
-from yt_dlp.compat import compat_etree_fromstring, compat_expanduser, compat_datetime_from_timestamp
-from yt_dlp.compat.urllib.request import getproxies
-
-
-class TestCompat(unittest.TestCase):
- def test_compat_passthrough(self):
- with self.assertWarns(DeprecationWarning):
- _ = compat.compat_basestring
-
- self.assertEqual(urllib.request.getproxies, getproxies)
-
- with self.assertWarns(DeprecationWarning):
- _ = compat.compat_pycrypto_AES # Must not raise error
-
- def test_compat_expanduser(self):
- old_home = os.environ.get('HOME')
- test_str = R'C:\Documents and Settings\тест\Application Data'
- try:
- os.environ['HOME'] = test_str
- self.assertEqual(compat_expanduser('~'), test_str)
- finally:
- os.environ['HOME'] = old_home or ''
-
- def test_compat_etree_fromstring(self):
- xml = '''
-
- foo
- 中文
- spam
-
- '''
- doc = compat_etree_fromstring(xml.encode())
- self.assertTrue(isinstance(doc.attrib['foo'], str))
- self.assertTrue(isinstance(doc.attrib['spam'], str))
- self.assertTrue(isinstance(doc.find('normal').text, str))
- self.assertTrue(isinstance(doc.find('chinese').text, str))
- self.assertTrue(isinstance(doc.find('foo/bar').text, str))
-
- def test_compat_etree_fromstring_doctype(self):
- xml = '''
-
- '''
- compat_etree_fromstring(xml)
-
- def test_struct_unpack(self):
- self.assertEqual(struct.unpack('!B', b'\x00'), (0,))
-
- def test_compat_datetime_from_timestamp(self):
- self.assertEqual(
- compat_datetime_from_timestamp(0),
- dt.datetime(1970, 1, 1, 0, 0, 0, tzinfo=dt.timezone.utc))
- self.assertEqual(
- compat_datetime_from_timestamp(1),
- dt.datetime(1970, 1, 1, 0, 0, 1, tzinfo=dt.timezone.utc))
- self.assertEqual(
- compat_datetime_from_timestamp(3600),
- dt.datetime(1970, 1, 1, 1, 0, 0, tzinfo=dt.timezone.utc))
-
- self.assertEqual(
- compat_datetime_from_timestamp(-1),
- dt.datetime(1969, 12, 31, 23, 59, 59, tzinfo=dt.timezone.utc))
- self.assertEqual(
- compat_datetime_from_timestamp(-86400),
- dt.datetime(1969, 12, 31, 0, 0, 0, tzinfo=dt.timezone.utc))
-
- self.assertEqual(
- compat_datetime_from_timestamp(0.5),
- dt.datetime(1970, 1, 1, 0, 0, 0, 500000, tzinfo=dt.timezone.utc))
- self.assertEqual(
- compat_datetime_from_timestamp(1.000001),
- dt.datetime(1970, 1, 1, 0, 0, 1, 1, tzinfo=dt.timezone.utc))
- self.assertEqual(
- compat_datetime_from_timestamp(-1.25),
- dt.datetime(1969, 12, 31, 23, 59, 58, 750000, tzinfo=dt.timezone.utc))
-
- self.assertEqual(
- compat_datetime_from_timestamp(-1577923200),
- dt.datetime(1920, 1, 1, 0, 0, 0, tzinfo=dt.timezone.utc))
- self.assertEqual(
- compat_datetime_from_timestamp(4102444800),
- dt.datetime(2100, 1, 1, 0, 0, 0, tzinfo=dt.timezone.utc))
-
- self.assertEqual(
- compat_datetime_from_timestamp(173568960000),
- dt.datetime(7470, 3, 8, 0, 0, 0, tzinfo=dt.timezone.utc))
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_config.py b/test/test_config.py
deleted file mode 100644
index 238ca66d0..000000000
--- a/test/test_config.py
+++ /dev/null
@@ -1,227 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-import unittest.mock
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-import contextlib
-import itertools
-from pathlib import Path
-
-from yt_dlp.compat import compat_expanduser
-from yt_dlp.options import create_parser, parseOpts
-from yt_dlp.utils import Config, get_executable_path
-
-ENVIRON_DEFAULTS = {
- 'HOME': None,
- 'XDG_CONFIG_HOME': '/_xdg_config_home/',
- 'USERPROFILE': 'C:/Users/testing/',
- 'APPDATA': 'C:/Users/testing/AppData/Roaming/',
- 'HOMEDRIVE': 'C:/',
- 'HOMEPATH': 'Users/testing/',
-}
-
-
-@contextlib.contextmanager
-def set_environ(**kwargs):
- saved_environ = os.environ.copy()
-
- for name, value in {**ENVIRON_DEFAULTS, **kwargs}.items():
- if value is None:
- os.environ.pop(name, None)
- else:
- os.environ[name] = value
-
- yield
-
- os.environ.clear()
- os.environ.update(saved_environ)
-
-
-def _generate_expected_groups():
- xdg_config_home = os.getenv('XDG_CONFIG_HOME') or compat_expanduser('~/.config')
- appdata_dir = os.getenv('appdata')
- home_dir = compat_expanduser('~')
- return {
- 'Portable': [
- Path(get_executable_path(), 'yt-dlp.conf'),
- ],
- 'Home': [
- Path('yt-dlp.conf'),
- ],
- 'User': [
- Path(xdg_config_home, 'yt-dlp.conf'),
- Path(xdg_config_home, 'yt-dlp', 'config'),
- Path(xdg_config_home, 'yt-dlp', 'config.txt'),
- *((
- Path(appdata_dir, 'yt-dlp.conf'),
- Path(appdata_dir, 'yt-dlp', 'config'),
- Path(appdata_dir, 'yt-dlp', 'config.txt'),
- ) if appdata_dir else ()),
- Path(home_dir, 'yt-dlp.conf'),
- Path(home_dir, 'yt-dlp.conf.txt'),
- Path(home_dir, '.yt-dlp', 'config'),
- Path(home_dir, '.yt-dlp', 'config.txt'),
- ],
- 'System': [
- Path('/etc/yt-dlp.conf'),
- Path('/etc/yt-dlp/config'),
- Path('/etc/yt-dlp/config.txt'),
- ],
- }
-
-
-class TestConfig(unittest.TestCase):
- maxDiff = None
-
- @set_environ()
- def test_config__ENVIRON_DEFAULTS_sanity(self):
- expected = make_expected()
- self.assertCountEqual(
- set(expected), expected,
- 'ENVIRON_DEFAULTS produces non unique names')
-
- def test_config_all_environ_values(self):
- for name, value in ENVIRON_DEFAULTS.items():
- for new_value in (None, '', '.', value or '/some/dir'):
- with set_environ(**{name: new_value}):
- self._simple_grouping_test()
-
- def test_config_default_expected_locations(self):
- files, _ = self._simple_config_test()
- self.assertEqual(
- files, make_expected(),
- 'Not all expected locations have been checked')
-
- def test_config_default_grouping(self):
- self._simple_grouping_test()
-
- def _simple_grouping_test(self):
- expected_groups = make_expected_groups()
- for name, group in expected_groups.items():
- for index, existing_path in enumerate(group):
- result, opts = self._simple_config_test(existing_path)
- expected = expected_from_expected_groups(expected_groups, existing_path)
- self.assertEqual(
- result, expected,
- f'The checked locations do not match the expected ({name}, {index})')
- self.assertEqual(
- opts.outtmpl['default'], '1',
- f'The used result value was incorrect ({name}, {index})')
-
- def _simple_config_test(self, *stop_paths):
- encountered = 0
- paths = []
-
- def read_file(filename, default=[]):
- nonlocal encountered
- path = Path(filename)
- paths.append(path)
- if path in stop_paths:
- encountered += 1
- return ['-o', f'{encountered}']
-
- with ConfigMock(read_file):
- _, opts, _ = parseOpts([], False)
-
- return paths, opts
-
- @set_environ()
- def test_config_early_exit_commandline(self):
- self._early_exit_test(0, '--ignore-config')
-
- @set_environ()
- def test_config_early_exit_files(self):
- for index, _ in enumerate(make_expected(), 1):
- self._early_exit_test(index)
-
- def _early_exit_test(self, allowed_reads, *args):
- reads = 0
-
- def read_file(filename, default=[]):
- nonlocal reads
- reads += 1
-
- if reads > allowed_reads:
- self.fail('The remaining config was not ignored')
- elif reads == allowed_reads:
- return ['--ignore-config']
-
- with ConfigMock(read_file):
- parseOpts(args, False)
-
- @set_environ()
- def test_config_override_commandline(self):
- self._override_test(0, '-o', 'pass')
-
- @set_environ()
- def test_config_override_files(self):
- for index, _ in enumerate(make_expected(), 1):
- self._override_test(index)
-
- def _override_test(self, start_index, *args):
- index = 0
-
- def read_file(filename, default=[]):
- nonlocal index
- index += 1
-
- if index > start_index:
- return ['-o', 'fail']
- elif index == start_index:
- return ['-o', 'pass']
-
- with ConfigMock(read_file):
- _, opts, _ = parseOpts(args, False)
-
- self.assertEqual(
- opts.outtmpl['default'], 'pass',
- 'The earlier group did not override the later ones')
-
-
-@contextlib.contextmanager
-def ConfigMock(read_file=None):
- with unittest.mock.patch('yt_dlp.options.Config') as mock:
- mock.return_value = Config(create_parser())
- if read_file is not None:
- mock.read_file = read_file
-
- yield mock
-
-
-def make_expected(*filepaths):
- return expected_from_expected_groups(_generate_expected_groups(), *filepaths)
-
-
-def make_expected_groups(*filepaths):
- return _filter_expected_groups(_generate_expected_groups(), filepaths)
-
-
-def expected_from_expected_groups(expected_groups, *filepaths):
- return list(itertools.chain.from_iterable(
- _filter_expected_groups(expected_groups, filepaths).values()))
-
-
-def _filter_expected_groups(expected, filepaths):
- if not filepaths:
- return expected
-
- result = {}
- for group, paths in expected.items():
- new_paths = []
- for path in paths:
- new_paths.append(path)
- if path in filepaths:
- break
-
- result[group] = new_paths
-
- return result
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_cookies.py b/test/test_cookies.py
deleted file mode 100644
index f64a1535c..000000000
--- a/test/test_cookies.py
+++ /dev/null
@@ -1,357 +0,0 @@
-import datetime as dt
-import unittest
-
-from yt_dlp import cookies
-from yt_dlp.cookies import (
- LenientSimpleCookie,
- LinuxChromeCookieDecryptor,
- MacChromeCookieDecryptor,
- WindowsChromeCookieDecryptor,
- _get_linux_desktop_environment,
- _LinuxDesktopEnvironment,
- parse_safari_cookies,
- pbkdf2_sha1,
-)
-
-
-class Logger:
- def debug(self, message, *args, **kwargs):
- print(f'[verbose] {message}')
-
- def info(self, message, *args, **kwargs):
- print(message)
-
- def warning(self, message, *args, **kwargs):
- self.error(message)
-
- def error(self, message, *args, **kwargs):
- raise Exception(message)
-
-
-class MonkeyPatch:
- def __init__(self, module, temporary_values):
- self._module = module
- self._temporary_values = temporary_values
- self._backup_values = {}
-
- def __enter__(self):
- for name, temp_value in self._temporary_values.items():
- self._backup_values[name] = getattr(self._module, name)
- setattr(self._module, name, temp_value)
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- for name, backup_value in self._backup_values.items():
- setattr(self._module, name, backup_value)
-
-
-class TestCookies(unittest.TestCase):
- def test_get_desktop_environment(self):
- """ based on https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util_unittest.cc """
- test_cases = [
- ({}, _LinuxDesktopEnvironment.OTHER),
- ({'DESKTOP_SESSION': 'my_custom_de'}, _LinuxDesktopEnvironment.OTHER),
- ({'XDG_CURRENT_DESKTOP': 'my_custom_de'}, _LinuxDesktopEnvironment.OTHER),
-
- ({'DESKTOP_SESSION': 'gnome'}, _LinuxDesktopEnvironment.GNOME),
- ({'DESKTOP_SESSION': 'mate'}, _LinuxDesktopEnvironment.GNOME),
- ({'DESKTOP_SESSION': 'kde4'}, _LinuxDesktopEnvironment.KDE4),
- ({'DESKTOP_SESSION': 'kde'}, _LinuxDesktopEnvironment.KDE3),
- ({'DESKTOP_SESSION': 'xfce'}, _LinuxDesktopEnvironment.XFCE),
-
- ({'XDG_CURRENT_DESKTOP': 'my_custom_de', 'DESKTOP_SESSION': 'gnome'}, _LinuxDesktopEnvironment.GNOME),
- ({'XDG_CURRENT_DESKTOP': 'my_custom_de', 'DESKTOP_SESSION': 'mate'}, _LinuxDesktopEnvironment.GNOME),
- ({'XDG_CURRENT_DESKTOP': 'my_custom_de', 'DESKTOP_SESSION': 'kde4'}, _LinuxDesktopEnvironment.KDE4),
- ({'XDG_CURRENT_DESKTOP': 'my_custom_de', 'DESKTOP_SESSION': 'kde'}, _LinuxDesktopEnvironment.KDE3),
- ({'XDG_CURRENT_DESKTOP': 'my_custom_de', 'DESKTOP_SESSION': 'xfce'}, _LinuxDesktopEnvironment.XFCE),
-
- ({'XDG_CURRENT_DESKTOP': 'my_custom_de', 'DESKTOP_SESSION': 'my_custom_de', 'GNOME_DESKTOP_SESSION_ID': 1}, _LinuxDesktopEnvironment.GNOME),
-
- ({'GNOME_DESKTOP_SESSION_ID': 1}, _LinuxDesktopEnvironment.GNOME),
- ({'KDE_FULL_SESSION': 1}, _LinuxDesktopEnvironment.KDE3),
- ({'KDE_FULL_SESSION': 1, 'DESKTOP_SESSION': 'kde4'}, _LinuxDesktopEnvironment.KDE4),
-
- ({'XDG_CURRENT_DESKTOP': 'X-Cinnamon'}, _LinuxDesktopEnvironment.CINNAMON),
- ({'XDG_CURRENT_DESKTOP': 'Deepin'}, _LinuxDesktopEnvironment.DEEPIN),
- ({'XDG_CURRENT_DESKTOP': 'GNOME'}, _LinuxDesktopEnvironment.GNOME),
- ({'XDG_CURRENT_DESKTOP': 'GNOME:GNOME-Classic'}, _LinuxDesktopEnvironment.GNOME),
- ({'XDG_CURRENT_DESKTOP': 'GNOME : GNOME-Classic'}, _LinuxDesktopEnvironment.GNOME),
- ({'XDG_CURRENT_DESKTOP': 'ubuntu:GNOME'}, _LinuxDesktopEnvironment.GNOME),
-
- ({'XDG_CURRENT_DESKTOP': 'Unity', 'DESKTOP_SESSION': 'gnome-fallback'}, _LinuxDesktopEnvironment.GNOME),
- ({'XDG_CURRENT_DESKTOP': 'KDE', 'KDE_SESSION_VERSION': '5'}, _LinuxDesktopEnvironment.KDE5),
- ({'XDG_CURRENT_DESKTOP': 'KDE', 'KDE_SESSION_VERSION': '6'}, _LinuxDesktopEnvironment.KDE6),
- ({'XDG_CURRENT_DESKTOP': 'KDE'}, _LinuxDesktopEnvironment.KDE4),
- ({'XDG_CURRENT_DESKTOP': 'Pantheon'}, _LinuxDesktopEnvironment.PANTHEON),
- ({'XDG_CURRENT_DESKTOP': 'UKUI'}, _LinuxDesktopEnvironment.UKUI),
- ({'XDG_CURRENT_DESKTOP': 'Unity'}, _LinuxDesktopEnvironment.UNITY),
- ({'XDG_CURRENT_DESKTOP': 'Unity:Unity7'}, _LinuxDesktopEnvironment.UNITY),
- ({'XDG_CURRENT_DESKTOP': 'Unity:Unity8'}, _LinuxDesktopEnvironment.UNITY),
- ]
-
- for env, expected_desktop_environment in test_cases:
- self.assertEqual(_get_linux_desktop_environment(env, Logger()), expected_desktop_environment)
-
- def test_chrome_cookie_decryptor_linux_derive_key(self):
- key = LinuxChromeCookieDecryptor.derive_key(b'abc')
- self.assertEqual(key, b'7\xa1\xec\xd4m\xfcA\xc7\xb19Z\xd0\x19\xdcM\x17')
-
- def test_chrome_cookie_decryptor_mac_derive_key(self):
- key = MacChromeCookieDecryptor.derive_key(b'abc')
- self.assertEqual(key, b'Y\xe2\xc0\xd0P\xf6\xf4\xe1l\xc1\x8cQ\xcb|\xcdY')
-
- def test_chrome_cookie_decryptor_linux_v10(self):
- with MonkeyPatch(cookies, {'_get_linux_keyring_password': lambda *args, **kwargs: b''}):
- encrypted_value = b'v10\xccW%\xcd\xe6\xe6\x9fM" \xa7\xb0\xca\xe4\x07\xd6'
- value = 'USD'
- decryptor = LinuxChromeCookieDecryptor('Chrome', Logger())
- self.assertEqual(decryptor.decrypt(encrypted_value), value)
-
- def test_chrome_cookie_decryptor_linux_v11(self):
- with MonkeyPatch(cookies, {'_get_linux_keyring_password': lambda *args, **kwargs: b''}):
- encrypted_value = b'v11#\x81\x10>`w\x8f)\xc0\xb2\xc1\r\xf4\x1al\xdd\x93\xfd\xf8\xf8N\xf2\xa9\x83\xf1\xe9o\x0elVQd'
- value = 'tz=Europe.London'
- decryptor = LinuxChromeCookieDecryptor('Chrome', Logger())
- self.assertEqual(decryptor.decrypt(encrypted_value), value)
-
- def test_chrome_cookie_decryptor_linux_v10_meta24(self):
- with MonkeyPatch(cookies, {'_get_linux_keyring_password': lambda *args, **kwargs: b''}):
- encrypted_value = b'v10\x1f\xe4\x0e[\x83\x0c\xcc*kPi \xce\x8d\x1d\xbb\x80\r\x11\t\xbb\x9e^Hy\x94\xf4\x963\x9f\x82\xba\xfe\xa1\xed\xb9\xf1)\x00710\x92\xc8/<\x96B'
- value = 'DE'
- decryptor = LinuxChromeCookieDecryptor('Chrome', Logger(), meta_version=24)
- self.assertEqual(decryptor.decrypt(encrypted_value), value)
-
- def test_chrome_cookie_decryptor_windows_v10(self):
- with MonkeyPatch(cookies, {
- '_get_windows_v10_key': lambda *args, **kwargs: b'Y\xef\xad\xad\xeerp\xf0Y\xe6\x9b\x12\xc2\xc3A\x00\x00\x80\xc3\x07:\xc3A'
- b'localhost\x00foo\x00/\x00test%20%3Bcookie\x00\x00\x00\x054\x07\x17 \x05\x00\x00\x00Kbplist00\xd1\x01'
- b'\x02_\x10\x18NSHTTPCookieAcceptPolicy\x10\x02\x08\x0b&\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00'
- b'\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00(')
-
- jar = parse_safari_cookies(cookies)
- self.assertEqual(len(jar), 1)
- cookie = next(iter(jar))
- self.assertEqual(cookie.domain, 'localhost')
- self.assertEqual(cookie.port, None)
- self.assertEqual(cookie.path, '/')
- self.assertEqual(cookie.name, 'foo')
- self.assertEqual(cookie.value, 'test%20%3Bcookie')
- self.assertFalse(cookie.secure)
- expected_expiration = dt.datetime(2021, 6, 18, 21, 39, 19, tzinfo=dt.timezone.utc)
- self.assertEqual(cookie.expires, int(expected_expiration.timestamp()))
-
- def test_pbkdf2_sha1(self):
- key = pbkdf2_sha1(b'peanuts', b' ' * 16, 1, 16)
- self.assertEqual(key, b'g\xe1\x8e\x0fQ\x1c\x9b\xf3\xc9`!\xaa\x90\xd9\xd34')
-
-
-class TestLenientSimpleCookie(unittest.TestCase):
- def _run_tests(self, *cases):
- for message, raw_cookie, expected in cases:
- cookie = LenientSimpleCookie(raw_cookie)
-
- with self.subTest(message, expected=expected):
- self.assertEqual(cookie.keys(), expected.keys(), message)
-
- for key, expected_value in expected.items():
- morsel = cookie[key]
- if isinstance(expected_value, tuple):
- expected_value, expected_attributes = expected_value
- else:
- expected_attributes = {}
-
- attributes = {
- key: value
- for key, value in dict(morsel).items()
- if value != ''
- }
- self.assertEqual(attributes, expected_attributes, message)
-
- self.assertEqual(morsel.value, expected_value, message)
-
- def test_parsing(self):
- self._run_tests(
- # Copied from https://github.com/python/cpython/blob/v3.10.7/Lib/test/test_http_cookies.py
- (
- 'Test basic cookie',
- 'chips=ahoy; vienna=finger',
- {'chips': 'ahoy', 'vienna': 'finger'},
- ),
- (
- 'Test quoted cookie',
- 'keebler="E=mc2; L=\\"Loves\\"; fudge=;"',
- {'keebler': 'E=mc2; L="Loves"; fudge=;'},
- ),
- (
- "Allow '=' in an unquoted value",
- 'keebler=E=mc2',
- {'keebler': 'E=mc2'},
- ),
- (
- "Allow cookies with ':' in their name",
- 'key:term=value:term',
- {'key:term': 'value:term'},
- ),
- (
- "Allow '[' and ']' in cookie values",
- 'a=b; c=[; d=r; f=h',
- {'a': 'b', 'c': '[', 'd': 'r', 'f': 'h'},
- ),
- (
- 'Test basic cookie attributes',
- 'Customer="WILE_E_COYOTE"; Version=1; Path=/acme',
- {'Customer': ('WILE_E_COYOTE', {'version': '1', 'path': '/acme'})},
- ),
- (
- 'Test flag only cookie attributes',
- 'Customer="WILE_E_COYOTE"; HttpOnly; Secure',
- {'Customer': ('WILE_E_COYOTE', {'httponly': True, 'secure': True})},
- ),
- (
- 'Test flag only attribute with values',
- 'eggs=scrambled; httponly=foo; secure=bar; Path=/bacon',
- {'eggs': ('scrambled', {'httponly': 'foo', 'secure': 'bar', 'path': '/bacon'})},
- ),
- (
- "Test special case for 'expires' attribute, 4 digit year",
- 'Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT',
- {'Customer': ('W', {'expires': 'Wed, 01 Jan 2010 00:00:00 GMT'})},
- ),
- (
- "Test special case for 'expires' attribute, 2 digit year",
- 'Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT',
- {'Customer': ('W', {'expires': 'Wed, 01 Jan 98 00:00:00 GMT'})},
- ),
- (
- 'Test extra spaces in keys and values',
- 'eggs = scrambled ; secure ; path = bar ; foo=foo ',
- {'eggs': ('scrambled', {'secure': True, 'path': 'bar'}), 'foo': 'foo'},
- ),
- (
- 'Test quoted attributes',
- 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"',
- {'Customer': ('WILE_E_COYOTE', {'version': '1', 'path': '/acme'})},
- ),
- # Our own tests that CPython passes
- (
- "Allow ';' in quoted value",
- 'chips="a;hoy"; vienna=finger',
- {'chips': 'a;hoy', 'vienna': 'finger'},
- ),
- (
- 'Keep only the last set value',
- 'a=c; a=b',
- {'a': 'b'},
- ),
- )
-
- def test_lenient_parsing(self):
- self._run_tests(
- (
- 'Ignore and try to skip invalid cookies',
- 'chips={"ahoy;": 1}; vienna="finger;"',
- {'vienna': 'finger;'},
- ),
- (
- 'Ignore cookies without a name',
- 'a=b; unnamed; c=d',
- {'a': 'b', 'c': 'd'},
- ),
- (
- "Ignore '\"' cookie without name",
- 'a=b; "; c=d',
- {'a': 'b', 'c': 'd'},
- ),
- (
- 'Skip all space separated values',
- 'x a=b c=d x; e=f',
- {'a': 'b', 'c': 'd', 'e': 'f'},
- ),
- (
- 'Skip all space separated values',
- 'x a=b; data={"complex": "json", "with": "key=value"}; x c=d x',
- {'a': 'b', 'c': 'd'},
- ),
- (
- 'Expect quote mending',
- 'a=b; invalid="; c=d',
- {'a': 'b', 'c': 'd'},
- ),
- (
- 'Reset morsel after invalid to not capture attributes',
- 'a=b; invalid; Version=1; c=d',
- {'a': 'b', 'c': 'd'},
- ),
- (
- 'Reset morsel after invalid to not capture attributes',
- 'a=b; $invalid; $Version=1; c=d',
- {'a': 'b', 'c': 'd'},
- ),
- (
- 'Continue after non-flag attribute without value',
- 'a=b; path; Version=1; c=d',
- {'a': 'b', 'c': 'd'},
- ),
- (
- 'Allow cookie attributes with `$` prefix',
- 'Customer="WILE_E_COYOTE"; $Version=1; $Secure; $Path=/acme',
- {'Customer': ('WILE_E_COYOTE', {'version': '1', 'secure': True, 'path': '/acme'})},
- ),
- (
- 'Invalid Morsel keys should not result in an error',
- 'Key=Value; [Invalid]=Value; Another=Value',
- {'Key': 'Value', 'Another': 'Value'},
- ),
- # Ref: https://github.com/python/cpython/issues/143919
- (
- 'Test invalid cookie name w/ control character',
- 'foo\012=bar;',
- {},
- ),
- (
- 'Test invalid cookie name w/ control character 2',
- 'foo\015baz=bar',
- {},
- ),
- (
- 'Test invalid cookie name w/ control character followed by valid cookie',
- 'foo\015=bar; x=y;',
- {'x': 'y'},
- ),
- (
- 'Test invalid cookie value w/ control character',
- 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
- {},
- ),
- (
- 'Test invalid quoted attribute value w/ control character',
- 'Customer="WILE_E_COYOTE"; Version="1\\012"; Path="/acme"',
- {},
- ),
- )
diff --git a/test/test_devalue.py b/test/test_devalue.py
deleted file mode 100644
index a9fdf8c91..000000000
--- a/test/test_devalue.py
+++ /dev/null
@@ -1,239 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import datetime as dt
-import json
-import math
-import re
-import unittest
-
-from yt_dlp.utils.jslib import devalue
-
-
-TEST_CASES_EQUALS = [{
- 'name': 'int',
- 'unparsed': [-42],
- 'parsed': -42,
-}, {
- 'name': 'str',
- 'unparsed': ['woo!!!'],
- 'parsed': 'woo!!!',
-}, {
- 'name': 'Number',
- 'unparsed': [['Object', 42]],
- 'parsed': 42,
-}, {
- 'name': 'String',
- 'unparsed': [['Object', 'yar']],
- 'parsed': 'yar',
-}, {
- 'name': 'Infinity',
- 'unparsed': -4,
- 'parsed': math.inf,
-}, {
- 'name': 'negative Infinity',
- 'unparsed': -5,
- 'parsed': -math.inf,
-}, {
- 'name': 'negative zero',
- 'unparsed': -6,
- 'parsed': -0.0,
-}, {
- 'name': 'RegExp',
- 'unparsed': [['RegExp', 'regexp', 'gim']], # XXX: flags are ignored
- 'parsed': re.compile('regexp'),
-}, {
- 'name': 'Date',
- 'unparsed': [['Date', '2001-09-09T01:46:40.000Z']],
- 'parsed': dt.datetime.fromtimestamp(1e9, tz=dt.timezone.utc),
-}, {
- 'name': 'Array',
- 'unparsed': [[1, 2, 3], 'a', 'b', 'c'],
- 'parsed': ['a', 'b', 'c'],
-}, {
- 'name': 'Array (empty)',
- 'unparsed': [[]],
- 'parsed': [],
-}, {
- 'name': 'Array (sparse)',
- 'unparsed': [[-2, 1, -2], 'b'],
- 'parsed': [None, 'b', None],
-}, {
- 'name': 'Object',
- 'unparsed': [{'foo': 1, 'x-y': 2}, 'bar', 'z'],
- 'parsed': {'foo': 'bar', 'x-y': 'z'},
-}, {
- 'name': 'Set',
- 'unparsed': [['Set', 1, 2, 3], 1, 2, 3],
- 'parsed': [1, 2, 3],
-}, {
- 'name': 'Map',
- 'unparsed': [['Map', 1, 2], 'a', 'b'],
- 'parsed': [['a', 'b']],
-}, {
- 'name': 'BigInt',
- 'unparsed': [['BigInt', '1']],
- 'parsed': 1,
-}, {
- 'name': 'Uint8Array',
- 'unparsed': [['Uint8Array', 'AQID']],
- 'parsed': [1, 2, 3],
-}, {
- 'name': 'ArrayBuffer',
- 'unparsed': [['ArrayBuffer', 'AQID']],
- 'parsed': [1, 2, 3],
-}, {
- 'name': 'str (repetition)',
- 'unparsed': [[1, 1], 'a string'],
- 'parsed': ['a string', 'a string'],
-}, {
- 'name': 'None (repetition)',
- 'unparsed': [[1, 1], None],
- 'parsed': [None, None],
-}, {
- 'name': 'dict (repetition)',
- 'unparsed': [[1, 1], {}],
- 'parsed': [{}, {}],
-}, {
- 'name': 'Object without prototype',
- 'unparsed': [['null']],
- 'parsed': {},
-}, {
- 'name': 'cross-realm POJO',
- 'unparsed': [{}],
- 'parsed': {},
-}]
-
-TEST_CASES_IS = [{
- 'name': 'bool',
- 'unparsed': [True],
- 'parsed': True,
-}, {
- 'name': 'Boolean',
- 'unparsed': [['Object', False]],
- 'parsed': False,
-}, {
- 'name': 'undefined',
- 'unparsed': -1,
- 'parsed': None,
-}, {
- 'name': 'null',
- 'unparsed': [None],
- 'parsed': None,
-}, {
- 'name': 'NaN',
- 'unparsed': -3,
- 'parsed': math.nan,
-}]
-
-TEST_CASES_INVALID = [{
- 'name': 'empty string',
- 'unparsed': '',
- 'error': ValueError,
- 'pattern': r'expected int or list as input',
-}, {
- 'name': 'hole',
- 'unparsed': -2,
- 'error': ValueError,
- 'pattern': r'invalid integer input',
-}, {
- 'name': 'string',
- 'unparsed': 'hello',
- 'error': ValueError,
- 'pattern': r'expected int or list as input',
-}, {
- 'name': 'number',
- 'unparsed': 42,
- 'error': ValueError,
- 'pattern': r'invalid integer input',
-}, {
- 'name': 'boolean',
- 'unparsed': True,
- 'error': ValueError,
- 'pattern': r'expected int or list as input',
-}, {
- 'name': 'null',
- 'unparsed': None,
- 'error': ValueError,
- 'pattern': r'expected int or list as input',
-}, {
- 'name': 'object',
- 'unparsed': {},
- 'error': ValueError,
- 'pattern': r'expected int or list as input',
-}, {
- 'name': 'empty array',
- 'unparsed': [],
- 'error': ValueError,
- 'pattern': r'expected a non-empty list as input',
-}, {
- 'name': 'Python negative indexing',
- 'unparsed': [[1, 2, 3, 4, 5, 6, 7, -7], 1, 2, 3, 4, 5, 6, 7],
- 'error': IndexError,
- 'pattern': r'invalid index: -7',
-}]
-
-
-class TestDevalue(unittest.TestCase):
- def test_devalue_parse_equals(self):
- for tc in TEST_CASES_EQUALS:
- self.assertEqual(devalue.parse(tc['unparsed']), tc['parsed'], tc['name'])
-
- def test_devalue_parse_is(self):
- for tc in TEST_CASES_IS:
- self.assertIs(devalue.parse(tc['unparsed']), tc['parsed'], tc['name'])
-
- def test_devalue_parse_invalid(self):
- for tc in TEST_CASES_INVALID:
- with self.assertRaisesRegex(tc['error'], tc['pattern'], msg=tc['name']):
- devalue.parse(tc['unparsed'])
-
- def test_devalue_parse_cyclical(self):
- name = 'Map (cyclical)'
- result = devalue.parse([['Map', 1, 0], 'self'])
- self.assertEqual(result[0][0], 'self', name)
- self.assertIs(result, result[0][1], name)
-
- name = 'Set (cyclical)'
- result = devalue.parse([['Set', 0, 1], 42])
- self.assertEqual(result[1], 42, name)
- self.assertIs(result, result[0], name)
-
- result = devalue.parse([[0]])
- self.assertIs(result, result[0], 'Array (cyclical)')
-
- name = 'Object (cyclical)'
- result = devalue.parse([{'self': 0}])
- self.assertIs(result, result['self'], name)
-
- name = 'Object with null prototype (cyclical)'
- result = devalue.parse([['null', 'self', 0]])
- self.assertIs(result, result['self'], name)
-
- name = 'Objects (cyclical)'
- result = devalue.parse([[1, 2], {'second': 2}, {'first': 1}])
- self.assertIs(result[0], result[1]['first'], name)
- self.assertIs(result[1], result[0]['second'], name)
-
- def test_devalue_parse_revivers(self):
- self.assertEqual(
- devalue.parse([['indirect', 1], {'a': 2}, 'b'], revivers={'indirect': lambda x: x}),
- {'a': 'b'}, 'revivers (indirect)')
-
- self.assertEqual(
- devalue.parse([['parse', 1], '{"a":0}'], revivers={'parse': json.loads}),
- {'a': 0}, 'revivers (parse)')
-
- self.assertEqual(
- devalue.parse([{'a': 1, 'b': 3}, ['EmptyRef', 2], 'false', ['EmptyRef', 2]], revivers={'EmptyRef': json.loads}),
- {'a': False, 'b': False}, msg='revivers (duplicate EmptyRef)')
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_download.py b/test/test_download.py
deleted file mode 100755
index 1714cb52e..000000000
--- a/test/test_download.py
+++ /dev/null
@@ -1,309 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import collections
-import hashlib
-import json
-
-from test.helper import (
- assertGreaterEqual,
- assertLessEqual,
- expect_info_dict,
- expect_warnings,
- get_params,
- gettestcases,
- getwebpagetestcases,
- is_download_test,
- try_rm,
-)
-
-import yt_dlp.YoutubeDL # isort: split
-from yt_dlp.extractor import get_info_extractor
-from yt_dlp.networking.exceptions import HTTPError, TransportError
-from yt_dlp.utils import (
- DownloadError,
- ExtractorError,
- UnavailableVideoError,
- YoutubeDLError,
- format_bytes,
- join_nonempty,
-)
-
-RETRIES = 3
-
-
-class YoutubeDL(yt_dlp.YoutubeDL):
- def __init__(self, *args, **kwargs):
- self.to_stderr = self.to_screen
- self.processed_info_dicts = []
- super().__init__(*args, **kwargs)
-
- def report_warning(self, message, *args, **kwargs):
- # Don't accept warnings during tests
- raise ExtractorError(message)
-
- def process_info(self, info_dict):
- self.processed_info_dicts.append(info_dict.copy())
- return super().process_info(info_dict)
-
-
-def _file_md5(fn):
- with open(fn, 'rb') as f:
- return hashlib.md5(f.read()).hexdigest()
-
-
-normal_test_cases = gettestcases()
-webpage_test_cases = getwebpagetestcases()
-tests_counter = collections.defaultdict(collections.Counter)
-
-
-@is_download_test
-class TestDownload(unittest.TestCase):
- maxDiff = None
-
- COMPLETED_TESTS = {}
-
- def __str__(self):
- """Identify each test with the `add_ie` attribute, if available."""
- cls, add_ie = type(self), getattr(self, self._testMethodName).add_ie
- return f'{self._testMethodName} ({cls.__module__}.{cls.__name__}){f" [{add_ie}]" if add_ie else ""}:'
-
-
-# Dynamically generate tests
-
-def generator(test_case, tname):
- def test_template(self):
- if self.COMPLETED_TESTS.get(tname):
- return
- self.COMPLETED_TESTS[tname] = True
- ie = yt_dlp.extractor.get_info_extractor(test_case['name'])()
- other_ies = [get_info_extractor(ie_key)() for ie_key in test_case.get('add_ie', [])]
- is_playlist = any(k.startswith('playlist') for k in test_case)
- test_cases = test_case.get(
- 'playlist', [] if is_playlist else [test_case])
-
- def print_skipping(reason):
- print('Skipping {}: {}'.format(test_case['name'], reason))
- self.skipTest(reason)
-
- if not ie.working():
- print_skipping('IE marked as not _WORKING')
-
- for tc in test_cases:
- if tc.get('expected_exception'):
- continue
- info_dict = tc.get('info_dict', {})
- params = tc.get('params', {})
- if not info_dict.get('id'):
- raise Exception(f'Test {tname} definition incorrect - "id" key is not present')
- elif not info_dict.get('ext') and info_dict.get('_type', 'video') == 'video':
- if params.get('skip_download') and params.get('ignore_no_formats_error'):
- continue
- raise Exception(f'Test {tname} definition incorrect - "ext" key must be present to define the output file')
-
- if 'skip' in test_case:
- print_skipping(test_case['skip'])
-
- for other_ie in other_ies:
- if not other_ie.working():
- print_skipping(f'test depends on {other_ie.ie_key()}IE, marked as not WORKING')
-
- params = get_params(test_case.get('params', {}))
- params['outtmpl'] = tname + '_' + params['outtmpl']
- if is_playlist and 'playlist' not in test_case:
- params.setdefault('playlistend', max(
- test_case.get('playlist_mincount', -1),
- test_case.get('playlist_count', -2) + 1,
- test_case.get('playlist_maxcount', -2) + 1))
- params.setdefault('skip_download', True)
- if 'playlist_duration_sum' not in test_case:
- params.setdefault('extract_flat', 'in_playlist')
-
- ydl = YoutubeDL(params, auto_init=False)
- ydl.add_default_info_extractors()
- finished_hook_called = set()
-
- def _hook(status):
- if status['status'] == 'finished':
- finished_hook_called.add(status['filename'])
- ydl.add_progress_hook(_hook)
- expect_warnings(ydl, test_case.get('expected_warnings', []))
-
- def get_tc_filename(tc):
- return ydl.prepare_filename(dict(tc.get('info_dict', {})))
-
- res_dict = None
-
- def match_exception(err):
- expected_exception = test_case.get('expected_exception')
- if not expected_exception:
- return False
- if err.__class__.__name__ == expected_exception:
- return True
- return any(exc.__class__.__name__ == expected_exception for exc in err.exc_info)
-
- def try_rm_tcs_files(tcs=None):
- if tcs is None:
- tcs = test_cases
- for tc in tcs:
- tc_filename = get_tc_filename(tc)
- try_rm(tc_filename)
- try_rm(tc_filename + '.part')
- try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
- try_rm_tcs_files()
- try:
- test_url = test_case['url']
- try_num = 1
- while True:
- try:
- # We're not using .download here since that is just a shim
- # for outside error handling, and returns the exit code
- # instead of the result dict.
- res_dict = ydl.extract_info(
- test_url,
- force_generic_extractor=params.get('force_generic_extractor', False))
- except (DownloadError, ExtractorError) as err:
- # Check if the exception is not a network related one
- if not isinstance(err.exc_info[1], (TransportError, UnavailableVideoError)) or (isinstance(err.exc_info[1], HTTPError) and err.exc_info[1].status == 503):
- if match_exception(err):
- return
- err.msg = f'{getattr(err, "msg", err)} ({tname})'
- raise
-
- if try_num == RETRIES:
- raise
-
- print(f'Retrying: {try_num} failed tries\n\n##########\n\n')
-
- try_num += 1
- except YoutubeDLError as err:
- if match_exception(err):
- return
- raise
- else:
- break
-
- if is_playlist:
- self.assertTrue(res_dict['_type'] in ['playlist', 'multi_video'])
- self.assertTrue('entries' in res_dict)
- expect_info_dict(self, res_dict, test_case.get('info_dict', {}))
-
- num_entries = len(res_dict.get('entries', []))
- if 'playlist_mincount' in test_case:
- mincount = test_case['playlist_mincount']
- assertGreaterEqual(
- self, num_entries, mincount,
- f'Expected at least {mincount} entries in playlist {test_url}, but got only {num_entries}')
- if 'playlist_count' in test_case:
- count = test_case['playlist_count']
- got = num_entries if num_entries <= count else 'more'
- self.assertEqual(
- num_entries, count,
- f'Expected exactly {count} entries in playlist {test_url}, but got {got}')
- if 'playlist_maxcount' in test_case:
- maxcount = test_case['playlist_maxcount']
- assertLessEqual(
- self, num_entries, maxcount,
- f'Expected at most {maxcount} entries in playlist {test_url}, but got more')
- if 'playlist_duration_sum' in test_case:
- got_duration = sum(e['duration'] for e in res_dict['entries'])
- self.assertEqual(
- test_case['playlist_duration_sum'], got_duration)
-
- # Generalize both playlists and single videos to unified format for
- # simplicity
- if 'entries' not in res_dict:
- res_dict['entries'] = [res_dict]
-
- for tc_num, tc in enumerate(test_cases):
- tc_res_dict = res_dict['entries'][tc_num]
- # First, check test cases' data against extracted data alone
- expect_info_dict(self, tc_res_dict, tc.get('info_dict', {}))
- if tc_res_dict.get('_type', 'video') != 'video':
- continue
- # Now, check downloaded file consistency
- tc_filename = get_tc_filename(tc)
- if not test_case.get('params', {}).get('skip_download', False):
- self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
- self.assertTrue(tc_filename in finished_hook_called)
- expected_minsize = tc.get('file_minsize', 10000)
- if expected_minsize is not None:
- if params.get('test'):
- expected_minsize = max(expected_minsize, 10000)
- got_fsize = os.path.getsize(tc_filename)
- assertGreaterEqual(
- self, got_fsize, expected_minsize,
- f'Expected {tc_filename} to be at least {format_bytes(expected_minsize)}, '
- f'but it\'s only {format_bytes(got_fsize)} ')
- if 'md5' in tc:
- md5_for_file = _file_md5(tc_filename)
- self.assertEqual(tc['md5'], md5_for_file)
- # Finally, check test cases' data again but this time against
- # extracted data from info JSON file written during processing
- info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
- self.assertTrue(
- os.path.exists(info_json_fn),
- f'Missing info file {info_json_fn}')
- with open(info_json_fn, encoding='utf-8') as infof:
- info_dict = json.load(infof)
- expect_info_dict(self, info_dict, tc.get('info_dict', {}))
- finally:
- try_rm_tcs_files()
- if is_playlist and res_dict is not None and res_dict.get('entries'):
- # Remove all other files that may have been extracted if the
- # extractor returns full results even with extract_flat
- res_tcs = [{'info_dict': e} for e in res_dict['entries']]
- try_rm_tcs_files(res_tcs)
- ydl.close()
- return test_template
-
-
-# And add them to TestDownload
-def inject_tests(test_cases, label=''):
- for test_case in test_cases:
- name = test_case['name']
- tname = join_nonempty('test', name, label, tests_counter[name][label], delim='_')
- tests_counter[name][label] += 1
-
- test_method = generator(test_case, tname)
- test_method.__name__ = tname
- test_method.add_ie = ','.join(test_case.get('add_ie', []))
- setattr(TestDownload, test_method.__name__, test_method)
-
-
-inject_tests(normal_test_cases)
-
-# TODO: disable redirection to the IE to ensure we are actually testing the webpage extraction
-inject_tests(webpage_test_cases, 'webpage')
-
-
-def batch_generator(name):
- def test_template(self):
- for label, num_tests in tests_counter[name].items():
- for i in range(num_tests):
- test_name = join_nonempty('test', name, label, i, delim='_')
- try:
- getattr(self, test_name)()
- except unittest.SkipTest:
- print(f'Skipped {test_name}')
-
- return test_template
-
-
-for name in tests_counter:
- test_method = batch_generator(name)
- test_method.__name__ = f'test_{name}_all'
- test_method.add_ie = ''
- setattr(TestDownload, test_method.__name__, test_method)
-del test_method
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_downloader_external.py b/test/test_downloader_external.py
deleted file mode 100644
index 62f7d45d4..000000000
--- a/test/test_downloader_external.py
+++ /dev/null
@@ -1,139 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-import http.cookiejar
-
-from test.helper import FakeYDL
-from yt_dlp.downloader.external import (
- Aria2cFD,
- AxelFD,
- CurlFD,
- FFmpegFD,
- HttpieFD,
- WgetFD,
-)
-
-TEST_COOKIE = {
- 'version': 0,
- 'name': 'test',
- 'value': 'ytdlp',
- 'port': None,
- 'port_specified': False,
- 'domain': '.example.com',
- 'domain_specified': True,
- 'domain_initial_dot': False,
- 'path': '/',
- 'path_specified': True,
- 'secure': False,
- 'expires': None,
- 'discard': False,
- 'comment': None,
- 'comment_url': None,
- 'rest': {},
-}
-
-TEST_INFO = {'url': 'http://www.example.com/'}
-
-
-class TestHttpieFD(unittest.TestCase):
- def test_make_cmd(self):
- with FakeYDL() as ydl:
- downloader = HttpieFD(ydl, {})
- self.assertEqual(
- downloader._make_cmd('test', TEST_INFO),
- ['http', '--download', '--output', 'test', 'http://www.example.com/'])
-
- # Test cookie header is added
- ydl.cookiejar.set_cookie(http.cookiejar.Cookie(**TEST_COOKIE))
- self.assertEqual(
- downloader._make_cmd('test', TEST_INFO),
- ['http', '--download', '--output', 'test', 'http://www.example.com/', 'Cookie:test=ytdlp'])
-
-
-class TestAxelFD(unittest.TestCase):
- def test_make_cmd(self):
- with FakeYDL() as ydl:
- downloader = AxelFD(ydl, {})
- self.assertEqual(
- downloader._make_cmd('test', TEST_INFO),
- ['axel', '-o', 'test', '--', 'http://www.example.com/'])
-
- # Test cookie header is added
- ydl.cookiejar.set_cookie(http.cookiejar.Cookie(**TEST_COOKIE))
- self.assertEqual(
- downloader._make_cmd('test', TEST_INFO),
- ['axel', '-o', 'test', '-H', 'Cookie: test=ytdlp', '--max-redirect=0', '--', 'http://www.example.com/'])
-
-
-class TestWgetFD(unittest.TestCase):
- def test_make_cmd(self):
- with FakeYDL() as ydl:
- downloader = WgetFD(ydl, {})
- self.assertNotIn('--load-cookies', downloader._make_cmd('test', TEST_INFO))
- # Test cookiejar tempfile arg is added
- ydl.cookiejar.set_cookie(http.cookiejar.Cookie(**TEST_COOKIE))
- self.assertIn('--load-cookies', downloader._make_cmd('test', TEST_INFO))
-
-
-class TestCurlFD(unittest.TestCase):
- def test_make_cmd(self):
- with FakeYDL() as ydl:
- downloader = CurlFD(ydl, {})
- self.assertNotIn('--cookie', downloader._make_cmd('test', TEST_INFO))
- # Test cookie header is added
- ydl.cookiejar.set_cookie(http.cookiejar.Cookie(**TEST_COOKIE))
- self.assertIn('--cookie', downloader._make_cmd('test', TEST_INFO))
- self.assertIn('test=ytdlp', downloader._make_cmd('test', TEST_INFO))
-
-
-class TestAria2cFD(unittest.TestCase):
- def test_make_cmd(self):
- with FakeYDL() as ydl:
- downloader = Aria2cFD(ydl, {})
- downloader._make_cmd('test', TEST_INFO)
- self.assertFalse(hasattr(downloader, '_cookies_tempfile'))
-
- # Test cookiejar tempfile arg is added
- ydl.cookiejar.set_cookie(http.cookiejar.Cookie(**TEST_COOKIE))
- cmd = downloader._make_cmd('test', TEST_INFO)
- self.assertIn(f'--load-cookies={downloader._cookies_tempfile}', cmd)
-
-
-@unittest.skipUnless(FFmpegFD.available(), 'ffmpeg not found')
-class TestFFmpegFD(unittest.TestCase):
- _args = []
-
- def _test_cmd(self, args):
- self._args = args
-
- def test_make_cmd(self):
- with FakeYDL() as ydl:
- downloader = FFmpegFD(ydl, {})
- downloader._debug_cmd = self._test_cmd
-
- downloader._call_downloader('test', {**TEST_INFO, 'ext': 'mp4'})
- self.assertEqual(self._args, [
- 'ffmpeg', '-y', '-hide_banner', '-i', 'http://www.example.com/',
- '-c', 'copy', '-f', 'mp4', 'file:test'])
-
- # Test cookies arg is added
- ydl.cookiejar.set_cookie(http.cookiejar.Cookie(**TEST_COOKIE))
- downloader._call_downloader('test', {**TEST_INFO, 'ext': 'mp4'})
- self.assertEqual(self._args, [
- 'ffmpeg', '-y', '-hide_banner', '-cookies', 'test=ytdlp; path=/; domain=.example.com;\r\n',
- '-i', 'http://www.example.com/', '-c', 'copy', '-f', 'mp4', 'file:test'])
-
- # Test with non-url input (ffmpeg reads from stdin '-' for websockets)
- downloader._call_downloader('test', {'url': 'x', 'ext': 'mp4'})
- self.assertEqual(self._args, [
- 'ffmpeg', '-y', '-hide_banner', '-i', 'x', '-c', 'copy', '-f', 'mp4', 'file:test'])
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_downloader_http.py b/test/test_downloader_http.py
deleted file mode 100644
index cf2e3fac1..000000000
--- a/test/test_downloader_http.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import http.server
-import re
-import threading
-
-from test.helper import http_server_port, try_rm
-from yt_dlp import YoutubeDL
-from yt_dlp.downloader.http import HttpFD
-from yt_dlp.utils._utils import _YDLLogger as FakeLogger
-
-TEST_DIR = os.path.dirname(os.path.abspath(__file__))
-
-
-TEST_SIZE = 10 * 1024
-
-
-class HTTPTestRequestHandler(http.server.BaseHTTPRequestHandler):
- def log_message(self, format, *args):
- pass
-
- def send_content_range(self, total=None):
- range_header = self.headers.get('Range')
- start = end = None
- if range_header:
- mobj = re.search(r'^bytes=(\d+)-(\d+)', range_header)
- if mobj:
- start = int(mobj.group(1))
- end = int(mobj.group(2))
- valid_range = start is not None and end is not None
- if valid_range:
- content_range = f'bytes {start}-{end}'
- if total:
- content_range += f'/{total}'
- self.send_header('Content-Range', content_range)
- return (end - start + 1) if valid_range else total
-
- def serve(self, range=True, content_length=True):
- self.send_response(200)
- self.send_header('Content-Type', 'video/mp4')
- size = TEST_SIZE
- if range:
- size = self.send_content_range(TEST_SIZE)
- if content_length:
- self.send_header('Content-Length', size)
- self.end_headers()
- self.wfile.write(b'#' * size)
-
- def do_GET(self):
- if self.path == '/regular':
- self.serve()
- elif self.path == '/no-content-length':
- self.serve(content_length=False)
- elif self.path == '/no-range':
- self.serve(range=False)
- elif self.path == '/no-range-no-content-length':
- self.serve(range=False, content_length=False)
- else:
- assert False
-
-
-class TestHttpFD(unittest.TestCase):
- def setUp(self):
- self.httpd = http.server.HTTPServer(
- ('127.0.0.1', 0), HTTPTestRequestHandler)
- self.port = http_server_port(self.httpd)
- self.server_thread = threading.Thread(target=self.httpd.serve_forever)
- self.server_thread.daemon = True
- self.server_thread.start()
-
- def download(self, params, ep):
- params['logger'] = FakeLogger()
- ydl = YoutubeDL(params)
- downloader = HttpFD(ydl, params)
- filename = 'testfile.mp4'
- try_rm(filename)
- self.assertTrue(downloader.real_download(filename, {
- 'url': f'http://127.0.0.1:{self.port}/{ep}',
- }), ep)
- self.assertEqual(os.path.getsize(filename), TEST_SIZE, ep)
- try_rm(filename)
-
- def download_all(self, params):
- for ep in ('regular', 'no-content-length', 'no-range', 'no-range-no-content-length'):
- self.download(params, ep)
-
- def test_regular(self):
- self.download_all({})
-
- def test_chunked(self):
- self.download_all({
- 'http_chunk_size': 1000,
- })
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_execution.py b/test/test_execution.py
deleted file mode 100644
index c6ee9cf9d..000000000
--- a/test/test_execution.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import contextlib
-import subprocess
-
-from yt_dlp.utils import Popen
-
-rootDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-LAZY_EXTRACTORS = 'yt_dlp/extractor/lazy_extractors.py'
-
-
-class TestExecution(unittest.TestCase):
- def run_yt_dlp(self, exe=(sys.executable, 'yt_dlp/__main__.py'), opts=('--version', )):
- stdout, stderr, returncode = Popen.run(
- [*exe, '--ignore-config', *opts], cwd=rootDir, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- print(stderr, file=sys.stderr)
- self.assertEqual(returncode, 0)
- return stdout.strip(), stderr.strip()
-
- def test_main_exec(self):
- self.run_yt_dlp()
-
- def test_import(self):
- self.run_yt_dlp(exe=(sys.executable, '-c', 'import yt_dlp'))
-
- def test_module_exec(self):
- self.run_yt_dlp(exe=(sys.executable, '-m', 'yt_dlp'))
-
- def test_cmdline_umlauts(self):
- _, stderr = self.run_yt_dlp(opts=('ä', '--version'))
- self.assertFalse(stderr)
-
- def test_lazy_extractors(self):
- try:
- subprocess.check_call([sys.executable, 'devscripts/make_lazy_extractors.py', LAZY_EXTRACTORS],
- cwd=rootDir, stdout=subprocess.DEVNULL)
- self.assertTrue(os.path.exists(LAZY_EXTRACTORS))
-
- _, stderr = self.run_yt_dlp(opts=('-s', 'test:'))
- # `MIN_RECOMMENDED` emits a deprecated feature warning for deprecated Python versions
- if stderr and stderr.startswith('Deprecated Feature: Support for Python'):
- stderr = ''
- self.assertFalse(stderr)
-
- subprocess.check_call([sys.executable, 'test/test_all_urls.py'], cwd=rootDir, stdout=subprocess.DEVNULL)
- finally:
- with contextlib.suppress(OSError):
- os.remove(LAZY_EXTRACTORS)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_http_proxy.py b/test/test_http_proxy.py
deleted file mode 100644
index 22ce3ca5d..000000000
--- a/test/test_http_proxy.py
+++ /dev/null
@@ -1,378 +0,0 @@
-import abc
-import base64
-import contextlib
-import functools
-import json
-import os
-import random
-import ssl
-import threading
-from http.server import BaseHTTPRequestHandler
-from socketserver import ThreadingTCPServer
-
-import pytest
-
-from test.helper import http_server_port, verify_address_availability
-from test.test_networking import TEST_DIR
-from test.test_socks import IPv6ThreadingTCPServer
-from yt_dlp.dependencies import urllib3
-from yt_dlp.networking import Request
-from yt_dlp.networking.exceptions import HTTPError, ProxyError, SSLError
-
-
-class HTTPProxyAuthMixin:
-
- def proxy_auth_error(self):
- self.send_response(407)
- self.send_header('Proxy-Authenticate', 'Basic realm="test http proxy"')
- self.end_headers()
- return False
-
- def do_proxy_auth(self, username, password):
- if username is None and password is None:
- return True
-
- proxy_auth_header = self.headers.get('Proxy-Authorization', None)
- if proxy_auth_header is None:
- return self.proxy_auth_error()
-
- if not proxy_auth_header.startswith('Basic '):
- return self.proxy_auth_error()
-
- auth = proxy_auth_header[6:]
-
- try:
- auth_username, auth_password = base64.b64decode(auth).decode().split(':', 1)
- except Exception:
- return self.proxy_auth_error()
-
- if auth_username != (username or '') or auth_password != (password or ''):
- return self.proxy_auth_error()
- return True
-
-
-class HTTPProxyHandler(BaseHTTPRequestHandler, HTTPProxyAuthMixin):
- def __init__(self, *args, proxy_info=None, username=None, password=None, request_handler=None, **kwargs):
- self.username = username
- self.password = password
- self.proxy_info = proxy_info
- super().__init__(*args, **kwargs)
-
- def do_GET(self):
- if not self.do_proxy_auth(self.username, self.password):
- self.server.close_request(self.request)
- return
- if self.path.endswith('/proxy_info'):
- payload = json.dumps(self.proxy_info or {
- 'client_address': self.client_address,
- 'connect': False,
- 'connect_host': None,
- 'connect_port': None,
- 'headers': dict(self.headers),
- 'path': self.path,
- 'proxy': ':'.join(str(y) for y in self.connection.getsockname()),
- })
- self.send_response(200)
- self.send_header('Content-Type', 'application/json; charset=utf-8')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload.encode())
- else:
- self.send_response(404)
- self.end_headers()
-
- self.server.close_request(self.request)
-
-
-if urllib3:
- import urllib3.util.ssltransport
-
- class SSLTransport(urllib3.util.ssltransport.SSLTransport):
- """
- Modified version of urllib3 SSLTransport to support server side SSL
-
- This allows us to chain multiple TLS connections.
- """
-
- def __init__(self, socket, ssl_context, server_hostname=None, suppress_ragged_eofs=True, server_side=False):
- self.incoming = ssl.MemoryBIO()
- self.outgoing = ssl.MemoryBIO()
-
- self.suppress_ragged_eofs = suppress_ragged_eofs
- self.socket = socket
-
- self.sslobj = ssl_context.wrap_bio(
- self.incoming,
- self.outgoing,
- server_hostname=server_hostname,
- server_side=server_side,
- )
- self._ssl_io_loop(self.sslobj.do_handshake)
-
- @property
- def _io_refs(self):
- return self.socket._io_refs
-
- @_io_refs.setter
- def _io_refs(self, value):
- self.socket._io_refs = value
-
- def shutdown(self, *args, **kwargs):
- self.socket.shutdown(*args, **kwargs)
-else:
- SSLTransport = None
-
-
-class HTTPSProxyHandler(HTTPProxyHandler):
- def __init__(self, request, *args, **kwargs):
- certfn = os.path.join(TEST_DIR, 'testcert.pem')
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.load_cert_chain(certfn, None)
- if isinstance(request, ssl.SSLSocket):
- request = SSLTransport(request, ssl_context=sslctx, server_side=True)
- else:
- request = sslctx.wrap_socket(request, server_side=True)
- super().__init__(request, *args, **kwargs)
-
-
-class HTTPConnectProxyHandler(BaseHTTPRequestHandler, HTTPProxyAuthMixin):
- protocol_version = 'HTTP/1.1'
- default_request_version = 'HTTP/1.1'
-
- def __init__(self, *args, username=None, password=None, request_handler=None, **kwargs):
- self.username = username
- self.password = password
- self.request_handler = request_handler
- super().__init__(*args, **kwargs)
-
- def do_CONNECT(self):
- if not self.do_proxy_auth(self.username, self.password):
- self.server.close_request(self.request)
- return
- self.send_response(200)
- self.end_headers()
- proxy_info = {
- 'client_address': self.client_address,
- 'connect': True,
- 'connect_host': self.path.split(':')[0],
- 'connect_port': int(self.path.split(':')[1]),
- 'headers': dict(self.headers),
- 'path': self.path,
- 'proxy': ':'.join(str(y) for y in self.connection.getsockname()),
- }
- self.request_handler(self.request, self.client_address, self.server, proxy_info=proxy_info)
- self.server.close_request(self.request)
-
-
-class HTTPSConnectProxyHandler(HTTPConnectProxyHandler):
- def __init__(self, request, *args, **kwargs):
- certfn = os.path.join(TEST_DIR, 'testcert.pem')
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.load_cert_chain(certfn, None)
- request = sslctx.wrap_socket(request, server_side=True)
- self._original_request = request
- super().__init__(request, *args, **kwargs)
-
- def do_CONNECT(self):
- super().do_CONNECT()
- self.server.close_request(self._original_request)
-
-
-@contextlib.contextmanager
-def proxy_server(proxy_server_class, request_handler, bind_ip=None, **proxy_server_kwargs):
- server = server_thread = None
- try:
- bind_address = bind_ip or '127.0.0.1'
- server_type = ThreadingTCPServer if '.' in bind_address else IPv6ThreadingTCPServer
- server = server_type(
- (bind_address, 0), functools.partial(proxy_server_class, request_handler=request_handler, **proxy_server_kwargs))
- server_port = http_server_port(server)
- server_thread = threading.Thread(target=server.serve_forever)
- server_thread.daemon = True
- server_thread.start()
- if '.' not in bind_address:
- yield f'[{bind_address}]:{server_port}'
- else:
- yield f'{bind_address}:{server_port}'
- finally:
- server.shutdown()
- server.server_close()
- server_thread.join(2.0)
-
-
-class HTTPProxyTestContext(abc.ABC):
- REQUEST_HANDLER_CLASS = None
- REQUEST_PROTO = None
-
- def http_server(self, server_class, *args, **kwargs):
- return proxy_server(server_class, self.REQUEST_HANDLER_CLASS, *args, **kwargs)
-
- @abc.abstractmethod
- def proxy_info_request(self, handler, target_domain=None, target_port=None, **req_kwargs) -> dict:
- """return a dict of proxy_info"""
-
-
-class HTTPProxyHTTPTestContext(HTTPProxyTestContext):
- # Standard HTTP Proxy for http requests
- REQUEST_HANDLER_CLASS = HTTPProxyHandler
- REQUEST_PROTO = 'http'
-
- def proxy_info_request(self, handler, target_domain=None, target_port=None, **req_kwargs):
- request = Request(f'http://{target_domain or "127.0.0.1"}:{target_port or "40000"}/proxy_info', **req_kwargs)
- handler.validate(request)
- return json.loads(handler.send(request).read().decode())
-
-
-class HTTPProxyHTTPSTestContext(HTTPProxyTestContext):
- # HTTP Connect proxy, for https requests
- REQUEST_HANDLER_CLASS = HTTPSProxyHandler
- REQUEST_PROTO = 'https'
-
- def proxy_info_request(self, handler, target_domain=None, target_port=None, **req_kwargs):
- request = Request(f'https://{target_domain or "127.0.0.1"}:{target_port or "40000"}/proxy_info', **req_kwargs)
- handler.validate(request)
- return json.loads(handler.send(request).read().decode())
-
-
-CTX_MAP = {
- 'http': HTTPProxyHTTPTestContext,
- 'https': HTTPProxyHTTPSTestContext,
-}
-
-
-@pytest.fixture(scope='module')
-def ctx(request):
- return CTX_MAP[request.param]()
-
-
-@pytest.mark.parametrize(
- 'handler', ['Urllib', 'Requests', 'CurlCFFI'], indirect=True)
-@pytest.mark.handler_flaky('CurlCFFI', reason='segfaults')
-@pytest.mark.parametrize('ctx', ['http'], indirect=True) # pure http proxy can only support http
-class TestHTTPProxy:
- def test_http_no_auth(self, handler, ctx):
- with ctx.http_server(HTTPProxyHandler) as server_address:
- with handler(proxies={ctx.REQUEST_PROTO: f'http://{server_address}'}) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert proxy_info['connect'] is False
- assert 'Proxy-Authorization' not in proxy_info['headers']
-
- def test_http_auth(self, handler, ctx):
- with ctx.http_server(HTTPProxyHandler, username='test', password='test') as server_address:
- with handler(proxies={ctx.REQUEST_PROTO: f'http://test:test@{server_address}'}) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert 'Proxy-Authorization' in proxy_info['headers']
-
- def test_http_bad_auth(self, handler, ctx):
- with ctx.http_server(HTTPProxyHandler, username='test', password='test') as server_address:
- with handler(proxies={ctx.REQUEST_PROTO: f'http://test:bad@{server_address}'}) as rh:
- with pytest.raises(HTTPError) as exc_info:
- ctx.proxy_info_request(rh)
- assert exc_info.value.response.status == 407
- exc_info.value.response.close()
-
- def test_http_source_address(self, handler, ctx):
- with ctx.http_server(HTTPProxyHandler) as server_address:
- source_address = f'127.0.0.{random.randint(5, 255)}'
- verify_address_availability(source_address)
- with handler(proxies={ctx.REQUEST_PROTO: f'http://{server_address}'},
- source_address=source_address) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert proxy_info['client_address'][0] == source_address
-
- @pytest.mark.skip_handler('Urllib', 'urllib does not support https proxies')
- def test_https(self, handler, ctx):
- with ctx.http_server(HTTPSProxyHandler) as server_address:
- with handler(verify=False, proxies={ctx.REQUEST_PROTO: f'https://{server_address}'}) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert proxy_info['connect'] is False
- assert 'Proxy-Authorization' not in proxy_info['headers']
-
- @pytest.mark.skip_handler('Urllib', 'urllib does not support https proxies')
- def test_https_verify_failed(self, handler, ctx):
- with ctx.http_server(HTTPSProxyHandler) as server_address:
- with handler(verify=True, proxies={ctx.REQUEST_PROTO: f'https://{server_address}'}) as rh:
- # Accept SSLError as may not be feasible to tell if it is proxy or request error.
- # note: if request proto also does ssl verification, this may also be the error of the request.
- # Until we can support passing custom cacerts to handlers, we cannot properly test this for all cases.
- with pytest.raises((ProxyError, SSLError)):
- ctx.proxy_info_request(rh)
-
- def test_http_with_idn(self, handler, ctx):
- with ctx.http_server(HTTPProxyHandler) as server_address:
- with handler(proxies={ctx.REQUEST_PROTO: f'http://{server_address}'}) as rh:
- proxy_info = ctx.proxy_info_request(rh, target_domain='中文.tw')
- assert proxy_info['proxy'] == server_address
- assert proxy_info['path'].startswith('http://xn--fiq228c.tw')
- assert proxy_info['headers']['Host'].split(':', 1)[0] == 'xn--fiq228c.tw'
-
-
-@pytest.mark.parametrize(
- 'handler,ctx', [
- ('Requests', 'https'),
- ('CurlCFFI', 'https'),
- ], indirect=True)
-@pytest.mark.handler_flaky('CurlCFFI', reason='segfaults')
-class TestHTTPConnectProxy:
- def test_http_connect_no_auth(self, handler, ctx):
- with ctx.http_server(HTTPConnectProxyHandler) as server_address:
- with handler(verify=False, proxies={ctx.REQUEST_PROTO: f'http://{server_address}'}) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert proxy_info['connect'] is True
- assert 'Proxy-Authorization' not in proxy_info['headers']
-
- def test_http_connect_auth(self, handler, ctx):
- with ctx.http_server(HTTPConnectProxyHandler, username='test', password='test') as server_address:
- with handler(verify=False, proxies={ctx.REQUEST_PROTO: f'http://test:test@{server_address}'}) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert 'Proxy-Authorization' in proxy_info['headers']
-
- def test_http_connect_bad_auth(self, handler, ctx):
- with ctx.http_server(HTTPConnectProxyHandler, username='test', password='test') as server_address:
- with handler(verify=False, proxies={ctx.REQUEST_PROTO: f'http://test:bad@{server_address}'}) as rh:
- with pytest.raises(ProxyError):
- ctx.proxy_info_request(rh)
-
- def test_http_connect_source_address(self, handler, ctx):
- with ctx.http_server(HTTPConnectProxyHandler) as server_address:
- source_address = f'127.0.0.{random.randint(5, 255)}'
- verify_address_availability(source_address)
- with handler(proxies={ctx.REQUEST_PROTO: f'http://{server_address}'},
- source_address=source_address,
- verify=False) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert proxy_info['client_address'][0] == source_address
-
- @pytest.mark.skipif(urllib3 is None, reason='requires urllib3 to test')
- def test_https_connect_proxy(self, handler, ctx):
- with ctx.http_server(HTTPSConnectProxyHandler) as server_address:
- with handler(verify=False, proxies={ctx.REQUEST_PROTO: f'https://{server_address}'}) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert proxy_info['connect'] is True
- assert 'Proxy-Authorization' not in proxy_info['headers']
-
- @pytest.mark.skipif(urllib3 is None, reason='requires urllib3 to test')
- def test_https_connect_verify_failed(self, handler, ctx):
- with ctx.http_server(HTTPSConnectProxyHandler) as server_address:
- with handler(verify=True, proxies={ctx.REQUEST_PROTO: f'https://{server_address}'}) as rh:
- # Accept SSLError as may not be feasible to tell if it is proxy or request error.
- # note: if request proto also does ssl verification, this may also be the error of the request.
- # Until we can support passing custom cacerts to handlers, we cannot properly test this for all cases.
- with pytest.raises((ProxyError, SSLError)):
- ctx.proxy_info_request(rh)
-
- @pytest.mark.skipif(urllib3 is None, reason='requires urllib3 to test')
- def test_https_connect_proxy_auth(self, handler, ctx):
- with ctx.http_server(HTTPSConnectProxyHandler, username='test', password='test') as server_address:
- with handler(verify=False, proxies={ctx.REQUEST_PROTO: f'https://test:test@{server_address}'}) as rh:
- proxy_info = ctx.proxy_info_request(rh)
- assert proxy_info['proxy'] == server_address
- assert 'Proxy-Authorization' in proxy_info['headers']
diff --git a/test/test_jsc/conftest.py b/test/test_jsc/conftest.py
deleted file mode 100644
index 28d673412..000000000
--- a/test/test_jsc/conftest.py
+++ /dev/null
@@ -1,60 +0,0 @@
-import re
-import pathlib
-
-import pytest
-
-import yt_dlp.globals
-from yt_dlp import YoutubeDL
-from yt_dlp.extractor.common import InfoExtractor
-
-
-_TESTDATA_PATH = pathlib.Path(__file__).parent.parent / 'testdata/sigs'
-_player_re = re.compile(r'^.+/player/(?P[a-zA-Z0-9_/.-]+)\.js$')
-_player_id_trans = str.maketrans(dict.fromkeys('/.-', '_'))
-
-
-@pytest.fixture
-def ie() -> InfoExtractor:
- runtime_names = yt_dlp.globals.supported_js_runtimes.value
- ydl = YoutubeDL({'js_runtimes': {key: {} for key in runtime_names}})
- ie = ydl.get_info_extractor('Youtube')
-
- def _load_player(video_id, player_url, fatal=True):
- match = _player_re.match(player_url)
- test_id = match.group('id').translate(_player_id_trans)
- cached_file = _TESTDATA_PATH / f'player-{test_id}.js'
-
- if cached_file.exists():
- return cached_file.read_text()
-
- if code := ie._download_webpage(player_url, video_id, fatal=fatal):
- _TESTDATA_PATH.mkdir(exist_ok=True, parents=True)
- cached_file.write_text(code)
- return code
-
- return None
-
- ie._load_player = _load_player
- return ie
-
-
-class MockLogger:
- def trace(self, message: str):
- print(f'trace: {message}')
-
- def debug(self, message: str, *, once=False):
- print(f'debug: {message}')
-
- def info(self, message: str):
- print(f'info: {message}')
-
- def warning(self, message: str, *, once=False):
- print(f'warning: {message}')
-
- def error(self, message: str):
- print(f'error: {message}')
-
-
-@pytest.fixture
-def logger():
- return MockLogger()
diff --git a/test/test_jsc/test_ejs_integration.py b/test/test_jsc/test_ejs_integration.py
deleted file mode 100644
index b2150e369..000000000
--- a/test/test_jsc/test_ejs_integration.py
+++ /dev/null
@@ -1,153 +0,0 @@
-from __future__ import annotations
-
-import dataclasses
-import enum
-import importlib.util
-import json
-
-import pytest
-
-from yt_dlp.extractor.youtube.jsc.provider import (
- JsChallengeRequest,
- JsChallengeType,
- JsChallengeProviderResponse,
- JsChallengeResponse,
- NChallengeInput,
- NChallengeOutput,
- SigChallengeInput,
- SigChallengeOutput,
-)
-from yt_dlp.extractor.youtube.jsc._builtin.bun import BunJCP
-from yt_dlp.extractor.youtube.jsc._builtin.deno import DenoJCP
-from yt_dlp.extractor.youtube.jsc._builtin.node import NodeJCP
-from yt_dlp.extractor.youtube.jsc._builtin.quickjs import QuickJSJCP
-
-
-_has_ejs = bool(importlib.util.find_spec('yt_dlp_ejs'))
-pytestmark = pytest.mark.skipif(not _has_ejs, reason='yt-dlp-ejs not available')
-
-
-class Variant(enum.Enum):
- main = 'player_ias.vflset/en_US/base.js'
- tcc = 'player_ias_tcc.vflset/en_US/base.js'
- tce = 'player_ias_tce.vflset/en_US/base.js'
- es5 = 'player_es5.vflset/en_US/base.js'
- es6 = 'player_es6.vflset/en_US/base.js'
- es6_tcc = 'player_es6_tcc.vflset/en_US/base.js'
- es6_tce = 'player_es6_tce.vflset/en_US/base.js'
- tv = 'tv-player-ias.vflset/tv-player-ias.js'
- tv_es6 = 'tv-player-es6.vflset/tv-player-es6.js'
- phone = 'player-plasma-ias-phone-en_US.vflset/base.js'
- house = 'house_brand_player.vflset/en_US/base.js'
-
-
-@dataclasses.dataclass
-class Challenge:
- player: str
- variant: Variant
- type: JsChallengeType
- values: dict[str, str] = dataclasses.field(default_factory=dict)
-
- def url(self, /):
- return f'https://www.youtube.com/s/player/{self.player}/{self.variant.value}'
-
-
-CHALLENGES: list[Challenge] = [
- # 20522
- Challenge('74edf1a3', Variant.main, JsChallengeType.N, {
- 'IlLiA21ny7gqA2m4p37': '9nRTxrbM1f0yHg',
- 'eabGFpsUKuWHXGh6FR4': 'izmYqDEY6kl7Sg',
- 'eabGF/ps%UK=uWHXGh6FR4': 'LACmqlhaBpiPlgE-a',
- }),
- Challenge('74edf1a3', Variant.main, JsChallengeType.SIG, {
- 'NJAJEij0EwRgIhAI0KExTgjfPk-MPM9MAdzyyPRt=BM8-XO5tm5hlMCSVpAiEAv7eP3CURqZNSPow8BXXAoazVoXgeMP7gH9BdylHCwgw=gwzz':
- 'NJAJEij0EwRgIhAI0KExTgjfPk-MPM9MAdzyyPRt=BM8-XO5tm5hzMCSVpAiEAv7eP3CURqZNSPow8BXXAoazVoXgeMP7gH9BdylHCwgw=gwzl',
- '\x00\x01\x02%\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49':
- '\x00\x01\x02%\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x40\x41\x42\x49\x44\x45\x46\x47\x48\x43',
- }),
- # 20523
- Challenge('901741ab', Variant.main, JsChallengeType.N, {
- 'BQoJvGBkC2nj1ZZLK-': 'UMPovvBZRh-sjb',
- }),
- Challenge('901741ab', Variant.main, JsChallengeType.SIG, {
- 'NJAJEij0EwRgIhAI0KExTgjfPk-MPM9MAdzyyPRt=BM8-XO5tm5hlMCSVpAiEAv7eP3CURqZNSPow8BXXAoazVoXgeMP7gH9BdylHCwgw=gwzz':
- 'wgwCHlydB9Hg7PMegXoVzaoAXXB8woPSNZqRUC3Pe7vAEiApVSCMlhwmt5ON-8MB=5RPyyzdAM9MPM-kPfjgTxEK0IAhIgRwE0jiEJA',
- }),
- # 20524
- Challenge('e7573094', Variant.main, JsChallengeType.N, {
- 'IlLiA21ny7gqA2m4p37': '3KuQ3235dojTSjo4',
- }),
- Challenge('e7573094', Variant.main, JsChallengeType.SIG, {
- 'NJAJEij0EwRgIhAI0KExTgjfPk-MPM9MAdzyyPRt=BM8-XO5tm5hlMCSVpAiEAv7eP3CURqZNSPow8BXXAoazVoXgeMP7gH9BdylHCwgw=gwzz':
- 'yEij0EwRgIhAI0KExTgjfPk-MPM9MAdzyNPRt=BM8-XO5tm5hlMCSVNAiEAvpeP3CURqZJSPow8BXXAoazVoXgeMP7gH9BdylHCwgw=g',
- }),
- # 20525
- Challenge('9fcf08e8', Variant.main, JsChallengeType.N, {
- 'Dyc5ALyWiO0VqwCiT': 'H2PLmmAmJsYjKA',
- }),
- Challenge('9fcf08e8', Variant.main, JsChallengeType.SIG, {
- '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a':
- '\x6a\x69\x68\x67\x66\x65\x64\x63\x62\x61\x60\x5f\x5e\x5d\x5c\x5b\x5a\x59\x58\x57\x56\x55\x54\x53\x52\x51\x50\x4f\x4e\x4d\x4c\x4b\x4a\x49\x48\x47\x46\x45\x44\x43\x42\x41\x40\x3f\x3e\x3d\x3c\x3b\x3a\x39\x38\x37\x36\x35\x34\x33\x32\x31\x30\x2f\x2e\x2d\x2c\x2b\x2a\x29\x28\x27\x26\x25\x24\x23\x22\x21\x20\x1f\x1e\x1d\x1c\x1b\x1a\x19\x18\x17\x16\x15\x14\x13\x12\x11\x10\x0f\x0e\x0d\x0c\x0b\x03\x09\x08\x07\x06\x05\x04\x0a',
- }),
- # 20527
- Challenge('21cd2156', Variant.main, JsChallengeType.N, {
- 'CiOxDbW1WEE8Ti4w': 'ZcBE4klItiC4rQ',
- }),
- Challenge('21cd2156', Variant.main, JsChallengeType.SIG, {
- '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a':
- '\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x00\x46\x47\x48\x49\x4a\x4b\x6a\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x4c',
- }),
- # 20528
- Challenge('5e55da5a', Variant.tv, JsChallengeType.N, {
- 'FgTvzyq4jKv482R7': 'l26nyYSotkzDxg',
- }),
- Challenge('5e55da5a', Variant.tv, JsChallengeType.SIG, {
- '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a':
- '\x46\x66\x65\x64\x63\x62\x61\x60\x5f\x5e\x67\x6a\x5b\x5a\x59\x58\x57\x56\x55\x54\x53\x52\x51\x50\x4f\x4e\x4d\x4c\x4b\x4a\x49\x48\x47\x2c\x45\x44\x43\x42\x41\x40\x3f\x3e\x3d\x3c\x3b\x3a\x39\x38\x13\x36\x35\x34\x33\x32\x31\x30\x2f\x2e\x2d\x5d\x2b\x2a\x29\x28\x27\x26\x25\x24\x23\x22\x21\x20\x1f\x1e\x1d\x1c\x1b\x1a\x19\x18\x17\x16\x15\x14\x0c\x12\x11\x10\x0f\x0e\x0d\x00\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x37',
- }),
- # 20529
- Challenge('631d3938', Variant.main, JsChallengeType.N, {
- 'KBx1qz7jMhxELa8c': 'ttPvh7WIptsgSw',
- }),
- Challenge('631d3938', Variant.main, JsChallengeType.SIG, {
- '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66':
- '\x19\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x00\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63',
- }),
-]
-
-requests: list[JsChallengeRequest] = []
-responses: list[JsChallengeProviderResponse] = []
-for test in CHALLENGES:
- input_type, output_type = {
- JsChallengeType.N: (NChallengeInput, NChallengeOutput),
- JsChallengeType.SIG: (SigChallengeInput, SigChallengeOutput),
- }[test.type]
-
- request = JsChallengeRequest(test.type, input_type(test.url(), list(test.values.keys())), test.player)
- requests.append(request)
- responses.append(JsChallengeProviderResponse(request, JsChallengeResponse(test.type, output_type(test.values))))
-
-
-@pytest.fixture(params=[BunJCP, DenoJCP, NodeJCP, QuickJSJCP])
-def jcp(request, ie, logger):
- obj = request.param(ie, logger, None)
- if not obj.is_available():
- pytest.skip(f'{obj.PROVIDER_NAME} is not available')
- obj.is_dev = True
- return obj
-
-
-@pytest.mark.download
-def test_bulk_requests(jcp):
- assert list(jcp.bulk_solve(requests)) == responses
-
-
-@pytest.mark.download
-def test_using_cached_player(jcp):
- first_player_requests = requests[:3]
- player = jcp._get_player(first_player_requests[0].video_id, first_player_requests[0].input.player_url)
- initial = json.loads(jcp._run_js_runtime(jcp._construct_stdin(player, False, first_player_requests)))
- preprocessed = initial.pop('preprocessed_player')
- result = json.loads(jcp._run_js_runtime(jcp._construct_stdin(preprocessed, True, first_player_requests)))
-
- assert initial == result
diff --git a/test/test_jsc/test_provider.py b/test/test_jsc/test_provider.py
deleted file mode 100644
index 3342f7754..000000000
--- a/test/test_jsc/test_provider.py
+++ /dev/null
@@ -1,194 +0,0 @@
-
-import pytest
-
-from yt_dlp.extractor.youtube.jsc.provider import (
- JsChallengeProvider,
- JsChallengeRequest,
- JsChallengeProviderResponse,
- JsChallengeProviderRejectedRequest,
- JsChallengeType,
- JsChallengeResponse,
- NChallengeOutput,
- NChallengeInput,
- JsChallengeProviderError,
- register_provider,
- register_preference,
-)
-from yt_dlp.extractor.youtube.pot._provider import IEContentProvider
-from yt_dlp.utils import ExtractorError
-from yt_dlp.extractor.youtube.jsc._registry import _jsc_preferences, _jsc_providers
-
-
-class ExampleJCP(JsChallengeProvider):
- PROVIDER_NAME = 'example-provider'
- PROVIDER_VERSION = '0.0.1'
- BUG_REPORT_LOCATION = 'https://example.com/issues'
-
- _SUPPORTED_TYPES = [JsChallengeType.N]
-
- def is_available(self) -> bool:
- return True
-
- def _real_bulk_solve(self, requests):
- for request in requests:
- results = dict.fromkeys(request.input.challenges, 'example-solution')
- response = JsChallengeResponse(
- type=request.type,
- output=NChallengeOutput(results=results))
- yield JsChallengeProviderResponse(request=request, response=response)
-
-
-PLAYER_URL = 'https://example.com/player.js'
-
-
-class TestJsChallengeProvider:
- # note: some test covered in TestPoTokenProvider which shares the same base class
- def test_base_type(self):
- assert issubclass(JsChallengeProvider, IEContentProvider)
-
- def test_create_provider_missing_bulk_solve_method(self, ie, logger):
- class MissingMethodsJCP(JsChallengeProvider):
- def is_available(self) -> bool:
- return True
-
- with pytest.raises(TypeError, match='bulk_solve'):
- MissingMethodsJCP(ie=ie, logger=logger, settings={})
-
- def test_create_provider_missing_available_method(self, ie, logger):
- class MissingMethodsJCP(JsChallengeProvider):
- def _real_bulk_solve(self, requests):
- raise JsChallengeProviderRejectedRequest('Not implemented')
-
- with pytest.raises(TypeError, match='is_available'):
- MissingMethodsJCP(ie=ie, logger=logger, settings={})
-
- def test_barebones_provider(self, ie, logger):
- class BarebonesProviderJCP(JsChallengeProvider):
- def is_available(self) -> bool:
- return True
-
- def _real_bulk_solve(self, requests):
- raise JsChallengeProviderRejectedRequest('Not implemented')
-
- provider = BarebonesProviderJCP(ie=ie, logger=logger, settings={})
- assert provider.PROVIDER_NAME == 'BarebonesProvider'
- assert provider.PROVIDER_KEY == 'BarebonesProvider'
- assert provider.PROVIDER_VERSION == '0.0.0'
- assert provider.BUG_REPORT_MESSAGE == 'please report this issue to the provider developer at (developer has not provided a bug report location) .'
-
- def test_example_provider_success(self, ie, logger):
- provider = ExampleJCP(ie=ie, logger=logger, settings={})
-
- request = JsChallengeRequest(
- type=JsChallengeType.N,
- input=NChallengeInput(player_url=PLAYER_URL, challenges=['example-challenge']))
-
- request_two = JsChallengeRequest(
- type=JsChallengeType.N,
- input=NChallengeInput(player_url=PLAYER_URL, challenges=['example-challenge-2']))
-
- responses = list(provider.bulk_solve([request, request_two]))
- assert len(responses) == 2
- assert all(isinstance(r, JsChallengeProviderResponse) for r in responses)
- assert responses == [
- JsChallengeProviderResponse(
- request=request,
- response=JsChallengeResponse(
- type=JsChallengeType.N,
- output=NChallengeOutput(results={'example-challenge': 'example-solution'}),
- ),
- ),
- JsChallengeProviderResponse(
- request=request_two,
- response=JsChallengeResponse(
- type=JsChallengeType.N,
- output=NChallengeOutput(results={'example-challenge-2': 'example-solution'}),
- ),
- ),
- ]
-
- def test_provider_unsupported_challenge_type(self, ie, logger):
- provider = ExampleJCP(ie=ie, logger=logger, settings={})
- request_supported = JsChallengeRequest(
- type=JsChallengeType.N,
- input=NChallengeInput(player_url=PLAYER_URL, challenges=['example-challenge']))
- request_unsupported = JsChallengeRequest(
- type=JsChallengeType.SIG,
- input=NChallengeInput(player_url=PLAYER_URL, challenges=['example-challenge']))
- responses = list(provider.bulk_solve([request_supported, request_unsupported, request_supported]))
- assert len(responses) == 3
- # Requests are validated first before continuing to _real_bulk_solve
- assert isinstance(responses[0], JsChallengeProviderResponse)
- assert isinstance(responses[0].error, JsChallengeProviderRejectedRequest)
- assert responses[0].request is request_unsupported
- assert str(responses[0].error) == 'JS Challenge type "JsChallengeType.SIG" is not supported by example-provider'
-
- assert responses[1:] == [
- JsChallengeProviderResponse(
- request=request_supported,
- response=JsChallengeResponse(
- type=JsChallengeType.N,
- output=NChallengeOutput(results={'example-challenge': 'example-solution'}),
- ),
- ),
- JsChallengeProviderResponse(
- request=request_supported,
- response=JsChallengeResponse(
- type=JsChallengeType.N,
- output=NChallengeOutput(results={'example-challenge': 'example-solution'}),
- ),
- ),
- ]
-
- def test_provider_get_player(self, ie, logger):
- ie._load_player = lambda video_id, player_url, fatal: (video_id, player_url, fatal)
- provider = ExampleJCP(ie=ie, logger=logger, settings={})
- assert provider._get_player('video123', PLAYER_URL) == ('video123', PLAYER_URL, True)
-
- def test_provider_get_player_error(self, ie, logger):
- def raise_error(video_id, player_url, fatal):
- raise ExtractorError('Failed to load player')
-
- ie._load_player = raise_error
- provider = ExampleJCP(ie=ie, logger=logger, settings={})
- with pytest.raises(JsChallengeProviderError, match='Failed to load player for JS challenge'):
- provider._get_player('video123', PLAYER_URL)
-
- def test_require_class_end_with_suffix(self, ie, logger):
- class InvalidSuffix(JsChallengeProvider):
- PROVIDER_NAME = 'invalid-suffix'
-
- def _real_bulk_solve(self, requests):
- raise JsChallengeProviderRejectedRequest('Not implemented')
-
- def is_available(self) -> bool:
- return True
-
- provider = InvalidSuffix(ie=ie, logger=logger, settings={})
-
- with pytest.raises(AssertionError):
- provider.PROVIDER_KEY # noqa: B018
-
-
-def test_register_provider(ie):
-
- @register_provider
- class UnavailableProviderJCP(JsChallengeProvider):
- def is_available(self) -> bool:
- return False
-
- def _real_bulk_solve(self, requests):
- raise JsChallengeProviderRejectedRequest('Not implemented')
-
- assert _jsc_providers.value.get('UnavailableProvider') == UnavailableProviderJCP
- _jsc_providers.value.pop('UnavailableProvider')
-
-
-def test_register_preference(ie):
- before = len(_jsc_preferences.value)
-
- @register_preference(ExampleJCP)
- def unavailable_preference(*args, **kwargs):
- return 1
-
- assert len(_jsc_preferences.value) == before + 1
diff --git a/test/test_jsinterp.py b/test/test_jsinterp.py
deleted file mode 100644
index 38240229e..000000000
--- a/test/test_jsinterp.py
+++ /dev/null
@@ -1,576 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-import math
-
-from yt_dlp.jsinterp import (
- JS_Undefined,
- JSInterpreter,
- int_to_int32,
- js_number_to_string,
-)
-
-
-class NaN:
- pass
-
-
-class TestJSInterpreter(unittest.TestCase):
- def _test(self, jsi_or_code, expected, func='f', args=()):
- if isinstance(jsi_or_code, str):
- jsi_or_code = JSInterpreter(jsi_or_code)
- got = jsi_or_code.call_function(func, *args)
- if expected is NaN:
- self.assertTrue(math.isnan(got), f'{got} is not NaN')
- else:
- self.assertEqual(got, expected)
-
- def test_basic(self):
- jsi = JSInterpreter('function f(){;}')
- self.assertEqual(repr(jsi.extract_function('f')), 'F')
- self._test(jsi, None)
-
- self._test('function f(){return 42;}', 42)
- self._test('function f(){42}', None)
- self._test('var f = function(){return 42;}', 42)
-
- def test_add(self):
- self._test('function f(){return 42 + 7;}', 49)
- self._test('function f(){return 42 + undefined;}', NaN)
- self._test('function f(){return 42 + null;}', 42)
-
- def test_sub(self):
- self._test('function f(){return 42 - 7;}', 35)
- self._test('function f(){return 42 - undefined;}', NaN)
- self._test('function f(){return 42 - null;}', 42)
-
- def test_mul(self):
- self._test('function f(){return 42 * 7;}', 294)
- self._test('function f(){return 42 * undefined;}', NaN)
- self._test('function f(){return 42 * null;}', 0)
-
- def test_div(self):
- jsi = JSInterpreter('function f(a, b){return a / b;}')
- self._test(jsi, NaN, args=(0, 0))
- self._test(jsi, NaN, args=(JS_Undefined, 1))
- self._test(jsi, float('inf'), args=(2, 0))
- self._test(jsi, 0, args=(0, 3))
-
- def test_mod(self):
- self._test('function f(){return 42 % 7;}', 0)
- self._test('function f(){return 42 % 0;}', NaN)
- self._test('function f(){return 42 % undefined;}', NaN)
-
- def test_exp(self):
- self._test('function f(){return 42 ** 2;}', 1764)
- self._test('function f(){return 42 ** undefined;}', NaN)
- self._test('function f(){return 42 ** null;}', 1)
- self._test('function f(){return undefined ** 42;}', NaN)
-
- def test_calc(self):
- self._test('function f(a){return 2*a+1;}', 7, args=[3])
-
- def test_empty_return(self):
- self._test('function f(){return; y()}', None)
-
- def test_morespace(self):
- self._test('function f (a) { return 2 * a + 1 ; }', 7, args=[3])
- self._test('function f () { x = 2 ; return x; }', 2)
-
- def test_strange_chars(self):
- self._test('function $_xY1 ($_axY1) { var $_axY2 = $_axY1 + 1; return $_axY2; }',
- 21, args=[20], func='$_xY1')
-
- def test_operators(self):
- self._test('function f(){return 1 << 5;}', 32)
- self._test('function f(){return 2 ** 5}', 32)
- self._test('function f(){return 19 & 21;}', 17)
- self._test('function f(){return 11 >> 2;}', 2)
- self._test('function f(){return []? 2+3: 4;}', 5)
- self._test('function f(){return 1 == 2}', False)
- self._test('function f(){return 0 && 1 || 2;}', 2)
- self._test('function f(){return 0 ?? 42;}', 0)
- self._test('function f(){return "life, the universe and everything" < 42;}', False)
- self._test('function f(){return 0 - 7 * - 6;}', 42)
- self._test('function f(){return true << "5";}', 32)
- self._test('function f(){return true << true;}', 2)
- self._test('function f(){return "19" & "21.9";}', 17)
- self._test('function f(){return "19" & false;}', 0)
- self._test('function f(){return "11.0" >> "2.1";}', 2)
- self._test('function f(){return 5 ^ 9;}', 12)
- self._test('function f(){return 0.0 << NaN}', 0)
- self._test('function f(){return null << undefined}', 0)
- self._test('function f(){return -12616 ^ 5041}', -8951)
- self._test('function f(){return 21 << 4294967297}', 42)
-
- def test_string_concat(self):
- self._test('function f(){return "a" + "b";}', 'ab')
- self._test('function f(){let x = "a"; x += "b"; return x;}', 'ab')
- self._test('function f(){return "a" + 1;}', 'a1')
- self._test('function f(){let x = "a"; x += 1; return x;}', 'a1')
- self._test('function f(){return 2 + "b";}', '2b')
- self._test('function f(){let x = 2; x += "b"; return x;}', '2b')
-
- def test_array_access(self):
- self._test('function f(){var x = [1,2,3]; x[0] = 4; x[0] = 5; x[2.0] = 7; return x;}', [5, 2, 7])
-
- def test_parens(self):
- self._test('function f(){return (1) + (2) * ((( (( (((((3)))))) )) ));}', 7)
- self._test('function f(){return (1 + 2) * 3;}', 9)
-
- def test_quotes(self):
- self._test(R'function f(){return "a\"\\("}', R'a"\(')
-
- def test_assignments(self):
- self._test('function f(){var x = 20; x = 30 + 1; return x;}', 31)
- self._test('function f(){var x = 20; x += 30 + 1; return x;}', 51)
- self._test('function f(){var x = 20; x -= 30 + 1; return x;}', -11)
- self._test('function f(){var x = 2; var y = ["a", "b"]; y[x%y["length"]]="z"; return y}', ['z', 'b'])
-
- @unittest.skip('Not implemented')
- def test_comments(self):
- self._test('''
- function f() {
- var x = /* 1 + */ 2;
- var y = /* 30
- * 40 */ 50;
- return x + y;
- }
- ''', 52)
-
- self._test('''
- function f() {
- var x = "/*";
- var y = 1 /* comment */ + 2;
- return y;
- }
- ''', 3)
-
- def test_precedence(self):
- self._test('''
- function f() {
- var a = [10, 20, 30, 40, 50];
- var b = 6;
- a[0]=a[b%a.length];
- return a;
- }
- ''', [20, 20, 30, 40, 50])
-
- def test_builtins(self):
- self._test('function f() { return NaN }', NaN)
-
- def test_date(self):
- self._test('function f() { return new Date("Wednesday 31 December 1969 18:01:26 MDT") - 0; }', 86000)
-
- jsi = JSInterpreter('function f(dt) { return new Date(dt) - 0; }')
- self._test(jsi, 86000, args=['Wednesday 31 December 1969 18:01:26 MDT'])
- self._test(jsi, 86000, args=['12/31/1969 18:01:26 MDT']) # m/d/y
- self._test(jsi, 0, args=['1 January 1970 00:00:00 UTC'])
-
- def test_call(self):
- jsi = JSInterpreter('''
- function x() { return 2; }
- function y(a) { return x() + (a?a:0); }
- function z() { return y(3); }
- ''')
- self._test(jsi, 5, func='z')
- self._test(jsi, 2, func='y')
-
- def test_if(self):
- self._test('''
- function f() {
- let a = 9;
- if (0==0) {a++}
- return a
- }
- ''', 10)
-
- self._test('''
- function f() {
- if (0==0) {return 10}
- }
- ''', 10)
-
- self._test('''
- function f() {
- if (0!=0) {return 1}
- else {return 10}
- }
- ''', 10)
-
- """ # Unsupported
- self._test('''
- function f() {
- if (0!=0) {return 1}
- else if (1==0) {return 2}
- else {return 10}
- }
- ''', 10)
- """
-
- def test_for_loop(self):
- self._test('function f() { a=0; for (i=0; i-10; i++) {a++} return a }', 10)
-
- def test_switch(self):
- jsi = JSInterpreter('''
- function f(x) { switch(x){
- case 1:x+=1;
- case 2:x+=2;
- case 3:x+=3;break;
- case 4:x+=4;
- default:x=0;
- } return x }
- ''')
- self._test(jsi, 7, args=[1])
- self._test(jsi, 6, args=[3])
- self._test(jsi, 0, args=[5])
-
- def test_switch_default(self):
- jsi = JSInterpreter('''
- function f(x) { switch(x){
- case 2: x+=2;
- default: x-=1;
- case 5:
- case 6: x+=6;
- case 0: break;
- case 1: x+=1;
- } return x }
- ''')
- self._test(jsi, 2, args=[1])
- self._test(jsi, 11, args=[5])
- self._test(jsi, 14, args=[9])
-
- def test_try(self):
- self._test('function f() { try{return 10} catch(e){return 5} }', 10)
-
- def test_catch(self):
- self._test('function f() { try{throw 10} catch(e){return 5} }', 5)
-
- def test_finally(self):
- self._test('function f() { try{throw 10} finally {return 42} }', 42)
- self._test('function f() { try{throw 10} catch(e){return 5} finally {return 42} }', 42)
-
- def test_nested_try(self):
- self._test('''
- function f() {try {
- try{throw 10} finally {throw 42}
- } catch(e){return 5} }
- ''', 5)
-
- def test_for_loop_continue(self):
- self._test('function f() { a=0; for (i=0; i-10; i++) { continue; a++ } return a }', 0)
-
- def test_for_loop_break(self):
- self._test('function f() { a=0; for (i=0; i-10; i++) { break; a++ } return a }', 0)
-
- def test_for_loop_try(self):
- self._test('''
- function f() {
- for (i=0; i-10; i++) { try { if (i == 5) throw i} catch {return 10} finally {break} };
- return 42 }
- ''', 42)
-
- def test_literal_list(self):
- self._test('function f() { return [1, 2, "asdf", [5, 6, 7]][3] }', [5, 6, 7])
-
- def test_comma(self):
- self._test('function f() { a=5; a -= 1, a+=3; return a }', 7)
- self._test('function f() { a=5; return (a -= 1, a+=3, a); }', 7)
- self._test('function f() { return (l=[0,1,2,3], function(a, b){return a+b})((l[1], l[2]), l[3]) }', 5)
-
- def test_void(self):
- self._test('function f() { return void 42; }', None)
-
- def test_return_function(self):
- jsi = JSInterpreter('''
- function f() { return [1, function(){return 1}][1] }
- ''')
- self.assertEqual(jsi.call_function('f')([]), 1)
-
- def test_null(self):
- self._test('function f() { return null; }', None)
- self._test('function f() { return [null > 0, null < 0, null == 0, null === 0]; }',
- [False, False, False, False])
- self._test('function f() { return [null >= 0, null <= 0]; }', [True, True])
-
- def test_undefined(self):
- self._test('function f() { return undefined === undefined; }', True)
- self._test('function f() { return undefined; }', JS_Undefined)
- self._test('function f() {return undefined ?? 42; }', 42)
- self._test('function f() { let v; return v; }', JS_Undefined)
- self._test('function f() { let v; return v**0; }', 1)
- self._test('function f() { let v; return [v>42, v<=42, v&&42, 42&&v]; }',
- [False, False, JS_Undefined, JS_Undefined])
-
- self._test('''
- function f() { return [
- undefined === undefined,
- undefined == undefined,
- undefined == null,
- undefined < undefined,
- undefined > undefined,
- undefined === 0,
- undefined == 0,
- undefined < 0,
- undefined > 0,
- undefined >= 0,
- undefined <= 0,
- undefined > null,
- undefined < null,
- undefined === null
- ]; }
- ''', list(map(bool, (1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))))
-
- jsi = JSInterpreter('''
- function f() { let v; return [42+v, v+42, v**42, 42**v, 0**v]; }
- ''')
- for y in jsi.call_function('f'):
- self.assertTrue(math.isnan(y))
-
- def test_object(self):
- self._test('function f() { return {}; }', {})
- self._test('function f() { let a = {m1: 42, m2: 0 }; return [a["m1"], a.m2]; }', [42, 0])
- self._test('function f() { let a; return a?.qq; }', JS_Undefined)
- self._test('function f() { let a = {m1: 42, m2: 0 }; return a?.qq; }', JS_Undefined)
- self._test('function f() { let a = {"1": 123}; return a[1]; }', 123)
-
- def test_regex(self):
- self._test('function f() { let a=/,,[/,913,/](,)}/; }', None)
- self._test('function f() { let a=/,,[/,913,/](,)}/; return a; }', R'/,,[/,913,/](,)}/0')
-
- R''' # We are not compiling regex
- jsi = JSInterpreter('function f() { let a=/,,[/,913,/](,)}/; return a; }')
- self.assertIsInstance(jsi.call_function('f'), re.Pattern)
-
- jsi = JSInterpreter('function f() { let a=/,,[/,913,/](,)}/i; return a; }')
- self.assertEqual(jsi.call_function('f').flags & re.I, re.I)
-
- jsi = JSInterpreter(R'function f() { let a=/,][}",],()}(\[)/; return a; }')
- self.assertEqual(jsi.call_function('f').pattern, r',][}",],()}(\[)')
-
- jsi = JSInterpreter(R'function f() { let a=[/[)\\]/]; return a[0]; }')
- self.assertEqual(jsi.call_function('f').pattern, r'[)\\]')
- '''
-
- @unittest.skip('Not implemented')
- def test_replace(self):
- self._test('function f() { let a="data-name".replace("data-", ""); return a }',
- 'name')
- self._test('function f() { let a="data-name".replace(new RegExp("^.+-"), ""); return a; }',
- 'name')
- self._test('function f() { let a="data-name".replace(/^.+-/, ""); return a; }',
- 'name')
- self._test('function f() { let a="data-name".replace(/a/g, "o"); return a; }',
- 'doto-nome')
- self._test('function f() { let a="data-name".replaceAll("a", "o"); return a; }',
- 'doto-nome')
-
- def test_char_code_at(self):
- jsi = JSInterpreter('function f(i){return "test".charCodeAt(i)}')
- self._test(jsi, 116, args=[0])
- self._test(jsi, 101, args=[1])
- self._test(jsi, 115, args=[2])
- self._test(jsi, 116, args=[3])
- self._test(jsi, None, args=[4])
- self._test(jsi, 116, args=['not_a_number'])
-
- def test_bitwise_operators_overflow(self):
- self._test('function f(){return -524999584 << 5}', 379882496)
- self._test('function f(){return 1236566549 << 5}', 915423904)
-
- def test_bitwise_operators_typecast(self):
- self._test('function f(){return null << 5}', 0)
- self._test('function f(){return undefined >> 5}', 0)
- self._test('function f(){return 42 << NaN}', 42)
-
- def test_negative(self):
- self._test('function f(){return 2 * -2.0 ;}', -4)
- self._test('function f(){return 2 - - -2 ;}', 0)
- self._test('function f(){return 2 - - - -2 ;}', 4)
- self._test('function f(){return 2 - + + - -2;}', 0)
- self._test('function f(){return 2 + - + - -2;}', 0)
-
- @unittest.skip('Not implemented')
- def test_packed(self):
- jsi = JSInterpreter('''function f(p,a,c,k,e,d){while(c--)if(k[c])p=p.replace(new RegExp('\\b'+c.toString(a)+'\\b','g'),k[c]);return p}''')
- self.assertEqual(jsi.call_function('f', '''h 7=g("1j");7.7h({7g:[{33:"w://7f-7e-7d-7c.v.7b/7a/79/78/77/76.74?t=73&s=2s&e=72&f=2t&71=70.0.0.1&6z=6y&6x=6w"}],6v:"w://32.v.u/6u.31",16:"r%",15:"r%",6t:"6s",6r:"",6q:"l",6p:"l",6o:"6n",6m:\'6l\',6k:"6j",9:[{33:"/2u?b=6i&n=50&6h=w://32.v.u/6g.31",6f:"6e"}],1y:{6d:1,6c:\'#6b\',6a:\'#69\',68:"67",66:30,65:r,},"64":{63:"%62 2m%m%61%5z%5y%5x.u%5w%5v%5u.2y%22 2k%m%1o%22 5t%m%1o%22 5s%m%1o%22 2j%m%5r%22 16%m%5q%22 15%m%5p%22 5o%2z%5n%5m%2z",5l:"w://v.u/d/1k/5k.2y",5j:[]},\'5i\':{"5h":"5g"},5f:"5e",5d:"w://v.u",5c:{},5b:l,1x:[0.25,0.50,0.75,1,1.25,1.5,2]});h 1m,1n,5a;h 59=0,58=0;h 7=g("1j");h 2x=0,57=0,56=0;$.55({54:{\'53-52\':\'2i-51\'}});7.j(\'4z\',6(x){c(5>0&&x.1l>=5&&1n!=1){1n=1;$(\'q.4y\').4x(\'4w\')}});7.j(\'13\',6(x){2x=x.1l});7.j(\'2g\',6(x){2w(x)});7.j(\'4v\',6(){$(\'q.2v\').4u()});6 2w(x){$(\'q.2v\').4t();c(1m)19;1m=1;17=0;c(4s.4r===l){17=1}$.4q(\'/2u?b=4p&2l=1k&4o=2t-4n-4m-2s-4l&4k=&4j=&4i=&17=\'+17,6(2r){$(\'#4h\').4g(2r)});$(\'.3-8-4f-4e:4d("4c")\').2h(6(e){2q();g().4b(0);g().4a(l)});6 2q(){h $14=$(" ").2p({1l:"49",16:"r%",15:"r%",48:0,2n:0,2o:47,46:"45(10%, 10%, 10%, 0.4)","44-43":"42"});$("<41 />").2p({16:"60%",15:"60%",2o:40,"3z-2n":"3y"}).3x({\'2m\':\'/?b=3w&2l=1k\',\'2k\':\'0\',\'2j\':\'2i\'}).2f($14);$14.2h(6(){$(3v).3u();g().2g()});$14.2f($(\'#1j\'))}g().13(0);}6 3t(){h 9=7.1b(2e);2d.2c(9);c(9.n>1){1r(i=0;i<9.n;i++){c(9[i].1a==2e){2d.2c(\'!!=\'+i);7.1p(i)}}}}7.j(\'3s\',6(){g().1h("/2a/3r.29","3q 10 28",6(){g().13(g().27()+10)},"2b");$("q[26=2b]").23().21(\'.3-20-1z\');g().1h("/2a/3p.29","3o 10 28",6(){h 12=g().27()-10;c(12<0)12=0;g().13(12)},"24");$("q[26=24]").23().21(\'.3-20-1z\');});6 1i(){}7.j(\'3n\',6(){1i()});7.j(\'3m\',6(){1i()});7.j("k",6(y){h 9=7.1b();c(9.n<2)19;$(\'.3-8-3l-3k\').3j(6(){$(\'#3-8-a-k\').1e(\'3-8-a-z\');$(\'.3-a-k\').p(\'o-1f\',\'11\')});7.1h("/3i/3h.3g","3f 3e",6(){$(\'.3-1w\').3d(\'3-8-1v\');$(\'.3-8-1y, .3-8-1x\').p(\'o-1g\',\'11\');c($(\'.3-1w\').3c(\'3-8-1v\')){$(\'.3-a-k\').p(\'o-1g\',\'l\');$(\'.3-a-k\').p(\'o-1f\',\'l\');$(\'.3-8-a\').1e(\'3-8-a-z\');$(\'.3-8-a:1u\').3b(\'3-8-a-z\')}3a{$(\'.3-a-k\').p(\'o-1g\',\'11\');$(\'.3-a-k\').p(\'o-1f\',\'11\');$(\'.3-8-a:1u\').1e(\'3-8-a-z\')}},"39");7.j("38",6(y){1d.37(\'1c\',y.9[y.36].1a)});c(1d.1t(\'1c\')){35("1s(1d.1t(\'1c\'));",34)}});h 18;6 1s(1q){h 9=7.1b();c(9.n>1){1r(i=0;i<9.n;i++){c(9[i].1a==1q){c(i==18){19}18=i;7.1p(i)}}}}',36,270,'|||jw|||function|player|settings|tracks|submenu||if||||jwplayer|var||on|audioTracks|true|3D|length|aria|attr|div|100|||sx|filemoon|https||event|active||false|tt|seek|dd|height|width|adb|current_audio|return|name|getAudioTracks|default_audio|localStorage|removeClass|expanded|checked|addButton|callMeMaybe|vplayer|0fxcyc2ajhp1|position|vvplay|vvad|220|setCurrentAudioTrack|audio_name|for|audio_set|getItem|last|open|controls|playbackRates|captions|rewind|icon|insertAfter||detach|ff00||button|getPosition|sec|png|player8|ff11|log|console|track_name|appendTo|play|click|no|scrolling|frameborder|file_code|src|top|zIndex|css|showCCform|data|1662367683|383371|dl|video_ad|doPlay|prevt|mp4|3E||jpg|thumbs|file|300|setTimeout|currentTrack|setItem|audioTrackChanged|dualSound|else|addClass|hasClass|toggleClass|Track|Audio|svg|dualy|images|mousedown|buttons|topbar|playAttemptFailed|beforePlay|Rewind|fr|Forward|ff|ready|set_audio_track|remove|this|upload_srt|prop|50px|margin|1000001|iframe|center|align|text|rgba|background|1000000|left|absolute|pause|setCurrentCaptions|Upload|contains|item|content|html|fviews|referer|prem|embed|3e57249ef633e0d03bf76ceb8d8a4b65|216|83|hash|view|get|TokenZir|window|hide|show|complete|slow|fadeIn|video_ad_fadein|time||cache|Cache|Content|headers|ajaxSetup|v2done|tott|vastdone2|vastdone1|vvbefore|playbackRateControls|cast|aboutlink|FileMoon|abouttext|UHD|1870|qualityLabels|sites|GNOME_POWER|link|2Fiframe|3C|allowfullscreen|22360|22640|22no|marginheight|marginwidth|2FGNOME_POWER|2F0fxcyc2ajhp1|2Fe|2Ffilemoon|2F|3A||22https|3Ciframe|code|sharing|fontOpacity|backgroundOpacity|Tahoma|fontFamily|303030|backgroundColor|FFFFFF|color|userFontScale|thumbnails|kind|0fxcyc2ajhp10000|url|get_slides|start|startparam|none|preload|html5|primary|hlshtml|androidhls|duration|uniform|stretching|0fxcyc2ajhp1_xt|image|2048|sp|6871|asn|127|srv|43200|_g3XlBcu2lmD9oDexD2NLWSmah2Nu3XcDrl93m9PwXY|m3u8||master|0fxcyc2ajhp1_x|00076|01|hls2|to|s01|delivery|storage|moon|sources|setup'''.split('|'))) # noqa: SIM905
-
- def test_join(self):
- test_input = list('test')
- tests = [
- 'function f(a, b){return a.join(b)}',
- 'function f(a, b){return Array.prototype.join.call(a, b)}',
- 'function f(a, b){return Array.prototype.join.apply(a, [b])}',
- ]
- for test in tests:
- jsi = JSInterpreter(test)
- self._test(jsi, 'test', args=[test_input, ''])
- self._test(jsi, 't-e-s-t', args=[test_input, '-'])
- self._test(jsi, '', args=[[], '-'])
-
- def test_split(self):
- test_result = list('test')
- tests = [
- 'function f(a, b){return a.split(b)}',
- 'function f(a, b){return a["split"](b)}',
- 'function f(a, b){let x = ["split"]; return a[x[0]](b)}',
- 'function f(a, b){return String.prototype.split.call(a, b)}',
- 'function f(a, b){return String.prototype.split.apply(a, [b])}',
- ]
- for test in tests:
- jsi = JSInterpreter(test)
- self._test(jsi, test_result, args=['test', ''])
- self._test(jsi, test_result, args=['t-e-s-t', '-'])
- self._test(jsi, [''], args=['', '-'])
- self._test(jsi, [], args=['', ''])
-
- def test_slice(self):
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice()}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0)}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(5)}', [5, 6, 7, 8])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(99)}', [])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-2)}', [7, 8])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-99)}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0, 0)}', [])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(1, 0)}', [])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0, 1)}', [0])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(3, 6)}', [3, 4, 5])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(1, -1)}', [1, 2, 3, 4, 5, 6, 7])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-1, 1)}', [])
- self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-3, -1)}', [6, 7])
- self._test('function f(){return "012345678".slice()}', '012345678')
- self._test('function f(){return "012345678".slice(0)}', '012345678')
- self._test('function f(){return "012345678".slice(5)}', '5678')
- self._test('function f(){return "012345678".slice(99)}', '')
- self._test('function f(){return "012345678".slice(-2)}', '78')
- self._test('function f(){return "012345678".slice(-99)}', '012345678')
- self._test('function f(){return "012345678".slice(0, 0)}', '')
- self._test('function f(){return "012345678".slice(1, 0)}', '')
- self._test('function f(){return "012345678".slice(0, 1)}', '0')
- self._test('function f(){return "012345678".slice(3, 6)}', '345')
- self._test('function f(){return "012345678".slice(1, -1)}', '1234567')
- self._test('function f(){return "012345678".slice(-1, 1)}', '')
- self._test('function f(){return "012345678".slice(-3, -1)}', '67')
-
- def test_splice(self):
- self._test('function f(){var T = ["0", "1", "2"]; T["splice"](2, 1, "0")[0]; return T }', ['0', '1', '0'])
-
- def test_int_to_int32(self):
- for inp, exp in [
- (0, 0),
- (1, 1),
- (-1, -1),
- (-8951, -8951),
- (2147483647, 2147483647),
- (2147483648, -2147483648),
- (2147483649, -2147483647),
- (-2147483649, 2147483647),
- (-2147483648, -2147483648),
- (-16799986688, 379882496),
- (39570129568, 915423904),
- ]:
- assert int_to_int32(inp) == exp
-
- def test_js_number_to_string(self):
- for test, radix, expected in [
- (0, None, '0'),
- (-0, None, '0'),
- (0.0, None, '0'),
- (-0.0, None, '0'),
- (math.nan, None, 'NaN'),
- (-math.nan, None, 'NaN'),
- (math.inf, None, 'Infinity'),
- (-math.inf, None, '-Infinity'),
- (10 ** 21.5, 8, '526665530627250154000000'),
- (6, 2, '110'),
- (254, 16, 'fe'),
- (-10, 2, '-1010'),
- (-0xff, 2, '-11111111'),
- (0.1 + 0.2, 16, '0.4cccccccccccd'),
- (1234.1234, 10, '1234.1234'),
- # (1000000000000000128, 10, '1000000000000000100')
- ]:
- assert js_number_to_string(test, radix) == expected
-
- def test_extract_function(self):
- jsi = JSInterpreter('function a(b) { return b + 1; }')
- func = jsi.extract_function('a')
- self.assertEqual(func([2]), 3)
-
- def test_extract_function_with_global_stack(self):
- jsi = JSInterpreter('function c(d) { return d + e + f + g; }')
- func = jsi.extract_function('c', {'e': 10}, {'f': 100, 'g': 1000})
- self.assertEqual(func([1]), 1111)
-
- def test_extract_object(self):
- jsi = JSInterpreter('var a={};a.xy={};var xy;var zxy={};xy={z:function(){return "abc"}};')
- self.assertTrue('z' in jsi.extract_object('xy', None))
-
- def test_increment_decrement(self):
- self._test('function f() { var x = 1; return ++x; }', 2)
- self._test('function f() { var x = 1; return x++; }', 1)
- self._test('function f() { var x = 1; x--; return x }', 0)
- self._test('function f() { var y; var x = 1; x++, --x, x--, x--, y="z", "abc", x++; return --x }', -1)
- self._test('function f() { var a = "test--"; return a; }', 'test--')
- self._test('function f() { var b = 1; var a = "b--"; return a; }', 'b--')
-
- def test_nested_function_scoping(self):
- self._test(R'''
- function f() {
- var g = function() {
- var P = 2;
- return P;
- };
- var P = 1;
- g();
- return P;
- }
- ''', 1)
- self._test(R'''
- function f() {
- var x = function() {
- for (var w = 1, M = []; w < 2; w++) switch (w) {
- case 1:
- M.push("a");
- case 2:
- M.push("b");
- }
- return M
- };
- var w = "c";
- var M = "d";
- var y = x();
- y.push(w);
- y.push(M);
- return y;
- }
- ''', ['a', 'b', 'c', 'd'])
- self._test(R'''
- function f() {
- var P, Q;
- var z = 100;
- var g = function() {
- var P, Q; P = 2; Q = 15;
- z = 0;
- return P+Q;
- };
- P = 1; Q = 10;
- var x = g(), y = 3;
- return P+Q+x+y+z;
- }
- ''', 31)
-
- def test_undefined_varnames(self):
- jsi = JSInterpreter('function f(){ var a; return [a, b]; }')
- self._test(jsi, [JS_Undefined, JS_Undefined])
- self.assertEqual(jsi._undefined_varnames, {'b'})
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_netrc.py b/test/test_netrc.py
deleted file mode 100644
index 1e0f4ee3b..000000000
--- a/test/test_netrc.py
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-from yt_dlp.extractor import gen_extractor_classes
-from yt_dlp.extractor.common import InfoExtractor
-
-NO_LOGIN = InfoExtractor._perform_login
-
-
-class TestNetRc(unittest.TestCase):
- def test_netrc_present(self):
- for ie in gen_extractor_classes():
- if ie._perform_login is NO_LOGIN:
- continue
- self.assertTrue(
- ie._NETRC_MACHINE,
- f'Extractor {ie.IE_NAME} supports login, but is missing a _NETRC_MACHINE property')
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_networking.py b/test/test_networking.py
deleted file mode 100644
index 067108905..000000000
--- a/test/test_networking.py
+++ /dev/null
@@ -1,2220 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-from unittest.mock import MagicMock
-
-import pytest
-
-from yt_dlp.networking.common import Features, DEFAULT_TIMEOUT
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-import gzip
-import http.client
-import http.cookiejar
-import http.server
-import io
-import logging
-import pathlib
-import random
-import ssl
-import tempfile
-import threading
-import time
-import urllib.request
-import warnings
-import zlib
-from email.message import Message
-from http.cookiejar import CookieJar
-
-from test.helper import (
- FakeYDL,
- http_server_port,
- validate_and_send,
- verify_address_availability,
-)
-from yt_dlp.cookies import YoutubeDLCookieJar
-from yt_dlp.dependencies import brotli, curl_cffi, requests, urllib3
-from yt_dlp.networking import (
- HEADRequest,
- PATCHRequest,
- PUTRequest,
- Request,
- RequestDirector,
- RequestHandler,
- Response,
-)
-from yt_dlp.networking._urllib import UrllibRH
-from yt_dlp.networking.exceptions import (
- CertificateVerifyError,
- HTTPError,
- IncompleteRead,
- NoSupportingHandlers,
- ProxyError,
- RequestError,
- SSLError,
- TransportError,
- UnsupportedRequest,
-)
-from yt_dlp.networking.impersonate import (
- ImpersonateRequestHandler,
- ImpersonateTarget,
-)
-from yt_dlp.utils import YoutubeDLError
-from yt_dlp.utils._utils import _YDLLogger as FakeLogger
-from yt_dlp.utils.networking import HTTPHeaderDict, std_headers
-
-TEST_DIR = os.path.dirname(os.path.abspath(__file__))
-
-
-class HTTPTestRequestHandler(http.server.BaseHTTPRequestHandler):
- protocol_version = 'HTTP/1.1'
- default_request_version = 'HTTP/1.1'
-
- def log_message(self, format, *args):
- pass
-
- def _headers(self):
- payload = str(self.headers).encode()
- self.send_response(200)
- self.send_header('Content-Type', 'application/json')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
-
- def _redirect(self):
- self.send_response(int(self.path[len('/redirect_'):]))
- self.send_header('Location', '/method')
- self.send_header('Content-Length', '0')
- self.end_headers()
-
- def _method(self, method, payload=None):
- self.send_response(200)
- self.send_header('Content-Length', str(len(payload or '')))
- self.send_header('Method', method)
- self.end_headers()
- if payload:
- self.wfile.write(payload)
-
- def _status(self, status):
- payload = f'{status} NOT FOUND'.encode()
- self.send_response(int(status))
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
-
- def _read_data(self):
- if 'Content-Length' in self.headers:
- return self.rfile.read(int(self.headers['Content-Length']))
- else:
- return b''
-
- def do_POST(self):
- data = self._read_data() + str(self.headers).encode()
- if self.path.startswith('/redirect_'):
- self._redirect()
- elif self.path.startswith('/method'):
- self._method('POST', data)
- elif self.path.startswith('/headers'):
- self._headers()
- else:
- self._status(404)
-
- def do_HEAD(self):
- if self.path.startswith('/redirect_'):
- self._redirect()
- elif self.path.startswith('/method'):
- self._method('HEAD')
- else:
- self._status(404)
-
- def do_PUT(self):
- data = self._read_data() + str(self.headers).encode()
- if self.path.startswith('/redirect_'):
- self._redirect()
- elif self.path.startswith('/method'):
- self._method('PUT', data)
- else:
- self._status(404)
-
- def do_GET(self):
- if self.path == '/video.html':
- payload = b' '
- self.send_response(200)
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
- elif self.path == '/vid.mp4':
- payload = b'\x00\x00\x00\x00\x20\x66\x74[video]'
- self.send_response(200)
- self.send_header('Content-Type', 'video/mp4')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
- elif self.path == '/%E4%B8%AD%E6%96%87.html':
- payload = b' '
- self.send_response(200)
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
- elif self.path == '/%c7%9f':
- payload = b' '
- self.send_response(200)
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
- elif self.path.startswith('/redirect_loop'):
- self.send_response(301)
- self.send_header('Location', self.path)
- self.send_header('Content-Length', '0')
- self.end_headers()
- elif self.path == '/redirect_dotsegments':
- self.send_response(301)
- # redirect to /headers but with dot segments before
- self.send_header('Location', '/a/b/./../../headers')
- self.send_header('Content-Length', '0')
- self.end_headers()
- elif self.path == '/redirect_dotsegments_absolute':
- self.send_response(301)
- # redirect to /headers but with dot segments before - absolute url
- self.send_header('Location', f'http://127.0.0.1:{http_server_port(self.server)}/a/b/./../../headers')
- self.send_header('Content-Length', '0')
- self.end_headers()
- elif self.path.startswith('/redirect_'):
- self._redirect()
- elif self.path.startswith('/method'):
- self._method('GET', str(self.headers).encode())
- elif self.path.startswith('/headers'):
- self._headers()
- elif self.path.startswith('/308-to-headers'):
- self.send_response(308)
- # redirect to "localhost" for testing cookie redirection handling
- self.send_header('Location', f'http://localhost:{self.connection.getsockname()[1]}/headers')
- self.send_header('Content-Length', '0')
- self.end_headers()
- elif self.path == '/trailing_garbage':
- payload = b' '
- self.send_response(200)
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.send_header('Content-Encoding', 'gzip')
- buf = io.BytesIO()
- with gzip.GzipFile(fileobj=buf, mode='wb') as f:
- f.write(payload)
- compressed = buf.getvalue() + b'trailing garbage'
- self.send_header('Content-Length', str(len(compressed)))
- self.end_headers()
- self.wfile.write(compressed)
- elif self.path == '/302-non-ascii-redirect':
- new_url = f'http://127.0.0.1:{http_server_port(self.server)}/中文.html'
- self.send_response(301)
- self.send_header('Location', new_url)
- self.send_header('Content-Length', '0')
- self.end_headers()
- elif self.path == '/content-encoding':
- encodings = self.headers.get('ytdl-encoding', '')
- payload = b' '
- for encoding in filter(None, (e.strip() for e in encodings.split(','))):
- if encoding == 'br' and brotli:
- payload = brotli.compress(payload)
- elif encoding == 'gzip':
- payload = gzip.compress(payload, mtime=0)
- elif encoding == 'deflate':
- payload = zlib.compress(payload)
- elif encoding == 'unsupported':
- payload = b'raw'
- break
- else:
- self._status(415)
- return
- self.send_response(200)
- self.send_header('Content-Encoding', encodings)
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
- elif self.path.startswith('/gen_'):
- payload = b''
- self.send_response(int(self.path[len('/gen_'):]))
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
- elif self.path.startswith('/incompleteread'):
- payload = b''
- self.send_response(200)
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.send_header('Content-Length', '234234')
- self.end_headers()
- self.wfile.write(payload)
- self.finish()
- elif self.path.startswith('/timeout_'):
- time.sleep(int(self.path[len('/timeout_'):]))
- self._headers()
- elif self.path == '/source_address':
- payload = str(self.client_address[0]).encode()
- self.send_response(200)
- self.send_header('Content-Type', 'text/html; charset=utf-8')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
- self.finish()
- elif self.path == '/get_cookie':
- self.send_response(200)
- self.send_header('Set-Cookie', 'test=ytdlp; path=/')
- self.end_headers()
- self.finish()
- else:
- self._status(404)
-
- def send_header(self, keyword, value):
- """
- Forcibly allow HTTP server to send non percent-encoded non-ASCII characters in headers.
- This is against what is defined in RFC 3986, however we need to test we support this
- since some sites incorrectly do this.
- """
- if keyword.lower() == 'connection':
- return super().send_header(keyword, value)
-
- if not hasattr(self, '_headers_buffer'):
- self._headers_buffer = []
-
- self._headers_buffer.append(f'{keyword}: {value}\r\n'.encode())
-
-
-class TestRequestHandlerBase:
- @classmethod
- def setup_class(cls):
- cls.http_httpd = http.server.ThreadingHTTPServer(
- ('127.0.0.1', 0), HTTPTestRequestHandler)
- cls.http_port = http_server_port(cls.http_httpd)
- cls.http_server_thread = threading.Thread(target=cls.http_httpd.serve_forever)
- # FIXME: we should probably stop the http server thread after each test
- # See: https://github.com/yt-dlp/yt-dlp/pull/7094#discussion_r1199746041
- cls.http_server_thread.daemon = True
- cls.http_server_thread.start()
-
- # HTTPS server
- certfn = os.path.join(TEST_DIR, 'testcert.pem')
- cls.https_httpd = http.server.ThreadingHTTPServer(
- ('127.0.0.1', 0), HTTPTestRequestHandler)
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.load_cert_chain(certfn, None)
- cls.https_httpd.socket = sslctx.wrap_socket(cls.https_httpd.socket, server_side=True)
- cls.https_port = http_server_port(cls.https_httpd)
- cls.https_server_thread = threading.Thread(target=cls.https_httpd.serve_forever)
- cls.https_server_thread.daemon = True
- cls.https_server_thread.start()
-
-
-@pytest.mark.parametrize('handler', ['Urllib', 'Requests', 'CurlCFFI'], indirect=True)
-@pytest.mark.handler_flaky('CurlCFFI', reason='segfaults')
-class TestHTTPRequestHandler(TestRequestHandlerBase):
-
- def test_verify_cert(self, handler):
- with handler() as rh:
- with pytest.raises(CertificateVerifyError):
- validate_and_send(rh, Request(f'https://127.0.0.1:{self.https_port}/headers'))
-
- with handler(verify=False) as rh:
- r = validate_and_send(rh, Request(f'https://127.0.0.1:{self.https_port}/headers'))
- assert r.status == 200
- r.close()
-
- def test_ssl_error(self, handler):
- # HTTPS server with too old TLS version
- # XXX: is there a better way to test this than to create a new server?
- https_httpd = http.server.ThreadingHTTPServer(
- ('127.0.0.1', 0), HTTPTestRequestHandler)
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- https_httpd.socket = sslctx.wrap_socket(https_httpd.socket, server_side=True)
- https_port = http_server_port(https_httpd)
- https_server_thread = threading.Thread(target=https_httpd.serve_forever)
- https_server_thread.daemon = True
- https_server_thread.start()
-
- with handler(verify=False) as rh:
- with pytest.raises(SSLError, match=r'(?i)ssl(?:v3|/tls).alert.handshake.failure') as exc_info:
- validate_and_send(rh, Request(f'https://127.0.0.1:{https_port}/headers'))
- assert not issubclass(exc_info.type, CertificateVerifyError)
-
- @pytest.mark.skip_handler('CurlCFFI', 'legacy_ssl ignored by CurlCFFI')
- def test_legacy_ssl_extension(self, handler):
- # HTTPS server with old ciphers
- # XXX: is there a better way to test this than to create a new server?
- https_httpd = http.server.ThreadingHTTPServer(
- ('127.0.0.1', 0), HTTPTestRequestHandler)
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.maximum_version = ssl.TLSVersion.TLSv1_2
- sslctx.set_ciphers('SHA1:AESCCM:aDSS:eNULL:aNULL')
- sslctx.load_cert_chain(os.path.join(TEST_DIR, 'testcert.pem'), None)
- https_httpd.socket = sslctx.wrap_socket(https_httpd.socket, server_side=True)
- https_port = http_server_port(https_httpd)
- https_server_thread = threading.Thread(target=https_httpd.serve_forever)
- https_server_thread.daemon = True
- https_server_thread.start()
-
- with handler(verify=False) as rh:
- res = validate_and_send(rh, Request(f'https://127.0.0.1:{https_port}/headers', extensions={'legacy_ssl': True}))
- assert res.status == 200
- res.close()
-
- # Ensure only applies to request extension
- with pytest.raises(SSLError):
- validate_and_send(rh, Request(f'https://127.0.0.1:{https_port}/headers'))
-
- @pytest.mark.skip_handler('CurlCFFI', 'legacy_ssl ignored by CurlCFFI')
- def test_legacy_ssl_support(self, handler):
- # HTTPS server with old ciphers
- # XXX: is there a better way to test this than to create a new server?
- https_httpd = http.server.ThreadingHTTPServer(
- ('127.0.0.1', 0), HTTPTestRequestHandler)
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.maximum_version = ssl.TLSVersion.TLSv1_2
- sslctx.set_ciphers('SHA1:AESCCM:aDSS:eNULL:aNULL')
- sslctx.load_cert_chain(os.path.join(TEST_DIR, 'testcert.pem'), None)
- https_httpd.socket = sslctx.wrap_socket(https_httpd.socket, server_side=True)
- https_port = http_server_port(https_httpd)
- https_server_thread = threading.Thread(target=https_httpd.serve_forever)
- https_server_thread.daemon = True
- https_server_thread.start()
-
- with handler(verify=False, legacy_ssl_support=True) as rh:
- res = validate_and_send(rh, Request(f'https://127.0.0.1:{https_port}/headers'))
- assert res.status == 200
- res.close()
-
- def test_percent_encode(self, handler):
- with handler() as rh:
- # Unicode characters should be encoded with uppercase percent-encoding
- res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/中文.html'))
- assert res.status == 200
- res.close()
- # don't normalize existing percent encodings
- res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/%c7%9f'))
- assert res.status == 200
- res.close()
-
- @pytest.mark.parametrize('path', [
- '/a/b/./../../headers',
- '/redirect_dotsegments',
- # https://github.com/yt-dlp/yt-dlp/issues/9020
- '/redirect_dotsegments_absolute',
- ])
- def test_remove_dot_segments(self, handler, path):
- with handler(verbose=True) as rh:
- # This isn't a comprehensive test,
- # but it should be enough to check whether the handler is removing dot segments in required scenarios
- res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}{path}'))
- assert res.status == 200
- assert res.url == f'http://127.0.0.1:{self.http_port}/headers'
- res.close()
-
- @pytest.mark.skip_handler('CurlCFFI', 'not supported by curl-cffi (non-standard)')
- def test_unicode_path_redirection(self, handler):
- with handler() as rh:
- r = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/302-non-ascii-redirect'))
- assert r.url == f'http://127.0.0.1:{self.http_port}/%E4%B8%AD%E6%96%87.html'
- r.close()
-
- def test_raise_http_error(self, handler):
- with handler() as rh:
- for bad_status in (400, 500, 599, 302):
- with pytest.raises(HTTPError):
- validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_{bad_status}'))
-
- # Should not raise an error
- validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_200')).close()
-
- def test_response_url(self, handler):
- with handler() as rh:
- # Response url should be that of the last url in redirect chain
- res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/redirect_301'))
- assert res.url == f'http://127.0.0.1:{self.http_port}/method'
- res.close()
- res2 = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_200'))
- assert res2.url == f'http://127.0.0.1:{self.http_port}/gen_200'
- res2.close()
-
- # Covers some basic cases we expect some level of consistency between request handlers for
- @pytest.mark.parametrize('redirect_status,method,expected', [
- # A 303 must either use GET or HEAD for subsequent request
- (303, 'POST', ('', 'GET', False)),
- (303, 'HEAD', ('', 'HEAD', False)),
-
- # 301 and 302 turn POST only into a GET
- (301, 'POST', ('', 'GET', False)),
- (301, 'HEAD', ('', 'HEAD', False)),
- (302, 'POST', ('', 'GET', False)),
- (302, 'HEAD', ('', 'HEAD', False)),
-
- # 307 and 308 should not change method
- (307, 'POST', ('testdata', 'POST', True)),
- (308, 'POST', ('testdata', 'POST', True)),
- (307, 'HEAD', ('', 'HEAD', False)),
- (308, 'HEAD', ('', 'HEAD', False)),
- ])
- def test_redirect(self, handler, redirect_status, method, expected):
- with handler() as rh:
- data = b'testdata' if method == 'POST' else None
- headers = {}
- if data is not None:
- headers['Content-Type'] = 'application/test'
- res = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/redirect_{redirect_status}', method=method, data=data,
- headers=headers))
-
- headers = b''
- data_recv = b''
- if data is not None:
- data_recv += res.read(len(data))
- if data_recv != data:
- headers += data_recv
- data_recv = b''
-
- headers += res.read()
-
- assert expected[0] == data_recv.decode()
- assert expected[1] == res.headers.get('method')
- assert expected[2] == ('content-length' in headers.decode().lower())
-
- def test_request_cookie_header(self, handler):
- # We should accept a Cookie header being passed as in normal headers and handle it appropriately.
- with handler() as rh:
- # Specified Cookie header should be used
- res = validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/headers',
- headers={'Cookie': 'test=test'})).read().decode()
- assert 'cookie: test=test' in res.lower()
-
- # Specified Cookie header should be removed on any redirect
- res = validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/308-to-headers',
- headers={'Cookie': 'test=test2'})).read().decode()
- assert 'cookie: test=test2' not in res.lower()
-
- # Specified Cookie header should override global cookiejar for that request
- # Whether cookies from the cookiejar is applied on the redirect is considered undefined for now
- cookiejar = YoutubeDLCookieJar()
- cookiejar.set_cookie(http.cookiejar.Cookie(
- version=0, name='test', value='ytdlp', port=None, port_specified=False,
- domain='127.0.0.1', domain_specified=True, domain_initial_dot=False, path='/',
- path_specified=True, secure=False, expires=None, discard=False, comment=None,
- comment_url=None, rest={}))
-
- with handler(cookiejar=cookiejar) as rh:
- data = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/headers', headers={'cookie': 'test=test3'})).read()
- assert b'cookie: test=ytdlp' not in data.lower()
- assert b'cookie: test=test3' in data.lower()
-
- def test_redirect_loop(self, handler):
- with handler() as rh:
- with pytest.raises(HTTPError, match='redirect loop'):
- validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/redirect_loop'))
-
- def test_incompleteread(self, handler):
- with handler(timeout=2) as rh:
- with pytest.raises(IncompleteRead, match='13 bytes read, 234221 more expected'):
- validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/incompleteread')).read()
-
- def test_cookies(self, handler):
- cookiejar = YoutubeDLCookieJar()
- cookiejar.set_cookie(http.cookiejar.Cookie(
- 0, 'test', 'ytdlp', None, False, '127.0.0.1', True,
- False, '/headers', True, False, None, False, None, None, {}))
-
- with handler(cookiejar=cookiejar) as rh:
- data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).read()
- assert b'cookie: test=ytdlp' in data.lower()
-
- # Per request
- with handler() as rh:
- data = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/headers', extensions={'cookiejar': cookiejar})).read()
- assert b'cookie: test=ytdlp' in data.lower()
-
- def test_cookie_sync_only_cookiejar(self, handler):
- # Ensure that cookies are ONLY being handled by the cookiejar
- with handler() as rh:
- validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/get_cookie', extensions={'cookiejar': YoutubeDLCookieJar()}))
- data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers', extensions={'cookiejar': YoutubeDLCookieJar()})).read()
- assert b'cookie: test=ytdlp' not in data.lower()
-
- def test_cookie_sync_delete_cookie(self, handler):
- # Ensure that cookies are ONLY being handled by the cookiejar
- cookiejar = YoutubeDLCookieJar()
- with handler(cookiejar=cookiejar) as rh:
- validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/get_cookie'))
- data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).read()
- assert b'cookie: test=ytdlp' in data.lower()
- cookiejar.clear_session_cookies()
- data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).read()
- assert b'cookie: test=ytdlp' not in data.lower()
-
- def test_headers(self, handler):
-
- with handler(headers=HTTPHeaderDict({'test1': 'test', 'test2': 'test2'})) as rh:
- # Global Headers
- data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).read().lower()
- assert b'test1: test' in data
-
- # Per request headers, merged with global
- data = validate_and_send(rh, Request(
- f'http://127.0.0.1:{self.http_port}/headers', headers={'test2': 'changed', 'test3': 'test3'})).read().lower()
- assert b'test1: test' in data
- assert b'test2: changed' in data
- assert b'test2: test2' not in data
- assert b'test3: test3' in data
-
- def test_read_timeout(self, handler):
- with handler() as rh:
- # Default timeout is 20 seconds, so this should go through
- validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/timeout_1'))
-
- with handler(timeout=0.1) as rh:
- with pytest.raises(TransportError):
- validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/timeout_5'))
-
- # Per request timeout, should override handler timeout
- validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/timeout_1', extensions={'timeout': 4}))
-
- def test_connect_timeout(self, handler):
- # nothing should be listening on this port
- connect_timeout_url = 'http://10.255.255.255'
- with handler(timeout=0.01) as rh, pytest.raises(TransportError):
- now = time.time()
- validate_and_send(rh, Request(connect_timeout_url))
- assert time.time() - now < DEFAULT_TIMEOUT
-
- # Per request timeout, should override handler timeout
- request = Request(connect_timeout_url, extensions={'timeout': 0.01})
- with handler() as rh, pytest.raises(TransportError):
- now = time.time()
- validate_and_send(rh, request)
- assert time.time() - now < DEFAULT_TIMEOUT
-
- def test_source_address(self, handler):
- source_address = f'127.0.0.{random.randint(5, 255)}'
- # on some systems these loopback addresses we need for testing may not be available
- # see: https://github.com/yt-dlp/yt-dlp/issues/8890
- verify_address_availability(source_address)
- with handler(source_address=source_address) as rh:
- data = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/source_address')).read().decode()
- assert source_address == data
-
- @pytest.mark.skip_handler('CurlCFFI', 'not supported by curl-cffi')
- def test_gzip_trailing_garbage(self, handler):
- with handler() as rh:
- res = validate_and_send(rh, Request(f'http://localhost:{self.http_port}/trailing_garbage'))
- data = res.read().decode()
- assert data == ' '
- # Should auto-close and mark the response adaptor as closed
- assert res.closed
-
- @pytest.mark.skip_handler('CurlCFFI', 'not applicable to curl-cffi')
- @pytest.mark.skipif(not brotli, reason='brotli support is not installed')
- def test_brotli(self, handler):
- with handler() as rh:
- res = validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/content-encoding',
- headers={'ytdl-encoding': 'br'}))
- assert res.headers.get('Content-Encoding') == 'br'
- assert res.read() == b' '
- # Should auto-close and mark the response adaptor as closed
- assert res.closed
-
- def test_deflate(self, handler):
- with handler() as rh:
- res = validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/content-encoding',
- headers={'ytdl-encoding': 'deflate'}))
- assert res.headers.get('Content-Encoding') == 'deflate'
- assert res.read() == b' '
- # Should auto-close and mark the response adaptor as closed
- assert res.closed
-
- def test_gzip(self, handler):
- with handler() as rh:
- res = validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/content-encoding',
- headers={'ytdl-encoding': 'gzip'}))
- assert res.headers.get('Content-Encoding') == 'gzip'
- assert res.read() == b' '
- # Should auto-close and mark the response adaptor as closed
- assert res.closed
-
- def test_multiple_encodings(self, handler):
- with handler() as rh:
- for pair in ('gzip,deflate', 'deflate, gzip', 'gzip, gzip', 'deflate, deflate'):
- res = validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/content-encoding',
- headers={'ytdl-encoding': pair}))
- assert res.headers.get('Content-Encoding') == pair
- assert res.read() == b' '
- # Should auto-close and mark the response adaptor as closed
- assert res.closed
-
- @pytest.mark.skip_handler('CurlCFFI', 'not supported by curl-cffi')
- def test_unsupported_encoding(self, handler):
- with handler() as rh:
- res = validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/content-encoding',
- headers={'ytdl-encoding': 'unsupported', 'Accept-Encoding': '*'}))
- assert res.headers.get('Content-Encoding') == 'unsupported'
- assert res.read() == b'raw'
- # Should auto-close and mark the response adaptor as closed
- assert res.closed
-
- def test_read(self, handler):
- with handler() as rh:
- res = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/headers'))
- assert res.readable()
- assert res.read(1) == b'H'
- # Ensure we don't close the adaptor yet
- assert not res.closed
- assert res.read(3) == b'ost'
- assert res.read().decode().endswith('\n\n')
- assert res.read() == b''
- # Should auto-close and mark the response adaptor as closed
- assert res.closed
-
- def test_request_disable_proxy(self, handler):
- for proxy_proto in handler._SUPPORTED_PROXY_SCHEMES or ['http']:
- # Given the handler is configured with a proxy
- with handler(proxies={'http': f'{proxy_proto}://10.255.255.255'}, timeout=5) as rh:
- # When a proxy is explicitly set to None for the request
- res = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/headers', proxies={'http': None}))
- # Then no proxy should be used
- res.close()
- assert res.status == 200
-
- @pytest.mark.skip_handlers_if(
- lambda _, handler: Features.NO_PROXY not in handler._SUPPORTED_FEATURES, 'handler does not support NO_PROXY')
- def test_noproxy(self, handler):
- for proxy_proto in handler._SUPPORTED_PROXY_SCHEMES or ['http']:
- # Given the handler is configured with a proxy
- with handler(proxies={'http': f'{proxy_proto}://10.255.255.255'}, timeout=5) as rh:
- for no_proxy in (f'127.0.0.1:{self.http_port}', '127.0.0.1', 'localhost'):
- # When request no proxy includes the request url host
- nop_response = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/headers', proxies={'no': no_proxy}))
- # Then the proxy should not be used
- assert nop_response.status == 200
- nop_response.close()
-
- @pytest.mark.skip_handlers_if(
- lambda _, handler: Features.ALL_PROXY not in handler._SUPPORTED_FEATURES, 'handler does not support ALL_PROXY')
- def test_allproxy(self, handler):
- # This is a bit of a hacky test, but it should be enough to check whether the handler is using the proxy.
- # 0.1s might not be enough of a timeout if proxy is not used in all cases, but should still get failures.
- with handler(proxies={'all': 'http://10.255.255.255'}, timeout=0.1) as rh:
- with pytest.raises(TransportError):
- validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).close()
-
- with handler(timeout=0.1) as rh:
- with pytest.raises(TransportError):
- validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/headers', proxies={'all': 'http://10.255.255.255'})).close()
-
- @pytest.mark.skip_handlers_if(lambda _, handler: handler not in ['Urllib', 'CurlCFFI'], 'handler does not support keep_header_casing')
- def test_keep_header_casing(self, handler):
- with handler() as rh:
- res = validate_and_send(
- rh, Request(
- f'http://127.0.0.1:{self.http_port}/headers', headers={'X-test-heaDer': 'test'}, extensions={'keep_header_casing': True})).read().decode()
-
- assert 'X-test-heaDer: test' in res
-
- def test_partial_read_then_full_read(self, handler):
- with handler() as rh:
- for encoding in ('', 'gzip', 'deflate'):
- res = validate_and_send(rh, Request(
- f'http://127.0.0.1:{self.http_port}/content-encoding',
- headers={'ytdl-encoding': encoding}))
- assert res.headers.get('Content-Encoding') == encoding
- assert res.read(6) == b''
- assert res.read(0) == b''
- assert res.read() == b' '
-
- def test_partial_read_greater_than_response_then_full_read(self, handler):
- with handler() as rh:
- for encoding in ('', 'gzip', 'deflate'):
- res = validate_and_send(rh, Request(
- f'http://127.0.0.1:{self.http_port}/content-encoding',
- headers={'ytdl-encoding': encoding}))
- assert res.headers.get('Content-Encoding') == encoding
- assert res.read(512) == b' '
- assert res.read(0) == b''
- assert res.read() == b''
-
-
-@pytest.mark.parametrize('handler', ['Urllib', 'Requests', 'CurlCFFI'], indirect=True)
-@pytest.mark.handler_flaky('CurlCFFI', reason='segfaults')
-class TestClientCertificate:
- @classmethod
- def setup_class(cls):
- certfn = os.path.join(TEST_DIR, 'testcert.pem')
- cls.certdir = os.path.join(TEST_DIR, 'testdata', 'certificate')
- cacertfn = os.path.join(cls.certdir, 'ca.crt')
- cls.httpd = http.server.ThreadingHTTPServer(('127.0.0.1', 0), HTTPTestRequestHandler)
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.verify_mode = ssl.CERT_REQUIRED
- sslctx.load_verify_locations(cafile=cacertfn)
- sslctx.load_cert_chain(certfn, None)
- cls.httpd.socket = sslctx.wrap_socket(cls.httpd.socket, server_side=True)
- cls.port = http_server_port(cls.httpd)
- cls.server_thread = threading.Thread(target=cls.httpd.serve_forever)
- cls.server_thread.daemon = True
- cls.server_thread.start()
-
- def _run_test(self, handler, **handler_kwargs):
- with handler(
- # Disable client-side validation of unacceptable self-signed testcert.pem
- # The test is of a check on the server side, so unaffected
- verify=False,
- **handler_kwargs,
- ) as rh:
- validate_and_send(rh, Request(f'https://127.0.0.1:{self.port}/video.html')).read().decode()
-
- def test_certificate_combined_nopass(self, handler):
- self._run_test(handler, client_cert={
- 'client_certificate': os.path.join(self.certdir, 'clientwithkey.crt'),
- })
-
- def test_certificate_nocombined_nopass(self, handler):
- self._run_test(handler, client_cert={
- 'client_certificate': os.path.join(self.certdir, 'client.crt'),
- 'client_certificate_key': os.path.join(self.certdir, 'client.key'),
- })
-
- def test_certificate_combined_pass(self, handler):
- self._run_test(handler, client_cert={
- 'client_certificate': os.path.join(self.certdir, 'clientwithencryptedkey.crt'),
- 'client_certificate_password': 'foobar',
- })
-
- def test_certificate_nocombined_pass(self, handler):
- self._run_test(handler, client_cert={
- 'client_certificate': os.path.join(self.certdir, 'client.crt'),
- 'client_certificate_key': os.path.join(self.certdir, 'clientencrypted.key'),
- 'client_certificate_password': 'foobar',
- })
-
-
-@pytest.mark.parametrize('handler', ['CurlCFFI'], indirect=True)
-class TestHTTPImpersonateRequestHandler(TestRequestHandlerBase):
- def test_supported_impersonate_targets(self, handler):
- with handler(headers=std_headers) as rh:
- # note: this assumes the impersonate request handler supports the impersonate extension
- for target in rh.supported_targets:
- res = validate_and_send(rh, Request(
- f'http://127.0.0.1:{self.http_port}/headers', extensions={'impersonate': target}))
- assert res.status == 200
- assert std_headers['user-agent'].lower() not in res.read().decode().lower()
-
- def test_response_extensions(self, handler):
- with handler() as rh:
- for target in rh.supported_targets:
- request = Request(
- f'http://127.0.0.1:{self.http_port}/gen_200', extensions={'impersonate': target})
- res = validate_and_send(rh, request)
- assert res.extensions['impersonate'] == rh._get_request_target(request)
-
- def test_http_error_response_extensions(self, handler):
- with handler() as rh:
- for target in rh.supported_targets:
- request = Request(
- f'http://127.0.0.1:{self.http_port}/gen_404', extensions={'impersonate': target})
- try:
- validate_and_send(rh, request)
- except HTTPError as e:
- res = e.response
- assert res.extensions['impersonate'] == rh._get_request_target(request)
-
-
-class TestRequestHandlerMisc:
- """Misc generic tests for request handlers, not related to request or validation testing"""
- @pytest.mark.parametrize('handler,logger_name', [
- ('Requests', 'urllib3'),
- ('Websockets', 'websockets.client'),
- ('Websockets', 'websockets.server'),
- ], indirect=['handler'])
- def test_remove_logging_handler(self, handler, logger_name):
- # Ensure any logging handlers, which may contain a YoutubeDL instance,
- # are removed when we close the request handler
- # See: https://github.com/yt-dlp/yt-dlp/issues/8922
- logging_handlers = logging.getLogger(logger_name).handlers
- before_count = len(logging_handlers)
- rh = handler()
- assert len(logging_handlers) == before_count + 1
- rh.close()
- assert len(logging_handlers) == before_count
-
- def test_wrap_request_errors(self):
- class TestRequestHandler(RequestHandler):
- def _validate(self, request):
- if request.headers.get('x-fail'):
- raise UnsupportedRequest('test error')
-
- def _send(self, request: Request):
- raise RequestError('test error')
-
- with TestRequestHandler(logger=FakeLogger()) as rh:
- with pytest.raises(UnsupportedRequest, match='test error') as exc_info:
- rh.validate(Request('http://example.com', headers={'x-fail': '1'}))
- assert exc_info.value.handler is rh
-
- with pytest.raises(RequestError, match='test error') as exc_info:
- rh.send(Request('http://example.com'))
- assert exc_info.value.handler is rh
-
-
-@pytest.mark.parametrize('handler', ['Urllib'], indirect=True)
-class TestUrllibRequestHandler(TestRequestHandlerBase):
- def test_file_urls(self, handler):
- # See https://github.com/ytdl-org/youtube-dl/issues/8227
- tf = tempfile.NamedTemporaryFile(delete=False)
- tf.write(b'foobar')
- tf.close()
- req = Request(pathlib.Path(tf.name).as_uri())
- with handler() as rh:
- with pytest.raises(UnsupportedRequest):
- rh.validate(req)
-
- # Test that urllib never loaded FileHandler
- with pytest.raises(TransportError):
- rh.send(req)
-
- with handler(enable_file_urls=True) as rh:
- res = validate_and_send(rh, req)
- assert res.read(1) == b'f'
- assert not res.fp.closed
- assert res.read() == b'oobar'
- # Should automatically close the underlying file object
- assert res.fp.closed
-
- os.unlink(tf.name)
-
- def test_data_uri_auto_close(self, handler):
- with handler() as rh:
- res = validate_and_send(rh, Request('data:text/plain,hello%20world'))
- assert res.read() == b'hello world'
- # Should automatically close the underlying file object
- assert res.fp.closed
- assert res.closed
-
- def test_http_response_auto_close(self, handler):
- with handler() as rh:
- res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_200'))
- assert res.read() == b''
- # Should automatically close the underlying file object in the HTTP Response
- assert isinstance(res.fp, http.client.HTTPResponse)
- assert res.fp.fp is None
- assert res.closed
-
- def test_data_uri_partial_read_then_full_read(self, handler):
- with handler() as rh:
- res = validate_and_send(rh, Request('data:text/plain,hello%20world'))
- assert res.read(6) == b'hello '
- assert res.read(0) == b''
- assert res.read() == b'world'
- # Should automatically close the underlying file object
- assert res.fp.closed
- assert res.closed
-
- def test_data_uri_partial_read_greater_than_response_then_full_read(self, handler):
- with handler() as rh:
- res = validate_and_send(rh, Request('data:text/plain,hello%20world'))
- assert res.read(512) == b'hello world'
- # Response and its underlying file object should already be closed now
- assert res.fp.closed
- assert res.closed
- assert res.read(0) == b''
- assert res.read() == b''
- assert res.fp.closed
- assert res.closed
-
- def test_http_error_returns_content(self, handler):
- # urllib HTTPError will try close the underlying response if reference to the HTTPError object is lost
- def get_response():
- with handler() as rh:
- # headers url
- try:
- validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_404'))
- except HTTPError as e:
- return e.response
-
- assert get_response().read() == b''
-
- def test_verify_cert_error_text(self, handler):
- # Check the output of the error message
- with handler() as rh:
- with pytest.raises(
- CertificateVerifyError,
- match=r'\[SSL: CERTIFICATE_VERIFY_FAILED\] certificate verify failed: self.signed certificate',
- ):
- validate_and_send(rh, Request(f'https://127.0.0.1:{self.https_port}/headers'))
-
- @pytest.mark.parametrize('req,match,version_check', [
- # https://github.com/python/cpython/blob/987b712b4aeeece336eed24fcc87a950a756c3e2/Lib/http/client.py#L1256
- # bpo-39603: Check implemented in 3.7.9+, 3.8.5+
- (
- Request('http://127.0.0.1', method='GET\n'),
- 'method can\'t contain control characters',
- lambda v: v < (3, 7, 9) or (3, 8, 0) <= v < (3, 8, 5),
- ),
- # https://github.com/python/cpython/blob/987b712b4aeeece336eed24fcc87a950a756c3e2/Lib/http/client.py#L1265
- # bpo-38576: Check implemented in 3.7.8+, 3.8.3+
- (
- Request('http://127.0.0. 1', method='GET'),
- 'URL can\'t contain control characters',
- lambda v: v < (3, 7, 8) or (3, 8, 0) <= v < (3, 8, 3),
- ),
- # https://github.com/python/cpython/blob/987b712b4aeeece336eed24fcc87a950a756c3e2/Lib/http/client.py#L1288C31-L1288C50
- (Request('http://127.0.0.1', headers={'foo\n': 'bar'}), 'Invalid header name', None),
- ])
- def test_httplib_validation_errors(self, handler, req, match, version_check):
- if version_check and version_check(sys.version_info):
- pytest.skip(f'Python {sys.version} version does not have the required validation for this test.')
-
- with handler() as rh:
- with pytest.raises(RequestError, match=match) as exc_info:
- validate_and_send(rh, req)
- assert not isinstance(exc_info.value, TransportError)
-
-
-@pytest.mark.parametrize('handler', ['Requests'], indirect=True)
-class TestRequestsRequestHandler(TestRequestHandlerBase):
- # ruff: disable[PLW0108] `requests` and/or `urllib3` may not be available
- @pytest.mark.parametrize('raised,expected', [
- (lambda: requests.exceptions.ConnectTimeout(), TransportError),
- (lambda: requests.exceptions.ReadTimeout(), TransportError),
- (lambda: requests.exceptions.Timeout(), TransportError),
- (lambda: requests.exceptions.ConnectionError(), TransportError),
- (lambda: requests.exceptions.ProxyError(), ProxyError),
- (lambda: requests.exceptions.SSLError('12[CERTIFICATE_VERIFY_FAILED]34'), CertificateVerifyError),
- (lambda: requests.exceptions.SSLError(), SSLError),
- (lambda: requests.exceptions.InvalidURL(), RequestError),
- (lambda: requests.exceptions.InvalidHeader(), RequestError),
- # catch-all: https://github.com/psf/requests/blob/main/src/requests/adapters.py#L535
- (lambda: urllib3.exceptions.HTTPError(), TransportError),
- (lambda: requests.exceptions.RequestException(), RequestError),
- # Needs a response object
- # (lambda: requests.exceptions.TooManyRedirects(), HTTPError),
- ])
- # ruff: enable[PLW0108]
- def test_request_error_mapping(self, handler, monkeypatch, raised, expected):
- with handler() as rh:
- def mock_get_instance(*args, **kwargs):
- class MockSession:
- def request(self, *args, **kwargs):
- raise raised()
- return MockSession()
-
- monkeypatch.setattr(rh, '_get_instance', mock_get_instance)
-
- with pytest.raises(expected) as exc_info:
- rh.send(Request('http://fake'))
-
- assert exc_info.type is expected
-
- # ruff: disable[PLW0108] `urllib3` may not be available
- @pytest.mark.parametrize('raised,expected,match', [
- (lambda: urllib3.exceptions.SSLError(), SSLError, None),
- (lambda: urllib3.exceptions.TimeoutError(), TransportError, None),
- (lambda: urllib3.exceptions.ReadTimeoutError(None, None, None), TransportError, None),
- (lambda: urllib3.exceptions.ProtocolError(), TransportError, None),
- (lambda: urllib3.exceptions.DecodeError(), TransportError, None),
- (lambda: urllib3.exceptions.HTTPError(), TransportError, None), # catch-all
- (
- lambda: urllib3.exceptions.ProtocolError('error', http.client.IncompleteRead(partial=b'abc', expected=4)),
- IncompleteRead,
- '3 bytes read, 4 more expected',
- ),
- (
- lambda: urllib3.exceptions.ProtocolError('error', urllib3.exceptions.IncompleteRead(partial=3, expected=5)),
- IncompleteRead,
- '3 bytes read, 5 more expected',
- ),
- ])
- # ruff: enable[PLW0108]
- def test_response_error_mapping(self, handler, monkeypatch, raised, expected, match):
- from requests.models import Response as RequestsResponse
- from urllib3.response import HTTPResponse as Urllib3Response
-
- from yt_dlp.networking._requests import RequestsResponseAdapter
- requests_res = RequestsResponse()
- requests_res.raw = Urllib3Response(body=b'', status=200)
- res = RequestsResponseAdapter(requests_res)
-
- def mock_read(*args, **kwargs):
- raise raised()
- monkeypatch.setattr(res.fp, 'read', mock_read)
-
- with pytest.raises(expected, match=match) as exc_info:
- res.read()
-
- assert exc_info.type is expected
-
- def test_close(self, handler, monkeypatch):
- rh = handler()
- session = rh._get_instance(cookiejar=rh.cookiejar)
- called = False
- original_close = session.close
-
- def mock_close(*args, **kwargs):
- nonlocal called
- called = True
- return original_close(*args, **kwargs)
-
- monkeypatch.setattr(session, 'close', mock_close)
- rh.close()
- assert called
-
- def test_http_response_auto_close(self, handler):
- with handler() as rh:
- res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_200'))
- assert res.read() == b''
- # Should automatically close the underlying file object in the HTTP Response
- assert res.fp.closed
- assert res.closed
-
-
-@pytest.mark.parametrize('handler', ['CurlCFFI'], indirect=True)
-@pytest.mark.handler_flaky('CurlCFFI', reason='segfaults')
-class TestCurlCFFIRequestHandler(TestRequestHandlerBase):
-
- @pytest.mark.parametrize('params,extensions', [
- ({'impersonate': ImpersonateTarget('chrome', '110')}, {}),
- ({'impersonate': ImpersonateTarget('chrome', '99')}, {'impersonate': ImpersonateTarget('chrome', '110')}),
- ])
- def test_impersonate(self, handler, params, extensions):
- with handler(headers=std_headers, **params) as rh:
- res = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/headers', extensions=extensions)).read().decode()
- assert 'sec-ch-ua: "Chromium";v="110"' in res
- # Check that user agent is added over ours
- assert 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36' in res
-
- def test_headers(self, handler):
- with handler(headers=std_headers) as rh:
- # Ensure curl-impersonate overrides our standard headers (usually added
- res = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/headers', extensions={
- 'impersonate': ImpersonateTarget('safari')}, headers={'x-custom': 'test', 'sec-fetch-mode': 'custom'})).read().decode().lower()
-
- assert std_headers['user-agent'].lower() not in res
- assert std_headers['accept-language'].lower() not in res
- assert std_headers['sec-fetch-mode'].lower() not in res
- # other than UA, custom headers that differ from std_headers should be kept
- assert 'sec-fetch-mode: custom' in res
- assert 'x-custom: test' in res
- # but when not impersonating don't remove std_headers
- res = validate_and_send(
- rh, Request(f'http://127.0.0.1:{self.http_port}/headers', headers={'x-custom': 'test'})).read().decode().lower()
- # std_headers should be present
- for k, v in std_headers.items():
- assert f'{k}: {v}'.lower() in res
-
- @pytest.mark.parametrize('raised,expected,match', [
- (lambda: curl_cffi.requests.errors.RequestsError(
- '', code=curl_cffi.const.CurlECode.PARTIAL_FILE), IncompleteRead, None),
- (lambda: curl_cffi.requests.errors.RequestsError(
- '', code=curl_cffi.const.CurlECode.OPERATION_TIMEDOUT), TransportError, None),
- (lambda: curl_cffi.requests.errors.RequestsError(
- '', code=curl_cffi.const.CurlECode.RECV_ERROR), TransportError, None),
- ])
- def test_response_error_mapping(self, handler, monkeypatch, raised, expected, match):
- import curl_cffi.requests
-
- from yt_dlp.networking._curlcffi import CurlCFFIResponseAdapter
- curl_res = curl_cffi.requests.Response()
- res = CurlCFFIResponseAdapter(curl_res)
-
- def mock_read(*args, **kwargs):
- try:
- raise raised()
- except Exception as e:
- e.response = curl_res
- raise
- monkeypatch.setattr(res.fp, 'read', mock_read)
-
- with pytest.raises(expected, match=match) as exc_info:
- res.read()
-
- assert exc_info.type is expected
-
- @pytest.mark.parametrize('raised,expected,match', [
- (lambda: curl_cffi.requests.errors.RequestsError(
- '', code=curl_cffi.const.CurlECode.OPERATION_TIMEDOUT), TransportError, None),
- (lambda: curl_cffi.requests.errors.RequestsError(
- '', code=curl_cffi.const.CurlECode.PEER_FAILED_VERIFICATION), CertificateVerifyError, None),
- (lambda: curl_cffi.requests.errors.RequestsError(
- '', code=curl_cffi.const.CurlECode.SSL_CONNECT_ERROR), SSLError, None),
- (lambda: curl_cffi.requests.errors.RequestsError(
- '', code=curl_cffi.const.CurlECode.TOO_MANY_REDIRECTS), HTTPError, None),
- (lambda: curl_cffi.requests.errors.RequestsError(
- '', code=curl_cffi.const.CurlECode.PROXY), ProxyError, None),
- ])
- def test_request_error_mapping(self, handler, monkeypatch, raised, expected, match):
- import curl_cffi.requests
- curl_res = curl_cffi.requests.Response()
- curl_res.status_code = 301
-
- with handler() as rh:
- original_get_instance = rh._get_instance
-
- def mock_get_instance(*args, **kwargs):
- instance = original_get_instance(*args, **kwargs)
-
- def request(*_, **__):
- try:
- raise raised()
- except Exception as e:
- e.response = curl_res
- raise
- monkeypatch.setattr(instance, 'request', request)
- return instance
-
- monkeypatch.setattr(rh, '_get_instance', mock_get_instance)
-
- with pytest.raises(expected) as exc_info:
- rh.send(Request('http://fake'))
-
- assert exc_info.type is expected
-
- def test_response_reader(self, handler):
- class FakeResponse:
- def __init__(self, raise_error=False):
- self.raise_error = raise_error
- self.closed = False
-
- def iter_content(self):
- yield b'foo'
- yield b'bar'
- yield b'z'
- if self.raise_error:
- raise Exception('test')
-
- def close(self):
- self.closed = True
-
- from yt_dlp.networking._curlcffi import CurlCFFIResponseReader
-
- res = CurlCFFIResponseReader(FakeResponse())
- assert res.readable
- assert res.bytes_read == 0
- assert res.read(1) == b'f'
- assert res.bytes_read == 3
- assert res._buffer == b'oo'
-
- assert res.read(2) == b'oo'
- assert res.bytes_read == 3
- assert res._buffer == b''
-
- assert res.read(2) == b'ba'
- assert res.bytes_read == 6
- assert res._buffer == b'r'
-
- assert res.read(3) == b'rz'
- assert res.bytes_read == 7
- assert res._buffer == b''
- assert res.closed
- assert res._response.closed
-
- # should handle no size param
- res2 = CurlCFFIResponseReader(FakeResponse())
- assert res2.read() == b'foobarz'
- assert res2.bytes_read == 7
- assert res2._buffer == b''
- assert res2.closed
-
- # should close on an exception
- res3 = CurlCFFIResponseReader(FakeResponse(raise_error=True))
- with pytest.raises(Exception, match='test'):
- res3.read()
- assert res3._buffer == b''
- assert res3.bytes_read == 7
- assert res3.closed
-
- # buffer should be cleared on close
- res4 = CurlCFFIResponseReader(FakeResponse())
- res4.read(2)
- assert res4._buffer == b'o'
- res4.close()
- assert res4.closed
- assert res4._buffer == b''
-
- def test_http_response_auto_close(self, handler):
- with handler() as rh:
- res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_200'))
- assert res.read() == b''
- # Should automatically close the underlying file object in the HTTP Response
- assert res.fp.closed
- assert res.closed
-
-
-def run_validation(handler, error, req, **handler_kwargs):
- with handler(**handler_kwargs) as rh:
- if error:
- with pytest.raises(error):
- rh.validate(req)
- else:
- rh.validate(req)
-
-
-class TestRequestHandlerValidation:
-
- class ValidationRH(RequestHandler):
- def _send(self, request):
- raise RequestError('test')
-
- class NoCheckRH(ValidationRH):
- _SUPPORTED_FEATURES = None
- _SUPPORTED_PROXY_SCHEMES = None
- _SUPPORTED_URL_SCHEMES = None
-
- def _check_extensions(self, extensions):
- extensions.clear()
-
- class HTTPSupportedRH(ValidationRH):
- _SUPPORTED_URL_SCHEMES = ('http',)
-
- URL_SCHEME_TESTS = [
- # scheme, expected to fail, handler kwargs
- ('Urllib', [
- ('http', False, {}),
- ('https', False, {}),
- ('data', False, {}),
- ('ftp', False, {}),
- ('file', UnsupportedRequest, {}),
- ('file', False, {'enable_file_urls': True}),
- ]),
- ('Requests', [
- ('http', False, {}),
- ('https', False, {}),
- ]),
- ('Websockets', [
- ('ws', False, {}),
- ('wss', False, {}),
- ]),
- ('CurlCFFI', [
- ('http', False, {}),
- ('https', False, {}),
- ]),
- (NoCheckRH, [('http', False, {})]),
- (ValidationRH, [('http', UnsupportedRequest, {})]),
- ]
-
- PROXY_SCHEME_TESTS = [
- # proxy scheme, expected to fail
- ('Urllib', 'http', [
- ('http', False),
- ('https', UnsupportedRequest),
- ('socks4', False),
- ('socks4a', False),
- ('socks5', False),
- ('socks5h', False),
- ('socks', UnsupportedRequest),
- ]),
- ('Requests', 'http', [
- ('http', False),
- ('https', False),
- ('socks4', False),
- ('socks4a', False),
- ('socks5', False),
- ('socks5h', False),
- ]),
- ('CurlCFFI', 'http', [
- ('http', False),
- ('https', False),
- ('socks4', False),
- ('socks4a', False),
- ('socks5', False),
- ('socks5h', False),
- ]),
- ('Websockets', 'ws', [
- ('http', UnsupportedRequest),
- ('https', UnsupportedRequest),
- ('socks4', False),
- ('socks4a', False),
- ('socks5', False),
- ('socks5h', False),
- ]),
- (NoCheckRH, 'http', [('http', False)]),
- (HTTPSupportedRH, 'http', [('http', UnsupportedRequest)]),
- (NoCheckRH, 'http', [('http', False)]),
- (HTTPSupportedRH, 'http', [('http', UnsupportedRequest)]),
- ]
-
- PROXY_KEY_TESTS = [
- # proxy key, proxy scheme, expected to fail
- ('Urllib', 'http', [
- ('all', 'http', False),
- ('unrelated', 'http', False),
- ]),
- ('Requests', 'http', [
- ('all', 'http', False),
- ('unrelated', 'http', False),
- ]),
- ('CurlCFFI', 'http', [
- ('all', 'http', False),
- ('unrelated', 'http', False),
- ]),
- ('Websockets', 'ws', [
- ('all', 'socks5', False),
- ('unrelated', 'socks5', False),
- ]),
- (NoCheckRH, 'http', [('all', 'http', False)]),
- (HTTPSupportedRH, 'http', [('all', 'http', UnsupportedRequest)]),
- (HTTPSupportedRH, 'http', [('no', 'http', UnsupportedRequest)]),
- ]
-
- EXTENSION_TESTS = [
- ('Urllib', 'http', [
- ({'cookiejar': 'notacookiejar'}, AssertionError),
- ({'cookiejar': YoutubeDLCookieJar()}, False),
- ({'cookiejar': CookieJar()}, AssertionError),
- ({'timeout': 1}, False),
- ({'timeout': 'notatimeout'}, AssertionError),
- ({'unsupported': 'value'}, UnsupportedRequest),
- ({'legacy_ssl': False}, False),
- ({'legacy_ssl': True}, False),
- ({'legacy_ssl': 'notabool'}, AssertionError),
- ({'keep_header_casing': True}, UnsupportedRequest),
- ]),
- ('Requests', 'http', [
- ({'cookiejar': 'notacookiejar'}, AssertionError),
- ({'cookiejar': YoutubeDLCookieJar()}, False),
- ({'timeout': 1}, False),
- ({'timeout': 'notatimeout'}, AssertionError),
- ({'unsupported': 'value'}, UnsupportedRequest),
- ({'legacy_ssl': False}, False),
- ({'legacy_ssl': True}, False),
- ({'legacy_ssl': 'notabool'}, AssertionError),
- ({'keep_header_casing': False}, False),
- ({'keep_header_casing': True}, False),
- ({'keep_header_casing': 'notabool'}, AssertionError),
- ]),
- ('CurlCFFI', 'http', [
- ({'cookiejar': 'notacookiejar'}, AssertionError),
- ({'cookiejar': YoutubeDLCookieJar()}, False),
- ({'timeout': 1}, False),
- ({'timeout': 'notatimeout'}, AssertionError),
- ({'unsupported': 'value'}, UnsupportedRequest),
- ({'impersonate': ImpersonateTarget('badtarget', None, None, None)}, UnsupportedRequest),
- ({'impersonate': 123}, AssertionError),
- ({'impersonate': ImpersonateTarget('chrome', None, None, None)}, False),
- ({'impersonate': ImpersonateTarget(None, None, None, None)}, False),
- ({'impersonate': ImpersonateTarget()}, False),
- ({'impersonate': 'chrome'}, AssertionError),
- ({'legacy_ssl': False}, False),
- ({'legacy_ssl': True}, False),
- ({'legacy_ssl': 'notabool'}, AssertionError),
- ]),
- (NoCheckRH, 'http', [
- ({'cookiejar': 'notacookiejar'}, False),
- ({'somerandom': 'test'}, False), # but any extension is allowed through
- ]),
- ('Websockets', 'ws', [
- ({'cookiejar': YoutubeDLCookieJar()}, False),
- ({'timeout': 2}, False),
- ({'legacy_ssl': False}, False),
- ({'legacy_ssl': True}, False),
- ({'legacy_ssl': 'notabool'}, AssertionError),
- ]),
- ]
-
- @pytest.mark.parametrize('handler,fail,scheme', [
- ('Urllib', False, 'http'),
- ('Requests', False, 'http'),
- ('CurlCFFI', False, 'http'),
- ('Websockets', False, 'ws'),
- ], indirect=['handler'])
- def test_no_proxy(self, handler, fail, scheme):
- run_validation(handler, fail, Request(f'{scheme}://', proxies={'no': '127.0.0.1,github.com'}))
- run_validation(handler, fail, Request(f'{scheme}://'), proxies={'no': '127.0.0.1,github.com'})
-
- @pytest.mark.parametrize('handler,scheme', [
- ('Urllib', 'http'),
- (HTTPSupportedRH, 'http'),
- ('Requests', 'http'),
- ('CurlCFFI', 'http'),
- ('Websockets', 'ws'),
- ], indirect=['handler'])
- def test_empty_proxy(self, handler, scheme):
- run_validation(handler, False, Request(f'{scheme}://', proxies={scheme: None}))
- run_validation(handler, False, Request(f'{scheme}://'), proxies={scheme: None})
-
- @pytest.mark.parametrize('proxy_url', ['//example.com', 'example.com', '127.0.0.1', '/a/b/c'])
- @pytest.mark.parametrize('handler,scheme', [
- ('Urllib', 'http'),
- (HTTPSupportedRH, 'http'),
- ('Requests', 'http'),
- ('CurlCFFI', 'http'),
- ('Websockets', 'ws'),
- ], indirect=['handler'])
- def test_invalid_proxy_url(self, handler, scheme, proxy_url):
- run_validation(handler, UnsupportedRequest, Request(f'{scheme}://', proxies={scheme: proxy_url}))
-
- @pytest.mark.parametrize('handler,scheme,fail,handler_kwargs', [
- (handler_tests[0], scheme, fail, handler_kwargs)
- for handler_tests in URL_SCHEME_TESTS
- for scheme, fail, handler_kwargs in handler_tests[1]
- ], indirect=['handler'])
- def test_url_scheme(self, handler, scheme, fail, handler_kwargs):
- run_validation(handler, fail, Request(f'{scheme}://'), **(handler_kwargs or {}))
-
- @pytest.mark.parametrize('handler,scheme,proxy_key,proxy_scheme,fail', [
- (handler_tests[0], handler_tests[1], proxy_key, proxy_scheme, fail)
- for handler_tests in PROXY_KEY_TESTS
- for proxy_key, proxy_scheme, fail in handler_tests[2]
- ], indirect=['handler'])
- def test_proxy_key(self, handler, scheme, proxy_key, proxy_scheme, fail):
- run_validation(handler, fail, Request(f'{scheme}://', proxies={proxy_key: f'{proxy_scheme}://example.com'}))
- run_validation(handler, fail, Request(f'{scheme}://'), proxies={proxy_key: f'{proxy_scheme}://example.com'})
-
- @pytest.mark.parametrize('handler,req_scheme,scheme,fail', [
- (handler_tests[0], handler_tests[1], scheme, fail)
- for handler_tests in PROXY_SCHEME_TESTS
- for scheme, fail in handler_tests[2]
- ], indirect=['handler'])
- def test_proxy_scheme(self, handler, req_scheme, scheme, fail):
- run_validation(handler, fail, Request(f'{req_scheme}://', proxies={req_scheme: f'{scheme}://example.com'}))
- run_validation(handler, fail, Request(f'{req_scheme}://'), proxies={req_scheme: f'{scheme}://example.com'})
-
- @pytest.mark.parametrize('handler,scheme,extensions,fail', [
- (handler_tests[0], handler_tests[1], extensions, fail)
- for handler_tests in EXTENSION_TESTS
- for extensions, fail in handler_tests[2]
- ], indirect=['handler'])
- def test_extension(self, handler, scheme, extensions, fail):
- run_validation(
- handler, fail, Request(f'{scheme}://', extensions=extensions))
-
- def test_invalid_request_type(self):
- rh = self.ValidationRH(logger=FakeLogger())
- for method in (rh.validate, rh.send):
- with pytest.raises(TypeError, match='Expected an instance of Request'):
- method('not a request')
-
-
-class FakeResponse(Response):
- def __init__(self, request):
- # XXX: we could make request part of standard response interface
- self.request = request
- super().__init__(fp=io.BytesIO(b''), headers={}, url=request.url)
-
-
-class FakeRH(RequestHandler):
-
- def __init__(self, *args, **params):
- self.params = params
- super().__init__(*args, **params)
-
- def _validate(self, request):
- return
-
- def _send(self, request: Request):
- if request.url.startswith('ssl://'):
- raise SSLError(request.url[len('ssl://'):])
- return FakeResponse(request)
-
-
-class FakeRHYDL(FakeYDL):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self._request_director = self.build_request_director([FakeRH])
-
-
-class AllUnsupportedRHYDL(FakeYDL):
-
- def __init__(self, *args, **kwargs):
-
- class UnsupportedRH(RequestHandler):
- def _send(self, request: Request):
- pass
-
- _SUPPORTED_FEATURES = ()
- _SUPPORTED_PROXY_SCHEMES = ()
- _SUPPORTED_URL_SCHEMES = ()
-
- super().__init__(*args, **kwargs)
- self._request_director = self.build_request_director([UnsupportedRH])
-
-
-class TestRequestDirector:
-
- def test_handler_operations(self):
- director = RequestDirector(logger=FakeLogger())
- handler = FakeRH(logger=FakeLogger())
- director.add_handler(handler)
- assert director.handlers.get(FakeRH.RH_KEY) is handler
-
- # Handler should overwrite
- handler2 = FakeRH(logger=FakeLogger())
- director.add_handler(handler2)
- assert director.handlers.get(FakeRH.RH_KEY) is not handler
- assert director.handlers.get(FakeRH.RH_KEY) is handler2
- assert len(director.handlers) == 1
-
- class AnotherFakeRH(FakeRH):
- pass
- director.add_handler(AnotherFakeRH(logger=FakeLogger()))
- assert len(director.handlers) == 2
- assert director.handlers.get(AnotherFakeRH.RH_KEY).RH_KEY == AnotherFakeRH.RH_KEY
-
- director.handlers.pop(FakeRH.RH_KEY, None)
- assert director.handlers.get(FakeRH.RH_KEY) is None
- assert len(director.handlers) == 1
-
- # RequestErrors should passthrough
- with pytest.raises(SSLError):
- director.send(Request('ssl://something'))
-
- def test_send(self):
- director = RequestDirector(logger=FakeLogger())
- with pytest.raises(RequestError):
- director.send(Request('any://'))
- director.add_handler(FakeRH(logger=FakeLogger()))
- assert isinstance(director.send(Request('http://')), FakeResponse)
-
- def test_unsupported_handlers(self):
- class SupportedRH(RequestHandler):
- _SUPPORTED_URL_SCHEMES = ['http']
-
- def _send(self, request: Request):
- return Response(fp=io.BytesIO(b'supported'), headers={}, url=request.url)
-
- director = RequestDirector(logger=FakeLogger())
- director.add_handler(SupportedRH(logger=FakeLogger()))
- director.add_handler(FakeRH(logger=FakeLogger()))
-
- # First should take preference
- assert director.send(Request('http://')).read() == b'supported'
- assert director.send(Request('any://')).read() == b''
-
- director.handlers.pop(FakeRH.RH_KEY)
- with pytest.raises(NoSupportingHandlers):
- director.send(Request('any://'))
-
- def test_unexpected_error(self):
- director = RequestDirector(logger=FakeLogger())
-
- class UnexpectedRH(FakeRH):
- def _send(self, request: Request):
- raise TypeError('something')
-
- director.add_handler(UnexpectedRH(logger=FakeLogger))
- with pytest.raises(NoSupportingHandlers, match=r'1 unexpected error'):
- director.send(Request('any://'))
-
- director.handlers.clear()
- assert len(director.handlers) == 0
-
- # Should not be fatal
- director.add_handler(FakeRH(logger=FakeLogger()))
- director.add_handler(UnexpectedRH(logger=FakeLogger))
- assert director.send(Request('any://'))
-
- def test_preference(self):
- director = RequestDirector(logger=FakeLogger())
- director.add_handler(FakeRH(logger=FakeLogger()))
-
- class SomeRH(RequestHandler):
- _SUPPORTED_URL_SCHEMES = ['http']
-
- def _send(self, request: Request):
- return Response(fp=io.BytesIO(b'supported'), headers={}, url=request.url)
-
- def some_preference(rh, request):
- return (0 if not isinstance(rh, SomeRH)
- else 100 if 'prefer' in request.headers
- else -1)
-
- director.add_handler(SomeRH(logger=FakeLogger()))
- director.preferences.add(some_preference)
-
- assert director.send(Request('http://')).read() == b''
- assert director.send(Request('http://', headers={'prefer': '1'})).read() == b'supported'
-
- def test_close(self, monkeypatch):
- director = RequestDirector(logger=FakeLogger())
- director.add_handler(FakeRH(logger=FakeLogger()))
- called = False
-
- def mock_close(*args, **kwargs):
- nonlocal called
- called = True
-
- monkeypatch.setattr(director.handlers[FakeRH.RH_KEY], 'close', mock_close)
- director.close()
- assert called
-
-
-# XXX: do we want to move this to test_YoutubeDL.py?
-class TestYoutubeDLNetworking:
-
- @staticmethod
- def build_handler(ydl, handler: RequestHandler = FakeRH):
- return ydl.build_request_director([handler]).handlers.get(handler.RH_KEY)
-
- def test_compat_opener(self):
- with FakeYDL() as ydl:
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', category=DeprecationWarning)
- assert isinstance(ydl._opener, urllib.request.OpenerDirector)
-
- @pytest.mark.parametrize('proxy,expected', [
- ('http://127.0.0.1:8080', {'all': 'http://127.0.0.1:8080'}),
- ('', {'all': '__noproxy__'}),
- (None, {'http': 'http://127.0.0.1:8081', 'https': 'http://127.0.0.1:8081'}), # env, set https
- ])
- def test_proxy(self, proxy, expected, monkeypatch):
- monkeypatch.setenv('HTTP_PROXY', 'http://127.0.0.1:8081')
- with FakeYDL({'proxy': proxy}) as ydl:
- assert ydl.proxies == expected
-
- def test_compat_request(self):
- with FakeRHYDL() as ydl:
- assert ydl.urlopen('test://')
- urllib_req = urllib.request.Request('http://foo.bar', data=b'test', method='PUT', headers={'X-Test': '1'})
- urllib_req.add_unredirected_header('Cookie', 'bob=bob')
- urllib_req.timeout = 2
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', category=DeprecationWarning)
- req = ydl.urlopen(urllib_req).request
- assert req.url == urllib_req.get_full_url()
- assert req.data == urllib_req.data
- assert req.method == urllib_req.get_method()
- assert 'X-Test' in req.headers
- assert 'Cookie' in req.headers
- assert req.extensions.get('timeout') == 2
-
- with pytest.raises(AssertionError):
- ydl.urlopen(None)
-
- def test_extract_basic_auth(self):
- with FakeRHYDL() as ydl:
- res = ydl.urlopen(Request('http://user:pass@foo.bar'))
- assert res.request.headers['Authorization'] == 'Basic dXNlcjpwYXNz'
-
- def test_sanitize_url(self):
- with FakeRHYDL() as ydl:
- res = ydl.urlopen(Request('httpss://foo.bar'))
- assert res.request.url == 'https://foo.bar'
-
- def test_file_urls_error(self):
- # use urllib handler
- with FakeYDL() as ydl:
- with pytest.raises(RequestError, match=r'file:// URLs are disabled by default'):
- ydl.urlopen('file://')
-
- @pytest.mark.parametrize('scheme', (['ws', 'wss']))
- def test_websocket_unavailable_error(self, scheme):
- with AllUnsupportedRHYDL() as ydl:
- with pytest.raises(RequestError, match=r'This request requires WebSocket support'):
- ydl.urlopen(f'{scheme}://')
-
- def test_legacy_server_connect_error(self):
- with FakeRHYDL() as ydl:
- for error in ('UNSAFE_LEGACY_RENEGOTIATION_DISABLED', 'SSLV3_ALERT_HANDSHAKE_FAILURE'):
- with pytest.raises(RequestError, match=r'Try using --legacy-server-connect'):
- ydl.urlopen(f'ssl://{error}')
-
- with pytest.raises(SSLError, match='testerror'):
- ydl.urlopen('ssl://testerror')
-
- def test_unsupported_impersonate_target(self):
- class FakeImpersonationRHYDL(FakeYDL):
- def __init__(self, *args, **kwargs):
- class HTTPRH(RequestHandler):
- def _send(self, request: Request):
- pass
- _SUPPORTED_URL_SCHEMES = ('http',)
- _SUPPORTED_PROXY_SCHEMES = None
-
- super().__init__(*args, **kwargs)
- self._request_director = self.build_request_director([HTTPRH])
-
- with FakeImpersonationRHYDL() as ydl:
- with pytest.raises(
- RequestError,
- match=r'Impersonate target "test" is not available',
- ):
- ydl.urlopen(Request('http://', extensions={'impersonate': ImpersonateTarget('test', None, None, None)}))
-
- def test_unsupported_impersonate_extension(self):
- class FakeHTTPRHYDL(FakeYDL):
- def __init__(self, *args, **kwargs):
- class IRH(ImpersonateRequestHandler):
- def _send(self, request: Request):
- pass
-
- _SUPPORTED_URL_SCHEMES = ('http',)
- _SUPPORTED_IMPERSONATE_TARGET_MAP = {ImpersonateTarget('abc'): 'test'}
- _SUPPORTED_PROXY_SCHEMES = None
-
- super().__init__(*args, **kwargs)
- self._request_director = self.build_request_director([IRH])
-
- with FakeHTTPRHYDL() as ydl:
- with pytest.raises(
- RequestError,
- match=r'Impersonate target "test" is not available',
- ):
- ydl.urlopen(Request('http://', extensions={'impersonate': ImpersonateTarget('test', None, None, None)}))
-
- def test_raise_impersonate_error(self):
- with pytest.raises(
- YoutubeDLError,
- match=r'Impersonate target "test" is not available',
- ):
- FakeYDL({'impersonate': ImpersonateTarget('test', None, None, None)})
-
- def test_pass_impersonate_param(self, monkeypatch):
-
- class IRH(ImpersonateRequestHandler):
- def _send(self, request: Request):
- pass
-
- _SUPPORTED_URL_SCHEMES = ('http',)
- _SUPPORTED_IMPERSONATE_TARGET_MAP = {ImpersonateTarget('abc'): 'test'}
-
- # Bypass the check on initialize
- brh = FakeYDL.build_request_director
- monkeypatch.setattr(FakeYDL, 'build_request_director', lambda cls, handlers, preferences=None: brh(cls, handlers=[IRH]))
-
- with FakeYDL({
- 'impersonate': ImpersonateTarget('abc', None, None, None),
- }) as ydl:
- rh = self.build_handler(ydl, IRH)
- assert rh.impersonate == ImpersonateTarget('abc', None, None, None)
-
- def test_get_impersonate_targets(self):
- handlers = []
- for target_client in ('abc', 'xyz', 'asd'):
- class TestRH(ImpersonateRequestHandler):
- def _send(self, request: Request):
- pass
- _SUPPORTED_URL_SCHEMES = ('http',)
- _SUPPORTED_IMPERSONATE_TARGET_MAP = {ImpersonateTarget(target_client): 'test'}
- RH_KEY = target_client
- RH_NAME = target_client
- handlers.append(TestRH)
-
- with FakeYDL() as ydl:
- ydl._request_director = ydl.build_request_director(handlers)
- assert set(ydl._get_available_impersonate_targets()) == {
- (ImpersonateTarget('xyz'), 'xyz'),
- (ImpersonateTarget('abc'), 'abc'),
- (ImpersonateTarget('asd'), 'asd'),
- }
- assert ydl._impersonate_target_available(ImpersonateTarget('abc'))
- assert ydl._impersonate_target_available(ImpersonateTarget())
- assert not ydl._impersonate_target_available(ImpersonateTarget('zxy'))
-
- @pytest.mark.parametrize('proxy_key,proxy_url,expected', [
- ('http', '__noproxy__', None),
- ('no', '127.0.0.1,foo.bar', '127.0.0.1,foo.bar'),
- ('https', 'example.com', 'http://example.com'),
- ('https', '//example.com', 'http://example.com'),
- ('https', 'socks5://example.com', 'socks5h://example.com'),
- ('http', 'socks://example.com', 'socks4://example.com'),
- ('http', 'socks4://example.com', 'socks4://example.com'),
- ('unrelated', '/bad/proxy', '/bad/proxy'), # clean_proxies should ignore bad proxies
- ])
- def test_clean_proxy(self, proxy_key, proxy_url, expected, monkeypatch):
- # proxies should be cleaned in urlopen()
- with FakeRHYDL() as ydl:
- req = ydl.urlopen(Request('test://', proxies={proxy_key: proxy_url})).request
- assert req.proxies[proxy_key] == expected
-
- # and should also be cleaned when building the handler
- monkeypatch.setenv(f'{proxy_key.upper()}_PROXY', proxy_url)
- with FakeYDL() as ydl:
- rh = self.build_handler(ydl)
- assert rh.proxies[proxy_key] == expected
-
- def test_clean_proxy_header(self):
- with FakeRHYDL() as ydl:
- req = ydl.urlopen(Request('test://', headers={'ytdl-request-proxy': '//foo.bar'})).request
- assert 'ytdl-request-proxy' not in req.headers
- assert req.proxies == {'all': 'http://foo.bar'}
-
- with FakeYDL({'http_headers': {'ytdl-request-proxy': '//foo.bar'}}) as ydl:
- rh = self.build_handler(ydl)
- assert 'ytdl-request-proxy' not in rh.headers
- assert rh.proxies == {'all': 'http://foo.bar'}
-
- def test_clean_header(self):
- with FakeRHYDL() as ydl:
- res = ydl.urlopen(Request('test://', headers={'Youtubedl-no-compression': True}))
- assert 'Youtubedl-no-compression' not in res.request.headers
- assert res.request.headers.get('Accept-Encoding') == 'identity'
-
- with FakeYDL({'http_headers': {'Youtubedl-no-compression': True}}) as ydl:
- rh = self.build_handler(ydl)
- assert 'Youtubedl-no-compression' not in rh.headers
- assert rh.headers.get('Accept-Encoding') == 'identity'
-
- with FakeYDL({'http_headers': {'Ytdl-socks-proxy': 'socks://localhost:1080'}}) as ydl:
- rh = self.build_handler(ydl)
- assert 'Ytdl-socks-proxy' not in rh.headers
-
- def test_build_handler_params(self):
- with FakeYDL({
- 'http_headers': {'test': 'testtest'},
- 'socket_timeout': 2,
- 'proxy': 'http://127.0.0.1:8080',
- 'source_address': '127.0.0.45',
- 'debug_printtraffic': True,
- 'compat_opts': ['no-certifi'],
- 'nocheckcertificate': True,
- 'legacyserverconnect': True,
- }) as ydl:
- rh = self.build_handler(ydl)
- assert rh.headers.get('test') == 'testtest'
- assert 'Accept' in rh.headers # ensure std_headers are still there
- assert rh.timeout == 2
- assert rh.proxies.get('all') == 'http://127.0.0.1:8080'
- assert rh.source_address == '127.0.0.45'
- assert rh.verbose is True
- assert rh.prefer_system_certs is True
- assert rh.verify is False
- assert rh.legacy_ssl_support is True
-
- @pytest.mark.parametrize('ydl_params', [
- {'client_certificate': 'fakecert.crt'},
- {'client_certificate': 'fakecert.crt', 'client_certificate_key': 'fakekey.key'},
- {'client_certificate': 'fakecert.crt', 'client_certificate_key': 'fakekey.key', 'client_certificate_password': 'foobar'},
- {'client_certificate_key': 'fakekey.key', 'client_certificate_password': 'foobar'},
- ])
- def test_client_certificate(self, ydl_params):
- with FakeYDL(ydl_params) as ydl:
- rh = self.build_handler(ydl)
- assert rh._client_cert == ydl_params # XXX: Too bound to implementation
-
- def test_urllib_file_urls(self):
- with FakeYDL({'enable_file_urls': False}) as ydl:
- rh = self.build_handler(ydl, UrllibRH)
- assert rh.enable_file_urls is False
-
- with FakeYDL({'enable_file_urls': True}) as ydl:
- rh = self.build_handler(ydl, UrllibRH)
- assert rh.enable_file_urls is True
-
- def test_compat_opt_prefer_urllib(self):
- # This assumes urllib only has a preference when this compat opt is given
- with FakeYDL({'compat_opts': ['prefer-legacy-http-handler']}) as ydl:
- director = ydl.build_request_director([UrllibRH])
- assert len(director.preferences) == 1
- assert director.preferences.pop()(UrllibRH, None)
-
-
-class TestRequest:
-
- def test_query(self):
- req = Request('http://example.com?q=something', query={'v': 'xyz'})
- assert req.url == 'http://example.com?q=something&v=xyz'
-
- req.update(query={'v': '123'})
- assert req.url == 'http://example.com?q=something&v=123'
- req.update(url='http://example.com', query={'v': 'xyz'})
- assert req.url == 'http://example.com?v=xyz'
-
- def test_method(self):
- req = Request('http://example.com')
- assert req.method == 'GET'
- req.data = b'test'
- assert req.method == 'POST'
- req.data = None
- assert req.method == 'GET'
- req.data = b'test2'
- req.method = 'PUT'
- assert req.method == 'PUT'
- req.data = None
- assert req.method == 'PUT'
- with pytest.raises(TypeError):
- req.method = 1
-
- def test_request_helpers(self):
- assert HEADRequest('http://example.com').method == 'HEAD'
- assert PATCHRequest('http://example.com').method == 'PATCH'
- assert PUTRequest('http://example.com').method == 'PUT'
-
- def test_headers(self):
- req = Request('http://example.com', headers={'tesT': 'test'})
- assert req.headers == HTTPHeaderDict({'test': 'test'})
- req.update(headers={'teSt2': 'test2'})
- assert req.headers == HTTPHeaderDict({'test': 'test', 'test2': 'test2'})
-
- req.headers = new_headers = HTTPHeaderDict({'test': 'test'})
- assert req.headers == HTTPHeaderDict({'test': 'test'})
- assert req.headers is new_headers
-
- # test converts dict to case insensitive dict
- req.headers = new_headers = {'test2': 'test2'}
- assert isinstance(req.headers, HTTPHeaderDict)
- assert req.headers is not new_headers
-
- with pytest.raises(TypeError):
- req.headers = None
-
- def test_data_type(self):
- req = Request('http://example.com')
- assert req.data is None
- # test bytes is allowed
- req.data = b'test'
- assert req.data == b'test'
- # test iterable of bytes is allowed
- i = [b'test', b'test2']
- req.data = i
- assert req.data == i
-
- # test file-like object is allowed
- f = io.BytesIO(b'test')
- req.data = f
- assert req.data == f
-
- # common mistake: test str not allowed
- with pytest.raises(TypeError):
- req.data = 'test'
- assert req.data != 'test'
-
- # common mistake: test dict is not allowed
- with pytest.raises(TypeError):
- req.data = {'test': 'test'}
- assert req.data != {'test': 'test'}
-
- def test_content_length_header(self):
- req = Request('http://example.com', headers={'Content-Length': '0'}, data=b'')
- assert req.headers.get('Content-Length') == '0'
-
- req.data = b'test'
- assert 'Content-Length' not in req.headers
-
- req = Request('http://example.com', headers={'Content-Length': '10'})
- assert 'Content-Length' not in req.headers
-
- def test_content_type_header(self):
- req = Request('http://example.com', headers={'Content-Type': 'test'}, data=b'test')
- assert req.headers.get('Content-Type') == 'test'
- req.data = b'test2'
- assert req.headers.get('Content-Type') == 'test'
- req.data = None
- assert 'Content-Type' not in req.headers
- req.data = b'test3'
- assert req.headers.get('Content-Type') == 'application/x-www-form-urlencoded'
-
- def test_update_req(self):
- req = Request('http://example.com')
- assert req.data is None
- assert req.method == 'GET'
- assert 'Content-Type' not in req.headers
- # Test that zero-byte payloads will be sent
- req.update(data=b'')
- assert req.data == b''
- assert req.method == 'POST'
- assert req.headers.get('Content-Type') == 'application/x-www-form-urlencoded'
-
- def test_proxies(self):
- req = Request(url='http://example.com', proxies={'http': 'http://127.0.0.1:8080'})
- assert req.proxies == {'http': 'http://127.0.0.1:8080'}
-
- def test_extensions(self):
- req = Request(url='http://example.com', extensions={'timeout': 2})
- assert req.extensions == {'timeout': 2}
-
- def test_copy(self):
- req = Request(
- url='http://example.com',
- extensions={'cookiejar': CookieJar()},
- headers={'Accept-Encoding': 'br'},
- proxies={'http': 'http://127.0.0.1'},
- data=[b'123'],
- )
- req_copy = req.copy()
- assert req_copy is not req
- assert req_copy.url == req.url
- assert req_copy.headers == req.headers
- assert req_copy.headers is not req.headers
- assert req_copy.proxies == req.proxies
- assert req_copy.proxies is not req.proxies
-
- # Data is not able to be copied
- assert req_copy.data == req.data
- assert req_copy.data is req.data
-
- # Shallow copy extensions
- assert req_copy.extensions is not req.extensions
- assert req_copy.extensions['cookiejar'] == req.extensions['cookiejar']
-
- # Subclasses are copied by default
- class AnotherRequest(Request):
- pass
-
- req = AnotherRequest(url='http://127.0.0.1')
- assert isinstance(req.copy(), AnotherRequest)
-
- def test_url(self):
- req = Request(url='https://фtest.example.com/ some spaceв?ä=c')
- assert req.url == 'https://xn--test-z6d.example.com/%20some%20space%D0%B2?%C3%A4=c'
-
- assert Request(url='//example.com').url == 'http://example.com'
-
- with pytest.raises(TypeError):
- Request(url='https://').url = None
-
-
-class TestResponse:
-
- @pytest.mark.parametrize('reason,status,expected', [
- ('custom', 200, 'custom'),
- (None, 404, 'Not Found'), # fallback status
- ('', 403, 'Forbidden'),
- (None, 999, None),
- ])
- def test_reason(self, reason, status, expected):
- res = Response(io.BytesIO(b''), url='test://', headers={}, status=status, reason=reason)
- assert res.reason == expected
-
- def test_headers(self):
- headers = Message()
- headers.add_header('Test', 'test')
- headers.add_header('Test', 'test2')
- headers.add_header('content-encoding', 'br')
- res = Response(io.BytesIO(b''), headers=headers, url='test://')
- assert res.headers.get_all('test') == ['test', 'test2']
- assert 'Content-Encoding' in res.headers
-
- def test_get_header(self):
- headers = Message()
- headers.add_header('Set-Cookie', 'cookie1')
- headers.add_header('Set-cookie', 'cookie2')
- headers.add_header('Test', 'test')
- headers.add_header('Test', 'test2')
- res = Response(io.BytesIO(b''), headers=headers, url='test://')
- assert res.get_header('test') == 'test, test2'
- assert res.get_header('set-Cookie') == 'cookie1'
- assert res.get_header('notexist', 'default') == 'default'
-
- def test_compat(self):
- res = Response(io.BytesIO(b''), url='test://', status=404, headers={'test': 'test'})
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', category=DeprecationWarning)
- assert res.code == res.getcode() == res.status
- assert res.geturl() == res.url
- assert res.info() is res.headers
- assert res.getheader('test') == res.get_header('test')
-
- def test_auto_close(self):
- # Should mark the response as closed if the underlying file is closed
- class AutoCloseBytesIO(io.BytesIO):
- def read(self, size=-1, /):
- data = super().read(size)
- self.close()
- return data
-
- fp = AutoCloseBytesIO(b'test')
- res = Response(fp, url='test://', headers={}, status=200)
- assert not res.closed
- res.read()
- assert res.closed
-
- def test_close(self):
- # Should not call close() on the underlying file when already closed
- fp = MagicMock()
- fp.closed = False
- res = Response(fp, url='test://', headers={}, status=200)
- res.close()
- fp.closed = True
- res.close()
- assert fp.close.call_count == 1
-
-
-class TestImpersonateTarget:
- @pytest.mark.parametrize('target_str,expected', [
- ('abc', ImpersonateTarget('abc', None, None, None)),
- ('abc-120_esr', ImpersonateTarget('abc', '120_esr', None, None)),
- ('abc-120:xyz', ImpersonateTarget('abc', '120', 'xyz', None)),
- ('abc-120:xyz-5.6', ImpersonateTarget('abc', '120', 'xyz', '5.6')),
- ('abc:xyz', ImpersonateTarget('abc', None, 'xyz', None)),
- ('abc:', ImpersonateTarget('abc', None, None, None)),
- ('abc-120:', ImpersonateTarget('abc', '120', None, None)),
- (':xyz', ImpersonateTarget(None, None, 'xyz', None)),
- (':xyz-6.5', ImpersonateTarget(None, None, 'xyz', '6.5')),
- (':', ImpersonateTarget(None, None, None, None)),
- ('', ImpersonateTarget(None, None, None, None)),
- ])
- def test_target_from_str(self, target_str, expected):
- assert ImpersonateTarget.from_str(target_str) == expected
-
- @pytest.mark.parametrize('target_str', [
- '-120', ':-12.0', '-12:-12', '-:-',
- '::', 'a-c-d:', 'a-c-d:e-f-g', 'a:b:',
- ])
- def test_target_from_invalid_str(self, target_str):
- with pytest.raises(ValueError):
- ImpersonateTarget.from_str(target_str)
-
- @pytest.mark.parametrize('target,expected', [
- (ImpersonateTarget('abc', None, None, None), 'abc'),
- (ImpersonateTarget('abc', '120', None, None), 'abc-120'),
- (ImpersonateTarget('abc', '120', 'xyz', None), 'abc-120:xyz'),
- (ImpersonateTarget('abc', '120', 'xyz', '5'), 'abc-120:xyz-5'),
- (ImpersonateTarget('abc', None, 'xyz', None), 'abc:xyz'),
- (ImpersonateTarget('abc', '120', None, None), 'abc-120'),
- (ImpersonateTarget('abc', '120', 'xyz', None), 'abc-120:xyz'),
- (ImpersonateTarget('abc', None, 'xyz'), 'abc:xyz'),
- (ImpersonateTarget(None, None, 'xyz', '6.5'), ':xyz-6.5'),
- (ImpersonateTarget('abc'), 'abc'),
- (ImpersonateTarget(None, None, None, None), ''),
- ])
- def test_str(self, target, expected):
- assert str(target) == expected
-
- @pytest.mark.parametrize('args', [
- ('abc', None, None, '5'),
- ('abc', '120', None, '5'),
- (None, '120', None, None),
- (None, '120', None, '5'),
- (None, None, None, '5'),
- (None, '120', 'xyz', '5'),
- ])
- def test_invalid_impersonate_target(self, args):
- with pytest.raises(ValueError):
- ImpersonateTarget(*args)
-
- @pytest.mark.parametrize('target1,target2,is_in,is_eq', [
- (ImpersonateTarget('abc', None, None, None), ImpersonateTarget('abc', None, None, None), True, True),
- (ImpersonateTarget('abc', None, None, None), ImpersonateTarget('abc', '120', None, None), True, False),
- (ImpersonateTarget('abc', None, 'xyz', 'test'), ImpersonateTarget('abc', '120', 'xyz', None), True, False),
- (ImpersonateTarget('abc', '121', 'xyz', 'test'), ImpersonateTarget('abc', '120', 'xyz', 'test'), False, False),
- (ImpersonateTarget('abc'), ImpersonateTarget('abc', '120', 'xyz', 'test'), True, False),
- (ImpersonateTarget('abc', '120', 'xyz', 'test'), ImpersonateTarget('abc'), True, False),
- (ImpersonateTarget(), ImpersonateTarget('abc', '120', 'xyz'), True, False),
- (ImpersonateTarget(), ImpersonateTarget(), True, True),
- ])
- def test_impersonate_target_in(self, target1, target2, is_in, is_eq):
- assert (target1 in target2) is is_in
- assert (target1 == target2) is is_eq
diff --git a/test/test_networking_utils.py b/test/test_networking_utils.py
deleted file mode 100644
index a2feacba7..000000000
--- a/test/test_networking_utils.py
+++ /dev/null
@@ -1,207 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-
-import pytest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-import io
-import random
-import ssl
-
-from yt_dlp.cookies import YoutubeDLCookieJar
-from yt_dlp.dependencies import certifi
-from yt_dlp.networking import Response
-from yt_dlp.networking._helper import (
- InstanceStoreMixin,
- add_accept_encoding_header,
- get_redirect_method,
- make_socks_proxy_opts,
- ssl_load_certs,
-)
-from yt_dlp.networking.exceptions import (
- HTTPError,
- IncompleteRead,
-)
-from yt_dlp.socks import ProxyType
-from yt_dlp.utils.networking import HTTPHeaderDict, select_proxy
-
-TEST_DIR = os.path.dirname(os.path.abspath(__file__))
-
-
-class TestNetworkingUtils:
-
- def test_select_proxy(self):
- proxies = {
- 'all': 'socks5://example.com',
- 'http': 'http://example.com:1080',
- 'no': 'bypass.example.com,yt-dl.org',
- }
-
- assert select_proxy('https://example.com', proxies) == proxies['all']
- assert select_proxy('http://example.com', proxies) == proxies['http']
- assert select_proxy('http://bypass.example.com', proxies) is None
- assert select_proxy('https://yt-dl.org', proxies) is None
-
- @pytest.mark.parametrize('socks_proxy,expected', [
- ('socks5h://example.com', {
- 'proxytype': ProxyType.SOCKS5,
- 'addr': 'example.com',
- 'port': 1080,
- 'rdns': True,
- 'username': None,
- 'password': None,
- }),
- ('socks5://user:@example.com:5555', {
- 'proxytype': ProxyType.SOCKS5,
- 'addr': 'example.com',
- 'port': 5555,
- 'rdns': False,
- 'username': 'user',
- 'password': '',
- }),
- ('socks4://u%40ser:pa%20ss@127.0.0.1:1080', {
- 'proxytype': ProxyType.SOCKS4,
- 'addr': '127.0.0.1',
- 'port': 1080,
- 'rdns': False,
- 'username': 'u@ser',
- 'password': 'pa ss',
- }),
- ('socks4a://:pa%20ss@127.0.0.1', {
- 'proxytype': ProxyType.SOCKS4A,
- 'addr': '127.0.0.1',
- 'port': 1080,
- 'rdns': True,
- 'username': '',
- 'password': 'pa ss',
- }),
- ])
- def test_make_socks_proxy_opts(self, socks_proxy, expected):
- assert make_socks_proxy_opts(socks_proxy) == expected
-
- def test_make_socks_proxy_unknown(self):
- with pytest.raises(ValueError, match='Unknown SOCKS proxy version: socks'):
- make_socks_proxy_opts('socks://127.0.0.1')
-
- @pytest.mark.skipif(not certifi, reason='certifi is not installed')
- def test_load_certifi(self):
- context_certifi = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
- context_certifi.load_verify_locations(cafile=certifi.where())
- context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
- ssl_load_certs(context, use_certifi=True)
- assert context.get_ca_certs() == context_certifi.get_ca_certs()
-
- context_default = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
- context_default.load_default_certs()
- context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
- ssl_load_certs(context, use_certifi=False)
- assert context.get_ca_certs() == context_default.get_ca_certs()
-
- if context_default.get_ca_certs() == context_certifi.get_ca_certs():
- pytest.skip('System uses certifi as default. The test is not valid')
-
- @pytest.mark.parametrize('method,status,expected', [
- ('GET', 303, 'GET'),
- ('HEAD', 303, 'HEAD'),
- ('PUT', 303, 'GET'),
- ('POST', 301, 'GET'),
- ('HEAD', 301, 'HEAD'),
- ('POST', 302, 'GET'),
- ('HEAD', 302, 'HEAD'),
- ('PUT', 302, 'PUT'),
- ('POST', 308, 'POST'),
- ('POST', 307, 'POST'),
- ('HEAD', 308, 'HEAD'),
- ('HEAD', 307, 'HEAD'),
- ])
- def test_get_redirect_method(self, method, status, expected):
- assert get_redirect_method(method, status) == expected
-
- @pytest.mark.parametrize('headers,supported_encodings,expected', [
- ({'Accept-Encoding': 'br'}, ['gzip', 'br'], {'Accept-Encoding': 'br'}),
- ({}, ['gzip', 'br'], {'Accept-Encoding': 'gzip, br'}),
- ({'Content-type': 'application/json'}, [], {'Content-type': 'application/json', 'Accept-Encoding': 'identity'}),
- ])
- def test_add_accept_encoding_header(self, headers, supported_encodings, expected):
- headers = HTTPHeaderDict(headers)
- add_accept_encoding_header(headers, supported_encodings)
- assert headers == HTTPHeaderDict(expected)
-
-
-class TestInstanceStoreMixin:
-
- class FakeInstanceStoreMixin(InstanceStoreMixin):
- def _create_instance(self, **kwargs):
- return random.randint(0, 1000000)
-
- def _close_instance(self, instance):
- pass
-
- def test_mixin(self):
- mixin = self.FakeInstanceStoreMixin()
- assert mixin._get_instance(d={'a': 1, 'b': 2, 'c': {'d', 4}}) == mixin._get_instance(d={'a': 1, 'b': 2, 'c': {'d', 4}})
-
- assert mixin._get_instance(d={'a': 1, 'b': 2, 'c': {'e', 4}}) != mixin._get_instance(d={'a': 1, 'b': 2, 'c': {'d', 4}})
-
- assert mixin._get_instance(d={'a': 1, 'b': 2, 'c': {'d', 4}} != mixin._get_instance(d={'a': 1, 'b': 2, 'g': {'d', 4}}))
-
- assert mixin._get_instance(d={'a': 1}, e=[1, 2, 3]) == mixin._get_instance(d={'a': 1}, e=[1, 2, 3])
-
- assert mixin._get_instance(d={'a': 1}, e=[1, 2, 3]) != mixin._get_instance(d={'a': 1}, e=[1, 2, 3, 4])
-
- cookiejar = YoutubeDLCookieJar()
- assert mixin._get_instance(b=[1, 2], c=cookiejar) == mixin._get_instance(b=[1, 2], c=cookiejar)
-
- assert mixin._get_instance(b=[1, 2], c=cookiejar) != mixin._get_instance(b=[1, 2], c=YoutubeDLCookieJar())
-
- # Different order
- assert mixin._get_instance(c=cookiejar, b=[1, 2]) == mixin._get_instance(b=[1, 2], c=cookiejar)
-
- m = mixin._get_instance(t=1234)
- assert mixin._get_instance(t=1234) == m
- mixin._clear_instances()
- assert mixin._get_instance(t=1234) != m
-
-
-class TestNetworkingExceptions:
-
- @staticmethod
- def create_response(status):
- return Response(fp=io.BytesIO(b'test'), url='http://example.com', headers={'tesT': 'test'}, status=status)
-
- def test_http_error(self):
-
- response = self.create_response(403)
- error = HTTPError(response)
-
- assert error.status == 403
- assert str(error) == error.msg == 'HTTP Error 403: Forbidden'
- assert error.reason == response.reason
- assert error.response is response
-
- data = error.response.read()
- assert data == b'test'
- assert repr(error) == ''
-
- def test_redirect_http_error(self):
- response = self.create_response(301)
- error = HTTPError(response, redirect_loop=True)
- assert str(error) == error.msg == 'HTTP Error 301: Moved Permanently (redirect loop detected)'
- assert error.reason == 'Moved Permanently'
-
- def test_incomplete_read_error(self):
- error = IncompleteRead(4, 3, cause='test')
- assert isinstance(error, IncompleteRead)
- assert repr(error) == ''
- assert str(error) == error.msg == '4 bytes read, 3 more expected'
- assert error.partial == 4
- assert error.expected == 3
- assert error.cause == 'test'
-
- error = IncompleteRead(3)
- assert repr(error) == ''
- assert str(error) == '3 bytes read'
diff --git a/test/test_overwrites.py b/test/test_overwrites.py
deleted file mode 100644
index 96a77a008..000000000
--- a/test/test_overwrites.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import subprocess
-
-from test.helper import is_download_test, try_rm
-
-root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-download_file = os.path.join(root_dir, 'test.webm')
-
-
-@is_download_test
-class TestOverwrites(unittest.TestCase):
- def setUp(self):
- # create an empty file
- open(download_file, 'a').close()
-
- def test_default_overwrites(self):
- outp = subprocess.Popen(
- [
- sys.executable, 'yt_dlp/__main__.py',
- '-o', 'test.webm',
- 'https://www.youtube.com/watch?v=jNQXAC9IVRw',
- ], cwd=root_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- sout, _ = outp.communicate()
- self.assertTrue(b'has already been downloaded' in sout)
- # if the file has no content, it has not been redownloaded
- self.assertTrue(os.path.getsize(download_file) < 1)
-
- def test_yes_overwrites(self):
- outp = subprocess.Popen(
- [
- sys.executable, 'yt_dlp/__main__.py', '--yes-overwrites',
- '-o', 'test.webm',
- 'https://www.youtube.com/watch?v=jNQXAC9IVRw',
- ], cwd=root_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- sout, _ = outp.communicate()
- self.assertTrue(b'has already been downloaded' not in sout)
- # if the file has no content, it has not been redownloaded
- self.assertTrue(os.path.getsize(download_file) > 1)
-
- def tearDown(self):
- try_rm(os.path.join(root_dir, 'test.webm'))
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_plugins.py b/test/test_plugins.py
deleted file mode 100644
index 195726b18..000000000
--- a/test/test_plugins.py
+++ /dev/null
@@ -1,246 +0,0 @@
-import importlib
-import os
-import shutil
-import sys
-import unittest
-from pathlib import Path
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-TEST_DATA_DIR = Path(os.path.dirname(os.path.abspath(__file__)), 'testdata')
-sys.path.append(str(TEST_DATA_DIR))
-importlib.invalidate_caches()
-
-from yt_dlp.plugins import (
- PACKAGE_NAME,
- PluginSpec,
- directories,
- load_plugins,
- load_all_plugins,
- register_plugin_spec,
-)
-
-from yt_dlp.globals import (
- extractors,
- postprocessors,
- plugin_dirs,
- plugin_ies,
- plugin_pps,
- all_plugins_loaded,
- plugin_specs,
-)
-
-
-EXTRACTOR_PLUGIN_SPEC = PluginSpec(
- module_name='extractor',
- suffix='IE',
- destination=extractors,
- plugin_destination=plugin_ies,
-)
-
-POSTPROCESSOR_PLUGIN_SPEC = PluginSpec(
- module_name='postprocessor',
- suffix='PP',
- destination=postprocessors,
- plugin_destination=plugin_pps,
-)
-
-
-def reset_plugins():
- plugin_ies.value = {}
- plugin_pps.value = {}
- plugin_dirs.value = ['default']
- plugin_specs.value = {}
- all_plugins_loaded.value = False
- # Clearing override plugins is probably difficult
- for module_name in tuple(sys.modules):
- for plugin_type in ('extractor', 'postprocessor'):
- if module_name.startswith(f'{PACKAGE_NAME}.{plugin_type}.'):
- del sys.modules[module_name]
-
- importlib.invalidate_caches()
-
-
-class TestPlugins(unittest.TestCase):
-
- TEST_PLUGIN_DIR = TEST_DATA_DIR / PACKAGE_NAME
-
- def setUp(self):
- reset_plugins()
-
- def tearDown(self):
- reset_plugins()
-
- def test_directories_containing_plugins(self):
- self.assertIn(self.TEST_PLUGIN_DIR, map(Path, directories()))
-
- def test_extractor_classes(self):
- plugins_ie = load_plugins(EXTRACTOR_PLUGIN_SPEC)
-
- self.assertIn(f'{PACKAGE_NAME}.extractor.normal', sys.modules.keys())
- self.assertIn('NormalPluginIE', plugins_ie.keys())
-
- # don't load modules with underscore prefix
- self.assertFalse(
- f'{PACKAGE_NAME}.extractor._ignore' in sys.modules,
- 'loaded module beginning with underscore')
- self.assertNotIn('IgnorePluginIE', plugins_ie.keys())
- self.assertNotIn('IgnorePluginIE', plugin_ies.value)
-
- # Don't load extractors with underscore prefix
- self.assertNotIn('_IgnoreUnderscorePluginIE', plugins_ie.keys())
- self.assertNotIn('_IgnoreUnderscorePluginIE', plugin_ies.value)
-
- # Don't load extractors not specified in __all__ (if supplied)
- self.assertNotIn('IgnoreNotInAllPluginIE', plugins_ie.keys())
- self.assertNotIn('IgnoreNotInAllPluginIE', plugin_ies.value)
- self.assertIn('InAllPluginIE', plugins_ie.keys())
- self.assertIn('InAllPluginIE', plugin_ies.value)
-
- # Don't load override extractors
- self.assertNotIn('OverrideGenericIE', plugins_ie.keys())
- self.assertNotIn('OverrideGenericIE', plugin_ies.value)
- self.assertNotIn('_UnderscoreOverrideGenericIE', plugins_ie.keys())
- self.assertNotIn('_UnderscoreOverrideGenericIE', plugin_ies.value)
-
- def test_postprocessor_classes(self):
- plugins_pp = load_plugins(POSTPROCESSOR_PLUGIN_SPEC)
- self.assertIn('NormalPluginPP', plugins_pp.keys())
- self.assertIn(f'{PACKAGE_NAME}.postprocessor.normal', sys.modules.keys())
- self.assertIn('NormalPluginPP', plugin_pps.value)
-
- def test_importing_zipped_module(self):
- zip_path = TEST_DATA_DIR / 'zipped_plugins.zip'
- shutil.make_archive(str(zip_path)[:-4], 'zip', str(zip_path)[:-4])
- sys.path.append(str(zip_path)) # add zip to search paths
- importlib.invalidate_caches() # reset the import caches
-
- try:
- for plugin_type in ('extractor', 'postprocessor'):
- package = importlib.import_module(f'{PACKAGE_NAME}.{plugin_type}')
- self.assertIn(zip_path / PACKAGE_NAME / plugin_type, map(Path, package.__path__))
-
- plugins_ie = load_plugins(EXTRACTOR_PLUGIN_SPEC)
- self.assertIn('ZippedPluginIE', plugins_ie.keys())
-
- plugins_pp = load_plugins(POSTPROCESSOR_PLUGIN_SPEC)
- self.assertIn('ZippedPluginPP', plugins_pp.keys())
-
- finally:
- sys.path.remove(str(zip_path))
- os.remove(zip_path)
- importlib.invalidate_caches() # reset the import caches
-
- def test_reloading_plugins(self):
- reload_plugins_path = TEST_DATA_DIR / 'reload_plugins'
- load_plugins(EXTRACTOR_PLUGIN_SPEC)
- load_plugins(POSTPROCESSOR_PLUGIN_SPEC)
-
- # Remove default folder and add reload_plugin path
- sys.path.remove(str(TEST_DATA_DIR))
- sys.path.append(str(reload_plugins_path))
- importlib.invalidate_caches()
- try:
- for plugin_type in ('extractor', 'postprocessor'):
- package = importlib.import_module(f'{PACKAGE_NAME}.{plugin_type}')
- self.assertIn(reload_plugins_path / PACKAGE_NAME / plugin_type, map(Path, package.__path__))
-
- plugins_ie = load_plugins(EXTRACTOR_PLUGIN_SPEC)
- self.assertIn('NormalPluginIE', plugins_ie.keys())
- self.assertTrue(
- plugins_ie['NormalPluginIE'].REPLACED,
- msg='Reloading has not replaced original extractor plugin')
- self.assertTrue(
- extractors.value['NormalPluginIE'].REPLACED,
- msg='Reloading has not replaced original extractor plugin globally')
-
- plugins_pp = load_plugins(POSTPROCESSOR_PLUGIN_SPEC)
- self.assertIn('NormalPluginPP', plugins_pp.keys())
- self.assertTrue(plugins_pp['NormalPluginPP'].REPLACED,
- msg='Reloading has not replaced original postprocessor plugin')
- self.assertTrue(
- postprocessors.value['NormalPluginPP'].REPLACED,
- msg='Reloading has not replaced original postprocessor plugin globally')
-
- finally:
- sys.path.remove(str(reload_plugins_path))
- sys.path.append(str(TEST_DATA_DIR))
- importlib.invalidate_caches()
-
- def test_extractor_override_plugin(self):
- load_plugins(EXTRACTOR_PLUGIN_SPEC)
-
- from yt_dlp.extractor.generic import GenericIE
-
- self.assertEqual(GenericIE.TEST_FIELD, 'override')
- self.assertEqual(GenericIE.SECONDARY_TEST_FIELD, 'underscore-override')
-
- self.assertEqual(GenericIE.IE_NAME, 'generic+override+underscore-override')
- importlib.invalidate_caches()
- # test that loading a second time doesn't wrap a second time
- load_plugins(EXTRACTOR_PLUGIN_SPEC)
- from yt_dlp.extractor.generic import GenericIE
- self.assertEqual(GenericIE.IE_NAME, 'generic+override+underscore-override')
-
- def test_load_all_plugin_types(self):
-
- # no plugin specs registered
- load_all_plugins()
-
- self.assertNotIn(f'{PACKAGE_NAME}.extractor.normal', sys.modules.keys())
- self.assertNotIn(f'{PACKAGE_NAME}.postprocessor.normal', sys.modules.keys())
-
- register_plugin_spec(EXTRACTOR_PLUGIN_SPEC)
- register_plugin_spec(POSTPROCESSOR_PLUGIN_SPEC)
- load_all_plugins()
- self.assertTrue(all_plugins_loaded.value)
-
- self.assertIn(f'{PACKAGE_NAME}.extractor.normal', sys.modules.keys())
- self.assertIn(f'{PACKAGE_NAME}.postprocessor.normal', sys.modules.keys())
-
- def test_no_plugin_dirs(self):
- register_plugin_spec(EXTRACTOR_PLUGIN_SPEC)
- register_plugin_spec(POSTPROCESSOR_PLUGIN_SPEC)
-
- plugin_dirs.value = []
- load_all_plugins()
-
- self.assertNotIn(f'{PACKAGE_NAME}.extractor.normal', sys.modules.keys())
- self.assertNotIn(f'{PACKAGE_NAME}.postprocessor.normal', sys.modules.keys())
-
- def test_set_plugin_dirs(self):
- custom_plugin_dir = str(TEST_DATA_DIR / 'plugin_packages')
- plugin_dirs.value = [custom_plugin_dir]
-
- load_plugins(EXTRACTOR_PLUGIN_SPEC)
-
- self.assertIn(f'{PACKAGE_NAME}.extractor.package', sys.modules.keys())
- self.assertIn('PackagePluginIE', plugin_ies.value)
-
- def test_invalid_plugin_dir(self):
- plugin_dirs.value = ['invalid_dir']
- with self.assertRaises(ValueError):
- load_plugins(EXTRACTOR_PLUGIN_SPEC)
-
- def test_append_plugin_dirs(self):
- custom_plugin_dir = str(TEST_DATA_DIR / 'plugin_packages')
-
- self.assertEqual(plugin_dirs.value, ['default'])
- plugin_dirs.value.append(custom_plugin_dir)
- self.assertEqual(plugin_dirs.value, ['default', custom_plugin_dir])
-
- load_plugins(EXTRACTOR_PLUGIN_SPEC)
-
- self.assertIn(f'{PACKAGE_NAME}.extractor.package', sys.modules.keys())
- self.assertIn('PackagePluginIE', plugin_ies.value)
-
- def test_get_plugin_spec(self):
- register_plugin_spec(EXTRACTOR_PLUGIN_SPEC)
- register_plugin_spec(POSTPROCESSOR_PLUGIN_SPEC)
-
- self.assertEqual(plugin_specs.value.get('extractor'), EXTRACTOR_PLUGIN_SPEC)
- self.assertEqual(plugin_specs.value.get('postprocessor'), POSTPROCESSOR_PLUGIN_SPEC)
- self.assertIsNone(plugin_specs.value.get('invalid'))
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_post_hooks.py b/test/test_post_hooks.py
deleted file mode 100644
index 6500dd386..000000000
--- a/test/test_post_hooks.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-from test.helper import get_params, is_download_test, try_rm
-import yt_dlp.YoutubeDL # isort: split
-from yt_dlp.utils import DownloadError
-
-
-class YoutubeDL(yt_dlp.YoutubeDL):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.to_stderr = self.to_screen
-
-
-TEST_ID = 'gr51aVj-mLg'
-EXPECTED_NAME = 'gr51aVj-mLg'
-
-
-@is_download_test
-class TestPostHooks(unittest.TestCase):
- def setUp(self):
- self.stored_name_1 = None
- self.stored_name_2 = None
- self.params = get_params({
- 'skip_download': False,
- 'writeinfojson': False,
- 'quiet': True,
- 'verbose': False,
- 'cachedir': False,
- })
- self.files = []
-
- def test_post_hooks(self):
- self.params['post_hooks'] = [self.hook_one, self.hook_two]
- ydl = YoutubeDL(self.params)
- ydl.download([TEST_ID])
- self.assertEqual(self.stored_name_1, EXPECTED_NAME, 'Not the expected name from hook 1')
- self.assertEqual(self.stored_name_2, EXPECTED_NAME, 'Not the expected name from hook 2')
-
- def test_post_hook_exception(self):
- self.params['post_hooks'] = [self.hook_three]
- ydl = YoutubeDL(self.params)
- self.assertRaises(DownloadError, ydl.download, [TEST_ID])
-
- def hook_one(self, filename):
- self.stored_name_1, _ = os.path.splitext(os.path.basename(filename))
- self.files.append(filename)
-
- def hook_two(self, filename):
- self.stored_name_2, _ = os.path.splitext(os.path.basename(filename))
- self.files.append(filename)
-
- def hook_three(self, filename):
- self.files.append(filename)
- raise Exception(f'Test exception for \'{filename}\'')
-
- def tearDown(self):
- for f in self.files:
- try_rm(f)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_postprocessors.py b/test/test_postprocessors.py
deleted file mode 100644
index d58a97fc6..000000000
--- a/test/test_postprocessors.py
+++ /dev/null
@@ -1,636 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import subprocess
-
-from yt_dlp import YoutubeDL
-from yt_dlp.utils import shell_quote
-from yt_dlp.postprocessor import (
- ExecPP,
- FFmpegThumbnailsConvertorPP,
- MetadataFromFieldPP,
- MetadataParserPP,
- ModifyChaptersPP,
- SponsorBlockPP,
-)
-
-
-class TestMetadataFromField(unittest.TestCase):
-
- def test_format_to_regex(self):
- self.assertEqual(
- MetadataParserPP.format_to_regex('%(title)s - %(artist)s'),
- r'(?P.+)\ \-\ (?P.+)')
- self.assertEqual(MetadataParserPP.format_to_regex(r'(?P.+)'), r'(?P.+)')
- self.assertEqual(MetadataParserPP.format_to_regex(r'text (?P.+)'), r'text (?P.+)')
- self.assertEqual(MetadataParserPP.format_to_regex('x'), r'(?s)(?P.+)')
- self.assertEqual(MetadataParserPP.format_to_regex('Field_Name1'), r'(?s)(?P.+)')
- self.assertEqual(MetadataParserPP.format_to_regex('é'), r'(?s)(?P<é>.+)')
- self.assertEqual(MetadataParserPP.format_to_regex('invalid '), 'invalid ')
-
- def test_field_to_template(self):
- self.assertEqual(MetadataParserPP.field_to_template('title'), '%(title)s')
- self.assertEqual(MetadataParserPP.field_to_template('1'), '1')
- self.assertEqual(MetadataParserPP.field_to_template('foo bar'), 'foo bar')
- self.assertEqual(MetadataParserPP.field_to_template(' literal'), ' literal')
-
- def test_metadatafromfield(self):
- self.assertEqual(
- MetadataFromFieldPP.to_action('%(title)s \\: %(artist)s:%(title)s : %(artist)s'),
- (MetadataParserPP.Actions.INTERPRET, '%(title)s : %(artist)s', '%(title)s : %(artist)s'))
-
-
-class TestConvertThumbnail(unittest.TestCase):
- def test_escaping(self):
- pp = FFmpegThumbnailsConvertorPP()
- if not pp.available:
- print('Skipping: ffmpeg not found')
- return
-
- test_data_dir = 'test/testdata/thumbnails'
- generated_file = f'{test_data_dir}/empty.webp'
-
- subprocess.check_call([
- pp.executable, '-y', '-f', 'lavfi', '-i', 'color=c=black:s=320x320',
- '-c:v', 'libwebp', '-pix_fmt', 'yuv420p', '-vframes', '1', generated_file,
- ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
-
- file = test_data_dir + '/foo %d bar/foo_%d.{}'
- initial_file = file.format('webp')
- os.replace(generated_file, initial_file)
-
- tests = (('webp', 'png'), ('png', 'jpg'))
-
- for inp, out in tests:
- out_file = file.format(out)
- if os.path.exists(out_file):
- os.remove(out_file)
- pp.convert_thumbnail(file.format(inp), out)
- self.assertTrue(os.path.exists(out_file))
-
- for _, out in tests:
- os.remove(file.format(out))
-
- os.remove(initial_file)
-
-
-class TestExec(unittest.TestCase):
- def test_parse_cmd(self):
- pp = ExecPP(YoutubeDL(), '')
- info = {'filepath': 'file name'}
- cmd = 'echo {}'.format(shell_quote(info['filepath']))
-
- self.assertEqual(pp.parse_cmd('echo', info), cmd)
- self.assertEqual(pp.parse_cmd('echo {}', info), cmd)
- self.assertEqual(pp.parse_cmd('echo %(filepath)q', info), cmd)
-
-
-class TestModifyChaptersPP(unittest.TestCase):
- def setUp(self):
- self._pp = ModifyChaptersPP(YoutubeDL())
-
- @staticmethod
- def _sponsor_chapter(start, end, cat, remove=False, title=None):
- if title is None:
- title = SponsorBlockPP.CATEGORIES[cat]
- return {
- 'start_time': start,
- 'end_time': end,
- '_categories': [(cat, start, end, title)],
- **({'remove': True} if remove else {}),
- }
-
- @staticmethod
- def _chapter(start, end, title=None, remove=False):
- c = {'start_time': start, 'end_time': end}
- if title is not None:
- c['title'] = title
- if remove:
- c['remove'] = True
- return c
-
- def _chapters(self, ends, titles):
- self.assertEqual(len(ends), len(titles))
- start = 0
- chapters = []
- for e, t in zip(ends, titles, strict=True):
- chapters.append(self._chapter(start, e, t))
- start = e
- return chapters
-
- def _remove_marked_arrange_sponsors_test_impl(
- self, chapters, expected_chapters, expected_removed):
- actual_chapters, actual_removed = (
- self._pp._remove_marked_arrange_sponsors(chapters))
- for c in actual_removed:
- c.pop('title', None)
- c.pop('_categories', None)
- actual_chapters = [{
- 'start_time': c['start_time'],
- 'end_time': c['end_time'],
- 'title': c['title'],
- } for c in actual_chapters]
- self.assertSequenceEqual(expected_chapters, actual_chapters)
- self.assertSequenceEqual(expected_removed, actual_removed)
-
- def test_remove_marked_arrange_sponsors_CanGetThroughUnaltered(self):
- chapters = self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, chapters, [])
-
- def test_remove_marked_arrange_sponsors_ChapterWithSponsors(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 20, 'sponsor'),
- self._sponsor_chapter(30, 40, 'preview'),
- self._sponsor_chapter(50, 60, 'filler')]
- expected = self._chapters(
- [10, 20, 30, 40, 50, 60, 70],
- ['c', '[SponsorBlock]: Sponsor', 'c', '[SponsorBlock]: Preview/Recap',
- 'c', '[SponsorBlock]: Filler Tangent', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_SponsorBlockChapters(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 20, 'chapter', title='sb c1'),
- self._sponsor_chapter(15, 16, 'chapter', title='sb c2'),
- self._sponsor_chapter(30, 40, 'preview'),
- self._sponsor_chapter(50, 60, 'filler')]
- expected = self._chapters(
- [10, 15, 16, 20, 30, 40, 50, 60, 70],
- ['c', '[SponsorBlock]: sb c1', '[SponsorBlock]: sb c1, sb c2', '[SponsorBlock]: sb c1',
- 'c', '[SponsorBlock]: Preview/Recap',
- 'c', '[SponsorBlock]: Filler Tangent', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_UniqueNamesForOverlappingSponsors(self):
- chapters = [
- *self._chapters([120], ['c']),
- self._sponsor_chapter(10, 45, 'sponsor'),
- self._sponsor_chapter(20, 40, 'selfpromo'),
- self._sponsor_chapter(50, 70, 'sponsor'),
- self._sponsor_chapter(60, 85, 'selfpromo'),
- self._sponsor_chapter(90, 120, 'selfpromo'),
- self._sponsor_chapter(100, 110, 'sponsor')]
- expected = self._chapters(
- [10, 20, 40, 45, 50, 60, 70, 85, 90, 100, 110, 120],
- ['c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Sponsor, Unpaid/Self Promotion',
- '[SponsorBlock]: Sponsor',
- 'c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Sponsor, Unpaid/Self Promotion',
- '[SponsorBlock]: Unpaid/Self Promotion',
- 'c', '[SponsorBlock]: Unpaid/Self Promotion', '[SponsorBlock]: Unpaid/Self Promotion, Sponsor',
- '[SponsorBlock]: Unpaid/Self Promotion'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_ChapterWithCuts(self):
- cuts = [self._chapter(10, 20, remove=True),
- self._sponsor_chapter(30, 40, 'sponsor', remove=True),
- self._chapter(50, 60, remove=True)]
- chapters = self._chapters([70], ['c']) + cuts
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([40], ['c']), cuts)
-
- def test_remove_marked_arrange_sponsors_ChapterWithSponsorsAndCuts(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 20, 'sponsor'),
- self._sponsor_chapter(30, 40, 'selfpromo', remove=True),
- self._sponsor_chapter(50, 60, 'interaction')]
- expected = self._chapters([10, 20, 40, 50, 60],
- ['c', '[SponsorBlock]: Sponsor', 'c',
- '[SponsorBlock]: Interaction Reminder', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, expected, [self._chapter(30, 40, remove=True)])
-
- def test_remove_marked_arrange_sponsors_ChapterWithSponsorCutInTheMiddle(self):
- cuts = [self._sponsor_chapter(20, 30, 'selfpromo', remove=True),
- self._chapter(40, 50, remove=True)]
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 60, 'sponsor'),
- *cuts]
- expected = self._chapters(
- [10, 40, 50], ['c', '[SponsorBlock]: Sponsor', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_ChapterWithCutHidingSponsor(self):
- cuts = [self._sponsor_chapter(20, 50, 'selfpromo', remove=True)]
- chapters = [
- *self._chapters([60], ['c']),
- self._sponsor_chapter(10, 20, 'intro'),
- self._sponsor_chapter(30, 40, 'sponsor'),
- self._sponsor_chapter(50, 60, 'outro'),
- *cuts]
- expected = self._chapters(
- [10, 20, 30], ['c', '[SponsorBlock]: Intermission/Intro Animation', '[SponsorBlock]: Endcards/Credits'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_ChapterWithAdjacentSponsors(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 20, 'sponsor'),
- self._sponsor_chapter(20, 30, 'selfpromo'),
- self._sponsor_chapter(30, 40, 'interaction')]
- expected = self._chapters(
- [10, 20, 30, 40, 70],
- ['c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Unpaid/Self Promotion',
- '[SponsorBlock]: Interaction Reminder', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_ChapterWithAdjacentCuts(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 20, 'sponsor'),
- self._sponsor_chapter(20, 30, 'interaction', remove=True),
- self._chapter(30, 40, remove=True),
- self._sponsor_chapter(40, 50, 'selfpromo', remove=True),
- self._sponsor_chapter(50, 60, 'interaction')]
- expected = self._chapters([10, 20, 30, 40],
- ['c', '[SponsorBlock]: Sponsor',
- '[SponsorBlock]: Interaction Reminder', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, expected, [self._chapter(20, 50, remove=True)])
-
- def test_remove_marked_arrange_sponsors_ChapterWithOverlappingSponsors(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 30, 'sponsor'),
- self._sponsor_chapter(20, 50, 'selfpromo'),
- self._sponsor_chapter(40, 60, 'interaction')]
- expected = self._chapters(
- [10, 20, 30, 40, 50, 60, 70],
- ['c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Sponsor, Unpaid/Self Promotion',
- '[SponsorBlock]: Unpaid/Self Promotion', '[SponsorBlock]: Unpaid/Self Promotion, Interaction Reminder',
- '[SponsorBlock]: Interaction Reminder', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_ChapterWithOverlappingCuts(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 30, 'sponsor', remove=True),
- self._sponsor_chapter(20, 50, 'selfpromo', remove=True),
- self._sponsor_chapter(40, 60, 'interaction', remove=True)]
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([20], ['c']), [self._chapter(10, 60, remove=True)])
-
- def test_remove_marked_arrange_sponsors_ChapterWithRunsOfOverlappingSponsors(self):
- chapters = [
- *self._chapters([170], ['c']),
- self._sponsor_chapter(0, 30, 'intro'),
- self._sponsor_chapter(20, 50, 'sponsor'),
- self._sponsor_chapter(40, 60, 'selfpromo'),
- self._sponsor_chapter(70, 90, 'sponsor'),
- self._sponsor_chapter(80, 100, 'sponsor'),
- self._sponsor_chapter(90, 110, 'sponsor'),
- self._sponsor_chapter(120, 140, 'selfpromo'),
- self._sponsor_chapter(130, 160, 'interaction'),
- self._sponsor_chapter(150, 170, 'outro')]
- expected = self._chapters(
- [20, 30, 40, 50, 60, 70, 110, 120, 130, 140, 150, 160, 170],
- ['[SponsorBlock]: Intermission/Intro Animation', '[SponsorBlock]: Intermission/Intro Animation, Sponsor', '[SponsorBlock]: Sponsor',
- '[SponsorBlock]: Sponsor, Unpaid/Self Promotion', '[SponsorBlock]: Unpaid/Self Promotion', 'c',
- '[SponsorBlock]: Sponsor', 'c', '[SponsorBlock]: Unpaid/Self Promotion',
- '[SponsorBlock]: Unpaid/Self Promotion, Interaction Reminder',
- '[SponsorBlock]: Interaction Reminder',
- '[SponsorBlock]: Interaction Reminder, Endcards/Credits', '[SponsorBlock]: Endcards/Credits'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_ChapterWithRunsOfOverlappingCuts(self):
- chapters = [
- *self._chapters([170], ['c']),
- self._chapter(0, 30, remove=True),
- self._sponsor_chapter(20, 50, 'sponsor', remove=True),
- self._chapter(40, 60, remove=True),
- self._sponsor_chapter(70, 90, 'sponsor', remove=True),
- self._chapter(80, 100, remove=True),
- self._chapter(90, 110, remove=True),
- self._sponsor_chapter(120, 140, 'sponsor', remove=True),
- self._sponsor_chapter(130, 160, 'selfpromo', remove=True),
- self._chapter(150, 170, remove=True)]
- expected_cuts = [self._chapter(0, 60, remove=True),
- self._chapter(70, 110, remove=True),
- self._chapter(120, 170, remove=True)]
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([20], ['c']), expected_cuts)
-
- def test_remove_marked_arrange_sponsors_OverlappingSponsorsDifferentTitlesAfterCut(self):
- chapters = [
- *self._chapters([60], ['c']),
- self._sponsor_chapter(10, 60, 'sponsor'),
- self._sponsor_chapter(10, 40, 'intro'),
- self._sponsor_chapter(30, 50, 'interaction'),
- self._sponsor_chapter(30, 50, 'selfpromo', remove=True),
- self._sponsor_chapter(40, 50, 'interaction'),
- self._sponsor_chapter(50, 60, 'outro')]
- expected = self._chapters(
- [10, 30, 40], ['c', '[SponsorBlock]: Sponsor, Intermission/Intro Animation', '[SponsorBlock]: Sponsor, Endcards/Credits'])
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, expected, [self._chapter(30, 50, remove=True)])
-
- def test_remove_marked_arrange_sponsors_SponsorsNoLongerOverlapAfterCut(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 30, 'sponsor'),
- self._sponsor_chapter(20, 50, 'interaction'),
- self._sponsor_chapter(30, 50, 'selfpromo', remove=True),
- self._sponsor_chapter(40, 60, 'sponsor'),
- self._sponsor_chapter(50, 60, 'interaction')]
- expected = self._chapters(
- [10, 20, 40, 50], ['c', '[SponsorBlock]: Sponsor',
- '[SponsorBlock]: Sponsor, Interaction Reminder', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, expected, [self._chapter(30, 50, remove=True)])
-
- def test_remove_marked_arrange_sponsors_SponsorsStillOverlapAfterCut(self):
- chapters = [
- *self._chapters([70], ['c']),
- self._sponsor_chapter(10, 60, 'sponsor'),
- self._sponsor_chapter(20, 60, 'interaction'),
- self._sponsor_chapter(30, 50, 'selfpromo', remove=True)]
- expected = self._chapters(
- [10, 20, 40, 50], ['c', '[SponsorBlock]: Sponsor',
- '[SponsorBlock]: Sponsor, Interaction Reminder', 'c'])
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, expected, [self._chapter(30, 50, remove=True)])
-
- def test_remove_marked_arrange_sponsors_ChapterWithRunsOfOverlappingSponsorsAndCuts(self):
- chapters = [
- *self._chapters([200], ['c']),
- self._sponsor_chapter(10, 40, 'sponsor'),
- self._sponsor_chapter(10, 30, 'intro'),
- self._chapter(20, 30, remove=True),
- self._sponsor_chapter(30, 40, 'selfpromo'),
- self._sponsor_chapter(50, 70, 'sponsor'),
- self._sponsor_chapter(60, 80, 'interaction'),
- self._chapter(70, 80, remove=True),
- self._sponsor_chapter(70, 90, 'sponsor'),
- self._sponsor_chapter(80, 100, 'interaction'),
- self._sponsor_chapter(120, 170, 'selfpromo'),
- self._sponsor_chapter(130, 180, 'outro'),
- self._chapter(140, 150, remove=True),
- self._chapter(150, 160, remove=True)]
- expected = self._chapters(
- [10, 20, 30, 40, 50, 70, 80, 100, 110, 130, 140, 160],
- ['c', '[SponsorBlock]: Sponsor, Intermission/Intro Animation', '[SponsorBlock]: Sponsor, Unpaid/Self Promotion',
- 'c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Sponsor, Interaction Reminder',
- '[SponsorBlock]: Interaction Reminder', 'c', '[SponsorBlock]: Unpaid/Self Promotion',
- '[SponsorBlock]: Unpaid/Self Promotion, Endcards/Credits', '[SponsorBlock]: Endcards/Credits', 'c'])
- expected_cuts = [self._chapter(20, 30, remove=True),
- self._chapter(70, 80, remove=True),
- self._chapter(140, 160, remove=True)]
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, expected_cuts)
-
- def test_remove_marked_arrange_sponsors_SponsorOverlapsMultipleChapters(self):
- chapters = [
- *self._chapters([20, 40, 60, 80, 100], ['c1', 'c2', 'c3', 'c4', 'c5']),
- self._sponsor_chapter(10, 90, 'sponsor')]
- expected = self._chapters([10, 90, 100], ['c1', '[SponsorBlock]: Sponsor', 'c5'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_CutOverlapsMultipleChapters(self):
- cuts = [self._chapter(10, 90, remove=True)]
- chapters = self._chapters([20, 40, 60, 80, 100], ['c1', 'c2', 'c3', 'c4', 'c5']) + cuts
- expected = self._chapters([10, 20], ['c1', 'c5'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_SponsorsWithinSomeChaptersAndOverlappingOthers(self):
- chapters = [
- *self._chapters([10, 40, 60, 80], ['c1', 'c2', 'c3', 'c4']),
- self._sponsor_chapter(20, 30, 'sponsor'),
- self._sponsor_chapter(50, 70, 'selfpromo')]
- expected = self._chapters([10, 20, 30, 40, 50, 70, 80],
- ['c1', 'c2', '[SponsorBlock]: Sponsor', 'c2', 'c3',
- '[SponsorBlock]: Unpaid/Self Promotion', 'c4'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_CutsWithinSomeChaptersAndOverlappingOthers(self):
- cuts = [self._chapter(20, 30, remove=True), self._chapter(50, 70, remove=True)]
- chapters = self._chapters([10, 40, 60, 80], ['c1', 'c2', 'c3', 'c4']) + cuts
- expected = self._chapters([10, 30, 40, 50], ['c1', 'c2', 'c3', 'c4'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_ChaptersAfterLastSponsor(self):
- chapters = [
- *self._chapters([20, 40, 50, 60], ['c1', 'c2', 'c3', 'c4']),
- self._sponsor_chapter(10, 30, 'music_offtopic')]
- expected = self._chapters(
- [10, 30, 40, 50, 60],
- ['c1', '[SponsorBlock]: Non-Music Section', 'c2', 'c3', 'c4'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_ChaptersAfterLastCut(self):
- cuts = [self._chapter(10, 30, remove=True)]
- chapters = self._chapters([20, 40, 50, 60], ['c1', 'c2', 'c3', 'c4']) + cuts
- expected = self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_SponsorStartsAtChapterStart(self):
- chapters = [
- *self._chapters([10, 20, 40], ['c1', 'c2', 'c3']),
- self._sponsor_chapter(20, 30, 'sponsor')]
- expected = self._chapters([10, 20, 30, 40], ['c1', 'c2', '[SponsorBlock]: Sponsor', 'c3'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_CutStartsAtChapterStart(self):
- cuts = [self._chapter(20, 30, remove=True)]
- chapters = self._chapters([10, 20, 40], ['c1', 'c2', 'c3']) + cuts
- expected = self._chapters([10, 20, 30], ['c1', 'c2', 'c3'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_SponsorEndsAtChapterEnd(self):
- chapters = [
- *self._chapters([10, 30, 40], ['c1', 'c2', 'c3']),
- self._sponsor_chapter(20, 30, 'sponsor')]
- expected = self._chapters([10, 20, 30, 40], ['c1', 'c2', '[SponsorBlock]: Sponsor', 'c3'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_CutEndsAtChapterEnd(self):
- cuts = [self._chapter(20, 30, remove=True)]
- chapters = self._chapters([10, 30, 40], ['c1', 'c2', 'c3']) + cuts
- expected = self._chapters([10, 20, 30], ['c1', 'c2', 'c3'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_SponsorCoincidesWithChapters(self):
- chapters = [
- *self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4']),
- self._sponsor_chapter(10, 30, 'sponsor')]
- expected = self._chapters([10, 30, 40], ['c1', '[SponsorBlock]: Sponsor', 'c4'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_CutCoincidesWithChapters(self):
- cuts = [self._chapter(10, 30, remove=True)]
- chapters = self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4']) + cuts
- expected = self._chapters([10, 20], ['c1', 'c4'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_SponsorsAtVideoBoundaries(self):
- chapters = [
- *self._chapters([20, 40, 60], ['c1', 'c2', 'c3']),
- self._sponsor_chapter(0, 10, 'intro'), self._sponsor_chapter(50, 60, 'outro')]
- expected = self._chapters(
- [10, 20, 40, 50, 60], ['[SponsorBlock]: Intermission/Intro Animation', 'c1', 'c2', 'c3', '[SponsorBlock]: Endcards/Credits'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_CutsAtVideoBoundaries(self):
- cuts = [self._chapter(0, 10, remove=True), self._chapter(50, 60, remove=True)]
- chapters = self._chapters([20, 40, 60], ['c1', 'c2', 'c3']) + cuts
- expected = self._chapters([10, 30, 40], ['c1', 'c2', 'c3'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_SponsorsOverlapChaptersAtVideoBoundaries(self):
- chapters = [
- *self._chapters([10, 40, 50], ['c1', 'c2', 'c3']),
- self._sponsor_chapter(0, 20, 'intro'),
- self._sponsor_chapter(30, 50, 'outro')]
- expected = self._chapters(
- [20, 30, 50], ['[SponsorBlock]: Intermission/Intro Animation', 'c2', '[SponsorBlock]: Endcards/Credits'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_CutsOverlapChaptersAtVideoBoundaries(self):
- cuts = [self._chapter(0, 20, remove=True), self._chapter(30, 50, remove=True)]
- chapters = self._chapters([10, 40, 50], ['c1', 'c2', 'c3']) + cuts
- expected = self._chapters([10], ['c2'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)
-
- def test_remove_marked_arrange_sponsors_EverythingSponsored(self):
- chapters = [
- *self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4']),
- self._sponsor_chapter(0, 20, 'intro'),
- self._sponsor_chapter(20, 40, 'outro')]
- expected = self._chapters([20, 40], ['[SponsorBlock]: Intermission/Intro Animation', '[SponsorBlock]: Endcards/Credits'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])
-
- def test_remove_marked_arrange_sponsors_EverythingCut(self):
- cuts = [self._chapter(0, 20, remove=True), self._chapter(20, 40, remove=True)]
- chapters = self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4']) + cuts
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, [], [self._chapter(0, 40, remove=True)])
-
- def test_remove_marked_arrange_sponsors_TinyChaptersInTheOriginalArePreserved(self):
- chapters = self._chapters([0.1, 0.2, 0.3, 0.4], ['c1', 'c2', 'c3', 'c4'])
- self._remove_marked_arrange_sponsors_test_impl(chapters, chapters, [])
-
- def test_remove_marked_arrange_sponsors_TinySponsorsAreIgnored(self):
- chapters = [self._sponsor_chapter(0, 0.1, 'intro'), self._chapter(0.1, 0.2, 'c1'),
- self._sponsor_chapter(0.2, 0.3, 'sponsor'), self._chapter(0.3, 0.4, 'c2'),
- self._sponsor_chapter(0.4, 0.5, 'outro')]
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([0.3, 0.5], ['c1', 'c2']), [])
-
- def test_remove_marked_arrange_sponsors_TinyChaptersResultingFromCutsAreIgnored(self):
- cuts = [self._chapter(1.5, 2.5, remove=True)]
- chapters = self._chapters([2, 3, 3.5], ['c1', 'c2', 'c3']) + cuts
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([2, 2.5], ['c1', 'c3']), cuts)
-
- def test_remove_marked_arrange_sponsors_SingleTinyChapterIsPreserved(self):
- cuts = [self._chapter(0.5, 2, remove=True)]
- chapters = self._chapters([2], ['c']) + cuts
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([0.5], ['c']), cuts)
-
- def test_remove_marked_arrange_sponsors_TinyChapterAtTheStartPrependedToTheNext(self):
- cuts = [self._chapter(0.5, 2, remove=True)]
- chapters = self._chapters([2, 4], ['c1', 'c2']) + cuts
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([2.5], ['c2']), cuts)
-
- def test_remove_marked_arrange_sponsors_TinyChaptersResultingFromSponsorOverlapAreIgnored(self):
- chapters = [
- *self._chapters([1, 3, 4], ['c1', 'c2', 'c3']),
- self._sponsor_chapter(1.5, 2.5, 'sponsor')]
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([1.5, 2.5, 4], ['c1', '[SponsorBlock]: Sponsor', 'c3']), [])
-
- def test_remove_marked_arrange_sponsors_TinySponsorsOverlapsAreIgnored(self):
- chapters = [
- *self._chapters([2, 3, 5], ['c1', 'c2', 'c3']),
- self._sponsor_chapter(1, 3, 'sponsor'),
- self._sponsor_chapter(2.5, 4, 'selfpromo')]
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([1, 3, 4, 5], [
- 'c1', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Unpaid/Self Promotion', 'c3']), [])
-
- def test_remove_marked_arrange_sponsors_TinySponsorsPrependedToTheNextSponsor(self):
- chapters = [
- *self._chapters([4], ['c']),
- self._sponsor_chapter(1.5, 2, 'sponsor'),
- self._sponsor_chapter(2, 4, 'selfpromo')]
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([1.5, 4], ['c', '[SponsorBlock]: Unpaid/Self Promotion']), [])
-
- def test_remove_marked_arrange_sponsors_SmallestSponsorInTheOverlapGetsNamed(self):
- self._pp._sponsorblock_chapter_title = '[SponsorBlock]: %(name)s'
- chapters = [
- *self._chapters([10], ['c']),
- self._sponsor_chapter(2, 8, 'sponsor'),
- self._sponsor_chapter(4, 6, 'selfpromo')]
- self._remove_marked_arrange_sponsors_test_impl(
- chapters, self._chapters([2, 4, 6, 8, 10], [
- 'c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Unpaid/Self Promotion',
- '[SponsorBlock]: Sponsor', 'c',
- ]), [])
-
- def test_make_concat_opts_CommonCase(self):
- sponsor_chapters = [self._chapter(1, 2, 's1'), self._chapter(10, 20, 's2')]
- expected = '''ffconcat version 1.0
-file 'file:test'
-outpoint 1.000000
-file 'file:test'
-inpoint 2.000000
-outpoint 10.000000
-file 'file:test'
-inpoint 20.000000
-'''
- opts = self._pp._make_concat_opts(sponsor_chapters, 30)
- self.assertEqual(expected, ''.join(self._pp._concat_spec(['test'] * len(opts), opts)))
-
- def test_make_concat_opts_NoZeroDurationChunkAtVideoStart(self):
- sponsor_chapters = [self._chapter(0, 1, 's1'), self._chapter(10, 20, 's2')]
- expected = '''ffconcat version 1.0
-file 'file:test'
-inpoint 1.000000
-outpoint 10.000000
-file 'file:test'
-inpoint 20.000000
-'''
- opts = self._pp._make_concat_opts(sponsor_chapters, 30)
- self.assertEqual(expected, ''.join(self._pp._concat_spec(['test'] * len(opts), opts)))
-
- def test_make_concat_opts_NoZeroDurationChunkAtVideoEnd(self):
- sponsor_chapters = [self._chapter(1, 2, 's1'), self._chapter(10, 20, 's2')]
- expected = '''ffconcat version 1.0
-file 'file:test'
-outpoint 1.000000
-file 'file:test'
-inpoint 2.000000
-outpoint 10.000000
-'''
- opts = self._pp._make_concat_opts(sponsor_chapters, 20)
- self.assertEqual(expected, ''.join(self._pp._concat_spec(['test'] * len(opts), opts)))
-
- def test_quote_for_concat_RunsOfQuotes(self):
- self.assertEqual(
- r"'special '\'' '\'\''characters'\'\'\''galore'",
- self._pp._quote_for_ffmpeg("special ' ''characters'''galore"))
-
- def test_quote_for_concat_QuotesAtStart(self):
- self.assertEqual(
- r"\'\'\''special '\'' characters '\'' galore'",
- self._pp._quote_for_ffmpeg("'''special ' characters ' galore"))
-
- def test_quote_for_concat_QuotesAtEnd(self):
- self.assertEqual(
- r"'special '\'' characters '\'' galore'\'\'\'",
- self._pp._quote_for_ffmpeg("special ' characters ' galore'''"))
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_pot/conftest.py b/test/test_pot/conftest.py
deleted file mode 100644
index ff0667e92..000000000
--- a/test/test_pot/conftest.py
+++ /dev/null
@@ -1,71 +0,0 @@
-import collections
-
-import pytest
-
-from yt_dlp import YoutubeDL
-from yt_dlp.cookies import YoutubeDLCookieJar
-from yt_dlp.extractor.common import InfoExtractor
-from yt_dlp.extractor.youtube.pot._provider import IEContentProviderLogger
-from yt_dlp.extractor.youtube.pot.provider import PoTokenRequest, PoTokenContext
-from yt_dlp.utils.networking import HTTPHeaderDict
-
-
-class MockLogger(IEContentProviderLogger):
-
- log_level = IEContentProviderLogger.LogLevel.TRACE
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.messages = collections.defaultdict(list)
-
- def trace(self, message: str):
- self.messages['trace'].append(message)
-
- def debug(self, message: str):
- self.messages['debug'].append(message)
-
- def info(self, message: str):
- self.messages['info'].append(message)
-
- def warning(self, message: str, *, once=False):
- self.messages['warning'].append(message)
-
- def error(self, message: str):
- self.messages['error'].append(message)
-
-
-@pytest.fixture
-def ie() -> InfoExtractor:
- ydl = YoutubeDL()
- return ydl.get_info_extractor('Youtube')
-
-
-@pytest.fixture
-def logger() -> MockLogger:
- return MockLogger()
-
-
-@pytest.fixture()
-def pot_request() -> PoTokenRequest:
- return PoTokenRequest(
- context=PoTokenContext.GVS,
- innertube_context={'client': {'clientName': 'WEB'}},
- innertube_host='youtube.com',
- session_index=None,
- player_url=None,
- is_authenticated=False,
- video_webpage=None,
-
- visitor_data='example-visitor-data',
- data_sync_id='example-data-sync-id',
- video_id='example-video-id',
-
- request_cookiejar=YoutubeDLCookieJar(),
- request_proxy=None,
- request_headers=HTTPHeaderDict(),
- request_timeout=None,
- request_source_address=None,
- request_verify_tls=True,
-
- bypass_cache=False,
- )
diff --git a/test/test_pot/test_pot_builtin_memorycache.py b/test/test_pot/test_pot_builtin_memorycache.py
deleted file mode 100644
index ea19fbe29..000000000
--- a/test/test_pot/test_pot_builtin_memorycache.py
+++ /dev/null
@@ -1,117 +0,0 @@
-import threading
-import time
-from collections import OrderedDict
-import pytest
-from yt_dlp.extractor.youtube.pot._provider import IEContentProvider, BuiltinIEContentProvider
-from yt_dlp.utils import bug_reports_message
-from yt_dlp.extractor.youtube.pot._builtin.memory_cache import MemoryLRUPCP, memorylru_preference, initialize_global_cache
-from yt_dlp.version import __version__
-from yt_dlp.extractor.youtube.pot._registry import _pot_cache_providers, _pot_memory_cache
-
-
-class TestMemoryLRUPCS:
-
- def test_base_type(self):
- assert issubclass(MemoryLRUPCP, IEContentProvider)
- assert issubclass(MemoryLRUPCP, BuiltinIEContentProvider)
-
- @pytest.fixture
- def pcp(self, ie, logger) -> MemoryLRUPCP:
- return MemoryLRUPCP(ie, logger, {}, initialize_cache=lambda max_size: (OrderedDict(), threading.Lock(), max_size))
-
- def test_is_registered(self):
- assert _pot_cache_providers.value.get('MemoryLRU') == MemoryLRUPCP
-
- def test_initialization(self, pcp):
- assert pcp.PROVIDER_NAME == 'memory'
- assert pcp.PROVIDER_VERSION == __version__
- assert pcp.BUG_REPORT_MESSAGE == bug_reports_message(before='')
- assert pcp.is_available()
-
- def test_store_and_get(self, pcp):
- pcp.store('key1', 'value1', int(time.time()) + 60)
- assert pcp.get('key1') == 'value1'
- assert len(pcp.cache) == 1
-
- def test_store_ignore_expired(self, pcp):
- pcp.store('key1', 'value1', int(time.time()) - 1)
- assert len(pcp.cache) == 0
- assert pcp.get('key1') is None
- assert len(pcp.cache) == 0
-
- def test_store_override_existing_key(self, ie, logger):
- MAX_SIZE = 2
- pcp = MemoryLRUPCP(ie, logger, {}, initialize_cache=lambda max_size: (OrderedDict(), threading.Lock(), MAX_SIZE))
- pcp.store('key1', 'value1', int(time.time()) + 60)
- pcp.store('key2', 'value2', int(time.time()) + 60)
- assert len(pcp.cache) == 2
- pcp.store('key1', 'value2', int(time.time()) + 60)
- # Ensure that the override key gets added to the end of the cache instead of in the same position
- pcp.store('key3', 'value3', int(time.time()) + 60)
- assert pcp.get('key1') == 'value2'
-
- def test_store_ignore_expired_existing_key(self, pcp):
- pcp.store('key1', 'value2', int(time.time()) + 60)
- pcp.store('key1', 'value1', int(time.time()) - 1)
- assert len(pcp.cache) == 1
- assert pcp.get('key1') == 'value2'
- assert len(pcp.cache) == 1
-
- def test_get_key_expired(self, pcp):
- pcp.store('key1', 'value1', int(time.time()) + 60)
- assert pcp.get('key1') == 'value1'
- assert len(pcp.cache) == 1
- pcp.cache['key1'] = ('value1', int(time.time()) - 1)
- assert pcp.get('key1') is None
- assert len(pcp.cache) == 0
-
- def test_lru_eviction(self, ie, logger):
- MAX_SIZE = 2
- provider = MemoryLRUPCP(ie, logger, {}, initialize_cache=lambda max_size: (OrderedDict(), threading.Lock(), MAX_SIZE))
- provider.store('key1', 'value1', int(time.time()) + 5)
- provider.store('key2', 'value2', int(time.time()) + 5)
- assert len(provider.cache) == 2
-
- assert provider.get('key1') == 'value1'
-
- provider.store('key3', 'value3', int(time.time()) + 5)
- assert len(provider.cache) == 2
-
- assert provider.get('key2') is None
-
- provider.store('key4', 'value4', int(time.time()) + 5)
- assert len(provider.cache) == 2
-
- assert provider.get('key1') is None
- assert provider.get('key3') == 'value3'
- assert provider.get('key4') == 'value4'
-
- def test_delete(self, pcp):
- pcp.store('key1', 'value1', int(time.time()) + 5)
- assert len(pcp.cache) == 1
- assert pcp.get('key1') == 'value1'
- pcp.delete('key1')
- assert len(pcp.cache) == 0
- assert pcp.get('key1') is None
-
- def test_use_global_cache_default(self, ie, logger):
- pcp = MemoryLRUPCP(ie, logger, {})
- assert pcp.max_size == _pot_memory_cache.value['max_size'] == 25
- assert pcp.cache is _pot_memory_cache.value['cache']
- assert pcp.lock is _pot_memory_cache.value['lock']
-
- pcp2 = MemoryLRUPCP(ie, logger, {})
- assert pcp.max_size == pcp2.max_size == _pot_memory_cache.value['max_size'] == 25
- assert pcp.cache is pcp2.cache is _pot_memory_cache.value['cache']
- assert pcp.lock is pcp2.lock is _pot_memory_cache.value['lock']
-
- def test_fail_max_size_change_global(self, ie, logger):
- pcp = MemoryLRUPCP(ie, logger, {})
- assert pcp.max_size == _pot_memory_cache.value['max_size'] == 25
- with pytest.raises(ValueError, match='Cannot change max_size of initialized global memory cache'):
- initialize_global_cache(50)
-
- assert pcp.max_size == _pot_memory_cache.value['max_size'] == 25
-
- def test_memory_lru_preference(self, pcp, ie, pot_request):
- assert memorylru_preference(pcp, pot_request) == 10000
diff --git a/test/test_pot/test_pot_builtin_utils.py b/test/test_pot/test_pot_builtin_utils.py
deleted file mode 100644
index 15a25cff2..000000000
--- a/test/test_pot/test_pot_builtin_utils.py
+++ /dev/null
@@ -1,52 +0,0 @@
-import pytest
-from yt_dlp.extractor.youtube.pot.provider import (
- PoTokenContext,
-
-)
-
-from yt_dlp.extractor.youtube.pot.utils import get_webpo_content_binding, ContentBindingType
-
-
-class TestGetWebPoContentBinding:
-
- @pytest.mark.parametrize('client_name, context, is_authenticated, expected', [
- *[(client, context, is_authenticated, expected) for client in [
- 'WEB', 'MWEB', 'TVHTML5', 'WEB_EMBEDDED_PLAYER', 'WEB_CREATOR', 'TVHTML5_SIMPLY_EMBEDDED_PLAYER', 'TVHTML5_SIMPLY']
- for context, is_authenticated, expected in [
- (PoTokenContext.GVS, False, ('example-visitor-data', ContentBindingType.VISITOR_DATA)),
- (PoTokenContext.PLAYER, False, ('example-video-id', ContentBindingType.VIDEO_ID)),
- (PoTokenContext.SUBS, False, ('example-video-id', ContentBindingType.VIDEO_ID)),
- (PoTokenContext.GVS, True, ('example-data-sync-id', ContentBindingType.DATASYNC_ID)),
- ]],
- ('WEB_REMIX', PoTokenContext.GVS, False, ('example-visitor-data', ContentBindingType.VISITOR_DATA)),
- ('WEB_REMIX', PoTokenContext.PLAYER, False, ('example-visitor-data', ContentBindingType.VISITOR_DATA)),
- ('ANDROID', PoTokenContext.GVS, False, (None, None)),
- ('IOS', PoTokenContext.GVS, False, (None, None)),
- ])
- def test_get_webpo_content_binding(self, pot_request, client_name, context, is_authenticated, expected):
- pot_request.innertube_context['client']['clientName'] = client_name
- pot_request.context = context
- pot_request.is_authenticated = is_authenticated
- assert get_webpo_content_binding(pot_request) == expected
-
- def test_extract_visitor_id(self, pot_request):
- pot_request.visitor_data = 'CgsxMjNhYmNYWVpfLSiA4s%2DqBg%3D%3D'
- assert get_webpo_content_binding(pot_request, bind_to_visitor_id=True) == ('123abcXYZ_-', ContentBindingType.VISITOR_ID)
-
- def test_invalid_visitor_id(self, pot_request):
- # visitor id not alphanumeric (i.e. protobuf extraction failed)
- pot_request.visitor_data = 'CggxMjM0NTY3OCiA4s-qBg%3D%3D'
- assert get_webpo_content_binding(pot_request, bind_to_visitor_id=True) == (pot_request.visitor_data, ContentBindingType.VISITOR_DATA)
-
- def test_no_visitor_id(self, pot_request):
- pot_request.visitor_data = 'KIDiz6oG'
- assert get_webpo_content_binding(pot_request, bind_to_visitor_id=True) == (pot_request.visitor_data, ContentBindingType.VISITOR_DATA)
-
- def test_invalid_base64(self, pot_request):
- pot_request.visitor_data = 'invalid-base64'
- assert get_webpo_content_binding(pot_request, bind_to_visitor_id=True) == (pot_request.visitor_data, ContentBindingType.VISITOR_DATA)
-
- def test_gvs_video_id_binding_experiment(self, pot_request):
- pot_request.context = PoTokenContext.GVS
- pot_request._gvs_bind_to_video_id = True
- assert get_webpo_content_binding(pot_request) == ('example-video-id', ContentBindingType.VIDEO_ID)
diff --git a/test/test_pot/test_pot_builtin_webpospec.py b/test/test_pot/test_pot_builtin_webpospec.py
deleted file mode 100644
index 078008415..000000000
--- a/test/test_pot/test_pot_builtin_webpospec.py
+++ /dev/null
@@ -1,92 +0,0 @@
-import pytest
-
-from yt_dlp.extractor.youtube.pot._provider import IEContentProvider, BuiltinIEContentProvider
-from yt_dlp.extractor.youtube.pot.cache import CacheProviderWritePolicy
-from yt_dlp.utils import bug_reports_message
-from yt_dlp.extractor.youtube.pot.provider import (
- PoTokenRequest,
- PoTokenContext,
-
-)
-from yt_dlp.version import __version__
-
-from yt_dlp.extractor.youtube.pot._builtin.webpo_cachespec import WebPoPCSP
-from yt_dlp.extractor.youtube.pot._registry import _pot_pcs_providers
-
-
-@pytest.fixture()
-def pot_request(pot_request) -> PoTokenRequest:
- pot_request.visitor_data = 'CgsxMjNhYmNYWVpfLSiA4s%2DqBg%3D%3D' # visitor_id=123abcXYZ_-
- return pot_request
-
-
-class TestWebPoPCSP:
- def test_base_type(self):
- assert issubclass(WebPoPCSP, IEContentProvider)
- assert issubclass(WebPoPCSP, BuiltinIEContentProvider)
-
- def test_init(self, ie, logger):
- pcs = WebPoPCSP(ie=ie, logger=logger, settings={})
- assert pcs.PROVIDER_NAME == 'webpo'
- assert pcs.PROVIDER_VERSION == __version__
- assert pcs.BUG_REPORT_MESSAGE == bug_reports_message(before='')
- assert pcs.is_available()
-
- def test_is_registered(self):
- assert _pot_pcs_providers.value.get('WebPo') == WebPoPCSP
-
- @pytest.mark.parametrize('client_name, context, is_authenticated', [
- ('ANDROID', PoTokenContext.GVS, False),
- ('IOS', PoTokenContext.GVS, False),
- ('IOS', PoTokenContext.PLAYER, False),
- ])
- def test_not_supports(self, ie, logger, pot_request, client_name, context, is_authenticated):
- pcs = WebPoPCSP(ie=ie, logger=logger, settings={})
- pot_request.innertube_context['client']['clientName'] = client_name
- pot_request.context = context
- pot_request.is_authenticated = is_authenticated
- assert pcs.generate_cache_spec(pot_request) is None
-
- @pytest.mark.parametrize('client_name, context, is_authenticated, remote_host, source_address, request_proxy, expected', [
- *[(client, context, is_authenticated, remote_host, source_address, request_proxy, expected) for client in [
- 'WEB', 'MWEB', 'TVHTML5', 'WEB_EMBEDDED_PLAYER', 'WEB_CREATOR', 'TVHTML5_SIMPLY_EMBEDDED_PLAYER', 'TVHTML5_SIMPLY']
- for context, is_authenticated, remote_host, source_address, request_proxy, expected in [
- (PoTokenContext.GVS, False, 'example-remote-host', 'example-source-address', 'example-request-proxy', {'t': 'webpo', 'ip': 'example-remote-host', 'sa': 'example-source-address', 'px': 'example-request-proxy', 'cb': '123abcXYZ_-', 'cbt': 'visitor_id'}),
- (PoTokenContext.PLAYER, False, 'example-remote-host', 'example-source-address', 'example-request-proxy', {'t': 'webpo', 'ip': 'example-remote-host', 'sa': 'example-source-address', 'px': 'example-request-proxy', 'cb': '123abcXYZ_-', 'cbt': 'video_id'}),
- (PoTokenContext.GVS, True, 'example-remote-host', 'example-source-address', 'example-request-proxy', {'t': 'webpo', 'ip': 'example-remote-host', 'sa': 'example-source-address', 'px': 'example-request-proxy', 'cb': 'example-data-sync-id', 'cbt': 'datasync_id'}),
- ]],
- ('WEB_REMIX', PoTokenContext.PLAYER, False, 'example-remote-host', 'example-source-address', 'example-request-proxy', {'t': 'webpo', 'ip': 'example-remote-host', 'sa': 'example-source-address', 'px': 'example-request-proxy', 'cb': '123abcXYZ_-', 'cbt': 'visitor_id'}),
- ('WEB', PoTokenContext.GVS, False, None, None, None, {'t': 'webpo', 'cb': '123abcXYZ_-', 'cbt': 'visitor_id', 'ip': None, 'sa': None, 'px': None}),
- ('TVHTML5', PoTokenContext.PLAYER, False, None, None, 'http://example.com', {'t': 'webpo', 'cb': '123abcXYZ_-', 'cbt': 'video_id', 'ip': None, 'sa': None, 'px': 'http://example.com'}),
-
- ])
- def test_generate_key_bindings(self, ie, logger, pot_request, client_name, context, is_authenticated, remote_host, source_address, request_proxy, expected):
- pcs = WebPoPCSP(ie=ie, logger=logger, settings={})
- pot_request.innertube_context['client']['clientName'] = client_name
- pot_request.context = context
- pot_request.is_authenticated = is_authenticated
- pot_request.innertube_context['client']['remoteHost'] = remote_host
- pot_request.request_source_address = source_address
- pot_request.request_proxy = request_proxy
- pot_request.video_id = '123abcXYZ_-' # same as visitor id to test type
-
- assert pcs.generate_cache_spec(pot_request).key_bindings == expected
-
- def test_no_bind_visitor_id(self, ie, logger, pot_request):
- # Should not bind to visitor id if setting is set to False
- pcs = WebPoPCSP(ie=ie, logger=logger, settings={'bind_to_visitor_id': ['false']})
- pot_request.innertube_context['client']['clientName'] = 'WEB'
- pot_request.context = PoTokenContext.GVS
- pot_request.is_authenticated = False
- assert pcs.generate_cache_spec(pot_request).key_bindings == {'t': 'webpo', 'ip': None, 'sa': None, 'px': None, 'cb': 'CgsxMjNhYmNYWVpfLSiA4s%2DqBg%3D%3D', 'cbt': 'visitor_data'}
-
- def test_default_ttl(self, ie, logger, pot_request):
- pcs = WebPoPCSP(ie=ie, logger=logger, settings={})
- assert pcs.generate_cache_spec(pot_request).default_ttl == 6 * 60 * 60 # should default to 6 hours
-
- def test_write_policy(self, ie, logger, pot_request):
- pcs = WebPoPCSP(ie=ie, logger=logger, settings={})
- pot_request.context = PoTokenContext.GVS
- assert pcs.generate_cache_spec(pot_request).write_policy == CacheProviderWritePolicy.WRITE_ALL
- pot_request.context = PoTokenContext.PLAYER
- assert pcs.generate_cache_spec(pot_request).write_policy == CacheProviderWritePolicy.WRITE_FIRST
diff --git a/test/test_pot/test_pot_director.py b/test/test_pot/test_pot_director.py
deleted file mode 100644
index bbfdd0e98..000000000
--- a/test/test_pot/test_pot_director.py
+++ /dev/null
@@ -1,1529 +0,0 @@
-from __future__ import annotations
-import abc
-import base64
-import dataclasses
-import hashlib
-import json
-import time
-import pytest
-
-from yt_dlp.extractor.youtube.pot._provider import BuiltinIEContentProvider, IEContentProvider
-
-from yt_dlp.extractor.youtube.pot.provider import (
- PoTokenRequest,
- PoTokenContext,
- PoTokenProviderError,
- PoTokenProviderRejectedRequest,
-)
-from yt_dlp.extractor.youtube.pot._director import (
- PoTokenCache,
- validate_cache_spec,
- clean_pot,
- validate_response,
- PoTokenRequestDirector,
- provider_display_list,
-)
-
-from yt_dlp.extractor.youtube.pot.cache import (
- PoTokenCacheSpec,
- PoTokenCacheSpecProvider,
- PoTokenCacheProvider,
- CacheProviderWritePolicy,
- PoTokenCacheProviderError,
-)
-
-
-from yt_dlp.extractor.youtube.pot.provider import (
- PoTokenResponse,
- PoTokenProvider,
-)
-
-
-class BaseMockPoTokenProvider(PoTokenProvider, abc.ABC):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.available_called_times = 0
- self.request_called_times = 0
- self.close_called = False
-
- def is_available(self) -> bool:
- self.available_called_times += 1
- return True
-
- def request_pot(self, *args, **kwargs):
- self.request_called_times += 1
- return super().request_pot(*args, **kwargs)
-
- def close(self):
- self.close_called = True
- super().close()
-
-
-class ExamplePTP(BaseMockPoTokenProvider):
- PROVIDER_NAME = 'example'
- PROVIDER_VERSION = '0.0.1'
- BUG_REPORT_LOCATION = 'https://example.com/issues'
-
- _SUPPORTED_CLIENTS = ('WEB',)
- _SUPPORTED_CONTEXTS = (PoTokenContext.GVS, )
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- if request.data_sync_id == 'example':
- return PoTokenResponse(request.video_id)
- return PoTokenResponse(EXAMPLE_PO_TOKEN)
-
-
-def success_ptp(response: PoTokenResponse | None = None, key: str | None = None):
- class SuccessPTP(BaseMockPoTokenProvider):
- PROVIDER_NAME = 'success'
- PROVIDER_VERSION = '0.0.1'
- BUG_REPORT_LOCATION = 'https://success.example.com/issues'
-
- _SUPPORTED_CLIENTS = ('WEB',)
- _SUPPORTED_CONTEXTS = (PoTokenContext.GVS,)
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- return response or PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- if key:
- SuccessPTP.PROVIDER_KEY = key
- return SuccessPTP
-
-
-@pytest.fixture
-def pot_provider(ie, logger):
- return success_ptp()(ie=ie, logger=logger, settings={})
-
-
-class UnavailablePTP(BaseMockPoTokenProvider):
- PROVIDER_NAME = 'unavailable'
- BUG_REPORT_LOCATION = 'https://unavailable.example.com/issues'
- _SUPPORTED_CLIENTS = None
- _SUPPORTED_CONTEXTS = None
-
- def is_available(self) -> bool:
- super().is_available()
- return False
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- raise PoTokenProviderError('something went wrong')
-
-
-class UnsupportedPTP(BaseMockPoTokenProvider):
- PROVIDER_NAME = 'unsupported'
- BUG_REPORT_LOCATION = 'https://unsupported.example.com/issues'
- _SUPPORTED_CLIENTS = None
- _SUPPORTED_CONTEXTS = None
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- raise PoTokenProviderRejectedRequest('unsupported request')
-
-
-class ErrorPTP(BaseMockPoTokenProvider):
- PROVIDER_NAME = 'error'
- BUG_REPORT_LOCATION = 'https://error.example.com/issues'
- _SUPPORTED_CLIENTS = None
- _SUPPORTED_CONTEXTS = None
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- expected = request.video_id == 'expected'
- raise PoTokenProviderError('an error occurred', expected=expected)
-
-
-class UnexpectedErrorPTP(BaseMockPoTokenProvider):
- PROVIDER_NAME = 'unexpected_error'
- BUG_REPORT_LOCATION = 'https://unexpected.example.com/issues'
- _SUPPORTED_CLIENTS = None
- _SUPPORTED_CONTEXTS = None
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- raise ValueError('an unexpected error occurred')
-
-
-class InvalidPTP(BaseMockPoTokenProvider):
- PROVIDER_NAME = 'invalid'
- BUG_REPORT_LOCATION = 'https://invalid.example.com/issues'
- _SUPPORTED_CLIENTS = None
- _SUPPORTED_CONTEXTS = None
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- if request.video_id == 'invalid_type':
- return 'invalid-response'
- else:
- return PoTokenResponse('example-token?', expires_at='123')
-
-
-class BaseMockCacheSpecProvider(PoTokenCacheSpecProvider, abc.ABC):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.generate_called_times = 0
- self.is_available_called_times = 0
- self.close_called = False
-
- def is_available(self) -> bool:
- self.is_available_called_times += 1
- return super().is_available()
-
- def generate_cache_spec(self, request: PoTokenRequest):
- self.generate_called_times += 1
-
- def close(self):
- self.close_called = True
- super().close()
-
-
-class ExampleCacheSpecProviderPCSP(BaseMockCacheSpecProvider):
-
- PROVIDER_NAME = 'example'
- PROVIDER_VERSION = '0.0.1'
- BUG_REPORT_LOCATION = 'https://example.com/issues'
-
- def generate_cache_spec(self, request: PoTokenRequest):
- super().generate_cache_spec(request)
- return PoTokenCacheSpec(
- key_bindings={'v': request.video_id, 'e': None},
- default_ttl=60,
- )
-
-
-class UnavailableCacheSpecProviderPCSP(BaseMockCacheSpecProvider):
-
- PROVIDER_NAME = 'unavailable'
- PROVIDER_VERSION = '0.0.1'
-
- def is_available(self) -> bool:
- super().is_available()
- return False
-
- def generate_cache_spec(self, request: PoTokenRequest):
- super().generate_cache_spec(request)
- return None
-
-
-class UnsupportedCacheSpecProviderPCSP(BaseMockCacheSpecProvider):
-
- PROVIDER_NAME = 'unsupported'
- PROVIDER_VERSION = '0.0.1'
-
- def generate_cache_spec(self, request: PoTokenRequest):
- super().generate_cache_spec(request)
- return None
-
-
-class InvalidSpecCacheSpecProviderPCSP(BaseMockCacheSpecProvider):
-
- PROVIDER_NAME = 'invalid'
- PROVIDER_VERSION = '0.0.1'
-
- def generate_cache_spec(self, request: PoTokenRequest):
- super().generate_cache_spec(request)
- return 'invalid-spec'
-
-
-class ErrorSpecCacheSpecProviderPCSP(BaseMockCacheSpecProvider):
-
- PROVIDER_NAME = 'invalid'
- PROVIDER_VERSION = '0.0.1'
-
- def generate_cache_spec(self, request: PoTokenRequest):
- super().generate_cache_spec(request)
- raise ValueError('something went wrong')
-
-
-class BaseMockCacheProvider(PoTokenCacheProvider, abc.ABC):
- BUG_REPORT_MESSAGE = 'example bug report message'
-
- def __init__(self, *args, available=True, **kwargs):
- super().__init__(*args, **kwargs)
- self.store_calls = 0
- self.delete_calls = 0
- self.get_calls = 0
- self.available_called_times = 0
- self.available = available
-
- def is_available(self) -> bool:
- self.available_called_times += 1
- return self.available
-
- def store(self, *args, **kwargs):
- self.store_calls += 1
-
- def delete(self, *args, **kwargs):
- self.delete_calls += 1
-
- def get(self, *args, **kwargs):
- self.get_calls += 1
-
- def close(self):
- self.close_called = True
- super().close()
-
-
-class ErrorPCP(BaseMockCacheProvider):
- PROVIDER_NAME = 'error'
-
- def store(self, *args, **kwargs):
- super().store(*args, **kwargs)
- raise PoTokenCacheProviderError('something went wrong')
-
- def get(self, *args, **kwargs):
- super().get(*args, **kwargs)
- raise PoTokenCacheProviderError('something went wrong')
-
-
-class UnexpectedErrorPCP(BaseMockCacheProvider):
- PROVIDER_NAME = 'unexpected_error'
-
- def store(self, *args, **kwargs):
- super().store(*args, **kwargs)
- raise ValueError('something went wrong')
-
- def get(self, *args, **kwargs):
- super().get(*args, **kwargs)
- raise ValueError('something went wrong')
-
-
-class MockMemoryPCP(BaseMockCacheProvider):
- PROVIDER_NAME = 'memory'
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.cache = {}
-
- def store(self, key, value, expires_at):
- super().store(key, value, expires_at)
- self.cache[key] = (value, expires_at)
-
- def delete(self, key):
- super().delete(key)
- self.cache.pop(key, None)
-
- def get(self, key):
- super().get(key)
- return self.cache.get(key, [None])[0]
-
-
-def create_memory_pcp(ie, logger, provider_key='memory', provider_name='memory', available=True):
- cache = MockMemoryPCP(ie, logger, {}, available=available)
- cache.PROVIDER_KEY = provider_key
- cache.PROVIDER_NAME = provider_name
- return cache
-
-
-@pytest.fixture
-def memorypcp(ie, logger) -> MockMemoryPCP:
- return create_memory_pcp(ie, logger)
-
-
-@pytest.fixture
-def pot_cache(ie, logger):
- class MockPoTokenCache(PoTokenCache):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.get_calls = 0
- self.store_calls = 0
- self.close_called = False
-
- def get(self, *args, **kwargs):
- self.get_calls += 1
- return super().get(*args, **kwargs)
-
- def store(self, *args, **kwargs):
- self.store_calls += 1
- return super().store(*args, **kwargs)
-
- def close(self):
- self.close_called = True
- super().close()
-
- return MockPoTokenCache(
- cache_providers=[MockMemoryPCP(ie, logger, {})],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie, logger, settings={})],
- logger=logger,
- )
-
-
-EXAMPLE_PO_TOKEN = base64.urlsafe_b64encode(b'example-token').decode()
-
-
-class TestPoTokenCache:
-
- def test_cache_success(self, memorypcp, pot_request, ie, logger):
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- assert cache.get(pot_request) is None
- cache.store(pot_request, response)
-
- cached_response = cache.get(pot_request)
- assert cached_response is not None
- assert cached_response.po_token == EXAMPLE_PO_TOKEN
- assert cached_response.expires_at is not None
-
- assert cache.get(dataclasses.replace(pot_request, video_id='another-video-id')) is None
-
- def test_unsupported_cache_spec_no_fallback(self, memorypcp, pot_request, ie, logger):
- unsupported_provider = UnsupportedCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[unsupported_provider],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- assert cache.get(pot_request) is None
- assert unsupported_provider.generate_called_times == 1
- cache.store(pot_request, response)
- assert len(memorypcp.cache) == 0
- assert unsupported_provider.generate_called_times == 2
- assert cache.get(pot_request) is None
- assert unsupported_provider.generate_called_times == 3
- assert len(logger.messages.get('error', [])) == 0
-
- def test_unsupported_cache_spec_fallback(self, memorypcp, pot_request, ie, logger):
- unsupported_provider = UnsupportedCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- example_provider = ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[unsupported_provider, example_provider],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- assert cache.get(pot_request) is None
- assert unsupported_provider.generate_called_times == 1
- assert example_provider.generate_called_times == 1
-
- cache.store(pot_request, response)
- assert unsupported_provider.generate_called_times == 2
- assert example_provider.generate_called_times == 2
-
- cached_response = cache.get(pot_request)
- assert unsupported_provider.generate_called_times == 3
- assert example_provider.generate_called_times == 3
- assert cached_response is not None
- assert cached_response.po_token == EXAMPLE_PO_TOKEN
- assert cached_response.expires_at is not None
-
- assert len(logger.messages.get('error', [])) == 0
-
- def test_invalid_cache_spec_no_fallback(self, memorypcp, pot_request, ie, logger):
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[InvalidSpecCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- assert cache.get(pot_request) is None
- cache.store(pot_request, response)
-
- assert cache.get(pot_request) is None
-
- assert 'PoTokenCacheSpecProvider "InvalidSpecCacheSpecProvider" generate_cache_spec() returned invalid spec invalid-spec; please report this issue to the provider developer at (developer has not provided a bug report location) .' in logger.messages['error']
-
- def test_invalid_cache_spec_fallback(self, memorypcp, pot_request, ie, logger):
-
- invalid_provider = InvalidSpecCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- example_provider = ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[invalid_provider, example_provider],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- assert cache.get(pot_request) is None
- assert invalid_provider.generate_called_times == example_provider.generate_called_times == 1
-
- cache.store(pot_request, response)
- assert invalid_provider.generate_called_times == example_provider.generate_called_times == 2
-
- cached_response = cache.get(pot_request)
- assert invalid_provider.generate_called_times == example_provider.generate_called_times == 3
- assert cached_response is not None
- assert cached_response.po_token == EXAMPLE_PO_TOKEN
- assert cached_response.expires_at is not None
-
- assert 'PoTokenCacheSpecProvider "InvalidSpecCacheSpecProvider" generate_cache_spec() returned invalid spec invalid-spec; please report this issue to the provider developer at (developer has not provided a bug report location) .' in logger.messages['error']
-
- def test_unavailable_cache_spec_no_fallback(self, memorypcp, pot_request, ie, logger):
- unavailable_provider = UnavailableCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[unavailable_provider],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- assert cache.get(pot_request) is None
- cache.store(pot_request, response)
- assert cache.get(pot_request) is None
- assert unavailable_provider.generate_called_times == 0
-
- def test_unavailable_cache_spec_fallback(self, memorypcp, pot_request, ie, logger):
- unavailable_provider = UnavailableCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- example_provider = ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[unavailable_provider, example_provider],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- assert cache.get(pot_request) is None
- assert unavailable_provider.generate_called_times == 0
- assert unavailable_provider.is_available_called_times == 1
- assert example_provider.generate_called_times == 1
-
- cache.store(pot_request, response)
- assert unavailable_provider.generate_called_times == 0
- assert unavailable_provider.is_available_called_times == 2
- assert example_provider.generate_called_times == 2
-
- cached_response = cache.get(pot_request)
- assert unavailable_provider.generate_called_times == 0
- assert unavailable_provider.is_available_called_times == 3
- assert example_provider.generate_called_times == 3
- assert example_provider.is_available_called_times == 3
- assert cached_response is not None
- assert cached_response.po_token == EXAMPLE_PO_TOKEN
- assert cached_response.expires_at is not None
-
- def test_unexpected_error_cache_spec(self, memorypcp, pot_request, ie, logger):
- error_provider = ErrorSpecCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[error_provider],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- assert cache.get(pot_request) is None
- cache.store(pot_request, response)
- assert cache.get(pot_request) is None
- assert error_provider.generate_called_times == 3
- assert error_provider.is_available_called_times == 3
-
- assert 'Error occurred with "invalid" PO Token cache spec provider: ValueError(\'something went wrong\'); please report this issue to the provider developer at (developer has not provided a bug report location) .' in logger.messages['error']
-
- def test_unexpected_error_cache_spec_fallback(self, memorypcp, pot_request, ie, logger):
- error_provider = ErrorSpecCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- example_provider = ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[error_provider, example_provider],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- assert cache.get(pot_request) is None
- assert error_provider.generate_called_times == 1
- assert error_provider.is_available_called_times == 1
- assert example_provider.generate_called_times == 1
-
- cache.store(pot_request, response)
- assert error_provider.generate_called_times == 2
- assert error_provider.is_available_called_times == 2
- assert example_provider.generate_called_times == 2
-
- cached_response = cache.get(pot_request)
- assert error_provider.generate_called_times == 3
- assert error_provider.is_available_called_times == 3
- assert example_provider.generate_called_times == 3
- assert example_provider.is_available_called_times == 3
- assert cached_response is not None
- assert cached_response.po_token == EXAMPLE_PO_TOKEN
- assert cached_response.expires_at is not None
-
- assert 'Error occurred with "invalid" PO Token cache spec provider: ValueError(\'something went wrong\'); please report this issue to the provider developer at (developer has not provided a bug report location) .' in logger.messages['error']
-
- def test_key_bindings_spec_provider(self, memorypcp, pot_request, ie, logger):
-
- class ExampleProviderPCSP(PoTokenCacheSpecProvider):
- PROVIDER_NAME = 'example'
-
- def generate_cache_spec(self, request: PoTokenRequest):
- return PoTokenCacheSpec(
- key_bindings={'v': request.video_id},
- default_ttl=60,
- )
-
- class ExampleProviderTwoPCSP(ExampleProviderPCSP):
- pass
-
- example_provider = ExampleProviderPCSP(ie=ie, logger=logger, settings={})
- example_provider_two = ExampleProviderTwoPCSP(ie=ie, logger=logger, settings={})
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
-
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[example_provider],
- logger=logger,
- )
-
- assert cache.get(pot_request) is None
- cache.store(pot_request, response)
- assert len(memorypcp.cache) == 1
- assert hashlib.sha256(
- f"{{'_dlp_cache': 'v1', '_p': 'ExampleProvider', 'v': '{pot_request.video_id}'}}".encode()).hexdigest() in memorypcp.cache
-
- # The second spec provider returns the exact same key bindings as the first one,
- # however the PoTokenCache should use the provider key to differentiate between them
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[example_provider_two],
- logger=logger,
- )
-
- assert cache.get(pot_request) is None
- cache.store(pot_request, response)
- assert len(memorypcp.cache) == 2
- assert hashlib.sha256(
- f"{{'_dlp_cache': 'v1', '_p': 'ExampleProviderTwo', 'v': '{pot_request.video_id}'}}".encode()).hexdigest() in memorypcp.cache
-
- def test_cache_provider_preferences(self, pot_request, ie, logger):
- pcp_one = create_memory_pcp(ie, logger, provider_key='memory_pcp_one')
- pcp_two = create_memory_pcp(ie, logger, provider_key='memory_pcp_two')
-
- cache = PoTokenCache(
- cache_providers=[pcp_one, pcp_two],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- cache.store(pot_request, PoTokenResponse(EXAMPLE_PO_TOKEN), write_policy=CacheProviderWritePolicy.WRITE_FIRST)
- assert len(pcp_one.cache) == 1
- assert len(pcp_two.cache) == 0
-
- assert cache.get(pot_request)
- assert pcp_one.get_calls == 1
- assert pcp_two.get_calls == 0
-
- standard_preference_called = False
- pcp_one_preference_claled = False
-
- def standard_preference(provider, request, *_, **__):
- nonlocal standard_preference_called
- standard_preference_called = True
- assert isinstance(provider, PoTokenCacheProvider)
- assert isinstance(request, PoTokenRequest)
- return 1
-
- def pcp_one_preference(provider, request, *_, **__):
- nonlocal pcp_one_preference_claled
- pcp_one_preference_claled = True
- assert isinstance(provider, PoTokenCacheProvider)
- assert isinstance(request, PoTokenRequest)
- if provider.PROVIDER_KEY == pcp_one.PROVIDER_KEY:
- return -100
- return 0
-
- # test that it can hanldle multiple preferences
- cache.cache_provider_preferences.append(standard_preference)
- cache.cache_provider_preferences.append(pcp_one_preference)
-
- cache.store(pot_request, PoTokenResponse(EXAMPLE_PO_TOKEN), write_policy=CacheProviderWritePolicy.WRITE_FIRST)
- assert cache.get(pot_request)
- assert len(pcp_one.cache) == len(pcp_two.cache) == 1
- assert pcp_two.get_calls == pcp_one.get_calls == 1
- assert pcp_one.store_calls == pcp_two.store_calls == 1
- assert standard_preference_called
- assert pcp_one_preference_claled
-
- def test_secondary_cache_provider_hit(self, pot_request, ie, logger):
- pcp_one = create_memory_pcp(ie, logger, provider_key='memory_pcp_one')
- pcp_two = create_memory_pcp(ie, logger, provider_key='memory_pcp_two')
-
- cache = PoTokenCache(
- cache_providers=[pcp_two],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- # Given the lower priority provider has the cache hit, store the response in the higher priority provider
- cache.store(pot_request, PoTokenResponse(EXAMPLE_PO_TOKEN))
- assert cache.get(pot_request)
-
- cache.cache_providers[pcp_one.PROVIDER_KEY] = pcp_one
-
- def pcp_one_pref(provider, *_, **__):
- if provider.PROVIDER_KEY == pcp_one.PROVIDER_KEY:
- return 1
- return -1
-
- cache.cache_provider_preferences.append(pcp_one_pref)
-
- assert cache.get(pot_request)
- assert pcp_one.get_calls == 1
- assert pcp_two.get_calls == 2
- # Should write back to pcp_one (now the highest priority cache provider)
- assert pcp_one.store_calls == pcp_two.store_calls == 1
- assert 'Writing PO Token response to highest priority cache provider' in logger.messages['trace']
-
- def test_cache_provider_no_hits(self, pot_request, ie, logger):
- pcp_one = create_memory_pcp(ie, logger, provider_key='memory_pcp_one')
- pcp_two = create_memory_pcp(ie, logger, provider_key='memory_pcp_two')
-
- cache = PoTokenCache(
- cache_providers=[pcp_one, pcp_two],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- assert cache.get(pot_request) is None
- assert pcp_one.get_calls == pcp_two.get_calls == 1
-
- def test_get_invalid_po_token_response(self, pot_request, ie, logger):
- # Test various scenarios where the po token response stored in the cache provider is invalid
- pcp_one = create_memory_pcp(ie, logger, provider_key='memory_pcp_one')
- pcp_two = create_memory_pcp(ie, logger, provider_key='memory_pcp_two')
-
- cache = PoTokenCache(
- cache_providers=[pcp_one, pcp_two],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- valid_response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, valid_response)
- assert len(pcp_one.cache) == len(pcp_two.cache) == 1
- # Overwrite the valid response with an invalid one in the cache
- pcp_one.store(next(iter(pcp_one.cache.keys())), json.dumps(dataclasses.asdict(PoTokenResponse(None))), int(time.time() + 1000))
- assert cache.get(pot_request).po_token == valid_response.po_token
- assert pcp_one.get_calls == pcp_two.get_calls == 1
- assert pcp_one.delete_calls == 1 # Invalid response should be deleted from cache
- assert pcp_one.store_calls == 3 # Since response was fetched from second cache provider, it should be stored in the first one
- assert len(pcp_one.cache) == 1
- assert 'Invalid PO Token response retrieved from cache provider "memory": {"po_token": null, "expires_at": null}; example bug report message' in logger.messages['error']
-
- # Overwrite the valid response with an invalid json in the cache
- pcp_one.store(next(iter(pcp_one.cache.keys())), 'invalid-json', int(time.time() + 1000))
- assert cache.get(pot_request).po_token == valid_response.po_token
- assert pcp_one.get_calls == pcp_two.get_calls == 2
- assert pcp_one.delete_calls == 2
- assert pcp_one.store_calls == 5 # 3 + 1 store we made in the test + 1 store from lower priority cache provider
- assert len(pcp_one.cache) == 1
-
- assert 'Invalid PO Token response retrieved from cache provider "memory": invalid-json; example bug report message' in logger.messages['error']
-
- # Valid json, but missing required fields
- pcp_one.store(next(iter(pcp_one.cache.keys())), '{"unknown_param": 0}', int(time.time() + 1000))
- assert cache.get(pot_request).po_token == valid_response.po_token
- assert pcp_one.get_calls == pcp_two.get_calls == 3
- assert pcp_one.delete_calls == 3
- assert pcp_one.store_calls == 7 # 5 + 1 store from test + 1 store from lower priority cache provider
- assert len(pcp_one.cache) == 1
-
- assert 'Invalid PO Token response retrieved from cache provider "memory": {"unknown_param": 0}; example bug report message' in logger.messages['error']
-
- def test_store_invalid_po_token_response(self, pot_request, ie, logger):
- # Should not store an invalid po token response
- pcp_one = create_memory_pcp(ie, logger, provider_key='memory_pcp_one')
-
- cache = PoTokenCache(
- cache_providers=[pcp_one],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- cache.store(pot_request, PoTokenResponse(po_token=EXAMPLE_PO_TOKEN, expires_at=80))
- assert cache.get(pot_request) is None
- assert pcp_one.store_calls == 0
- assert 'Invalid PO Token response provided to PoTokenCache.store()' in logger.messages['error'][0]
-
- def test_store_write_policy(self, pot_request, ie, logger):
- pcp_one = create_memory_pcp(ie, logger, provider_key='memory_pcp_one')
- pcp_two = create_memory_pcp(ie, logger, provider_key='memory_pcp_two')
-
- cache = PoTokenCache(
- cache_providers=[pcp_one, pcp_two],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- cache.store(pot_request, PoTokenResponse(EXAMPLE_PO_TOKEN), write_policy=CacheProviderWritePolicy.WRITE_FIRST)
- assert pcp_one.store_calls == 1
- assert pcp_two.store_calls == 0
-
- cache.store(pot_request, PoTokenResponse(EXAMPLE_PO_TOKEN), write_policy=CacheProviderWritePolicy.WRITE_ALL)
- assert pcp_one.store_calls == 2
- assert pcp_two.store_calls == 1
-
- def test_store_write_first_policy_cache_spec(self, pot_request, ie, logger):
- pcp_one = create_memory_pcp(ie, logger, provider_key='memory_pcp_one')
- pcp_two = create_memory_pcp(ie, logger, provider_key='memory_pcp_two')
-
- class WriteFirstPCSP(BaseMockCacheSpecProvider):
- def generate_cache_spec(self, request: PoTokenRequest):
- super().generate_cache_spec(request)
- return PoTokenCacheSpec(
- key_bindings={'v': request.video_id, 'e': None},
- default_ttl=60,
- write_policy=CacheProviderWritePolicy.WRITE_FIRST,
- )
-
- cache = PoTokenCache(
- cache_providers=[pcp_one, pcp_two],
- cache_spec_providers=[WriteFirstPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- cache.store(pot_request, PoTokenResponse(EXAMPLE_PO_TOKEN))
- assert pcp_one.store_calls == 1
- assert pcp_two.store_calls == 0
-
- def test_store_write_all_policy_cache_spec(self, pot_request, ie, logger):
- pcp_one = create_memory_pcp(ie, logger, provider_key='memory_pcp_one')
- pcp_two = create_memory_pcp(ie, logger, provider_key='memory_pcp_two')
-
- class WriteAllPCSP(BaseMockCacheSpecProvider):
- def generate_cache_spec(self, request: PoTokenRequest):
- super().generate_cache_spec(request)
- return PoTokenCacheSpec(
- key_bindings={'v': request.video_id, 'e': None},
- default_ttl=60,
- write_policy=CacheProviderWritePolicy.WRITE_ALL,
- )
-
- cache = PoTokenCache(
- cache_providers=[pcp_one, pcp_two],
- cache_spec_providers=[WriteAllPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- cache.store(pot_request, PoTokenResponse(EXAMPLE_PO_TOKEN))
- assert pcp_one.store_calls == 1
- assert pcp_two.store_calls == 1
-
- def test_expires_at_pot_response(self, pot_request, memorypcp, ie, logger):
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=10000000000)
- cache.store(pot_request, response)
- assert next(iter(memorypcp.cache.values()))[1] == 10000000000
-
- def test_expires_at_default_spec(self, pot_request, memorypcp, ie, logger):
-
- class TtlPCSP(BaseMockCacheSpecProvider):
- def generate_cache_spec(self, request: PoTokenRequest):
- super().generate_cache_spec(request)
- return PoTokenCacheSpec(
- key_bindings={'v': request.video_id, 'e': None},
- default_ttl=10000000000,
- )
-
- cache = PoTokenCache(
- cache_providers=[memorypcp],
- cache_spec_providers=[TtlPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response)
- assert next(iter(memorypcp.cache.values()))[1] >= 10000000000
-
- def test_cache_provider_error_no_fallback(self, pot_request, ie, logger):
- error_pcp = ErrorPCP(ie, logger, {})
- cache = PoTokenCache(
- cache_providers=[error_pcp],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response)
- assert cache.get(pot_request) is None
- assert error_pcp.get_calls == 1
- assert error_pcp.store_calls == 1
-
- assert logger.messages['warning'].count("Error from \"error\" PO Token cache provider: PoTokenCacheProviderError('something went wrong'); example bug report message") == 2
-
- def test_cache_provider_error_fallback(self, pot_request, ie, logger):
- error_pcp = ErrorPCP(ie, logger, {})
- memory_pcp = create_memory_pcp(ie, logger, provider_key='memory')
-
- cache = PoTokenCache(
- cache_providers=[error_pcp, memory_pcp],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response)
-
- # 1. Store fails for error_pcp, stored in memory_pcp
- # 2. Get fails for error_pcp, fetched from memory_pcp
- # 3. Since fetched from lower priority, it should be stored in the highest priority cache provider
- # 4. Store fails in error_pcp. Since write policy is WRITE_FIRST, it should not try to store in memory_pcp regardless of if the store in error_pcp fails
-
- assert cache.get(pot_request)
- assert error_pcp.get_calls == 1
- assert error_pcp.store_calls == 2 # since highest priority, when fetched from lower priority, it should be stored in the highest priority cache provider
- assert memory_pcp.get_calls == 1
- assert memory_pcp.store_calls == 1
-
- assert logger.messages['warning'].count("Error from \"error\" PO Token cache provider: PoTokenCacheProviderError('something went wrong'); example bug report message") == 3
-
- def test_cache_provider_unexpected_error_no_fallback(self, pot_request, ie, logger):
- error_pcp = UnexpectedErrorPCP(ie, logger, {})
- cache = PoTokenCache(
- cache_providers=[error_pcp],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response)
- assert cache.get(pot_request) is None
- assert error_pcp.get_calls == 1
- assert error_pcp.store_calls == 1
-
- assert logger.messages['error'].count("Error occurred with \"unexpected_error\" PO Token cache provider: ValueError('something went wrong'); example bug report message") == 2
-
- def test_cache_provider_unexpected_error_fallback(self, pot_request, ie, logger):
- error_pcp = UnexpectedErrorPCP(ie, logger, {})
- memory_pcp = create_memory_pcp(ie, logger, provider_key='memory')
-
- cache = PoTokenCache(
- cache_providers=[error_pcp, memory_pcp],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response)
-
- # 1. Store fails for error_pcp, stored in memory_pcp
- # 2. Get fails for error_pcp, fetched from memory_pcp
- # 3. Since fetched from lower priority, it should be stored in the highest priority cache provider
- # 4. Store fails in error_pcp. Since write policy is WRITE_FIRST, it should not try to store in memory_pcp regardless of if the store in error_pcp fails
-
- assert cache.get(pot_request)
- assert error_pcp.get_calls == 1
- assert error_pcp.store_calls == 2 # since highest priority, when fetched from lower priority, it should be stored in the highest priority cache provider
- assert memory_pcp.get_calls == 1
- assert memory_pcp.store_calls == 1
-
- assert logger.messages['error'].count("Error occurred with \"unexpected_error\" PO Token cache provider: ValueError('something went wrong'); example bug report message") == 3
-
- def test_cache_provider_unavailable_no_fallback(self, pot_request, ie, logger):
- provider = create_memory_pcp(ie, logger, available=False)
-
- cache = PoTokenCache(
- cache_providers=[provider],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response)
- assert cache.get(pot_request) is None
- assert provider.get_calls == 0
- assert provider.store_calls == 0
- assert provider.available_called_times
-
- def test_cache_provider_unavailable_fallback(self, pot_request, ie, logger):
- provider_unavailable = create_memory_pcp(ie, logger, provider_key='unavailable', provider_name='unavailable', available=False)
- provider_available = create_memory_pcp(ie, logger, provider_key='available', provider_name='available')
-
- cache = PoTokenCache(
- cache_providers=[provider_unavailable, provider_available],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response)
- assert cache.get(pot_request) is not None
- assert provider_unavailable.get_calls == 0
- assert provider_unavailable.store_calls == 0
- assert provider_available.get_calls == 1
- assert provider_available.store_calls == 1
- assert provider_unavailable.available_called_times
- assert provider_available.available_called_times
-
- # should not even try to use the provider for the request
- assert 'Attempting to fetch a PO Token response from "unavailable" provider' not in logger.messages['trace']
- assert 'Attempting to fetch a PO Token response from "available" provider' not in logger.messages['trace']
-
- def test_available_not_called(self, ie, pot_request, logger):
- # Test that the available method is not called when provider higher in the list is available
- provider_unavailable = create_memory_pcp(
- ie, logger, provider_key='unavailable', provider_name='unavailable', available=False)
- provider_available = create_memory_pcp(ie, logger, provider_key='available', provider_name='available')
-
- logger.log_level = logger.LogLevel.INFO
-
- cache = PoTokenCache(
- cache_providers=[provider_available, provider_unavailable],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response, write_policy=CacheProviderWritePolicy.WRITE_FIRST)
- assert cache.get(pot_request) is not None
- assert provider_unavailable.get_calls == 0
- assert provider_unavailable.store_calls == 0
- assert provider_available.get_calls == 1
- assert provider_available.store_calls == 1
- assert provider_unavailable.available_called_times == 0
- assert provider_available.available_called_times
- assert 'PO Token Cache Providers: available-0.0.0 (external), unavailable-0.0.0 (external, unavailable)' not in logger.messages.get('trace', [])
-
- def test_available_called_trace(self, ie, pot_request, logger):
- # But if logging level is trace should call available (as part of debug logging)
- provider_unavailable = create_memory_pcp(
- ie, logger, provider_key='unavailable', provider_name='unavailable', available=False)
- provider_available = create_memory_pcp(ie, logger, provider_key='available', provider_name='available')
-
- logger.log_level = logger.LogLevel.TRACE
-
- cache = PoTokenCache(
- cache_providers=[provider_available, provider_unavailable],
- cache_spec_providers=[ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})],
- logger=logger,
- )
-
- response = PoTokenResponse(EXAMPLE_PO_TOKEN)
- cache.store(pot_request, response, write_policy=CacheProviderWritePolicy.WRITE_FIRST)
- assert cache.get(pot_request) is not None
- assert provider_unavailable.get_calls == 0
- assert provider_unavailable.store_calls == 0
- assert provider_available.get_calls == 1
- assert provider_available.store_calls == 1
- assert provider_unavailable.available_called_times
- assert provider_available.available_called_times
- assert 'PO Token Cache Providers: available-0.0.0 (external), unavailable-0.0.0 (external, unavailable)' in logger.messages.get('trace', [])
-
- def test_close(self, ie, pot_request, logger):
- # Should call close on the cache providers and cache specs
- memory_pcp = create_memory_pcp(ie, logger, provider_key='memory')
- memory2_pcp = create_memory_pcp(ie, logger, provider_key='memory2')
-
- spec1 = ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- spec2 = UnavailableCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
-
- cache = PoTokenCache(
- cache_providers=[memory2_pcp, memory_pcp],
- cache_spec_providers=[spec1, spec2],
- logger=logger,
- )
-
- cache.close()
- assert memory_pcp.close_called
- assert memory2_pcp.close_called
- assert spec1.close_called
- assert spec2.close_called
-
-
-class TestPoTokenRequestDirector:
-
- def test_request_pot_success(self, ie, pot_request, pot_cache, pot_provider, logger):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- director.register_provider(pot_provider)
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
-
- def test_request_and_cache(self, ie, pot_request, pot_cache, pot_provider, logger):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- director.register_provider(pot_provider)
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert pot_provider.request_called_times == 1
- assert pot_cache.get_calls == 1
- assert pot_cache.store_calls == 1
-
- # Second request, should be cached
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert pot_cache.get_calls == 2
- assert pot_cache.store_calls == 1
- assert pot_provider.request_called_times == 1
-
- def test_bypass_cache(self, ie, pot_request, pot_cache, logger, pot_provider):
- pot_request.bypass_cache = True
-
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- director.register_provider(pot_provider)
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert pot_provider.request_called_times == 1
- assert pot_cache.get_calls == 0
- assert pot_cache.store_calls == 1
-
- # Second request, should not get from cache
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert pot_provider.request_called_times == 2
- assert pot_cache.get_calls == 0
- assert pot_cache.store_calls == 2
-
- # POT is still cached, should get from cache
- pot_request.bypass_cache = False
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert pot_provider.request_called_times == 2
- assert pot_cache.get_calls == 1
- assert pot_cache.store_calls == 2
-
- def test_clean_pot_generate(self, ie, pot_request, pot_cache, logger):
- # Token should be cleaned before returning
- base_token = base64.urlsafe_b64encode(b'token').decode()
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = success_ptp(PoTokenResponse(base_token + '?extra=params'))(ie, logger, settings={})
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response == base_token
- assert provider.request_called_times == 1
-
- # Confirm the cleaned version was stored in the cache
- cached_token = pot_cache.get(pot_request)
- assert cached_token.po_token == base_token
-
- def test_clean_pot_cache(self, ie, pot_request, pot_cache, logger, pot_provider):
- # Token retrieved from cache should be cleaned before returning
- base_token = base64.urlsafe_b64encode(b'token').decode()
- pot_cache.store(pot_request, PoTokenResponse(base_token + '?extra=params'))
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- director.register_provider(pot_provider)
-
- response = director.get_po_token(pot_request)
- assert response == base_token
- assert pot_cache.get_calls == 1
- assert pot_provider.request_called_times == 0
-
- def test_cache_expires_at_none(self, ie, pot_request, pot_cache, logger, pot_provider):
- # Should cache if expires_at=None in the response
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = success_ptp(PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=None))(ie, logger, settings={})
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert pot_cache.store_calls == 1
- assert pot_cache.get(pot_request).po_token == EXAMPLE_PO_TOKEN
-
- def test_cache_expires_at_positive(self, ie, pot_request, pot_cache, logger, pot_provider):
- # Should cache if expires_at is a positive number in the response
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = success_ptp(PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=99999999999))(ie, logger, settings={})
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert pot_cache.store_calls == 1
- assert pot_cache.get(pot_request).po_token == EXAMPLE_PO_TOKEN
-
- @pytest.mark.parametrize('expires_at', [0, -1])
- def test_not_cache_expires_at(self, ie, pot_request, pot_cache, logger, pot_provider, expires_at):
- # Should not cache if expires_at <= 0 in the response
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = success_ptp(PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=expires_at))(ie, logger, settings={})
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert pot_cache.store_calls == 0
- assert pot_cache.get(pot_request) is None
-
- def test_no_providers(self, ie, pot_request, pot_cache, logger):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- response = director.get_po_token(pot_request)
- assert response is None
-
- def test_try_cache_no_providers(self, ie, pot_request, pot_cache, logger):
- # Should still try the cache even if no providers are configured
- pot_cache.store(pot_request, PoTokenResponse(EXAMPLE_PO_TOKEN))
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
-
- def test_close(self, ie, pot_request, pot_cache, pot_provider, logger):
- # Should call close on the pot cache and any providers
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
-
- provider2 = UnavailablePTP(ie, logger, {})
- director.register_provider(pot_provider)
- director.register_provider(provider2)
-
- director.close()
- assert pot_provider.close_called
- assert provider2.close_called
- assert pot_cache.close_called
-
- def test_pot_provider_preferences(self, pot_request, pot_cache, ie, logger):
- pot_request.bypass_cache = True
- provider_two_pot = base64.urlsafe_b64encode(b'token2').decode()
-
- example_provider = success_ptp(response=PoTokenResponse(EXAMPLE_PO_TOKEN), key='exampleone')(ie, logger, settings={})
- example_provider_two = success_ptp(response=PoTokenResponse(provider_two_pot), key='exampletwo')(ie, logger, settings={})
-
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- director.register_provider(example_provider)
- director.register_provider(example_provider_two)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert example_provider.request_called_times == 1
- assert example_provider_two.request_called_times == 0
-
- standard_preference_called = False
- example_preference_called = False
-
- # Test that the provider preferences are respected
- def standard_preference(provider, request, *_, **__):
- nonlocal standard_preference_called
- standard_preference_called = True
- assert isinstance(provider, PoTokenProvider)
- assert isinstance(request, PoTokenRequest)
- return 1
-
- def example_preference(provider, request, *_, **__):
- nonlocal example_preference_called
- example_preference_called = True
- assert isinstance(provider, PoTokenProvider)
- assert isinstance(request, PoTokenRequest)
- if provider.PROVIDER_KEY == example_provider.PROVIDER_KEY:
- return -100
- return 0
-
- # test that it can handle multiple preferences
- director.register_preference(example_preference)
- director.register_preference(standard_preference)
-
- response = director.get_po_token(pot_request)
- assert response == provider_two_pot
- assert example_provider.request_called_times == 1
- assert example_provider_two.request_called_times == 1
- assert standard_preference_called
- assert example_preference_called
-
- def test_unsupported_request_no_fallback(self, ie, logger, pot_cache, pot_request):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = UnsupportedPTP(ie, logger, {})
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response is None
- assert provider.request_called_times == 1
-
- def test_unsupported_request_fallback(self, ie, logger, pot_cache, pot_request, pot_provider):
- # Should fallback to the next provider if the first one does not support the request
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = UnsupportedPTP(ie, logger, {})
- director.register_provider(provider)
- director.register_provider(pot_provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert provider.request_called_times == 1
- assert pot_provider.request_called_times == 1
- assert 'PO Token Provider "unsupported" rejected this request, trying next available provider. Reason: unsupported request' in logger.messages['trace']
-
- def test_unavailable_request_no_fallback(self, ie, logger, pot_cache, pot_request):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = UnavailablePTP(ie, logger, {})
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response is None
- assert provider.request_called_times == 0
- assert provider.available_called_times
-
- def test_unavailable_request_fallback(self, ie, logger, pot_cache, pot_request, pot_provider):
- # Should fallback to the next provider if the first one is unavailable
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = UnavailablePTP(ie, logger, {})
- director.register_provider(provider)
- director.register_provider(pot_provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert provider.request_called_times == 0
- assert provider.available_called_times
- assert pot_provider.request_called_times == 1
- assert pot_provider.available_called_times
- # should not even try use the provider for the request
- assert 'Attempting to fetch a PO Token from "unavailable" provider' not in logger.messages['trace']
- assert 'Attempting to fetch a PO Token from "success" provider' in logger.messages['trace']
-
- def test_available_not_called(self, ie, logger, pot_cache, pot_request, pot_provider):
- # Test that the available method is not called when provider higher in the list is available
- logger.log_level = logger.LogLevel.INFO
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = UnavailablePTP(ie, logger, {})
- director.register_provider(pot_provider)
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert provider.request_called_times == 0
- assert provider.available_called_times == 0
- assert pot_provider.request_called_times == 1
- assert pot_provider.available_called_times == 2
- assert 'PO Token Providers: success-0.0.1 (external), unavailable-0.0.0 (external, unavailable)' not in logger.messages.get('trace', [])
-
- def test_available_called_trace(self, ie, logger, pot_cache, pot_request, pot_provider):
- # But if logging level is trace should call available (as part of debug logging)
- logger.log_level = logger.LogLevel.TRACE
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = UnavailablePTP(ie, logger, {})
- director.register_provider(pot_provider)
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert provider.request_called_times == 0
- assert provider.available_called_times == 1
- assert pot_provider.request_called_times == 1
- assert pot_provider.available_called_times == 3
- assert 'PO Token Providers: success-0.0.1 (external), unavailable-0.0.0 (external, unavailable)' in logger.messages['trace']
-
- def test_provider_error_no_fallback_unexpected(self, ie, logger, pot_cache, pot_request):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = ErrorPTP(ie, logger, {})
- director.register_provider(provider)
- pot_request.video_id = 'unexpected'
- response = director.get_po_token(pot_request)
- assert response is None
- assert provider.request_called_times == 1
- assert "Error fetching PO Token from \"error\" provider: PoTokenProviderError('an error occurred'); please report this issue to the provider developer at https://error.example.com/issues ." in logger.messages['warning']
-
- def test_provider_error_no_fallback_expected(self, ie, logger, pot_cache, pot_request):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = ErrorPTP(ie, logger, {})
- director.register_provider(provider)
- pot_request.video_id = 'expected'
- response = director.get_po_token(pot_request)
- assert response is None
- assert provider.request_called_times == 1
- assert "Error fetching PO Token from \"error\" provider: PoTokenProviderError('an error occurred')" in logger.messages['warning']
-
- def test_provider_error_fallback(self, ie, logger, pot_cache, pot_request, pot_provider):
- # Should fallback to the next provider if the first one raises an error
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = ErrorPTP(ie, logger, {})
- director.register_provider(provider)
- director.register_provider(pot_provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert provider.request_called_times == 1
- assert pot_provider.request_called_times == 1
- assert "Error fetching PO Token from \"error\" provider: PoTokenProviderError('an error occurred'); please report this issue to the provider developer at https://error.example.com/issues ." in logger.messages['warning']
-
- def test_provider_unexpected_error_no_fallback(self, ie, logger, pot_cache, pot_request):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = UnexpectedErrorPTP(ie, logger, {})
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response is None
- assert provider.request_called_times == 1
- assert "Unexpected error when fetching PO Token from \"unexpected_error\" provider: ValueError('an unexpected error occurred'); please report this issue to the provider developer at https://unexpected.example.com/issues ." in logger.messages['error']
-
- def test_provider_unexpected_error_fallback(self, ie, logger, pot_cache, pot_request, pot_provider):
- # Should fallback to the next provider if the first one raises an unexpected error
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = UnexpectedErrorPTP(ie, logger, {})
- director.register_provider(provider)
- director.register_provider(pot_provider)
-
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert provider.request_called_times == 1
- assert pot_provider.request_called_times == 1
- assert "Unexpected error when fetching PO Token from \"unexpected_error\" provider: ValueError('an unexpected error occurred'); please report this issue to the provider developer at https://unexpected.example.com/issues ." in logger.messages['error']
-
- def test_invalid_po_token_response_type(self, ie, logger, pot_cache, pot_request, pot_provider):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = InvalidPTP(ie, logger, {})
- director.register_provider(provider)
-
- pot_request.video_id = 'invalid_type'
-
- response = director.get_po_token(pot_request)
- assert response is None
- assert provider.request_called_times == 1
- assert 'Invalid PO Token response received from "invalid" provider: invalid-response; please report this issue to the provider developer at https://invalid.example.com/issues .' in logger.messages['error']
-
- # Should fallback to next available provider
- director.register_provider(pot_provider)
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert provider.request_called_times == 2
- assert pot_provider.request_called_times == 1
-
- def test_invalid_po_token_response(self, ie, logger, pot_cache, pot_request, pot_provider):
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
- provider = InvalidPTP(ie, logger, {})
- director.register_provider(provider)
-
- response = director.get_po_token(pot_request)
- assert response is None
- assert provider.request_called_times == 1
- assert "Invalid PO Token response received from \"invalid\" provider: PoTokenResponse(po_token='example-token?', expires_at='123'); please report this issue to the provider developer at https://invalid.example.com/issues ." in logger.messages['error']
-
- # Should fallback to next available provider
- director.register_provider(pot_provider)
- response = director.get_po_token(pot_request)
- assert response == EXAMPLE_PO_TOKEN
- assert provider.request_called_times == 2
- assert pot_provider.request_called_times == 1
-
- def test_copy_request_provider(self, ie, logger, pot_cache, pot_request):
-
- class BadProviderPTP(BaseMockPoTokenProvider):
- _SUPPORTED_CONTEXTS = None
- _SUPPORTED_CLIENTS = None
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- # Providers should not modify the request object, but we should guard against it
- request.video_id = 'bad'
- raise PoTokenProviderRejectedRequest('bad request')
-
- class GoodProviderPTP(BaseMockPoTokenProvider):
- _SUPPORTED_CONTEXTS = None
- _SUPPORTED_CLIENTS = None
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- return PoTokenResponse(base64.urlsafe_b64encode(request.video_id.encode()).decode())
-
- director = PoTokenRequestDirector(logger=logger, cache=pot_cache)
-
- bad_provider = BadProviderPTP(ie, logger, {})
- good_provider = GoodProviderPTP(ie, logger, {})
-
- director.register_provider(bad_provider)
- director.register_provider(good_provider)
-
- pot_request.video_id = 'good'
- response = director.get_po_token(pot_request)
- assert response == base64.urlsafe_b64encode(b'good').decode()
- assert bad_provider.request_called_times == 1
- assert good_provider.request_called_times == 1
- assert pot_request.video_id == 'good'
-
-
-@pytest.mark.parametrize('spec, expected', [
- (None, False),
- (PoTokenCacheSpec(key_bindings={'v': 'video-id'}, default_ttl=60, write_policy=None), False), # type: ignore
- (PoTokenCacheSpec(key_bindings={'v': 'video-id'}, default_ttl='invalid'), False), # type: ignore
- (PoTokenCacheSpec(key_bindings='invalid', default_ttl=60), False), # type: ignore
- (PoTokenCacheSpec(key_bindings={2: 'video-id'}, default_ttl=60), False), # type: ignore
- (PoTokenCacheSpec(key_bindings={'v': 2}, default_ttl=60), False), # type: ignore
- (PoTokenCacheSpec(key_bindings={'v': None}, default_ttl=60), False), # type: ignore
-
- (PoTokenCacheSpec(key_bindings={'v': 'video_id', 'e': None}, default_ttl=60), True),
- (PoTokenCacheSpec(key_bindings={'v': 'video_id'}, default_ttl=60, write_policy=CacheProviderWritePolicy.WRITE_FIRST), True),
-])
-def test_validate_cache_spec(spec, expected):
- assert validate_cache_spec(spec) == expected
-
-
-@pytest.mark.parametrize('po_token', [
- 'invalid-token?',
- '123',
-])
-def test_clean_pot_fail(po_token):
- with pytest.raises(ValueError, match='Invalid PO Token'):
- clean_pot(po_token)
-
-
-@pytest.mark.parametrize('po_token,expected', [
- ('TwAA/+8=', 'TwAA_-8='),
- ('TwAA%5F%2D9VA6Q92v%5FvEQ4==?extra-param=2', 'TwAA_-9VA6Q92v_vEQ4='),
-])
-def test_clean_pot(po_token, expected):
- assert clean_pot(po_token) == expected
-
-
-@pytest.mark.parametrize(
- 'response, expected',
- [
- (None, False),
- (PoTokenResponse(None), False),
- (PoTokenResponse(1), False),
- (PoTokenResponse('invalid-token?'), False),
- (PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at='abc'), False), # type: ignore
- (PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=100), False),
- (PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=time.time() + 10000.0), False), # type: ignore
- (PoTokenResponse(EXAMPLE_PO_TOKEN), True),
- (PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=-1), True),
- (PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=0), True),
- (PoTokenResponse(EXAMPLE_PO_TOKEN, expires_at=int(time.time()) + 10000), True),
- ],
-)
-def test_validate_pot_response(response, expected):
- assert validate_response(response) == expected
-
-
-def test_built_in_provider(ie, logger):
- class BuiltinProviderDefaultT(BuiltinIEContentProvider, suffix='T'):
- def is_available(self):
- return True
-
- class BuiltinProviderCustomNameT(BuiltinIEContentProvider, suffix='T'):
- PROVIDER_NAME = 'CustomName'
-
- def is_available(self):
- return True
-
- class ExternalProviderDefaultT(IEContentProvider, suffix='T'):
- def is_available(self):
- return True
-
- class ExternalProviderCustomT(IEContentProvider, suffix='T'):
- PROVIDER_NAME = 'custom'
- PROVIDER_VERSION = '5.4b2'
-
- def is_available(self):
- return True
-
- class ExternalProviderUnavailableT(IEContentProvider, suffix='T'):
- def is_available(self) -> bool:
- return False
-
- class BuiltinProviderUnavailableT(IEContentProvider, suffix='T'):
- def is_available(self) -> bool:
- return False
-
- built_in_default = BuiltinProviderDefaultT(ie=ie, logger=logger, settings={})
- built_in_custom_name = BuiltinProviderCustomNameT(ie=ie, logger=logger, settings={})
- built_in_unavailable = BuiltinProviderUnavailableT(ie=ie, logger=logger, settings={})
- external_default = ExternalProviderDefaultT(ie=ie, logger=logger, settings={})
- external_custom = ExternalProviderCustomT(ie=ie, logger=logger, settings={})
- external_unavailable = ExternalProviderUnavailableT(ie=ie, logger=logger, settings={})
-
- assert provider_display_list([]) == 'none'
- assert provider_display_list([built_in_default]) == 'BuiltinProviderDefault'
- assert provider_display_list([external_unavailable]) == 'ExternalProviderUnavailable-0.0.0 (external, unavailable)'
- assert provider_display_list([
- built_in_default,
- built_in_custom_name,
- external_default,
- external_custom,
- external_unavailable,
- built_in_unavailable],
- ) == 'BuiltinProviderDefault, CustomName, ExternalProviderDefault-0.0.0 (external), custom-5.4b2 (external), ExternalProviderUnavailable-0.0.0 (external, unavailable), BuiltinProviderUnavailable-0.0.0 (external, unavailable)'
diff --git a/test/test_pot/test_pot_framework.py b/test/test_pot/test_pot_framework.py
deleted file mode 100644
index fae6c8002..000000000
--- a/test/test_pot/test_pot_framework.py
+++ /dev/null
@@ -1,639 +0,0 @@
-import pytest
-
-from yt_dlp.extractor.youtube.pot._provider import IEContentProvider, configuration_arg
-from yt_dlp.cookies import YoutubeDLCookieJar
-from yt_dlp.utils.networking import HTTPHeaderDict
-from yt_dlp.extractor.youtube.pot.provider import (
- PoTokenRequest,
- PoTokenContext,
- ExternalRequestFeature,
-
-)
-
-from yt_dlp.extractor.youtube.pot.cache import (
- PoTokenCacheProvider,
- PoTokenCacheSpec,
- PoTokenCacheSpecProvider,
- CacheProviderWritePolicy,
-)
-
-import yt_dlp.extractor.youtube.pot.cache as cache
-
-from yt_dlp.networking import Request
-from yt_dlp.extractor.youtube.pot.provider import (
- PoTokenResponse,
- PoTokenProvider,
- PoTokenProviderRejectedRequest,
- provider_bug_report_message,
- register_provider,
- register_preference,
-)
-
-from yt_dlp.extractor.youtube.pot._registry import _pot_providers, _ptp_preferences, _pot_pcs_providers, _pot_cache_providers, _pot_cache_provider_preferences
-
-
-class ExamplePTP(PoTokenProvider):
- PROVIDER_NAME = 'example'
- PROVIDER_VERSION = '0.0.1'
- BUG_REPORT_LOCATION = 'https://example.com/issues'
-
- _SUPPORTED_CLIENTS = ('WEB',)
- _SUPPORTED_CONTEXTS = (PoTokenContext.GVS, )
-
- _SUPPORTED_EXTERNAL_REQUEST_FEATURES = (
- ExternalRequestFeature.PROXY_SCHEME_HTTP,
- ExternalRequestFeature.PROXY_SCHEME_SOCKS5H,
- )
-
- def is_available(self) -> bool:
- return True
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- return PoTokenResponse('example-token', expires_at=123)
-
-
-class ExampleCacheProviderPCP(PoTokenCacheProvider):
-
- PROVIDER_NAME = 'example'
- PROVIDER_VERSION = '0.0.1'
- BUG_REPORT_LOCATION = 'https://example.com/issues'
-
- def is_available(self) -> bool:
- return True
-
- def get(self, key: str):
- return 'example-cache'
-
- def store(self, key: str, value: str, expires_at: int):
- pass
-
- def delete(self, key: str):
- pass
-
-
-class ExampleCacheSpecProviderPCSP(PoTokenCacheSpecProvider):
-
- PROVIDER_NAME = 'example'
- PROVIDER_VERSION = '0.0.1'
- BUG_REPORT_LOCATION = 'https://example.com/issues'
-
- def generate_cache_spec(self, request: PoTokenRequest):
- return PoTokenCacheSpec(
- key_bindings={'field': 'example-key'},
- default_ttl=60,
- write_policy=CacheProviderWritePolicy.WRITE_FIRST,
- )
-
-
-class TestPoTokenProvider:
-
- def test_base_type(self):
- assert issubclass(PoTokenProvider, IEContentProvider)
-
- def test_create_provider_missing_fetch_method(self, ie, logger):
- class MissingMethodsPTP(PoTokenProvider):
- def is_available(self) -> bool:
- return True
-
- with pytest.raises(TypeError):
- MissingMethodsPTP(ie=ie, logger=logger, settings={})
-
- def test_create_provider_missing_available_method(self, ie, logger):
- class MissingMethodsPTP(PoTokenProvider):
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- raise PoTokenProviderRejectedRequest('Not implemented')
-
- with pytest.raises(TypeError):
- MissingMethodsPTP(ie=ie, logger=logger, settings={})
-
- def test_barebones_provider(self, ie, logger):
- class BarebonesProviderPTP(PoTokenProvider):
- def is_available(self) -> bool:
- return True
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- raise PoTokenProviderRejectedRequest('Not implemented')
-
- provider = BarebonesProviderPTP(ie=ie, logger=logger, settings={})
- assert provider.PROVIDER_NAME == 'BarebonesProvider'
- assert provider.PROVIDER_KEY == 'BarebonesProvider'
- assert provider.PROVIDER_VERSION == '0.0.0'
- assert provider.BUG_REPORT_MESSAGE == 'please report this issue to the provider developer at (developer has not provided a bug report location) .'
-
- def test_example_provider_success(self, ie, logger, pot_request):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
- assert provider.PROVIDER_NAME == 'example'
- assert provider.PROVIDER_KEY == 'Example'
- assert provider.PROVIDER_VERSION == '0.0.1'
- assert provider.BUG_REPORT_MESSAGE == 'please report this issue to the provider developer at https://example.com/issues .'
- assert provider.is_available()
-
- response = provider.request_pot(pot_request)
-
- assert response.po_token == 'example-token'
- assert response.expires_at == 123
-
- def test_provider_unsupported_context(self, ie, logger, pot_request):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
- pot_request.context = PoTokenContext.PLAYER
-
- with pytest.raises(PoTokenProviderRejectedRequest):
- provider.request_pot(pot_request)
-
- def test_provider_unsupported_client(self, ie, logger, pot_request):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
- pot_request.innertube_context['client']['clientName'] = 'ANDROID'
-
- with pytest.raises(PoTokenProviderRejectedRequest):
- provider.request_pot(pot_request)
-
- def test_provider_unsupported_proxy_scheme(self, ie, logger, pot_request):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
- pot_request.request_proxy = 'socks4://example.com'
-
- with pytest.raises(
- PoTokenProviderRejectedRequest,
- match=r'External requests by "example" provider do not support proxy scheme "socks4"\. Supported proxy '
- 'schemes: http, socks5h',
- ):
- provider.request_pot(pot_request)
-
- pot_request.request_proxy = 'http://example.com'
-
- assert provider.request_pot(pot_request)
-
- def test_provider_ignore_external_request_features(self, ie, logger, pot_request):
- class InternalPTP(ExamplePTP):
- _SUPPORTED_EXTERNAL_REQUEST_FEATURES = None
-
- provider = InternalPTP(ie=ie, logger=logger, settings={})
-
- pot_request.request_proxy = 'socks5://example.com'
- assert provider.request_pot(pot_request)
- pot_request.request_source_address = '0.0.0.0'
- assert provider.request_pot(pot_request)
-
- def test_provider_unsupported_external_request_source_address(self, ie, logger, pot_request):
- class InternalPTP(ExamplePTP):
- _SUPPORTED_EXTERNAL_REQUEST_FEATURES = tuple()
-
- provider = InternalPTP(ie=ie, logger=logger, settings={})
-
- pot_request.request_source_address = None
- assert provider.request_pot(pot_request)
-
- pot_request.request_source_address = '0.0.0.0'
- with pytest.raises(
- PoTokenProviderRejectedRequest,
- match='External requests by "example" provider do not support setting source address',
- ):
- provider.request_pot(pot_request)
-
- def test_provider_supported_external_request_source_address(self, ie, logger, pot_request):
- class InternalPTP(ExamplePTP):
- _SUPPORTED_EXTERNAL_REQUEST_FEATURES = (
- ExternalRequestFeature.SOURCE_ADDRESS,
- )
-
- provider = InternalPTP(ie=ie, logger=logger, settings={})
-
- pot_request.request_source_address = None
- assert provider.request_pot(pot_request)
-
- pot_request.request_source_address = '0.0.0.0'
- assert provider.request_pot(pot_request)
-
- def test_provider_unsupported_external_request_tls_verification(self, ie, logger, pot_request):
- class InternalPTP(ExamplePTP):
- _SUPPORTED_EXTERNAL_REQUEST_FEATURES = tuple()
-
- provider = InternalPTP(ie=ie, logger=logger, settings={})
-
- pot_request.request_verify_tls = True
- assert provider.request_pot(pot_request)
-
- pot_request.request_verify_tls = False
- with pytest.raises(
- PoTokenProviderRejectedRequest,
- match='External requests by "example" provider do not support ignoring TLS certificate failures',
- ):
- provider.request_pot(pot_request)
-
- def test_provider_supported_external_request_tls_verification(self, ie, logger, pot_request):
- class InternalPTP(ExamplePTP):
- _SUPPORTED_EXTERNAL_REQUEST_FEATURES = (
- ExternalRequestFeature.DISABLE_TLS_VERIFICATION,
- )
-
- provider = InternalPTP(ie=ie, logger=logger, settings={})
-
- pot_request.request_verify_tls = True
- assert provider.request_pot(pot_request)
-
- pot_request.request_verify_tls = False
- assert provider.request_pot(pot_request)
-
- def test_provider_request_webpage(self, ie, logger, pot_request):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
-
- cookiejar = YoutubeDLCookieJar()
- pot_request.request_headers = HTTPHeaderDict({'User-Agent': 'example-user-agent'})
- pot_request.request_proxy = 'socks5://example-proxy.com'
- pot_request.request_cookiejar = cookiejar
-
- def mock_urlopen(request):
- return request
-
- ie._downloader.urlopen = mock_urlopen
-
- sent_request = provider._request_webpage(Request(
- 'https://example.com',
- ), pot_request=pot_request)
-
- assert sent_request.url == 'https://example.com'
- assert sent_request.headers['User-Agent'] == 'example-user-agent'
- assert sent_request.proxies == {'all': 'socks5://example-proxy.com'}
- assert sent_request.extensions['cookiejar'] is cookiejar
- assert 'Requesting webpage' in logger.messages['info']
-
- def test_provider_request_webpage_override(self, ie, logger, pot_request):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
-
- cookiejar_request = YoutubeDLCookieJar()
- pot_request.request_headers = HTTPHeaderDict({'User-Agent': 'example-user-agent'})
- pot_request.request_proxy = 'socks5://example-proxy.com'
- pot_request.request_cookiejar = cookiejar_request
-
- def mock_urlopen(request):
- return request
-
- ie._downloader.urlopen = mock_urlopen
-
- sent_request = provider._request_webpage(Request(
- 'https://example.com',
- headers={'User-Agent': 'override-user-agent-override'},
- proxies={'http': 'http://example-proxy-override.com'},
- extensions={'cookiejar': YoutubeDLCookieJar()},
- ), pot_request=pot_request, note='Custom requesting webpage')
-
- assert sent_request.url == 'https://example.com'
- assert sent_request.headers['User-Agent'] == 'override-user-agent-override'
- assert sent_request.proxies == {'http': 'http://example-proxy-override.com'}
- assert sent_request.extensions['cookiejar'] is not cookiejar_request
- assert 'Custom requesting webpage' in logger.messages['info']
-
- def test_provider_request_webpage_no_log(self, ie, logger, pot_request):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
-
- def mock_urlopen(request):
- return request
-
- ie._downloader.urlopen = mock_urlopen
-
- sent_request = provider._request_webpage(Request(
- 'https://example.com',
- ), note=False)
-
- assert sent_request.url == 'https://example.com'
- assert 'info' not in logger.messages
-
- def test_provider_request_webpage_no_pot_request(self, ie, logger):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
-
- def mock_urlopen(request):
- return request
-
- ie._downloader.urlopen = mock_urlopen
-
- sent_request = provider._request_webpage(Request(
- 'https://example.com',
- ), pot_request=None)
-
- assert sent_request.url == 'https://example.com'
-
- def test_get_config_arg(self, ie, logger):
- provider = ExamplePTP(ie=ie, logger=logger, settings={'abc': ['123D'], 'xyz': ['456a', '789B']})
-
- assert provider._configuration_arg('abc') == ['123d']
- assert provider._configuration_arg('abc', default=['default']) == ['123d']
- assert provider._configuration_arg('ABC', default=['default']) == ['default']
- assert provider._configuration_arg('abc', casesense=True) == ['123D']
- assert provider._configuration_arg('xyz', casesense=False) == ['456a', '789b']
-
- def test_require_class_end_with_suffix(self, ie, logger):
- class InvalidSuffix(PoTokenProvider):
- PROVIDER_NAME = 'invalid-suffix'
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- raise PoTokenProviderRejectedRequest('Not implemented')
-
- def is_available(self) -> bool:
- return True
-
- provider = InvalidSuffix(ie=ie, logger=logger, settings={})
-
- with pytest.raises(AssertionError):
- provider.PROVIDER_KEY # noqa: B018
-
-
-class TestPoTokenCacheProvider:
-
- def test_base_type(self):
- assert issubclass(PoTokenCacheProvider, IEContentProvider)
-
- def test_create_provider_missing_get_method(self, ie, logger):
- class MissingMethodsPCP(PoTokenCacheProvider):
- def store(self, key: str, value: str, expires_at: int):
- pass
-
- def delete(self, key: str):
- pass
-
- def is_available(self) -> bool:
- return True
-
- with pytest.raises(TypeError):
- MissingMethodsPCP(ie=ie, logger=logger, settings={})
-
- def test_create_provider_missing_store_method(self, ie, logger):
- class MissingMethodsPCP(PoTokenCacheProvider):
- def get(self, key: str):
- pass
-
- def delete(self, key: str):
- pass
-
- def is_available(self) -> bool:
- return True
-
- with pytest.raises(TypeError):
- MissingMethodsPCP(ie=ie, logger=logger, settings={})
-
- def test_create_provider_missing_delete_method(self, ie, logger):
- class MissingMethodsPCP(PoTokenCacheProvider):
- def get(self, key: str):
- pass
-
- def store(self, key: str, value: str, expires_at: int):
- pass
-
- def is_available(self) -> bool:
- return True
-
- with pytest.raises(TypeError):
- MissingMethodsPCP(ie=ie, logger=logger, settings={})
-
- def test_create_provider_missing_is_available_method(self, ie, logger):
- class MissingMethodsPCP(PoTokenCacheProvider):
- def get(self, key: str):
- pass
-
- def store(self, key: str, value: str, expires_at: int):
- pass
-
- def delete(self, key: str):
- pass
-
- with pytest.raises(TypeError):
- MissingMethodsPCP(ie=ie, logger=logger, settings={})
-
- def test_barebones_provider(self, ie, logger):
- class BarebonesProviderPCP(PoTokenCacheProvider):
-
- def is_available(self) -> bool:
- return True
-
- def get(self, key: str):
- return 'example-cache'
-
- def store(self, key: str, value: str, expires_at: int):
- pass
-
- def delete(self, key: str):
- pass
-
- provider = BarebonesProviderPCP(ie=ie, logger=logger, settings={})
- assert provider.PROVIDER_NAME == 'BarebonesProvider'
- assert provider.PROVIDER_KEY == 'BarebonesProvider'
- assert provider.PROVIDER_VERSION == '0.0.0'
- assert provider.BUG_REPORT_MESSAGE == 'please report this issue to the provider developer at (developer has not provided a bug report location) .'
-
- def test_create_provider_example(self, ie, logger):
- provider = ExampleCacheProviderPCP(ie=ie, logger=logger, settings={})
- assert provider.PROVIDER_NAME == 'example'
- assert provider.PROVIDER_KEY == 'ExampleCacheProvider'
- assert provider.PROVIDER_VERSION == '0.0.1'
- assert provider.BUG_REPORT_MESSAGE == 'please report this issue to the provider developer at https://example.com/issues .'
- assert provider.is_available()
-
- def test_get_config_arg(self, ie, logger):
- provider = ExampleCacheProviderPCP(ie=ie, logger=logger, settings={'abc': ['123D'], 'xyz': ['456a', '789B']})
- assert provider._configuration_arg('abc') == ['123d']
- assert provider._configuration_arg('abc', default=['default']) == ['123d']
- assert provider._configuration_arg('ABC', default=['default']) == ['default']
- assert provider._configuration_arg('abc', casesense=True) == ['123D']
- assert provider._configuration_arg('xyz', casesense=False) == ['456a', '789b']
-
- def test_require_class_end_with_suffix(self, ie, logger):
- class InvalidSuffix(PoTokenCacheProvider):
- def get(self, key: str):
- return 'example-cache'
-
- def store(self, key: str, value: str, expires_at: int):
- pass
-
- def delete(self, key: str):
- pass
-
- def is_available(self) -> bool:
- return True
-
- provider = InvalidSuffix(ie=ie, logger=logger, settings={})
-
- with pytest.raises(AssertionError):
- provider.PROVIDER_KEY # noqa: B018
-
-
-class TestPoTokenCacheSpecProvider:
-
- def test_base_type(self):
- assert issubclass(PoTokenCacheSpecProvider, IEContentProvider)
-
- def test_create_provider_missing_supports_method(self, ie, logger):
- class MissingMethodsPCS(PoTokenCacheSpecProvider):
- pass
-
- with pytest.raises(TypeError):
- MissingMethodsPCS(ie=ie, logger=logger, settings={})
-
- def test_create_provider_barebones(self, ie, pot_request, logger):
- class BarebonesProviderPCSP(PoTokenCacheSpecProvider):
- def generate_cache_spec(self, request: PoTokenRequest):
- return PoTokenCacheSpec(
- default_ttl=100,
- key_bindings={},
- )
-
- provider = BarebonesProviderPCSP(ie=ie, logger=logger, settings={})
- assert provider.PROVIDER_NAME == 'BarebonesProvider'
- assert provider.PROVIDER_KEY == 'BarebonesProvider'
- assert provider.PROVIDER_VERSION == '0.0.0'
- assert provider.BUG_REPORT_MESSAGE == 'please report this issue to the provider developer at (developer has not provided a bug report location) .'
- assert provider.is_available()
- assert provider.generate_cache_spec(request=pot_request).default_ttl == 100
- assert provider.generate_cache_spec(request=pot_request).key_bindings == {}
- assert provider.generate_cache_spec(request=pot_request).write_policy == CacheProviderWritePolicy.WRITE_ALL
-
- def test_create_provider_example(self, ie, pot_request, logger):
- provider = ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={})
- assert provider.PROVIDER_NAME == 'example'
- assert provider.PROVIDER_KEY == 'ExampleCacheSpecProvider'
- assert provider.PROVIDER_VERSION == '0.0.1'
- assert provider.BUG_REPORT_MESSAGE == 'please report this issue to the provider developer at https://example.com/issues .'
- assert provider.is_available()
- assert provider.generate_cache_spec(pot_request)
- assert provider.generate_cache_spec(pot_request).key_bindings == {'field': 'example-key'}
- assert provider.generate_cache_spec(pot_request).default_ttl == 60
- assert provider.generate_cache_spec(pot_request).write_policy == CacheProviderWritePolicy.WRITE_FIRST
-
- def test_get_config_arg(self, ie, logger):
- provider = ExampleCacheSpecProviderPCSP(ie=ie, logger=logger, settings={'abc': ['123D'], 'xyz': ['456a', '789B']})
-
- assert provider._configuration_arg('abc') == ['123d']
- assert provider._configuration_arg('abc', default=['default']) == ['123d']
- assert provider._configuration_arg('ABC', default=['default']) == ['default']
- assert provider._configuration_arg('abc', casesense=True) == ['123D']
- assert provider._configuration_arg('xyz', casesense=False) == ['456a', '789b']
-
- def test_require_class_end_with_suffix(self, ie, logger):
- class InvalidSuffix(PoTokenCacheSpecProvider):
- def generate_cache_spec(self, request: PoTokenRequest):
- return None
-
- provider = InvalidSuffix(ie=ie, logger=logger, settings={})
-
- with pytest.raises(AssertionError):
- provider.PROVIDER_KEY # noqa: B018
-
-
-class TestPoTokenRequest:
- def test_copy_request(self, pot_request):
- copied_request = pot_request.copy()
-
- assert copied_request is not pot_request
- assert copied_request.context == pot_request.context
- assert copied_request.innertube_context == pot_request.innertube_context
- assert copied_request.innertube_context is not pot_request.innertube_context
- copied_request.innertube_context['client']['clientName'] = 'ANDROID'
- assert pot_request.innertube_context['client']['clientName'] != 'ANDROID'
- assert copied_request.innertube_host == pot_request.innertube_host
- assert copied_request.session_index == pot_request.session_index
- assert copied_request.player_url == pot_request.player_url
- assert copied_request.is_authenticated == pot_request.is_authenticated
- assert copied_request.visitor_data == pot_request.visitor_data
- assert copied_request.data_sync_id == pot_request.data_sync_id
- assert copied_request.video_id == pot_request.video_id
- assert copied_request.request_cookiejar is pot_request.request_cookiejar
- assert copied_request.request_proxy == pot_request.request_proxy
- assert copied_request.request_headers == pot_request.request_headers
- assert copied_request.request_headers is not pot_request.request_headers
- assert copied_request.request_timeout == pot_request.request_timeout
- assert copied_request.request_source_address == pot_request.request_source_address
- assert copied_request.request_verify_tls == pot_request.request_verify_tls
- assert copied_request.bypass_cache == pot_request.bypass_cache
-
-
-def test_provider_bug_report_message(ie, logger):
- provider = ExamplePTP(ie=ie, logger=logger, settings={})
- assert provider.BUG_REPORT_MESSAGE == 'please report this issue to the provider developer at https://example.com/issues .'
-
- message = provider_bug_report_message(provider)
- assert message == '; please report this issue to the provider developer at https://example.com/issues .'
-
- message_before = provider_bug_report_message(provider, before='custom message!')
- assert message_before == 'custom message! Please report this issue to the provider developer at https://example.com/issues .'
-
-
-def test_register_provider(ie):
-
- @register_provider
- class UnavailableProviderPTP(PoTokenProvider):
- def is_available(self) -> bool:
- return False
-
- def _real_request_pot(self, request: PoTokenRequest) -> PoTokenResponse:
- raise PoTokenProviderRejectedRequest('Not implemented')
-
- assert _pot_providers.value.get('UnavailableProvider') == UnavailableProviderPTP
- _pot_providers.value.pop('UnavailableProvider')
-
-
-def test_register_pot_preference(ie):
- before = len(_ptp_preferences.value)
-
- @register_preference(ExamplePTP)
- def unavailable_preference(provider: PoTokenProvider, request: PoTokenRequest):
- return 1
-
- assert len(_ptp_preferences.value) == before + 1
-
-
-def test_register_cache_provider(ie):
-
- @cache.register_provider
- class UnavailableCacheProviderPCP(PoTokenCacheProvider):
- def is_available(self) -> bool:
- return False
-
- def get(self, key: str):
- return 'example-cache'
-
- def store(self, key: str, value: str, expires_at: int):
- pass
-
- def delete(self, key: str):
- pass
-
- assert _pot_cache_providers.value.get('UnavailableCacheProvider') == UnavailableCacheProviderPCP
- _pot_cache_providers.value.pop('UnavailableCacheProvider')
-
-
-def test_register_cache_provider_spec(ie):
-
- @cache.register_spec
- class UnavailableCacheProviderPCSP(PoTokenCacheSpecProvider):
- def is_available(self) -> bool:
- return False
-
- def generate_cache_spec(self, request: PoTokenRequest):
- return None
-
- assert _pot_pcs_providers.value.get('UnavailableCacheProvider') == UnavailableCacheProviderPCSP
- _pot_pcs_providers.value.pop('UnavailableCacheProvider')
-
-
-def test_register_cache_provider_preference(ie):
- before = len(_pot_cache_provider_preferences.value)
-
- @cache.register_preference(ExampleCacheProviderPCP)
- def unavailable_preference(provider: PoTokenCacheProvider, request: PoTokenRequest):
- return 1
-
- assert len(_pot_cache_provider_preferences.value) == before + 1
-
-
-def test_logger_log_level(logger):
- assert logger.LogLevel('INFO') == logger.LogLevel.INFO
- assert logger.LogLevel('debuG') == logger.LogLevel.DEBUG
- assert logger.LogLevel(10) == logger.LogLevel.DEBUG
- assert logger.LogLevel('UNKNOWN') == logger.LogLevel.INFO
-
-
-def test_configuration_arg():
- config = {'abc': ['123D'], 'xyz': ['456a', '789B']}
-
- assert configuration_arg(config, 'abc') == ['123d']
- assert configuration_arg(config, 'abc', default=['default']) == ['123d']
- assert configuration_arg(config, 'ABC', default=['default']) == ['default']
- assert configuration_arg(config, 'abc', casesense=True) == ['123D']
- assert configuration_arg(config, 'xyz', casesense=False) == ['456a', '789b']
diff --git a/test/test_socks.py b/test/test_socks.py
deleted file mode 100644
index 4ec4733bd..000000000
--- a/test/test_socks.py
+++ /dev/null
@@ -1,476 +0,0 @@
-#!/usr/bin/env python3
-# Allow direct execution
-import os
-import sys
-import threading
-import unittest
-
-import pytest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-import abc
-import contextlib
-import enum
-import functools
-import http.server
-import json
-import random
-import socket
-import struct
-import time
-from socketserver import (
- BaseRequestHandler,
- StreamRequestHandler,
- ThreadingTCPServer,
-)
-
-from test.helper import http_server_port, verify_address_availability
-from yt_dlp.networking import Request
-from yt_dlp.networking.exceptions import ProxyError, TransportError
-from yt_dlp.socks import (
- SOCKS4_REPLY_VERSION,
- SOCKS4_VERSION,
- SOCKS5_USER_AUTH_SUCCESS,
- SOCKS5_USER_AUTH_VERSION,
- SOCKS5_VERSION,
- Socks5AddressType,
- Socks5Auth,
-)
-
-SOCKS5_USER_AUTH_FAILURE = 0x1
-
-
-class Socks4CD(enum.IntEnum):
- REQUEST_GRANTED = 90
- REQUEST_REJECTED_OR_FAILED = 91
- REQUEST_REJECTED_CANNOT_CONNECT_TO_IDENTD = 92
- REQUEST_REJECTED_DIFFERENT_USERID = 93
-
-
-class Socks5Reply(enum.IntEnum):
- SUCCEEDED = 0x0
- GENERAL_FAILURE = 0x1
- CONNECTION_NOT_ALLOWED = 0x2
- NETWORK_UNREACHABLE = 0x3
- HOST_UNREACHABLE = 0x4
- CONNECTION_REFUSED = 0x5
- TTL_EXPIRED = 0x6
- COMMAND_NOT_SUPPORTED = 0x7
- ADDRESS_TYPE_NOT_SUPPORTED = 0x8
-
-
-class SocksTestRequestHandler(BaseRequestHandler):
-
- def __init__(self, *args, socks_info=None, **kwargs):
- self.socks_info = socks_info
- super().__init__(*args, **kwargs)
-
-
-class SocksProxyHandler(BaseRequestHandler):
- def __init__(self, request_handler_class, socks_server_kwargs, *args, **kwargs):
- self.socks_kwargs = socks_server_kwargs or {}
- self.request_handler_class = request_handler_class
- super().__init__(*args, **kwargs)
-
-
-class Socks5ProxyHandler(StreamRequestHandler, SocksProxyHandler):
-
- # SOCKS5 protocol https://tools.ietf.org/html/rfc1928
- # SOCKS5 username/password authentication https://tools.ietf.org/html/rfc1929
-
- def handle(self):
- sleep = self.socks_kwargs.get('sleep')
- if sleep:
- time.sleep(sleep)
- version, nmethods = self.connection.recv(2)
- assert version == SOCKS5_VERSION
- methods = list(self.connection.recv(nmethods))
-
- auth = self.socks_kwargs.get('auth')
-
- if auth is not None and Socks5Auth.AUTH_USER_PASS not in methods:
- self.connection.sendall(struct.pack('!BB', SOCKS5_VERSION, Socks5Auth.AUTH_NO_ACCEPTABLE))
- self.server.close_request(self.request)
- return
-
- elif Socks5Auth.AUTH_USER_PASS in methods:
- self.connection.sendall(struct.pack('!BB', SOCKS5_VERSION, Socks5Auth.AUTH_USER_PASS))
-
- _, user_len = struct.unpack('!BB', self.connection.recv(2))
- username = self.connection.recv(user_len).decode()
- pass_len = ord(self.connection.recv(1))
- password = self.connection.recv(pass_len).decode()
-
- if username == auth[0] and password == auth[1]:
- self.connection.sendall(struct.pack('!BB', SOCKS5_USER_AUTH_VERSION, SOCKS5_USER_AUTH_SUCCESS))
- else:
- self.connection.sendall(struct.pack('!BB', SOCKS5_USER_AUTH_VERSION, SOCKS5_USER_AUTH_FAILURE))
- self.server.close_request(self.request)
- return
-
- elif Socks5Auth.AUTH_NONE in methods:
- self.connection.sendall(struct.pack('!BB', SOCKS5_VERSION, Socks5Auth.AUTH_NONE))
- else:
- self.connection.sendall(struct.pack('!BB', SOCKS5_VERSION, Socks5Auth.AUTH_NO_ACCEPTABLE))
- self.server.close_request(self.request)
- return
-
- version, command, _, address_type = struct.unpack('!BBBB', self.connection.recv(4))
- socks_info = {
- 'version': version,
- 'auth_methods': methods,
- 'command': command,
- 'client_address': self.client_address,
- 'ipv4_address': None,
- 'domain_address': None,
- 'ipv6_address': None,
- }
- if address_type == Socks5AddressType.ATYP_IPV4:
- socks_info['ipv4_address'] = socket.inet_ntoa(self.connection.recv(4))
- elif address_type == Socks5AddressType.ATYP_DOMAINNAME:
- socks_info['domain_address'] = self.connection.recv(ord(self.connection.recv(1))).decode()
- elif address_type == Socks5AddressType.ATYP_IPV6:
- socks_info['ipv6_address'] = socket.inet_ntop(socket.AF_INET6, self.connection.recv(16))
- else:
- self.server.close_request(self.request)
-
- socks_info['port'] = struct.unpack('!H', self.connection.recv(2))[0]
-
- # dummy response, the returned IP is just a placeholder
- self.connection.sendall(struct.pack(
- '!BBBBIH', SOCKS5_VERSION, self.socks_kwargs.get('reply', Socks5Reply.SUCCEEDED), 0x0, 0x1, 0x7f000001, 40000))
-
- self.request_handler_class(self.request, self.client_address, self.server, socks_info=socks_info)
-
-
-class Socks4ProxyHandler(StreamRequestHandler, SocksProxyHandler):
-
- # SOCKS4 protocol http://www.openssh.com/txt/socks4.protocol
- # SOCKS4A protocol http://www.openssh.com/txt/socks4a.protocol
-
- def _read_until_null(self):
- return b''.join(iter(functools.partial(self.connection.recv, 1), b'\x00'))
-
- def handle(self):
- sleep = self.socks_kwargs.get('sleep')
- if sleep:
- time.sleep(sleep)
- socks_info = {
- 'version': SOCKS4_VERSION,
- 'command': None,
- 'client_address': self.client_address,
- 'ipv4_address': None,
- 'port': None,
- 'domain_address': None,
- }
- version, command, dest_port, dest_ip = struct.unpack('!BBHI', self.connection.recv(8))
- socks_info['port'] = dest_port
- socks_info['command'] = command
- if version != SOCKS4_VERSION:
- self.server.close_request(self.request)
- return
- use_remote_dns = False
- if 0x0 < dest_ip <= 0xFF:
- use_remote_dns = True
- else:
- socks_info['ipv4_address'] = socket.inet_ntoa(struct.pack('!I', dest_ip))
-
- user_id = self._read_until_null().decode()
- if user_id != (self.socks_kwargs.get('user_id') or ''):
- self.connection.sendall(struct.pack(
- '!BBHI', SOCKS4_REPLY_VERSION, Socks4CD.REQUEST_REJECTED_DIFFERENT_USERID, 0x00, 0x00000000))
- self.server.close_request(self.request)
- return
-
- if use_remote_dns:
- socks_info['domain_address'] = self._read_until_null().decode()
-
- # dummy response, the returned IP is just a placeholder
- self.connection.sendall(
- struct.pack(
- '!BBHI', SOCKS4_REPLY_VERSION,
- self.socks_kwargs.get('cd_reply', Socks4CD.REQUEST_GRANTED), 40000, 0x7f000001))
-
- self.request_handler_class(self.request, self.client_address, self.server, socks_info=socks_info)
-
-
-class IPv6ThreadingTCPServer(ThreadingTCPServer):
- address_family = socket.AF_INET6
-
-
-class SocksHTTPTestRequestHandler(http.server.BaseHTTPRequestHandler, SocksTestRequestHandler):
- def do_GET(self):
- if self.path == '/socks_info':
- payload = json.dumps(self.socks_info.copy())
- self.send_response(200)
- self.send_header('Content-Type', 'application/json; charset=utf-8')
- self.send_header('Content-Length', str(len(payload)))
- self.end_headers()
- self.wfile.write(payload.encode())
-
-
-class SocksWebSocketTestRequestHandler(SocksTestRequestHandler):
- def handle(self):
- import websockets.sync.server
- protocol = websockets.ServerProtocol()
- connection = websockets.sync.server.ServerConnection(socket=self.request, protocol=protocol, close_timeout=0)
- connection.handshake()
- for message in connection:
- if message == 'socks_info':
- connection.send(json.dumps(self.socks_info))
- connection.close()
-
-
-@contextlib.contextmanager
-def socks_server(socks_server_class, request_handler, bind_ip=None, **socks_server_kwargs):
- server = server_thread = None
- try:
- bind_address = bind_ip or '127.0.0.1'
- server_type = ThreadingTCPServer if '.' in bind_address else IPv6ThreadingTCPServer
- server = server_type(
- (bind_address, 0), functools.partial(socks_server_class, request_handler, socks_server_kwargs))
- server_port = http_server_port(server)
- server_thread = threading.Thread(target=server.serve_forever)
- server_thread.daemon = True
- server_thread.start()
- if '.' not in bind_address:
- yield f'[{bind_address}]:{server_port}'
- else:
- yield f'{bind_address}:{server_port}'
- finally:
- server.shutdown()
- server.server_close()
- server_thread.join(2.0)
-
-
-class SocksProxyTestContext(abc.ABC):
- REQUEST_HANDLER_CLASS = None
-
- def socks_server(self, server_class, *args, **kwargs):
- return socks_server(server_class, self.REQUEST_HANDLER_CLASS, *args, **kwargs)
-
- @abc.abstractmethod
- def socks_info_request(self, handler, target_domain=None, target_port=None, **req_kwargs) -> dict:
- """return a dict of socks_info"""
-
-
-class HTTPSocksTestProxyContext(SocksProxyTestContext):
- REQUEST_HANDLER_CLASS = SocksHTTPTestRequestHandler
-
- def socks_info_request(self, handler, target_domain=None, target_port=None, **req_kwargs):
- request = Request(f'http://{target_domain or "127.0.0.1"}:{target_port or "40000"}/socks_info', **req_kwargs)
- handler.validate(request)
- return json.loads(handler.send(request).read().decode())
-
-
-class WebSocketSocksTestProxyContext(SocksProxyTestContext):
- REQUEST_HANDLER_CLASS = SocksWebSocketTestRequestHandler
-
- def socks_info_request(self, handler, target_domain=None, target_port=None, **req_kwargs):
- request = Request(f'ws://{target_domain or "127.0.0.1"}:{target_port or "40000"}', **req_kwargs)
- handler.validate(request)
- ws = handler.send(request)
- ws.send('socks_info')
- socks_info = ws.recv()
- ws.close()
- return json.loads(socks_info)
-
-
-CTX_MAP = {
- 'http': HTTPSocksTestProxyContext,
- 'ws': WebSocketSocksTestProxyContext,
-}
-
-
-@pytest.fixture(scope='module')
-def ctx(request):
- return CTX_MAP[request.param]()
-
-
-@pytest.mark.parametrize(
- 'handler,ctx', [
- ('Urllib', 'http'),
- ('Requests', 'http'),
- ('Websockets', 'ws'),
- ('CurlCFFI', 'http'),
- ], indirect=True)
-@pytest.mark.handler_flaky('CurlCFFI', reason='segfaults')
-class TestSocks4Proxy:
- def test_socks4_no_auth(self, handler, ctx):
- with handler() as rh:
- with ctx.socks_server(Socks4ProxyHandler) as server_address:
- response = ctx.socks_info_request(
- rh, proxies={'all': f'socks4://{server_address}'})
- assert response['version'] == 4
-
- def test_socks4_auth(self, handler, ctx):
- with handler() as rh:
- with ctx.socks_server(Socks4ProxyHandler, user_id='user') as server_address:
- with pytest.raises(ProxyError):
- ctx.socks_info_request(rh, proxies={'all': f'socks4://{server_address}'})
- response = ctx.socks_info_request(
- rh, proxies={'all': f'socks4://user:@{server_address}'})
- assert response['version'] == 4
-
- def test_socks4a_ipv4_target(self, handler, ctx):
- with ctx.socks_server(Socks4ProxyHandler) as server_address:
- with handler(proxies={'all': f'socks4a://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='127.0.0.1')
- assert response['version'] == 4
- assert (response['ipv4_address'] == '127.0.0.1') != (response['domain_address'] == '127.0.0.1')
-
- def test_socks4a_domain_target(self, handler, ctx):
- with ctx.socks_server(Socks4ProxyHandler) as server_address:
- with handler(proxies={'all': f'socks4a://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='localhost')
- assert response['version'] == 4
- assert response['ipv4_address'] is None
- assert response['domain_address'] == 'localhost'
-
- def test_ipv4_client_source_address(self, handler, ctx):
- with ctx.socks_server(Socks4ProxyHandler) as server_address:
- source_address = f'127.0.0.{random.randint(5, 255)}'
- verify_address_availability(source_address)
- with handler(proxies={'all': f'socks4://{server_address}'},
- source_address=source_address) as rh:
- response = ctx.socks_info_request(rh)
- assert response['client_address'][0] == source_address
- assert response['version'] == 4
-
- @pytest.mark.parametrize('reply_code', [
- Socks4CD.REQUEST_REJECTED_OR_FAILED,
- Socks4CD.REQUEST_REJECTED_CANNOT_CONNECT_TO_IDENTD,
- Socks4CD.REQUEST_REJECTED_DIFFERENT_USERID,
- ])
- def test_socks4_errors(self, handler, ctx, reply_code):
- with ctx.socks_server(Socks4ProxyHandler, cd_reply=reply_code) as server_address:
- with handler(proxies={'all': f'socks4://{server_address}'}) as rh:
- with pytest.raises(ProxyError):
- ctx.socks_info_request(rh)
-
- def test_ipv6_socks4_proxy(self, handler, ctx):
- with ctx.socks_server(Socks4ProxyHandler, bind_ip='::1') as server_address:
- with handler(proxies={'all': f'socks4://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='127.0.0.1')
- assert response['client_address'][0] == '::1'
- assert response['ipv4_address'] == '127.0.0.1'
- assert response['version'] == 4
-
- def test_timeout(self, handler, ctx):
- with ctx.socks_server(Socks4ProxyHandler, sleep=2) as server_address:
- with handler(proxies={'all': f'socks4://{server_address}'}, timeout=0.5) as rh:
- with pytest.raises(TransportError):
- ctx.socks_info_request(rh)
-
-
-@pytest.mark.parametrize(
- 'handler,ctx', [
- ('Urllib', 'http'),
- ('Requests', 'http'),
- ('Websockets', 'ws'),
- ('CurlCFFI', 'http'),
- ], indirect=True)
-@pytest.mark.handler_flaky('CurlCFFI', reason='segfaults')
-class TestSocks5Proxy:
-
- def test_socks5_no_auth(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler) as server_address:
- with handler(proxies={'all': f'socks5://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh)
- assert response['auth_methods'] == [0x0]
- assert response['version'] == 5
-
- def test_socks5_user_pass(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler, auth=('test', 'testpass')) as server_address:
- with handler() as rh:
- with pytest.raises(ProxyError):
- ctx.socks_info_request(rh, proxies={'all': f'socks5://{server_address}'})
-
- response = ctx.socks_info_request(
- rh, proxies={'all': f'socks5://test:testpass@{server_address}'})
-
- assert response['auth_methods'] == [Socks5Auth.AUTH_NONE, Socks5Auth.AUTH_USER_PASS]
- assert response['version'] == 5
-
- def test_socks5_ipv4_target(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler) as server_address:
- with handler(proxies={'all': f'socks5://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='127.0.0.1')
- assert response['ipv4_address'] == '127.0.0.1'
- assert response['version'] == 5
-
- def test_socks5_domain_target(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler) as server_address:
- with handler(proxies={'all': f'socks5://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='localhost')
- assert (response['ipv4_address'] == '127.0.0.1') != (response['ipv6_address'] == '::1')
- assert response['version'] == 5
-
- def test_socks5h_domain_target(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler) as server_address:
- with handler(proxies={'all': f'socks5h://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='localhost')
- assert response['ipv4_address'] is None
- assert response['domain_address'] == 'localhost'
- assert response['version'] == 5
-
- def test_socks5h_ip_target(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler) as server_address:
- with handler(proxies={'all': f'socks5h://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='127.0.0.1')
- assert response['ipv4_address'] == '127.0.0.1'
- assert response['domain_address'] is None
- assert response['version'] == 5
-
- def test_socks5_ipv6_destination(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler) as server_address:
- with handler(proxies={'all': f'socks5://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='[::1]')
- assert response['ipv6_address'] == '::1'
- assert response['version'] == 5
-
- def test_ipv6_socks5_proxy(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler, bind_ip='::1') as server_address:
- with handler(proxies={'all': f'socks5://{server_address}'}) as rh:
- response = ctx.socks_info_request(rh, target_domain='127.0.0.1')
- assert response['client_address'][0] == '::1'
- assert response['ipv4_address'] == '127.0.0.1'
- assert response['version'] == 5
-
- # XXX: is there any feasible way of testing IPv6 source addresses?
- # Same would go for non-proxy source_address test...
- def test_ipv4_client_source_address(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler) as server_address:
- source_address = f'127.0.0.{random.randint(5, 255)}'
- verify_address_availability(source_address)
- with handler(proxies={'all': f'socks5://{server_address}'}, source_address=source_address) as rh:
- response = ctx.socks_info_request(rh)
- assert response['client_address'][0] == source_address
- assert response['version'] == 5
-
- @pytest.mark.parametrize('reply_code', [
- Socks5Reply.GENERAL_FAILURE,
- Socks5Reply.CONNECTION_NOT_ALLOWED,
- Socks5Reply.NETWORK_UNREACHABLE,
- Socks5Reply.HOST_UNREACHABLE,
- Socks5Reply.CONNECTION_REFUSED,
- Socks5Reply.TTL_EXPIRED,
- Socks5Reply.COMMAND_NOT_SUPPORTED,
- Socks5Reply.ADDRESS_TYPE_NOT_SUPPORTED,
- ])
- def test_socks5_errors(self, handler, ctx, reply_code):
- with ctx.socks_server(Socks5ProxyHandler, reply=reply_code) as server_address:
- with handler(proxies={'all': f'socks5://{server_address}'}) as rh:
- with pytest.raises(ProxyError):
- ctx.socks_info_request(rh)
-
- def test_timeout(self, handler, ctx):
- with ctx.socks_server(Socks5ProxyHandler, sleep=2) as server_address:
- with handler(proxies={'all': f'socks5://{server_address}'}, timeout=1) as rh:
- with pytest.raises(TransportError):
- ctx.socks_info_request(rh)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_subtitles.py b/test/test_subtitles.py
deleted file mode 100644
index 53e0b4eaf..000000000
--- a/test/test_subtitles.py
+++ /dev/null
@@ -1,418 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-from test.helper import FakeYDL, is_download_test, md5
-from yt_dlp.extractor import (
- NPOIE,
- NRKTVIE,
- PBSIE,
- CeskaTelevizeIE,
- DailymotionIE,
- DemocracynowIE,
- LyndaIE,
- RaiPlayIE,
- RTVEALaCartaIE,
- TedTalkIE,
- ThePlatformFeedIE,
- ThePlatformIE,
- VimeoIE,
- WallaIE,
- YoutubeIE,
-)
-
-
-@is_download_test
-class BaseTestSubtitles(unittest.TestCase):
- url = None
- IE = None
-
- def setUp(self):
- self.DL = FakeYDL()
- self.ie = self.IE()
- self.DL.add_info_extractor(self.ie)
- if not self.IE.working():
- print(f'Skipping: {self.IE.ie_key()} marked as not _WORKING')
- self.skipTest('IE marked as not _WORKING')
-
- def getInfoDict(self):
- return self.DL.extract_info(self.url, download=False)
-
- def getSubtitles(self):
- info_dict = self.getInfoDict()
- subtitles = info_dict['requested_subtitles']
- if not subtitles:
- return subtitles
- for sub_info in subtitles.values():
- if sub_info.get('data') is None:
- uf = self.DL.urlopen(sub_info['url'])
- sub_info['data'] = uf.read().decode()
- return {l: sub_info['data'] for l, sub_info in subtitles.items()}
-
-
-@is_download_test
-class TestYoutubeSubtitles(BaseTestSubtitles):
- # Available subtitles for QRS8MkLhQmM:
- # Language formats
- # ru vtt, ttml, srv3, srv2, srv1, json3
- # fr vtt, ttml, srv3, srv2, srv1, json3
- # en vtt, ttml, srv3, srv2, srv1, json3
- # nl vtt, ttml, srv3, srv2, srv1, json3
- # de vtt, ttml, srv3, srv2, srv1, json3
- # ko vtt, ttml, srv3, srv2, srv1, json3
- # it vtt, ttml, srv3, srv2, srv1, json3
- # zh-Hant vtt, ttml, srv3, srv2, srv1, json3
- # hi vtt, ttml, srv3, srv2, srv1, json3
- # pt-BR vtt, ttml, srv3, srv2, srv1, json3
- # es-MX vtt, ttml, srv3, srv2, srv1, json3
- # ja vtt, ttml, srv3, srv2, srv1, json3
- # pl vtt, ttml, srv3, srv2, srv1, json3
- url = 'QRS8MkLhQmM'
- IE = YoutubeIE
-
- def test_youtube_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(len(subtitles.keys()), 13)
- self.assertEqual(md5(subtitles['en']), 'ae1bd34126571a77aabd4d276b28044d')
- self.assertEqual(md5(subtitles['it']), '0e0b667ba68411d88fd1c5f4f4eab2f9')
- for lang in ['fr', 'de']:
- self.assertTrue(subtitles.get(lang) is not None, f'Subtitles for \'{lang}\' not extracted')
-
- def _test_subtitles_format(self, fmt, md5_hash, lang='en'):
- self.DL.params['writesubtitles'] = True
- self.DL.params['subtitlesformat'] = fmt
- subtitles = self.getSubtitles()
- self.assertEqual(md5(subtitles[lang]), md5_hash)
-
- def test_youtube_subtitles_ttml_format(self):
- self._test_subtitles_format('ttml', 'c97ddf1217390906fa9fbd34901f3da2')
-
- def test_youtube_subtitles_vtt_format(self):
- self._test_subtitles_format('vtt', 'ae1bd34126571a77aabd4d276b28044d')
-
- def test_youtube_subtitles_json3_format(self):
- self._test_subtitles_format('json3', '688dd1ce0981683867e7fe6fde2a224b')
-
- def _test_automatic_captions(self, url, lang):
- self.url = url
- self.DL.params['writeautomaticsub'] = True
- self.DL.params['subtitleslangs'] = [lang]
- subtitles = self.getSubtitles()
- self.assertTrue(subtitles[lang] is not None)
-
- def test_youtube_automatic_captions(self):
- # Available automatic captions for 8YoUxe5ncPo:
- # Language formats (all in vtt, ttml, srv3, srv2, srv1, json3)
- # gu, zh-Hans, zh-Hant, gd, ga, gl, lb, la, lo, tt, tr,
- # lv, lt, tk, th, tg, te, fil, haw, yi, ceb, yo, de, da,
- # el, eo, en, eu, et, es, ru, rw, ro, bn, be, bg, uk, jv,
- # bs, ja, or, xh, co, ca, cy, cs, ps, pt, pa, vi, pl, hy,
- # hr, ht, hu, hmn, hi, ha, mg, uz, ml, mn, mi, mk, ur,
- # mt, ms, mr, ug, ta, my, af, sw, is, am,
- # *it*, iw, sv, ar,
- # su, zu, az, id, ig, nl, no, ne, ny, fr, ku, fy, fa, fi,
- # ka, kk, sr, sq, ko, kn, km, st, sk, si, so, sn, sm, sl,
- # ky, sd
- # ...
- self._test_automatic_captions('8YoUxe5ncPo', 'it')
-
- @unittest.skip('Video unavailable')
- def test_youtube_translated_subtitles(self):
- # This video has a subtitles track, which can be translated (#4555)
- self._test_automatic_captions('Ky9eprVWzlI', 'it')
-
- def test_youtube_nosubtitles(self):
- self.DL.expect_warning('video doesn\'t have subtitles')
- # Available automatic captions for 8YoUxe5ncPo:
- # ...
- # 8YoUxe5ncPo has no subtitles
- self.url = '8YoUxe5ncPo'
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertFalse(subtitles)
-
-
-@is_download_test
-class TestDailymotionSubtitles(BaseTestSubtitles):
- url = 'http://www.dailymotion.com/video/xczg00'
- IE = DailymotionIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertTrue(len(subtitles.keys()) >= 6)
- self.assertEqual(md5(subtitles['en']), '976553874490cba125086bbfea3ff76f')
- self.assertEqual(md5(subtitles['fr']), '594564ec7d588942e384e920e5341792')
- for lang in ['es', 'fr', 'de']:
- self.assertTrue(subtitles.get(lang) is not None, f'Subtitles for \'{lang}\' not extracted')
-
- def test_nosubtitles(self):
- self.DL.expect_warning('video doesn\'t have subtitles')
- self.url = 'http://www.dailymotion.com/video/x12u166_le-zapping-tele-star-du-08-aout-2013_tv'
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertFalse(subtitles)
-
-
-@is_download_test
-@unittest.skip('IE broken')
-class TestTedSubtitles(BaseTestSubtitles):
- url = 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html'
- IE = TedTalkIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertTrue(len(subtitles.keys()) >= 28)
- self.assertEqual(md5(subtitles['en']), '4262c1665ff928a2dada178f62cb8d14')
- self.assertEqual(md5(subtitles['fr']), '66a63f7f42c97a50f8c0e90bc7797bb5')
- for lang in ['es', 'fr', 'de']:
- self.assertTrue(subtitles.get(lang) is not None, f'Subtitles for \'{lang}\' not extracted')
-
-
-@is_download_test
-class TestVimeoSubtitles(BaseTestSubtitles):
- url = 'http://vimeo.com/76979871'
- IE = VimeoIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'de', 'en', 'es', 'fr'})
- self.assertEqual(md5(subtitles['en']), '386cbc9320b94e25cb364b97935e5dd1')
- self.assertEqual(md5(subtitles['fr']), 'c9b69eef35bc6641c0d4da8a04f9dfac')
-
- def test_nosubtitles(self):
- self.DL.expect_warning('video doesn\'t have subtitles')
- self.url = 'http://vimeo.com/68093876'
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertFalse(subtitles)
-
-
-@is_download_test
-@unittest.skip('IE broken')
-class TestWallaSubtitles(BaseTestSubtitles):
- url = 'http://vod.walla.co.il/movie/2705958/the-yes-men'
- IE = WallaIE
-
- def test_allsubtitles(self):
- self.DL.expect_warning('Automatic Captions not supported by this server')
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'heb'})
- self.assertEqual(md5(subtitles['heb']), 'e758c5d7cb982f6bef14f377ec7a3920')
-
- def test_nosubtitles(self):
- self.DL.expect_warning('video doesn\'t have subtitles')
- self.url = 'http://vod.walla.co.il/movie/2642630/one-direction-all-for-one'
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertFalse(subtitles)
-
-
-@is_download_test
-@unittest.skip('IE broken')
-class TestCeskaTelevizeSubtitles(BaseTestSubtitles):
- url = 'http://www.ceskatelevize.cz/ivysilani/10600540290-u6-uzasny-svet-techniky'
- IE = CeskaTelevizeIE
-
- def test_allsubtitles(self):
- self.DL.expect_warning('Automatic Captions not supported by this server')
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'cs'})
- self.assertTrue(len(subtitles['cs']) > 20000)
-
- def test_nosubtitles(self):
- self.DL.expect_warning('video doesn\'t have subtitles')
- self.url = 'http://www.ceskatelevize.cz/ivysilani/ivysilani/10441294653-hyde-park-civilizace/214411058091220'
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertFalse(subtitles)
-
-
-@is_download_test
-@unittest.skip('IE broken')
-class TestLyndaSubtitles(BaseTestSubtitles):
- url = 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html'
- IE = LyndaIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'en'})
- self.assertEqual(md5(subtitles['en']), '09bbe67222259bed60deaa26997d73a7')
-
-
-@is_download_test
-@unittest.skip('IE broken')
-class TestNPOSubtitles(BaseTestSubtitles):
- url = 'http://www.npo.nl/nos-journaal/28-08-2014/POW_00722860'
- IE = NPOIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'nl'})
- self.assertEqual(md5(subtitles['nl']), 'fc6435027572b63fb4ab143abd5ad3f4')
-
-
-@is_download_test
-class TestNRKSubtitles(BaseTestSubtitles):
- url = 'http://tv.nrk.no/serie/ikke-gjoer-dette-hjemme/DMPV73000411/sesong-2/episode-1'
- IE = NRKTVIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'nb-ttv'})
- self.assertEqual(md5(subtitles['nb-ttv']), '67e06ff02d0deaf975e68f6cb8f6a149')
-
-
-@is_download_test
-class TestRaiPlaySubtitles(BaseTestSubtitles):
- IE = RaiPlayIE
-
- def test_subtitles_key(self):
- self.url = 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html'
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'it'})
- self.assertEqual(md5(subtitles['it']), 'b1d90a98755126b61e667567a1f6680a')
-
- def test_subtitles_array_key(self):
- self.url = 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html'
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'it'})
- self.assertEqual(md5(subtitles['it']), '4b3264186fbb103508abe5311cfcb9cd')
-
-
-@is_download_test
-class TestThePlatformSubtitles(BaseTestSubtitles):
- # from http://www.3playmedia.com/services-features/tools/integrations/theplatform/
- # (see http://theplatform.com/about/partners/type/subtitles-closed-captioning/)
- url = 'theplatform:JFUjUE1_ehvq'
- IE = ThePlatformIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'en'})
- self.assertEqual(md5(subtitles['en']), '97e7670cbae3c4d26ae8bcc7fdd78d4b')
-
-
-@is_download_test
-@unittest.skip('IE broken')
-class TestThePlatformFeedSubtitles(BaseTestSubtitles):
- url = 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207'
- IE = ThePlatformFeedIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'en'})
- self.assertEqual(md5(subtitles['en']), '48649a22e82b2da21c9a67a395eedade')
-
-
-@is_download_test
-class TestRtveSubtitles(BaseTestSubtitles):
- url = 'http://www.rtve.es/alacarta/videos/los-misterios-de-laura/misterios-laura-capitulo-32-misterio-del-numero-17-2-parte/2428621/'
- IE = RTVEALaCartaIE
-
- def test_allsubtitles(self):
- print('Skipping, only available from Spain')
- return
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'es'})
- self.assertEqual(md5(subtitles['es']), '69e70cae2d40574fb7316f31d6eb7fca')
-
-
-@is_download_test
-class TestDemocracynowSubtitles(BaseTestSubtitles):
- url = 'http://www.democracynow.org/shows/2015/7/3'
- IE = DemocracynowIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'en'})
- self.assertEqual(md5(subtitles['en']), 'a3cc4c0b5eadd74d9974f1c1f5101045')
-
- def test_subtitles_in_page(self):
- self.url = 'http://www.democracynow.org/2015/7/3/this_flag_comes_down_today_bree'
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'en'})
- self.assertEqual(md5(subtitles['en']), 'a3cc4c0b5eadd74d9974f1c1f5101045')
-
-
-@is_download_test
-class TestPBSSubtitles(BaseTestSubtitles):
- url = 'https://www.pbs.org/video/how-fantasy-reflects-our-world-picecq/'
- IE = PBSIE
-
- def test_allsubtitles(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['allsubtitles'] = True
- subtitles = self.getSubtitles()
- self.assertEqual(set(subtitles.keys()), {'en'})
-
- def test_subtitles_dfxp_format(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['subtitlesformat'] = 'dfxp'
- subtitles = self.getSubtitles()
- self.assertIn(md5(subtitles['en']), ['643b034254cdc3768ff1e750b6b5873b'])
-
- def test_subtitles_vtt_format(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['subtitlesformat'] = 'vtt'
- subtitles = self.getSubtitles()
- self.assertIn(
- md5(subtitles['en']), ['937a05711555b165d4c55a9667017045', 'f49ea998d6824d94959c8152a368ff73'])
-
- def test_subtitles_srt_format(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['subtitlesformat'] = 'srt'
- subtitles = self.getSubtitles()
- self.assertIn(md5(subtitles['en']), ['2082c21b43759d9bf172931b2f2ca371'])
-
- def test_subtitles_sami_format(self):
- self.DL.params['writesubtitles'] = True
- self.DL.params['subtitlesformat'] = 'sami'
- subtitles = self.getSubtitles()
- self.assertIn(md5(subtitles['en']), ['4256b16ac7da6a6780fafd04294e85cd'])
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_traversal.py b/test/test_traversal.py
deleted file mode 100644
index 45985afa9..000000000
--- a/test/test_traversal.py
+++ /dev/null
@@ -1,638 +0,0 @@
-import http.cookies
-import re
-import xml.etree.ElementTree
-
-import pytest
-
-from yt_dlp.utils import (
- ExtractorError,
- determine_ext,
- dict_get,
- int_or_none,
- join_nonempty,
- str_or_none,
-)
-from yt_dlp.utils.traversal import (
- find_element,
- find_elements,
- require,
- subs_list_to_dict,
- traverse_obj,
- trim_str,
- unpack,
-)
-
-_TEST_DATA = {
- 100: 100,
- 1.2: 1.2,
- 'str': 'str',
- 'None': None,
- '...': ...,
- 'urls': [
- {'index': 0, 'url': 'https://www.example.com/0'},
- {'index': 1, 'url': 'https://www.example.com/1'},
- ],
- 'data': (
- {'index': 2},
- {'index': 3},
- ),
- 'dict': {},
-}
-
-_TEST_HTML = '''
- 1
- 2
- 3
- 4
- 5
-'''
-
-
-class TestTraversal:
- def test_traversal_base(self):
- assert traverse_obj(_TEST_DATA, ('str',)) == 'str', \
- 'allow tuple path'
- assert traverse_obj(_TEST_DATA, ['str']) == 'str', \
- 'allow list path'
- assert traverse_obj(_TEST_DATA, (value for value in ('str',))) == 'str', \
- 'allow iterable path'
- assert traverse_obj(_TEST_DATA, 'str') == 'str', \
- 'single items should be treated as a path'
- assert traverse_obj(_TEST_DATA, 100) == 100, \
- 'allow int path'
- assert traverse_obj(_TEST_DATA, 1.2) == 1.2, \
- 'allow float path'
- assert traverse_obj(_TEST_DATA, None) == _TEST_DATA, \
- '`None` should not perform any modification'
-
- def test_traversal_ellipsis(self):
- assert traverse_obj(_TEST_DATA, ...) == [x for x in _TEST_DATA.values() if x not in (None, {})], \
- '`...` should give all non discarded values'
- assert traverse_obj(_TEST_DATA, ('urls', 0, ...)) == list(_TEST_DATA['urls'][0].values()), \
- '`...` selection for dicts should select all values'
- assert traverse_obj(_TEST_DATA, (..., ..., 'url')) == ['https://www.example.com/0', 'https://www.example.com/1'], \
- 'nested `...` queries should work'
- assert traverse_obj(_TEST_DATA, (..., ..., 'index')) == list(range(4)), \
- '`...` query result should be flattened'
- assert traverse_obj(iter(range(4)), ...) == list(range(4)), \
- '`...` should accept iterables'
-
- def test_traversal_function(self):
- filter_func = lambda x, y: x == 'urls' and isinstance(y, list)
- assert traverse_obj(_TEST_DATA, filter_func) == [_TEST_DATA['urls']], \
- 'function as query key should perform a filter based on (key, value)'
- assert traverse_obj(_TEST_DATA, lambda _, x: isinstance(x[0], str)) == ['str'], \
- 'exceptions in the query function should be catched'
- assert traverse_obj(iter(range(4)), lambda _, x: x % 2 == 0) == [0, 2], \
- 'function key should accept iterables'
- # Wrong function signature should raise (debug mode)
- with pytest.raises(Exception):
- traverse_obj(_TEST_DATA, lambda a: ...)
- with pytest.raises(Exception):
- traverse_obj(_TEST_DATA, lambda a, b, c: ...)
-
- def test_traversal_set(self):
- # transformation/type, like `expected_type`
- assert traverse_obj(_TEST_DATA, (..., {str.upper})) == ['STR'], \
- 'Function in set should be a transformation'
- assert traverse_obj(_TEST_DATA, (..., {str})) == ['str'], \
- 'Type in set should be a type filter'
- assert traverse_obj(_TEST_DATA, (..., {str, int})) == [100, 'str'], \
- 'Multiple types in set should be a type filter'
- assert traverse_obj(_TEST_DATA, {dict}) == _TEST_DATA, \
- 'A single set should be wrapped into a path'
- assert traverse_obj(_TEST_DATA, (..., {str.upper})) == ['STR'], \
- 'Transformation function should not raise'
- expected = [x for x in map(str_or_none, _TEST_DATA.values()) if x is not None]
- assert traverse_obj(_TEST_DATA, (..., {str_or_none})) == expected, \
- 'Function in set should be a transformation'
- assert traverse_obj(_TEST_DATA, ('fail', {lambda _: 'const'})) == 'const', \
- 'Function in set should always be called'
- # Sets with length < 1 or > 1 not including only types should raise
- with pytest.raises(Exception):
- traverse_obj(_TEST_DATA, set())
- with pytest.raises(Exception):
- traverse_obj(_TEST_DATA, {str.upper, str})
-
- def test_traversal_slice(self):
- _SLICE_DATA = [0, 1, 2, 3, 4]
-
- assert traverse_obj(_TEST_DATA, ('dict', slice(1))) is None, \
- 'slice on a dictionary should not throw'
- assert traverse_obj(_SLICE_DATA, slice(1)) == _SLICE_DATA[:1], \
- 'slice key should apply slice to sequence'
- assert traverse_obj(_SLICE_DATA, slice(1, 2)) == _SLICE_DATA[1:2], \
- 'slice key should apply slice to sequence'
- assert traverse_obj(_SLICE_DATA, slice(1, 4, 2)) == _SLICE_DATA[1:4:2], \
- 'slice key should apply slice to sequence'
-
- def test_traversal_alternatives(self):
- assert traverse_obj(_TEST_DATA, 'fail', 'str') == 'str', \
- 'multiple `paths` should be treated as alternative paths'
- assert traverse_obj(_TEST_DATA, 'str', 100) == 'str', \
- 'alternatives should exit early'
- assert traverse_obj(_TEST_DATA, 'fail', 'fail') is None, \
- 'alternatives should return `default` if exhausted'
- assert traverse_obj(_TEST_DATA, (..., 'fail'), 100) == 100, \
- 'alternatives should track their own branching return'
- assert traverse_obj(_TEST_DATA, ('dict', ...), ('data', ...)) == list(_TEST_DATA['data']), \
- 'alternatives on empty objects should search further'
-
- def test_traversal_branching_nesting(self):
- assert traverse_obj(_TEST_DATA, ('urls', (3, 0), 'url')) == ['https://www.example.com/0'], \
- 'tuple as key should be treated as branches'
- assert traverse_obj(_TEST_DATA, ('urls', [3, 0], 'url')) == ['https://www.example.com/0'], \
- 'list as key should be treated as branches'
- assert traverse_obj(_TEST_DATA, ('urls', ((1, 'fail'), (0, 'url')))) == ['https://www.example.com/0'], \
- 'double nesting in path should be treated as paths'
- assert traverse_obj(['0', [1, 2]], [(0, 1), 0]) == [1], \
- 'do not fail early on branching'
- expected = ['https://www.example.com/0', 'https://www.example.com/1']
- assert traverse_obj(_TEST_DATA, ('urls', ((0, ('fail', 'url')), (1, 'url')))) == expected, \
- 'tripple nesting in path should be treated as branches'
- assert traverse_obj(_TEST_DATA, ('urls', ('fail', (..., 'url')))) == expected, \
- 'ellipsis as branch path start gets flattened'
-
- def test_traversal_dict(self):
- assert traverse_obj(_TEST_DATA, {0: 100, 1: 1.2}) == {0: 100, 1: 1.2}, \
- 'dict key should result in a dict with the same keys'
- expected = {0: 'https://www.example.com/0'}
- assert traverse_obj(_TEST_DATA, {0: ('urls', 0, 'url')}) == expected, \
- 'dict key should allow paths'
- expected = {0: ['https://www.example.com/0']}
- assert traverse_obj(_TEST_DATA, {0: ('urls', (3, 0), 'url')}) == expected, \
- 'tuple in dict path should be treated as branches'
- assert traverse_obj(_TEST_DATA, {0: ('urls', ((1, 'fail'), (0, 'url')))}) == expected, \
- 'double nesting in dict path should be treated as paths'
- expected = {0: ['https://www.example.com/1', 'https://www.example.com/0']}
- assert traverse_obj(_TEST_DATA, {0: ('urls', ((1, ('fail', 'url')), (0, 'url')))}) == expected, \
- 'tripple nesting in dict path should be treated as branches'
- assert traverse_obj(_TEST_DATA, {0: 'fail'}) == {}, \
- 'remove `None` values when top level dict key fails'
- assert traverse_obj(_TEST_DATA, {0: 'fail'}, default=...) == {0: ...}, \
- 'use `default` if key fails and `default`'
- assert traverse_obj(_TEST_DATA, {0: 'dict'}) == {}, \
- 'remove empty values when dict key'
- assert traverse_obj(_TEST_DATA, {0: 'dict'}, default=...) == {0: ...}, \
- 'use `default` when dict key and `default`'
- assert traverse_obj(_TEST_DATA, {0: {0: 'fail'}}) == {}, \
- 'remove empty values when nested dict key fails'
- assert traverse_obj(None, {0: 'fail'}) == {}, \
- 'default to dict if pruned'
- assert traverse_obj(None, {0: 'fail'}, default=...) == {0: ...}, \
- 'default to dict if pruned and default is given'
- assert traverse_obj(_TEST_DATA, {0: {0: 'fail'}}, default=...) == {0: {0: ...}}, \
- 'use nested `default` when nested dict key fails and `default`'
- assert traverse_obj(_TEST_DATA, {0: ('dict', ...)}) == {}, \
- 'remove key if branch in dict key not successful'
-
- def test_traversal_default(self):
- _DEFAULT_DATA = {'None': None, 'int': 0, 'list': []}
-
- assert traverse_obj(_DEFAULT_DATA, 'fail') is None, \
- 'default value should be `None`'
- assert traverse_obj(_DEFAULT_DATA, 'fail', 'fail', default=...) == ..., \
- 'chained fails should result in default'
- assert traverse_obj(_DEFAULT_DATA, 'None', 'int') == 0, \
- 'should not short cirquit on `None`'
- assert traverse_obj(_DEFAULT_DATA, 'fail', default=1) == 1, \
- 'invalid dict key should result in `default`'
- assert traverse_obj(_DEFAULT_DATA, 'None', default=1) == 1, \
- '`None` is a deliberate sentinel and should become `default`'
- assert traverse_obj(_DEFAULT_DATA, ('list', 10)) is None, \
- '`IndexError` should result in `default`'
- assert traverse_obj(_DEFAULT_DATA, (..., 'fail'), default=1) == 1, \
- 'if branched but not successful return `default` if defined, not `[]`'
- assert traverse_obj(_DEFAULT_DATA, (..., 'fail'), default=None) is None, \
- 'if branched but not successful return `default` even if `default` is `None`'
- assert traverse_obj(_DEFAULT_DATA, (..., 'fail')) == [], \
- 'if branched but not successful return `[]`, not `default`'
- assert traverse_obj(_DEFAULT_DATA, ('list', ...)) == [], \
- 'if branched but object is empty return `[]`, not `default`'
- assert traverse_obj(None, ...) == [], \
- 'if branched but object is `None` return `[]`, not `default`'
- assert traverse_obj({0: None}, (0, ...)) == [], \
- 'if branched but state is `None` return `[]`, not `default`'
-
- @pytest.mark.parametrize('path', [
- ('fail', ...),
- (..., 'fail'),
- 100 * ('fail',) + (...,),
- (...,) + 100 * ('fail',),
- ])
- def test_traversal_branching(self, path):
- assert traverse_obj({}, path) == [], \
- 'if branched but state is `None`, return `[]` (not `default`)'
- assert traverse_obj({}, 'fail', path) == [], \
- 'if branching in last alternative and previous did not match, return `[]` (not `default`)'
- assert traverse_obj({0: 'x'}, 0, path) == 'x', \
- 'if branching in last alternative and previous did match, return single value'
- assert traverse_obj({0: 'x'}, path, 0) == 'x', \
- 'if branching in first alternative and non-branching path does match, return single value'
- assert traverse_obj({}, path, 'fail') is None, \
- 'if branching in first alternative and non-branching path does not match, return `default`'
-
- def test_traversal_expected_type(self):
- _EXPECTED_TYPE_DATA = {'str': 'str', 'int': 0}
-
- assert traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=str) == 'str', \
- 'accept matching `expected_type` type'
- assert traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=int) is None, \
- 'reject non matching `expected_type` type'
- # ruff: noqa: PLW0108 `type`s get special treatment, so wrap in lambda
- assert traverse_obj(_EXPECTED_TYPE_DATA, 'int', expected_type=lambda x: str(x)) == '0', \
- 'transform type using type function'
- assert traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=lambda _: 1 / 0) is None, \
- 'wrap expected_type fuction in try_call'
- assert traverse_obj(_EXPECTED_TYPE_DATA, ..., expected_type=str) == ['str'], \
- 'eliminate items that expected_type fails on'
- assert traverse_obj(_TEST_DATA, {0: 100, 1: 1.2}, expected_type=int) == {0: 100}, \
- 'type as expected_type should filter dict values'
- assert traverse_obj(_TEST_DATA, {0: 100, 1: 1.2, 2: 'None'}, expected_type=str_or_none) == {0: '100', 1: '1.2'}, \
- 'function as expected_type should transform dict values'
- assert traverse_obj(_TEST_DATA, ({0: 1.2}, 0, {int_or_none}), expected_type=int) == 1, \
- 'expected_type should not filter non final dict values'
- assert traverse_obj(_TEST_DATA, {0: {0: 100, 1: 'str'}}, expected_type=int) == {0: {0: 100}}, \
- 'expected_type should transform deep dict values'
- assert traverse_obj(_TEST_DATA, [({0: '...'}, {0: '...'})], expected_type=type(...)) == [{0: ...}, {0: ...}], \
- 'expected_type should transform branched dict values'
- assert traverse_obj({1: {3: 4}}, [(1, 2), 3], expected_type=int) == [4], \
- 'expected_type regression for type matching in tuple branching'
- assert traverse_obj(_TEST_DATA, ['data', ...], expected_type=int) == [], \
- 'expected_type regression for type matching in dict result'
-
- def test_traversal_get_all(self):
- _GET_ALL_DATA = {'key': [0, 1, 2]}
-
- assert traverse_obj(_GET_ALL_DATA, ('key', ...), get_all=False) == 0, \
- 'if not `get_all`, return only first matching value'
- assert traverse_obj(_GET_ALL_DATA, ..., get_all=False) == [0, 1, 2], \
- 'do not overflatten if not `get_all`'
-
- def test_traversal_casesense(self):
- _CASESENSE_DATA = {
- 'KeY': 'value0',
- 0: {
- 'KeY': 'value1',
- 0: {'KeY': 'value2'},
- },
- }
-
- assert traverse_obj(_CASESENSE_DATA, 'key') is None, \
- 'dict keys should be case sensitive unless `casesense`'
- assert traverse_obj(_CASESENSE_DATA, 'keY', casesense=False) == 'value0', \
- 'allow non matching key case if `casesense`'
- assert traverse_obj(_CASESENSE_DATA, [0, ('keY',)], casesense=False) == ['value1'], \
- 'allow non matching key case in branch if `casesense`'
- assert traverse_obj(_CASESENSE_DATA, [0, ([0, 'keY'],)], casesense=False) == ['value2'], \
- 'allow non matching key case in branch path if `casesense`'
-
- def test_traversal_traverse_string(self):
- _TRAVERSE_STRING_DATA = {'str': 'str', 1.2: 1.2}
-
- assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', 0)) is None, \
- 'do not traverse into string if not `traverse_string`'
- assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', 0), traverse_string=True) == 's', \
- 'traverse into string if `traverse_string`'
- assert traverse_obj(_TRAVERSE_STRING_DATA, (1.2, 1), traverse_string=True) == '.', \
- 'traverse into converted data if `traverse_string`'
- assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', ...), traverse_string=True) == 'str', \
- '`...` should result in string (same value) if `traverse_string`'
- assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', slice(0, None, 2)), traverse_string=True) == 'sr', \
- '`slice` should result in string if `traverse_string`'
- assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', lambda i, v: i or v == 's'), traverse_string=True) == 'str', \
- 'function should result in string if `traverse_string`'
- assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', (0, 2)), traverse_string=True) == ['s', 'r'], \
- 'branching should result in list if `traverse_string`'
- assert traverse_obj({}, (0, ...), traverse_string=True) == [], \
- 'branching should result in list if `traverse_string`'
- assert traverse_obj({}, (0, lambda x, y: True), traverse_string=True) == [], \
- 'branching should result in list if `traverse_string`'
- assert traverse_obj({}, (0, slice(1)), traverse_string=True) == [], \
- 'branching should result in list if `traverse_string`'
-
- def test_traversal_re(self):
- mobj = re.fullmatch(r'0(12)(?P3)(4)?', '0123')
- assert traverse_obj(mobj, ...) == [x for x in mobj.groups() if x is not None], \
- '`...` on a `re.Match` should give its `groups()`'
- assert traverse_obj(mobj, lambda k, _: k in (0, 2)) == ['0123', '3'], \
- 'function on a `re.Match` should give groupno, value starting at 0'
- assert traverse_obj(mobj, 'group') == '3', \
- 'str key on a `re.Match` should give group with that name'
- assert traverse_obj(mobj, 2) == '3', \
- 'int key on a `re.Match` should give group with that name'
- assert traverse_obj(mobj, 'gRoUp', casesense=False) == '3', \
- 'str key on a `re.Match` should respect casesense'
- assert traverse_obj(mobj, 'fail') is None, \
- 'failing str key on a `re.Match` should return `default`'
- assert traverse_obj(mobj, 'gRoUpS', casesense=False) is None, \
- 'failing str key on a `re.Match` should return `default`'
- assert traverse_obj(mobj, 8) is None, \
- 'failing int key on a `re.Match` should return `default`'
- assert traverse_obj(mobj, lambda k, _: k in (0, 'group')) == ['0123', '3'], \
- 'function on a `re.Match` should give group name as well'
-
- def test_traversal_xml_etree(self):
- etree = xml.etree.ElementTree.fromstring('''
-
-
- 1
- 2008
- 141100
-
-
-
-
- 4
- 2011
- 59900
-
-
-
- 68
- 2011
- 13600
-
-
-
- ''')
- assert traverse_obj(etree, '') == etree, \
- 'empty str key should return the element itself'
- assert traverse_obj(etree, 'country') == list(etree), \
- 'str key should lead all children with that tag name'
- assert traverse_obj(etree, ...) == list(etree), \
- '`...` as key should return all children'
- assert traverse_obj(etree, lambda _, x: x[0].text == '4') == [etree[1]], \
- 'function as key should get element as value'
- assert traverse_obj(etree, lambda i, _: i == 1) == [etree[1]], \
- 'function as key should get index as key'
- assert traverse_obj(etree, 0) == etree[0], \
- 'int key should return the nth child'
- expected = ['Austria', 'Switzerland', 'Malaysia', 'Costa Rica', 'Colombia']
- assert traverse_obj(etree, './/neighbor/@name') == expected, \
- '`@` at end of path should give that attribute'
- assert traverse_obj(etree, '//neighbor/@fail') == [None, None, None, None, None], \
- '`@` at end of path should give `None`'
- assert traverse_obj(etree, ('//neighbor/@', 2)) == {'name': 'Malaysia', 'direction': 'N'}, \
- '`@` should give the full attribute dict'
- assert traverse_obj(etree, '//year/text()') == ['2008', '2011', '2011'], \
- '`text()` at end of path should give the inner text'
- assert traverse_obj(etree, '//*[@direction]/@direction') == ['E', 'W', 'N', 'W', 'E'], \
- 'full Python xpath features should be supported'
- assert traverse_obj(etree, (0, '@name')) == 'Liechtenstein', \
- 'special transformations should act on current element'
- assert traverse_obj(etree, ('country', 0, ..., 'text()', {int_or_none})) == [1, 2008, 141100], \
- 'special transformations should act on current element'
-
- def test_traversal_unbranching(self):
- assert traverse_obj(_TEST_DATA, [(100, 1.2), all]) == [100, 1.2], \
- '`all` should give all results as list'
- assert traverse_obj(_TEST_DATA, [(100, 1.2), any]) == 100, \
- '`any` should give the first result'
- assert traverse_obj(_TEST_DATA, [100, all]) == [100], \
- '`all` should give list if non branching'
- assert traverse_obj(_TEST_DATA, [100, any]) == 100, \
- '`any` should give single item if non branching'
- assert traverse_obj(_TEST_DATA, [('dict', 'None', 100), all]) == [100], \
- '`all` should filter `None` and empty dict'
- assert traverse_obj(_TEST_DATA, [('dict', 'None', 100), any]) == 100, \
- '`any` should filter `None` and empty dict'
- assert traverse_obj(_TEST_DATA, [{
- 'all': [('dict', 'None', 100, 1.2), all],
- 'any': [('dict', 'None', 100, 1.2), any],
- }]) == {'all': [100, 1.2], 'any': 100}, \
- '`all`/`any` should apply to each dict path separately'
- assert traverse_obj(_TEST_DATA, [{
- 'all': [('dict', 'None', 100, 1.2), all],
- 'any': [('dict', 'None', 100, 1.2), any],
- }], get_all=False) == {'all': [100, 1.2], 'any': 100}, \
- '`all`/`any` should apply to dict regardless of `get_all`'
- assert traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), all, {float}]) is None, \
- '`all` should reset branching status'
- assert traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), any, {float}]) is None, \
- '`any` should reset branching status'
- assert traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), all, ..., {float}]) == [1.2], \
- '`all` should allow further branching'
- assert traverse_obj(_TEST_DATA, [('dict', 'None', 'urls', 'data'), any, ..., 'index']) == [0, 1], \
- '`any` should allow further branching'
-
- def test_traversal_morsel(self):
- morsel = http.cookies.Morsel()
- values = dict(zip(morsel, 'abcdefghijklmnop', strict=False))
- morsel.set('item_key', 'item_value', 'coded_value')
- morsel.update(values)
- values['key'] = 'item_key'
- values['value'] = 'item_value'
-
- for key, value in values.items():
- assert traverse_obj(morsel, key) == value, \
- 'Morsel should provide access to all values'
- assert traverse_obj(morsel, ...) == list(values.values()), \
- '`...` should yield all values'
- assert traverse_obj(morsel, lambda k, v: True) == list(values.values()), \
- 'function key should yield all values'
- assert traverse_obj(morsel, [(None,), any]) == morsel, \
- 'Morsel should not be implicitly changed to dict on usage'
-
- def test_traversal_filter(self):
- data = [None, False, True, 0, 1, 0.0, 1.1, '', 'str', {}, {0: 0}, [], [1]]
-
- assert traverse_obj(data, [..., filter]) == [True, 1, 1.1, 'str', {0: 0}, [1]], \
- '`filter` should filter falsy values'
-
-
-class TestTraversalHelpers:
- def test_traversal_require(self):
- with pytest.raises(ExtractorError):
- traverse_obj(_TEST_DATA, ['None', {require('value')}])
- assert traverse_obj(_TEST_DATA, ['str', {require('value')}]) == 'str', \
- '`require` should pass through non `None` values'
-
- def test_subs_list_to_dict(self):
- assert traverse_obj([
- {'name': 'de', 'url': 'https://example.com/subs/de.vtt'},
- {'name': 'en', 'url': 'https://example.com/subs/en1.ass'},
- {'name': 'en', 'url': 'https://example.com/subs/en2.ass'},
- ], [..., {
- 'id': 'name',
- 'url': 'url',
- }, all, {subs_list_to_dict}]) == {
- 'de': [{'url': 'https://example.com/subs/de.vtt'}],
- 'en': [
- {'url': 'https://example.com/subs/en1.ass'},
- {'url': 'https://example.com/subs/en2.ass'},
- ],
- }, 'function should build subtitle dict from list of subtitles'
- assert traverse_obj([
- {'name': 'de', 'url': 'https://example.com/subs/de.ass'},
- {'name': 'de'},
- {'name': 'en', 'content': 'content'},
- {'url': 'https://example.com/subs/en'},
- ], [..., {
- 'id': 'name',
- 'data': 'content',
- 'url': 'url',
- }, all, {subs_list_to_dict(lang=None)}]) == {
- 'de': [{'url': 'https://example.com/subs/de.ass'}],
- 'en': [{'data': 'content'}],
- }, 'subs with mandatory items missing should be filtered'
- assert traverse_obj([
- {'url': 'https://example.com/subs/de.ass', 'name': 'de'},
- {'url': 'https://example.com/subs/en', 'name': 'en'},
- ], [..., {
- 'id': 'name',
- 'ext': ['url', {determine_ext(default_ext=None)}],
- 'url': 'url',
- }, all, {subs_list_to_dict(ext='ext')}]) == {
- 'de': [{'url': 'https://example.com/subs/de.ass', 'ext': 'ass'}],
- 'en': [{'url': 'https://example.com/subs/en', 'ext': 'ext'}],
- }, '`ext` should set default ext but leave existing value untouched'
- assert traverse_obj([
- {'name': 'en', 'url': 'https://example.com/subs/en2', 'prio': True},
- {'name': 'en', 'url': 'https://example.com/subs/en1', 'prio': False},
- ], [..., {
- 'id': 'name',
- 'quality': ['prio', {int}],
- 'url': 'url',
- }, all, {subs_list_to_dict(ext='ext')}]) == {'en': [
- {'url': 'https://example.com/subs/en1', 'ext': 'ext'},
- {'url': 'https://example.com/subs/en2', 'ext': 'ext'},
- ]}, '`quality` key should sort subtitle list accordingly'
- assert traverse_obj([
- {'name': 'de', 'url': 'https://example.com/subs/de.ass'},
- {'name': 'de'},
- {'name': 'en', 'content': 'content'},
- {'url': 'https://example.com/subs/en'},
- ], [..., {
- 'id': 'name',
- 'url': 'url',
- 'data': 'content',
- }, all, {subs_list_to_dict(lang='en')}]) == {
- 'de': [{'url': 'https://example.com/subs/de.ass'}],
- 'en': [
- {'data': 'content'},
- {'url': 'https://example.com/subs/en'},
- ],
- }, 'optionally provided lang should be used if no id available'
- assert traverse_obj([
- {'name': 1, 'url': 'https://example.com/subs/de1'},
- {'name': {}, 'url': 'https://example.com/subs/de2'},
- {'name': 'de', 'ext': 1, 'url': 'https://example.com/subs/de3'},
- {'name': 'de', 'ext': {}, 'url': 'https://example.com/subs/de4'},
- ], [..., {
- 'id': 'name',
- 'url': 'url',
- 'ext': 'ext',
- }, all, {subs_list_to_dict(lang=None)}]) == {
- 'de': [
- {'url': 'https://example.com/subs/de3'},
- {'url': 'https://example.com/subs/de4'},
- ],
- }, 'non str types should be ignored for id and ext'
- assert traverse_obj([
- {'name': 1, 'url': 'https://example.com/subs/de1'},
- {'name': {}, 'url': 'https://example.com/subs/de2'},
- {'name': 'de', 'ext': 1, 'url': 'https://example.com/subs/de3'},
- {'name': 'de', 'ext': {}, 'url': 'https://example.com/subs/de4'},
- ], [..., {
- 'id': 'name',
- 'url': 'url',
- 'ext': 'ext',
- }, all, {subs_list_to_dict(lang='de')}]) == {
- 'de': [
- {'url': 'https://example.com/subs/de1'},
- {'url': 'https://example.com/subs/de2'},
- {'url': 'https://example.com/subs/de3'},
- {'url': 'https://example.com/subs/de4'},
- ],
- }, 'non str types should be replaced by default id'
-
- def test_trim_str(self):
- with pytest.raises(TypeError):
- trim_str('positional')
-
- assert callable(trim_str(start='a'))
- assert trim_str(start='ab')('abc') == 'c'
- assert trim_str(end='bc')('abc') == 'a'
- assert trim_str(start='a', end='c')('abc') == 'b'
- assert trim_str(start='ab', end='c')('abc') == ''
- assert trim_str(start='a', end='bc')('abc') == ''
- assert trim_str(start='ab', end='bc')('abc') == ''
- assert trim_str(start='abc', end='abc')('abc') == ''
- assert trim_str(start='', end='')('abc') == 'abc'
-
- def test_unpack(self):
- assert unpack(lambda *x: ''.join(map(str, x)))([1, 2, 3]) == '123'
- assert unpack(join_nonempty)([1, 2, 3]) == '1-2-3'
- assert unpack(join_nonempty, delim=' ')([1, 2, 3]) == '1 2 3'
- with pytest.raises(TypeError):
- unpack(join_nonempty)()
- with pytest.raises(TypeError):
- unpack()
-
- def test_find_element(self):
- for improper_kwargs in [
- dict(attr='data-id'),
- dict(value='y'),
- dict(attr='data-id', value='y', cls='a'),
- dict(attr='data-id', value='y', id='x'),
- dict(cls='a', id='x'),
- dict(cls='a', tag='p'),
- dict(cls='[ab]', regex=True),
- ]:
- with pytest.raises(AssertionError):
- find_element(**improper_kwargs)(_TEST_HTML)
-
- assert find_element(cls='a')(_TEST_HTML) == '1'
- assert find_element(cls='a', html=True)(_TEST_HTML) == '1
'
- assert find_element(id='x')(_TEST_HTML) == '2'
- assert find_element(id='[ex]')(_TEST_HTML) is None
- assert find_element(id='[ex]', regex=True)(_TEST_HTML) == '2'
- assert find_element(id='x', html=True)(_TEST_HTML) == '2
'
- assert find_element(attr='data-id', value='y')(_TEST_HTML) == '3'
- assert find_element(attr='data-id', value='y(?:es)?')(_TEST_HTML) is None
- assert find_element(attr='data-id', value='y(?:es)?', regex=True)(_TEST_HTML) == '3'
- assert find_element(
- attr='data-id', value='y', html=True)(_TEST_HTML) == '3
'
-
- def test_find_elements(self):
- for improper_kwargs in [
- dict(tag='p'),
- dict(attr='data-id'),
- dict(value='y'),
- dict(attr='data-id', value='y', cls='a'),
- dict(cls='a', tag='div'),
- dict(cls='[ab]', regex=True),
- ]:
- with pytest.raises(AssertionError):
- find_elements(**improper_kwargs)(_TEST_HTML)
-
- assert find_elements(cls='a')(_TEST_HTML) == ['1', '2', '4']
- assert find_elements(cls='a', html=True)(_TEST_HTML) == [
- '1
', '2
', '4
']
- assert find_elements(attr='custom', value='z')(_TEST_HTML) == ['2', '3']
- assert find_elements(attr='custom', value='[ez]')(_TEST_HTML) == []
- assert find_elements(attr='custom', value='[ez]', regex=True)(_TEST_HTML) == ['2', '3', '5']
-
-
-class TestDictGet:
- def test_dict_get(self):
- FALSE_VALUES = {
- 'none': None,
- 'false': False,
- 'zero': 0,
- 'empty_string': '',
- 'empty_list': [],
- }
- d = {**FALSE_VALUES, 'a': 42}
- assert dict_get(d, 'a') == 42
- assert dict_get(d, 'b') is None
- assert dict_get(d, 'b', 42) == 42
- assert dict_get(d, ('a',)) == 42
- assert dict_get(d, ('b', 'a')) == 42
- assert dict_get(d, ('b', 'c', 'a', 'd')) == 42
- assert dict_get(d, ('b', 'c')) is None
- assert dict_get(d, ('b', 'c'), 42) == 42
- for key, false_value in FALSE_VALUES.items():
- assert dict_get(d, ('b', 'c', key)) is None
- assert dict_get(d, ('b', 'c', key), skip_false_values=False) == false_value
diff --git a/test/test_update.py b/test/test_update.py
deleted file mode 100644
index 980470244..000000000
--- a/test/test_update.py
+++ /dev/null
@@ -1,305 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-from test.helper import FakeYDL, report_warning
-from yt_dlp.update import UpdateInfo, Updater, UPDATE_SOURCES, _make_label
-
-
-# XXX: Keep in sync with yt_dlp.update.UPDATE_SOURCES
-TEST_UPDATE_SOURCES = {
- 'stable': 'yt-dlp/yt-dlp',
- 'nightly': 'yt-dlp/yt-dlp-nightly-builds',
- 'master': 'yt-dlp/yt-dlp-master-builds',
-}
-
-TEST_API_DATA = {
- 'yt-dlp/yt-dlp/latest': {
- 'tag_name': '2023.12.31',
- 'target_commitish': 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
- 'name': 'yt-dlp 2023.12.31',
- 'body': 'BODY',
- },
- 'yt-dlp/yt-dlp-nightly-builds/latest': {
- 'tag_name': '2023.12.31.123456',
- 'target_commitish': 'master',
- 'name': 'yt-dlp nightly 2023.12.31.123456',
- 'body': 'Generated from: https://github.com/yt-dlp/yt-dlp/commit/cccccccccccccccccccccccccccccccccccccccc',
- },
- 'yt-dlp/yt-dlp-master-builds/latest': {
- 'tag_name': '2023.12.31.987654',
- 'target_commitish': 'master',
- 'name': 'yt-dlp master 2023.12.31.987654',
- 'body': 'Generated from: https://github.com/yt-dlp/yt-dlp/commit/dddddddddddddddddddddddddddddddddddddddd',
- },
- 'yt-dlp/yt-dlp/tags/testing': {
- 'tag_name': 'testing',
- 'target_commitish': '9999999999999999999999999999999999999999',
- 'name': 'testing',
- 'body': 'BODY',
- },
- 'fork/yt-dlp/latest': {
- 'tag_name': '2050.12.31',
- 'target_commitish': 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
- 'name': '2050.12.31',
- 'body': 'BODY',
- },
- 'fork/yt-dlp/tags/pr0000': {
- 'tag_name': 'pr0000',
- 'target_commitish': 'ffffffffffffffffffffffffffffffffffffffff',
- 'name': 'pr1234 2023.11.11.000000',
- 'body': 'BODY',
- },
- 'fork/yt-dlp/tags/pr1234': {
- 'tag_name': 'pr1234',
- 'target_commitish': '0000000000000000000000000000000000000000',
- 'name': 'pr1234 2023.12.31.555555',
- 'body': 'BODY',
- },
- 'fork/yt-dlp/tags/pr9999': {
- 'tag_name': 'pr9999',
- 'target_commitish': '1111111111111111111111111111111111111111',
- 'name': 'pr9999',
- 'body': 'BODY',
- },
- 'fork/yt-dlp-satellite/tags/pr987': {
- 'tag_name': 'pr987',
- 'target_commitish': 'master',
- 'name': 'pr987',
- 'body': 'Generated from: https://github.com/yt-dlp/yt-dlp/commit/2222222222222222222222222222222222222222',
- },
-}
-
-TEST_LOCKFILE_COMMENT = '# This file is used for regulating self-update'
-
-TEST_LOCKFILE_V1 = rf'''{TEST_LOCKFILE_COMMENT}
-lock 2022.08.18.36 .+ Python 3\.6
-lock 2023.11.16 (?!win_x86_exe).+ Python 3\.7
-lock 2023.11.16 win_x86_exe .+ Windows-(?:Vista|2008Server)
-lock 2024.10.22 py2exe .+
-lock 2024.10.22 linux_(?:armv7l|aarch64)_exe .+-glibc2\.(?:[12]?\d|30)\b
-lock 2024.10.22 zip Python 3\.8
-lock 2024.10.22 win(?:_x86)?_exe Python 3\.[78].+ Windows-(?:7-|2008ServerR2)
-lock 2025.08.11 darwin_legacy_exe .+
-'''
-
-TEST_LOCKFILE_V2_TMPL = r'''%s
-lockV2 yt-dlp/yt-dlp 2022.08.18.36 .+ Python 3\.6
-lockV2 yt-dlp/yt-dlp 2023.11.16 (?!win_x86_exe).+ Python 3\.7
-lockV2 yt-dlp/yt-dlp 2023.11.16 win_x86_exe .+ Windows-(?:Vista|2008Server)
-lockV2 yt-dlp/yt-dlp 2024.10.22 py2exe .+
-lockV2 yt-dlp/yt-dlp 2024.10.22 linux_(?:armv7l|aarch64)_exe .+-glibc2\.(?:[12]?\d|30)\b
-lockV2 yt-dlp/yt-dlp 2024.10.22 zip Python 3\.8
-lockV2 yt-dlp/yt-dlp 2024.10.22 win(?:_x86)?_exe Python 3\.[78].+ Windows-(?:7-|2008ServerR2)
-lockV2 yt-dlp/yt-dlp 2025.08.11 darwin_legacy_exe .+
-lockV2 yt-dlp/yt-dlp-nightly-builds 2023.11.15.232826 (?!win_x86_exe).+ Python 3\.7
-lockV2 yt-dlp/yt-dlp-nightly-builds 2023.11.15.232826 win_x86_exe .+ Windows-(?:Vista|2008Server)
-lockV2 yt-dlp/yt-dlp-nightly-builds 2024.10.22.051025 py2exe .+
-lockV2 yt-dlp/yt-dlp-nightly-builds 2024.10.22.051025 linux_(?:armv7l|aarch64)_exe .+-glibc2\.(?:[12]?\d|30)\b
-lockV2 yt-dlp/yt-dlp-nightly-builds 2024.10.22.051025 zip Python 3\.8
-lockV2 yt-dlp/yt-dlp-nightly-builds 2024.10.22.051025 win(?:_x86)?_exe Python 3\.[78].+ Windows-(?:7-|2008ServerR2)
-lockV2 yt-dlp/yt-dlp-nightly-builds 2025.08.12.233030 darwin_legacy_exe .+
-lockV2 yt-dlp/yt-dlp-master-builds 2023.11.15.232812 (?!win_x86_exe).+ Python 3\.7
-lockV2 yt-dlp/yt-dlp-master-builds 2023.11.15.232812 win_x86_exe .+ Windows-(?:Vista|2008Server)
-lockV2 yt-dlp/yt-dlp-master-builds 2024.10.22.045052 py2exe .+
-lockV2 yt-dlp/yt-dlp-master-builds 2024.10.22.060347 linux_(?:armv7l|aarch64)_exe .+-glibc2\.(?:[12]?\d|30)\b
-lockV2 yt-dlp/yt-dlp-master-builds 2024.10.22.060347 zip Python 3\.8
-lockV2 yt-dlp/yt-dlp-master-builds 2024.10.22.060347 win(?:_x86)?_exe Python 3\.[78].+ Windows-(?:7-|2008ServerR2)
-lockV2 yt-dlp/yt-dlp-master-builds 2025.08.12.232447 darwin_legacy_exe .+
-'''
-
-TEST_LOCKFILE_V2 = TEST_LOCKFILE_V2_TMPL % TEST_LOCKFILE_COMMENT
-
-TEST_LOCKFILE_ACTUAL = TEST_LOCKFILE_V2_TMPL % TEST_LOCKFILE_V1.rstrip('\n')
-
-TEST_LOCKFILE_FORK = rf'''{TEST_LOCKFILE_ACTUAL}# Test if a fork blocks updates to non-numeric tags
-lockV2 fork/yt-dlp pr0000 .+ Python 3.6
-lockV2 fork/yt-dlp pr1234 (?!win_x86_exe).+ Python 3\.7
-lockV2 fork/yt-dlp pr1234 win_x86_exe .+ Windows-(?:Vista|2008Server)
-lockV2 fork/yt-dlp pr9999 .+ Python 3.11
-'''
-
-
-class FakeUpdater(Updater):
- current_version = '2022.01.01'
- current_commit = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
-
- _channel = 'stable'
- _origin = 'yt-dlp/yt-dlp'
- _update_sources = TEST_UPDATE_SOURCES
-
- def _download_update_spec(self, *args, **kwargs):
- return TEST_LOCKFILE_ACTUAL
-
- def _call_api(self, tag):
- tag = f'tags/{tag}' if tag != 'latest' else tag
- return TEST_API_DATA[f'{self.requested_repo}/{tag}']
-
- def _report_error(self, msg, *args, **kwargs):
- report_warning(msg)
-
-
-class TestUpdate(unittest.TestCase):
- maxDiff = None
-
- def test_update_spec(self):
- ydl = FakeYDL()
- updater = FakeUpdater(ydl, 'stable')
-
- def test(lockfile, identifier, input_tag, expect_tag, exact=False, repo='yt-dlp/yt-dlp'):
- updater._identifier = identifier
- updater._exact = exact
- updater.requested_repo = repo
- result = updater._process_update_spec(lockfile, input_tag)
- self.assertEqual(
- result, expect_tag,
- f'{identifier!r} requesting {repo}@{input_tag} (exact={exact}) '
- f'returned {result!r} instead of {expect_tag!r}')
-
- for lockfile in (TEST_LOCKFILE_V1, TEST_LOCKFILE_V2, TEST_LOCKFILE_ACTUAL, TEST_LOCKFILE_FORK):
- # Normal operation
- test(lockfile, 'zip Python 3.12.0', '2023.12.31', '2023.12.31')
- test(lockfile, 'zip Python 3.12.0', '2023.12.31', '2023.12.31', exact=True)
- # py2exe should never update beyond 2024.10.22
- test(lockfile, 'py2exe Python 3.8', '2025.01.01', '2024.10.22')
- test(lockfile, 'py2exe Python 3.8', '2025.01.01', None, exact=True)
- # Python 3.6 --update should update only to the py3.6 lock
- test(lockfile, 'zip Python 3.6.0', '2023.11.16', '2022.08.18.36')
- # Python 3.6 --update-to an exact version later than the py3.6 lock should return None
- test(lockfile, 'zip Python 3.6.0', '2023.11.16', None, exact=True)
- # Python 3.7 should be able to update to the py3.7 lock
- test(lockfile, 'zip Python 3.7.0', '2023.11.16', '2023.11.16')
- test(lockfile, 'zip Python 3.7.1', '2023.11.16', '2023.11.16', exact=True)
- # Non-win_x86_exe builds on py3.7 must be locked at py3.7 lock
- test(lockfile, 'zip Python 3.7.1', '2023.12.31', '2023.11.16')
- test(lockfile, 'zip Python 3.7.1', '2023.12.31', None, exact=True)
- # Python 3.8 should only update to the py3.8 lock
- test(lockfile, 'zip Python 3.8.10', '2025.01.01', '2024.10.22')
- test(lockfile, 'zip Python 3.8.110', '2025.01.01', None, exact=True)
- test( # Windows Vista w/ win_x86_exe must be locked at Vista lock
- lockfile, 'win_x86_exe Python 3.7.9 (CPython x86 32bit) - Windows-Vista-6.0.6003-SP2',
- '2023.12.31', '2023.11.16')
- test( # Windows 2008Server w/ win_x86_exe must be locked at Vista lock
- lockfile, 'win_x86_exe Python 3.7.9 (CPython x86 32bit) - Windows-2008Server',
- '2023.12.31', None, exact=True)
- test( # Windows 7 w/ win_x86_exe py3.7 build should be able to update beyond py3.7 lock
- lockfile, 'win_x86_exe Python 3.7.9 (CPython x86 32bit) - Windows-7-6.1.7601-SP1',
- '2023.12.31', '2023.12.31', exact=True)
- test( # Windows 7 win_x86_exe should only update to Win7 lock
- lockfile, 'win_x86_exe Python 3.7.9 (CPython x86 32bit) - Windows-7-6.1.7601-SP1',
- '2025.01.01', '2024.10.22')
- test( # Windows 2008ServerR2 win_exe should only update to Win7 lock
- lockfile, 'win_exe Python 3.8.10 (CPython x86 32bit) - Windows-2008ServerR2',
- '2025.12.31', '2024.10.22')
- test( # Windows 8.1 w/ '2008Server' in platform string should be able to update beyond py3.7 lock
- lockfile, 'win_x86_exe Python 3.7.9 (CPython x86 32bit) - Windows-post2008Server-6.2.9200',
- '2023.12.31', '2023.12.31', exact=True)
- test( # win_exe built w/Python 3.8 on Windows>=8 should be able to update beyond py3.8 lock
- lockfile, 'win_exe Python 3.8.10 (CPython AMD64 64bit) - Windows-10-10.0.20348-SP0',
- '2025.01.01', '2025.01.01', exact=True)
- test( # linux_armv7l_exe w/glibc2.7 should only update to glibc<2.31 lock
- lockfile, 'linux_armv7l_exe Python 3.8.0 (CPython armv7l 32bit) - Linux-6.5.0-1025-azure-armv7l-with-glibc2.7',
- '2025.01.01', '2024.10.22')
- test( # linux_armv7l_exe w/Python 3.8 and glibc>=2.31 should be able to update beyond py3.8 and glibc<2.31 locks
- lockfile, 'linux_armv7l_exe Python 3.8.0 (CPython armv7l 32bit) - Linux-6.5.0-1025-azure-armv7l-with-glibc2.31',
- '2025.01.01', '2025.01.01')
- test( # linux_armv7l_exe w/glibc2.30 should only update to glibc<2.31 lock
- lockfile, 'linux_armv7l_exe Python 3.8.0 (CPython armv7l 64bit) - Linux-6.5.0-1025-azure-aarch64-with-glibc2.30 (OpenSSL',
- '2025.01.01', '2024.10.22')
- test( # linux_aarch64_exe w/glibc2.17 should only update to glibc<2.31 lock
- lockfile, 'linux_aarch64_exe Python 3.8.0 (CPython aarch64 64bit) - Linux-6.5.0-1025-azure-aarch64-with-glibc2.17',
- '2025.01.01', '2024.10.22')
- test( # linux_aarch64_exe w/glibc2.40 and glibc>=2.31 should be able to update beyond py3.8 and glibc<2.31 locks
- lockfile, 'linux_aarch64_exe Python 3.8.0 (CPython aarch64 64bit) - Linux-6.5.0-1025-azure-aarch64-with-glibc2.40',
- '2025.01.01', '2025.01.01')
- test( # linux_aarch64_exe w/glibc2.3 should only update to glibc<2.31 lock
- lockfile, 'linux_aarch64_exe Python 3.8.0 (CPython aarch64 64bit) - Linux-6.5.0-1025-azure-aarch64-with-glibc2.3 (OpenSSL',
- '2025.01.01', '2024.10.22')
- test(lockfile, 'darwin_legacy_exe Python 3.10.5', '2025.08.11', '2025.08.11')
- test(lockfile, 'darwin_legacy_exe Python 3.10.5', '2025.08.11', '2025.08.11', exact=True)
- test(lockfile, 'darwin_legacy_exe Python 3.10.5', '2025.08.12', '2025.08.11')
- test(lockfile, 'darwin_legacy_exe Python 3.10.5', '2025.08.12', None, exact=True)
-
- # Forks can block updates to non-numeric tags rather than lock
- test(TEST_LOCKFILE_FORK, 'zip Python 3.6.3', 'pr0000', None, repo='fork/yt-dlp')
- test(TEST_LOCKFILE_FORK, 'zip Python 3.7.4', 'pr0000', 'pr0000', repo='fork/yt-dlp')
- test(TEST_LOCKFILE_FORK, 'zip Python 3.7.4', 'pr1234', None, repo='fork/yt-dlp')
- test(TEST_LOCKFILE_FORK, 'zip Python 3.8.1', 'pr1234', 'pr1234', repo='fork/yt-dlp', exact=True)
- test(
- TEST_LOCKFILE_FORK, 'win_x86_exe Python 3.7.9 (CPython x86 32bit) - Windows-Vista-6.0.6003-SP2',
- 'pr1234', None, repo='fork/yt-dlp')
- test(
- TEST_LOCKFILE_FORK, 'win_x86_exe Python 3.7.9 (CPython x86 32bit) - Windows-7-6.1.7601-SP1',
- '2023.12.31', '2023.12.31', repo='fork/yt-dlp')
- test(TEST_LOCKFILE_FORK, 'zip Python 3.11.2', 'pr9999', None, repo='fork/yt-dlp', exact=True)
- test(TEST_LOCKFILE_FORK, 'zip Python 3.12.0', 'pr9999', 'pr9999', repo='fork/yt-dlp')
-
- def test_query_update(self):
- ydl = FakeYDL()
-
- def test(target, expected, current_version=None, current_commit=None, identifier=None):
- updater = FakeUpdater(ydl, target)
- if current_version:
- updater.current_version = current_version
- if current_commit:
- updater.current_commit = current_commit
- updater._identifier = identifier or 'zip'
- update_info = updater.query_update(_output=True)
- self.assertDictEqual(
- update_info.__dict__ if update_info else {}, expected.__dict__ if expected else {})
-
- test('yt-dlp/yt-dlp@latest', UpdateInfo(
- '2023.12.31', version='2023.12.31', requested_version='2023.12.31', commit='b' * 40))
- test('yt-dlp/yt-dlp-nightly-builds@latest', UpdateInfo(
- '2023.12.31.123456', version='2023.12.31.123456', requested_version='2023.12.31.123456', commit='c' * 40))
- test('yt-dlp/yt-dlp-master-builds@latest', UpdateInfo(
- '2023.12.31.987654', version='2023.12.31.987654', requested_version='2023.12.31.987654', commit='d' * 40))
- test('fork/yt-dlp@latest', UpdateInfo(
- '2050.12.31', version='2050.12.31', requested_version='2050.12.31', commit='e' * 40))
- test('fork/yt-dlp@pr0000', UpdateInfo(
- 'pr0000', version='2023.11.11.000000', requested_version='2023.11.11.000000', commit='f' * 40))
- test('fork/yt-dlp@pr1234', UpdateInfo(
- 'pr1234', version='2023.12.31.555555', requested_version='2023.12.31.555555', commit='0' * 40))
- test('fork/yt-dlp@pr9999', UpdateInfo(
- 'pr9999', version=None, requested_version=None, commit='1' * 40))
- test('fork/yt-dlp-satellite@pr987', UpdateInfo(
- 'pr987', version=None, requested_version=None, commit='2' * 40))
- test('yt-dlp/yt-dlp', None, current_version='2024.01.01')
- test('stable', UpdateInfo(
- '2023.12.31', version='2023.12.31', requested_version='2023.12.31', commit='b' * 40))
- test('nightly', UpdateInfo(
- '2023.12.31.123456', version='2023.12.31.123456', requested_version='2023.12.31.123456', commit='c' * 40))
- test('master', UpdateInfo(
- '2023.12.31.987654', version='2023.12.31.987654', requested_version='2023.12.31.987654', commit='d' * 40))
- test('testing', None, current_commit='9' * 40)
- test('testing', UpdateInfo('testing', commit='9' * 40))
-
- def test_make_label(self):
- STABLE_REPO = UPDATE_SOURCES['stable']
- NIGHTLY_REPO = UPDATE_SOURCES['nightly']
- MASTER_REPO = UPDATE_SOURCES['master']
-
- for inputs, expected in [
- ([STABLE_REPO, '2025.09.02', '2025.09.02'], f'stable@2025.09.02 from {STABLE_REPO}'),
- ([NIGHTLY_REPO, '2025.09.02.123456', '2025.09.02.123456'], f'nightly@2025.09.02.123456 from {NIGHTLY_REPO}'),
- ([MASTER_REPO, '2025.09.02.987654', '2025.09.02.987654'], f'master@2025.09.02.987654 from {MASTER_REPO}'),
- (['fork/yt-dlp', 'experimental', '2025.12.31.000000'], 'fork/yt-dlp@experimental build 2025.12.31.000000'),
- (['fork/yt-dlp', '2025.09.02', '2025.09.02'], 'fork/yt-dlp@2025.09.02'),
- ([STABLE_REPO, 'experimental', '2025.12.31.000000'], f'{STABLE_REPO}@experimental build 2025.12.31.000000'),
- ([STABLE_REPO, 'experimental'], f'{STABLE_REPO}@experimental'),
- (['fork/yt-dlp', 'experimental'], 'fork/yt-dlp@experimental'),
- ]:
- result = _make_label(*inputs)
- self.assertEqual(
- result, expected,
- f'{inputs!r} returned {result!r} instead of {expected!r}')
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_utils.py b/test/test_utils.py
deleted file mode 100644
index 180ede624..000000000
--- a/test/test_utils.py
+++ /dev/null
@@ -1,2248 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import contextlib
-import datetime as dt
-import io
-import itertools
-import json
-import ntpath
-import pickle
-import subprocess
-import unittest
-import unittest.mock
-import warnings
-import xml.etree.ElementTree
-
-from yt_dlp.compat import (
- compat_etree_fromstring,
- compat_HTMLParseError,
-)
-from yt_dlp.utils import (
- Config,
- DateRange,
- ExtractorError,
- InAdvancePagedList,
- LazyList,
- NO_DEFAULT,
- OnDemandPagedList,
- Popen,
- age_restricted,
- args_to_str,
- base_url,
- caesar,
- clean_html,
- clean_podcast_url,
- cli_bool_option,
- cli_option,
- cli_valueless_option,
- date_from_str,
- datetime_from_str,
- detect_exe_version,
- determine_ext,
- determine_file_encoding,
- dfxp2srt,
- encode_base_n,
- encode_compat_str,
- expand_path,
- extract_attributes,
- extract_basic_auth,
- find_xpath_attr,
- fix_xml_ampersands,
- float_or_none,
- format_bytes,
- get_compatible_ext,
- get_element_by_attribute,
- get_element_by_class,
- get_element_html_by_attribute,
- get_element_html_by_class,
- get_element_text_and_html_by_tag,
- get_elements_by_attribute,
- get_elements_by_class,
- get_elements_html_by_attribute,
- get_elements_html_by_class,
- get_elements_text_and_html_by_attribute,
- int_or_none,
- iri_to_uri,
- is_html,
- js_to_json,
- jwt_decode_hs256,
- jwt_encode,
- limit_length,
- locked_file,
- lowercase_escape,
- match_str,
- merge_dicts,
- mimetype2ext,
- month_by_name,
- multipart_encode,
- ohdave_rsa_encrypt,
- orderedSet,
- parse_age_limit,
- parse_bitrate,
- parse_codecs,
- parse_count,
- parse_dfxp_time_expr,
- parse_duration,
- parse_filesize,
- parse_iso8601,
- parse_qs,
- parse_resolution,
- pkcs1pad,
- prepend_extension,
- read_batch_urls,
- remove_end,
- remove_quotes,
- remove_start,
- render_table,
- replace_extension,
- datetime_round,
- rot47,
- sanitize_filename,
- sanitize_path,
- sanitize_url,
- shell_quote,
- strftime_or_none,
- smuggle_url,
- str_to_int,
- strip_jsonp,
- strip_or_none,
- subtitles_filename,
- timeconvert,
- try_call,
- unescapeHTML,
- unified_strdate,
- unified_timestamp,
- unsmuggle_url,
- update_url_query,
- uppercase_escape,
- url_basename,
- url_or_none,
- urlencode_postdata,
- urljoin,
- urshift,
- variadic,
- version_tuple,
- xpath_attr,
- xpath_element,
- xpath_text,
- xpath_with_ns,
-)
-from yt_dlp.utils._utils import _UnsafeExtensionError
-from yt_dlp.utils.networking import (
- HTTPHeaderDict,
- escape_rfc3986,
- normalize_url,
- remove_dot_segments,
-)
-
-
-class TestUtil(unittest.TestCase):
- def test_timeconvert(self):
- self.assertTrue(timeconvert('') is None)
- self.assertTrue(timeconvert('bougrg') is None)
-
- def test_sanitize_filename(self):
- self.assertEqual(sanitize_filename(''), '')
- self.assertEqual(sanitize_filename('abc'), 'abc')
- self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
-
- self.assertEqual(sanitize_filename('123'), '123')
-
- self.assertEqual('abc⧸de', sanitize_filename('abc/de'))
- self.assertFalse('/' in sanitize_filename('abc/de///'))
-
- self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', is_id=False))
- self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', is_id=False))
- self.assertEqual('yes no', sanitize_filename('yes? no', is_id=False))
- self.assertEqual('this - that', sanitize_filename('this: that', is_id=False))
-
- self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
- aumlaut = 'ä'
- self.assertEqual(sanitize_filename(aumlaut), aumlaut)
- tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
- self.assertEqual(sanitize_filename(tests), tests)
-
- self.assertEqual(
- sanitize_filename('New World record at 0:12:34'),
- 'New World record at 0_12_34')
-
- self.assertEqual(sanitize_filename('--gasdgf'), '--gasdgf')
- self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
- self.assertEqual(sanitize_filename('--gasdgf', is_id=False), '_-gasdgf')
- self.assertEqual(sanitize_filename('.gasdgf'), '.gasdgf')
- self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
- self.assertEqual(sanitize_filename('.gasdgf', is_id=False), 'gasdgf')
-
- forbidden = '"\0\\/'
- for fc in forbidden:
- for fbc in forbidden:
- self.assertTrue(fbc not in sanitize_filename(fc))
-
- def test_sanitize_filename_restricted(self):
- self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
- self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
-
- self.assertEqual(sanitize_filename('123', restricted=True), '123')
-
- self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
- self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
-
- self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
- self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
- self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
- self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
-
- tests = 'aäb\u4e2d\u56fd\u7684c'
- self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
- self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
-
- forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
- for fc in forbidden:
- for fbc in forbidden:
- self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
-
- # Handle a common case more neatly
- self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
- self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
- # .. but make sure the file name is never empty
- self.assertTrue(sanitize_filename('-', restricted=True) != '')
- self.assertTrue(sanitize_filename(':', restricted=True) != '')
-
- self.assertEqual(sanitize_filename(
- 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
- 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
-
- def test_sanitize_ids(self):
- self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
- self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
- self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
-
- @unittest.mock.patch('sys.platform', 'win32')
- def test_sanitize_path(self):
- self.assertEqual(sanitize_path('abc'), 'abc')
- self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
- self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
- self.assertEqual(sanitize_path('abc|def'), 'abc#def')
- self.assertEqual(sanitize_path('<>:"|?*'), '#######')
- self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
- self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
-
- self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
- self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
-
- self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
- self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
- self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
- self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
-
- self.assertEqual(
- sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
- 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
-
- self.assertEqual(
- sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
- 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
- self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
- self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
- self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
- self.assertEqual(sanitize_path('C:\\abc:%(title)s.%(ext)s'), 'C:\\abc#%(title)s.%(ext)s')
-
- for test, expected in [
- ('C:\\', 'C:\\'),
- ('../abc', '..\\abc'),
- ('../../abc', '..\\..\\abc'),
- ('./abc', 'abc'),
- ('./../abc', '..\\abc'),
- ('\\abc', '\\abc'),
- ('C:abc', 'C:abc'),
- ('C:abc\\..\\', 'C:'),
- ('C:abc\\..\\def\\..\\..\\', 'C:..'),
- ('C:\\abc\\xyz///..\\def\\', 'C:\\abc\\def'),
- ('abc/../', '.'),
- ('./abc/../', '.'),
- ]:
- result = sanitize_path(test)
- assert result == expected, f'{test} was incorrectly resolved'
- assert result == sanitize_path(result), f'{test} changed after sanitizing again'
- assert result == ntpath.normpath(test), f'{test} does not match ntpath.normpath'
-
- def test_sanitize_url(self):
- self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
- self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
- self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
- self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
- self.assertEqual(sanitize_url('foo bar'), 'foo bar')
-
- def test_expand_path(self):
- def env(var):
- return f'%{var}%' if sys.platform == 'win32' else f'${var}'
-
- os.environ['yt_dlp_EXPATH_PATH'] = 'expanded'
- self.assertEqual(expand_path(env('yt_dlp_EXPATH_PATH')), 'expanded')
-
- old_home = os.environ.get('HOME')
- test_str = R'C:\Documents and Settings\тест\Application Data'
- try:
- os.environ['HOME'] = test_str
- self.assertEqual(expand_path(env('HOME')), os.getenv('HOME'))
- self.assertEqual(expand_path('~'), os.getenv('HOME'))
- self.assertEqual(
- expand_path('~/{}'.format(env('yt_dlp_EXPATH_PATH'))),
- '{}/expanded'.format(os.getenv('HOME')))
- finally:
- os.environ['HOME'] = old_home or ''
-
- _uncommon_extensions = [
- ('exe', 'abc.exe.ext'),
- ('de', 'abc.de.ext'),
- ('../.mp4', None),
- ('..\\.mp4', None),
- ]
-
- def test_prepend_extension(self):
- self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
- self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
- self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
- self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
- self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
- self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
-
- # Test uncommon extensions
- self.assertEqual(prepend_extension('abc.ext', 'bin'), 'abc.bin.ext')
- for ext, result in self._uncommon_extensions:
- with self.assertRaises(_UnsafeExtensionError):
- prepend_extension('abc', ext)
- if result:
- self.assertEqual(prepend_extension('abc.ext', ext, 'ext'), result)
- else:
- with self.assertRaises(_UnsafeExtensionError):
- prepend_extension('abc.ext', ext, 'ext')
- with self.assertRaises(_UnsafeExtensionError):
- prepend_extension('abc.unexpected_ext', ext, 'ext')
-
- def test_replace_extension(self):
- self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
- self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
- self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
- self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
- self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
- self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
-
- # Test uncommon extensions
- self.assertEqual(replace_extension('abc.ext', 'bin'), 'abc.unknown_video')
- for ext, _ in self._uncommon_extensions:
- with self.assertRaises(_UnsafeExtensionError):
- replace_extension('abc', ext)
- with self.assertRaises(_UnsafeExtensionError):
- replace_extension('abc.ext', ext, 'ext')
- with self.assertRaises(_UnsafeExtensionError):
- replace_extension('abc.unexpected_ext', ext, 'ext')
-
- def test_subtitles_filename(self):
- self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt'), 'abc.en.vtt')
- self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt', 'ext'), 'abc.en.vtt')
- self.assertEqual(subtitles_filename('abc.unexpected_ext', 'en', 'vtt', 'ext'), 'abc.unexpected_ext.en.vtt')
-
- def test_remove_start(self):
- self.assertEqual(remove_start(None, 'A - '), None)
- self.assertEqual(remove_start('A - B', 'A - '), 'B')
- self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
- self.assertEqual(remove_start('non-empty', ''), 'non-empty')
-
- def test_remove_end(self):
- self.assertEqual(remove_end(None, ' - B'), None)
- self.assertEqual(remove_end('A - B', ' - B'), 'A')
- self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
- self.assertEqual(remove_end('non-empty', ''), 'non-empty')
-
- def test_remove_quotes(self):
- self.assertEqual(remove_quotes(None), None)
- self.assertEqual(remove_quotes('"'), '"')
- self.assertEqual(remove_quotes("'"), "'")
- self.assertEqual(remove_quotes(';'), ';')
- self.assertEqual(remove_quotes('";'), '";')
- self.assertEqual(remove_quotes('""'), '')
- self.assertEqual(remove_quotes('";"'), ';')
-
- def test_ordered_set(self):
- self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
- self.assertEqual(orderedSet([]), [])
- self.assertEqual(orderedSet([1]), [1])
- # keep the list ordered
- self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
-
- def test_unescape_html(self):
- self.assertEqual(unescapeHTML('%20;'), '%20;')
- self.assertEqual(unescapeHTML('/'), '/')
- self.assertEqual(unescapeHTML('/'), '/')
- self.assertEqual(unescapeHTML('é'), 'é')
- self.assertEqual(unescapeHTML(''), '')
- self.assertEqual(unescapeHTML('&a"'), '&a"')
- # HTML5 entities
- self.assertEqual(unescapeHTML('.''), '.\'')
-
- def test_date_from_str(self):
- self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
- self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
- self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
- self.assertEqual(date_from_str('20200229+365day'), date_from_str('20200229+1year'))
- self.assertEqual(date_from_str('20210131+28day'), date_from_str('20210131+1month'))
-
- def test_datetime_from_str(self):
- self.assertEqual(datetime_from_str('yesterday', precision='day'), datetime_from_str('now-1day', precision='auto'))
- self.assertEqual(datetime_from_str('now+7day', precision='day'), datetime_from_str('now+1week', precision='auto'))
- self.assertEqual(datetime_from_str('now+14day', precision='day'), datetime_from_str('now+2week', precision='auto'))
- self.assertEqual(datetime_from_str('20200229+365day', precision='day'), datetime_from_str('20200229+1year', precision='auto'))
- self.assertEqual(datetime_from_str('20210131+28day', precision='day'), datetime_from_str('20210131+1month', precision='auto'))
- self.assertEqual(datetime_from_str('20210131+59day', precision='day'), datetime_from_str('20210131+2month', precision='auto'))
- self.assertEqual(datetime_from_str('now+1day', precision='hour'), datetime_from_str('now+24hours', precision='auto'))
- self.assertEqual(datetime_from_str('now+23hours', precision='hour'), datetime_from_str('now+23hours', precision='auto'))
-
- def test_datetime_round(self):
- self.assertEqual(datetime_round(dt.datetime.strptime('1820-05-12T01:23:45Z', '%Y-%m-%dT%H:%M:%SZ')),
- dt.datetime(1820, 5, 12, tzinfo=dt.timezone.utc))
- self.assertEqual(datetime_round(dt.datetime.strptime('1969-12-31T23:34:45Z', '%Y-%m-%dT%H:%M:%SZ'), 'hour'),
- dt.datetime(1970, 1, 1, 0, tzinfo=dt.timezone.utc))
- self.assertEqual(datetime_round(dt.datetime.strptime('2024-12-25T01:23:45Z', '%Y-%m-%dT%H:%M:%SZ'), 'minute'),
- dt.datetime(2024, 12, 25, 1, 24, tzinfo=dt.timezone.utc))
- self.assertEqual(datetime_round(dt.datetime.strptime('2024-12-25T01:23:45.123Z', '%Y-%m-%dT%H:%M:%S.%fZ'), 'second'),
- dt.datetime(2024, 12, 25, 1, 23, 45, tzinfo=dt.timezone.utc))
- self.assertEqual(datetime_round(dt.datetime.strptime('2024-12-25T01:23:45.678Z', '%Y-%m-%dT%H:%M:%S.%fZ'), 'second'),
- dt.datetime(2024, 12, 25, 1, 23, 46, tzinfo=dt.timezone.utc))
-
- def test_strftime_or_none(self):
- self.assertEqual(strftime_or_none(-4722192000), '18200512')
- self.assertEqual(strftime_or_none(0), '19700101')
- self.assertEqual(strftime_or_none(1735084800), '20241225')
- # Throws OverflowError
- self.assertEqual(strftime_or_none(1735084800000), None)
-
- def test_daterange(self):
- _20century = DateRange('19000101', '20000101')
- self.assertFalse('17890714' in _20century)
- _ac = DateRange('00010101')
- self.assertTrue('19690721' in _ac)
- _firstmilenium = DateRange(end='10000101')
- self.assertTrue('07110427' in _firstmilenium)
-
- def test_unified_dates(self):
- self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
- self.assertEqual(unified_strdate('8/7/2009'), '20090708')
- self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
- self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
- self.assertEqual(unified_strdate('1968 12 10'), '19681210')
- self.assertEqual(unified_strdate('1968-12-10'), '19681210')
- self.assertEqual(unified_strdate('31-07-2022 20:00'), '20220731')
- self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
- self.assertEqual(
- unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
- '20141126')
- self.assertEqual(
- unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
- '20150202')
- self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
- self.assertEqual(unified_strdate('25-09-2014'), '20140925')
- self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
- self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
- self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
- self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
- self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
- self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
- self.assertEqual(unified_strdate('November 3rd, 2019'), '20191103')
- self.assertEqual(unified_strdate('October 23rd, 2005'), '20051023')
-
- def test_unified_timestamps(self):
- self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
- self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
- self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
- self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
- self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
- self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
- self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
- self.assertEqual(
- unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
- 1417001400)
- self.assertEqual(
- unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
- 1422902860)
- self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
- self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
- self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
- self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
- self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
- self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
- self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
- self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
- self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
- self.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
- self.assertEqual(unified_timestamp('Sunday, 26 Nov 2006, 19:00'), 1164567600)
- self.assertEqual(unified_timestamp('wed, aug 16, 2008, 12:00pm'), 1218931200)
-
- self.assertEqual(unified_timestamp('December 31 1969 20:00:01 EDT'), 1)
- self.assertEqual(unified_timestamp('Wednesday 31 December 1969 18:01:26 MDT'), 86)
- self.assertEqual(unified_timestamp('12/31/1969 20:01:18 EDT', False), 78)
-
- self.assertEqual(unified_timestamp('2026-01-01 00:00:00', tz_offset=0), 1767225600)
- self.assertEqual(unified_timestamp('2026-01-01 00:00:00', tz_offset=8), 1767196800)
- self.assertEqual(unified_timestamp('2026-01-01 00:00:00 +0800', tz_offset=-5), 1767196800)
-
- def test_determine_ext(self):
- self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
- self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
- self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
- self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
- self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
- self.assertEqual(determine_ext('foobar', None), None)
-
- def test_find_xpath_attr(self):
- testxml = '''
-
-
-
-
-
- '''
- doc = compat_etree_fromstring(testxml)
-
- self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
- self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
- self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
- self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
- self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
- self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
- self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
- self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
- self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
- self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
- self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
-
- def test_xpath_with_ns(self):
- testxml = '''
-
- The Author
- http://server.com/download.mp3
-
- '''
- doc = compat_etree_fromstring(testxml)
- find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
- self.assertTrue(find('media:song') is not None)
- self.assertEqual(find('media:song/media:author').text, 'The Author')
- self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
-
- def test_xpath_element(self):
- doc = xml.etree.ElementTree.Element('root')
- div = xml.etree.ElementTree.SubElement(doc, 'div')
- p = xml.etree.ElementTree.SubElement(div, 'p')
- p.text = 'Foo'
- self.assertEqual(xpath_element(doc, 'div/p'), p)
- self.assertEqual(xpath_element(doc, ['div/p']), p)
- self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
- self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
- self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
- self.assertTrue(xpath_element(doc, 'div/bar') is None)
- self.assertTrue(xpath_element(doc, ['div/bar']) is None)
- self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
- self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
- self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
- self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
-
- def test_xpath_text(self):
- testxml = '''
-
- '''
- doc = compat_etree_fromstring(testxml)
- self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
- self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
- self.assertTrue(xpath_text(doc, 'div/bar') is None)
- self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
-
- def test_xpath_attr(self):
- testxml = '''
-
- '''
- doc = compat_etree_fromstring(testxml)
- self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
- self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
- self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
- self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
- self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
- self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
- self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
-
- def test_smuggle_url(self):
- data = {'ö': 'ö', 'abc': [3]}
- url = 'https://foo.bar/baz?x=y#a'
- smug_url = smuggle_url(url, data)
- unsmug_url, unsmug_data = unsmuggle_url(smug_url)
- self.assertEqual(url, unsmug_url)
- self.assertEqual(data, unsmug_data)
-
- res_url, res_data = unsmuggle_url(url)
- self.assertEqual(res_url, url)
- self.assertEqual(res_data, None)
-
- smug_url = smuggle_url(url, {'a': 'b'})
- smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
- res_url, res_data = unsmuggle_url(smug_smug_url)
- self.assertEqual(res_url, url)
- self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
-
- def test_shell_quote(self):
- args = ['ffmpeg', '-i', 'ñ€ß\'.mp4']
- self.assertEqual(
- shell_quote(args),
- """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if os.name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
-
- def test_float_or_none(self):
- self.assertEqual(float_or_none('42.42'), 42.42)
- self.assertEqual(float_or_none('42'), 42.0)
- self.assertEqual(float_or_none(''), None)
- self.assertEqual(float_or_none(None), None)
- self.assertEqual(float_or_none([]), None)
- self.assertEqual(float_or_none(set()), None)
-
- def test_int_or_none(self):
- self.assertEqual(int_or_none('42'), 42)
- self.assertEqual(int_or_none(''), None)
- self.assertEqual(int_or_none(None), None)
- self.assertEqual(int_or_none([]), None)
- self.assertEqual(int_or_none(set()), None)
-
- def test_str_to_int(self):
- self.assertEqual(str_to_int('123,456'), 123456)
- self.assertEqual(str_to_int('123.456'), 123456)
- self.assertEqual(str_to_int(523), 523)
- self.assertEqual(str_to_int('noninteger'), None)
- self.assertEqual(str_to_int([]), None)
-
- def test_url_basename(self):
- self.assertEqual(url_basename('http://foo.de/'), '')
- self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
- self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
- self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
- self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
- self.assertEqual(
- url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
- 'trailer.mp4')
-
- def test_base_url(self):
- self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
- self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
- self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
- self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
- self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
- self.assertEqual(base_url('http://foo.de/bar/baz&x=z&w=y/x/c'), 'http://foo.de/bar/baz&x=z&w=y/x/')
-
- def test_urljoin(self):
- self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
- self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
- self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
- self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
- self.assertEqual(urljoin('http://foo.de/', None), None)
- self.assertEqual(urljoin('http://foo.de/', ''), None)
- self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
- self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
- self.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
- self.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
-
- def test_url_or_none(self):
- self.assertEqual(url_or_none(None), None)
- self.assertEqual(url_or_none(''), None)
- self.assertEqual(url_or_none('foo'), None)
- self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
- self.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
- self.assertEqual(url_or_none('http$://foo.de'), None)
- self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
- self.assertEqual(url_or_none('//foo.de'), '//foo.de')
- self.assertEqual(url_or_none('s3://foo.de'), None)
- self.assertEqual(url_or_none('rtmpte://foo.de'), 'rtmpte://foo.de')
- self.assertEqual(url_or_none('mms://foo.de'), 'mms://foo.de')
- self.assertEqual(url_or_none('rtspu://foo.de'), 'rtspu://foo.de')
- self.assertEqual(url_or_none('ftps://foo.de'), 'ftps://foo.de')
- self.assertEqual(url_or_none('ws://foo.de'), 'ws://foo.de')
- self.assertEqual(url_or_none('wss://foo.de'), 'wss://foo.de')
-
- def test_parse_age_limit(self):
- self.assertEqual(parse_age_limit(None), None)
- self.assertEqual(parse_age_limit(False), None)
- self.assertEqual(parse_age_limit('invalid'), None)
- self.assertEqual(parse_age_limit(0), 0)
- self.assertEqual(parse_age_limit(18), 18)
- self.assertEqual(parse_age_limit(21), 21)
- self.assertEqual(parse_age_limit(22), None)
- self.assertEqual(parse_age_limit('18'), 18)
- self.assertEqual(parse_age_limit('18+'), 18)
- self.assertEqual(parse_age_limit('PG-13'), 13)
- self.assertEqual(parse_age_limit('TV-14'), 14)
- self.assertEqual(parse_age_limit('TV-MA'), 17)
- self.assertEqual(parse_age_limit('TV14'), 14)
- self.assertEqual(parse_age_limit('TV_G'), 0)
-
- def test_parse_duration(self):
- self.assertEqual(parse_duration(None), None)
- self.assertEqual(parse_duration(False), None)
- self.assertEqual(parse_duration('invalid'), None)
- self.assertEqual(parse_duration('1'), 1)
- self.assertEqual(parse_duration('1337:12'), 80232)
- self.assertEqual(parse_duration('9:12:43'), 33163)
- self.assertEqual(parse_duration('12:00'), 720)
- self.assertEqual(parse_duration('00:01:01'), 61)
- self.assertEqual(parse_duration('x:y'), None)
- self.assertEqual(parse_duration('3h11m53s'), 11513)
- self.assertEqual(parse_duration('3h 11m 53s'), 11513)
- self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
- self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
- self.assertEqual(parse_duration('3 hours, 11 minutes, 53 seconds'), 11513)
- self.assertEqual(parse_duration('3 hours, 11 mins, 53 secs'), 11513)
- self.assertEqual(parse_duration('62m45s'), 3765)
- self.assertEqual(parse_duration('6m59s'), 419)
- self.assertEqual(parse_duration('49s'), 49)
- self.assertEqual(parse_duration('0h0m0s'), 0)
- self.assertEqual(parse_duration('0m0s'), 0)
- self.assertEqual(parse_duration('0s'), 0)
- self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
- self.assertEqual(parse_duration('T30M38S'), 1838)
- self.assertEqual(parse_duration('5 s'), 5)
- self.assertEqual(parse_duration('3 min'), 180)
- self.assertEqual(parse_duration('2.5 hours'), 9000)
- self.assertEqual(parse_duration('02:03:04'), 7384)
- self.assertEqual(parse_duration('01:02:03:04'), 93784)
- self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
- self.assertEqual(parse_duration('87 Min.'), 5220)
- self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
- self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
- self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
- self.assertEqual(parse_duration('01:02:03:050'), 3723.05)
- self.assertEqual(parse_duration('103:050'), 103.05)
- self.assertEqual(parse_duration('1HR 3MIN'), 3780)
- self.assertEqual(parse_duration('2hrs 3mins'), 7380)
-
- def test_fix_xml_ampersands(self):
- self.assertEqual(
- fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
- self.assertEqual(
- fix_xml_ampersands('"&x=y&wrong;&z=a'),
- '"&x=y&wrong;&z=a')
- self.assertEqual(
- fix_xml_ampersands('&'><"'),
- '&'><"')
- self.assertEqual(
- fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
- self.assertEqual(fix_xml_ampersands(''), '&#&#')
-
- def test_paged_list(self):
- def testPL(size, pagesize, sliceargs, expected):
- def get_page(pagenum):
- firstid = pagenum * pagesize
- upto = min(size, pagenum * pagesize + pagesize)
- yield from range(firstid, upto)
-
- pl = OnDemandPagedList(get_page, pagesize)
- got = pl.getslice(*sliceargs)
- self.assertEqual(got, expected)
-
- iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
- got = iapl.getslice(*sliceargs)
- self.assertEqual(got, expected)
-
- testPL(5, 2, (), [0, 1, 2, 3, 4])
- testPL(5, 2, (1,), [1, 2, 3, 4])
- testPL(5, 2, (2,), [2, 3, 4])
- testPL(5, 2, (4,), [4])
- testPL(5, 2, (0, 3), [0, 1, 2])
- testPL(5, 2, (1, 4), [1, 2, 3])
- testPL(5, 2, (2, 99), [2, 3, 4])
- testPL(5, 2, (20, 99), [])
-
- def test_read_batch_urls(self):
- f = io.StringIO('''\xef\xbb\xbf foo
- bar\r
- baz
- # More after this line\r
- ; or after this
- bam''')
- self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
-
- def test_urlencode_postdata(self):
- data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
- self.assertTrue(isinstance(data, bytes))
-
- def test_update_url_query(self):
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
- parse_qs('http://example.com/path?quality=HD&format=mp4'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
- parse_qs('http://example.com/path?system=LINUX&system=WINDOWS'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
- parse_qs('http://example.com/path?fields=id,formats,subtitles'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
- parse_qs('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path?manifest=f4m', {'manifest': []})),
- parse_qs('http://example.com/path'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
- parse_qs('http://example.com/path?system=LINUX'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
- parse_qs('http://example.com/path?fields=id,formats,subtitles'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path', {'width': 1080, 'height': 720})),
- parse_qs('http://example.com/path?width=1080&height=720'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path', {'bitrate': 5020.43})),
- parse_qs('http://example.com/path?bitrate=5020.43'))
- self.assertEqual(parse_qs(update_url_query(
- 'http://example.com/path', {'test': '第二行тест'})),
- parse_qs('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
-
- def test_multipart_encode(self):
- self.assertEqual(
- multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
- b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
- self.assertEqual(
- multipart_encode({'欄位'.encode(): '值'.encode()}, boundary='AAAAAA')[0],
- b'--AAAAAA\r\nContent-Disposition: form-data; name="\xe6\xac\x84\xe4\xbd\x8d"\r\n\r\n\xe5\x80\xbc\r\n--AAAAAA--\r\n')
- self.assertRaises(
- ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
-
- def test_merge_dicts(self):
- self.assertEqual(merge_dicts({'a': 1}, {'b': 2}), {'a': 1, 'b': 2})
- self.assertEqual(merge_dicts({'a': 1}, {'a': 2}), {'a': 1})
- self.assertEqual(merge_dicts({'a': 1}, {'a': None}), {'a': 1})
- self.assertEqual(merge_dicts({'a': 1}, {'a': ''}), {'a': 1})
- self.assertEqual(merge_dicts({'a': 1}, {}), {'a': 1})
- self.assertEqual(merge_dicts({'a': None}, {'a': 1}), {'a': 1})
- self.assertEqual(merge_dicts({'a': ''}, {'a': 1}), {'a': ''})
- self.assertEqual(merge_dicts({'a': ''}, {'a': 'abc'}), {'a': 'abc'})
- self.assertEqual(merge_dicts({'a': None}, {'a': ''}, {'a': 'abc'}), {'a': 'abc'})
-
- def test_encode_compat_str(self):
- self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
- self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
-
- def test_parse_iso8601(self):
- self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
- self.assertEqual(parse_iso8601('2014-03-23T23:04:26-07:00'), 1395641066)
- self.assertEqual(parse_iso8601('2014-03-23T23:04:26', timezone=dt.timedelta(hours=-7)), 1395641066)
- self.assertEqual(parse_iso8601('2014-03-23T23:04:26', timezone=NO_DEFAULT), None)
- # default does not override timezone in date_str
- self.assertEqual(parse_iso8601('2014-03-23T23:04:26-07:00', timezone=dt.timedelta(hours=-10)), 1395641066)
- self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
- self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
- self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
- self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
- self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
-
- def test_strip_jsonp(self):
- stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
- d = json.loads(stripped)
- self.assertEqual(d, [{'id': '532cb', 'x': 3}])
-
- stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
- d = json.loads(stripped)
- self.assertEqual(d, {'STATUS': 'OK'})
-
- stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
- d = json.loads(stripped)
- self.assertEqual(d, {'status': 'success'})
-
- stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
- d = json.loads(stripped)
- self.assertEqual(d, {'status': 'success'})
-
- stripped = strip_jsonp('window.cb && cb({"status": "success"});')
- d = json.loads(stripped)
- self.assertEqual(d, {'status': 'success'})
-
- stripped = strip_jsonp('({"status": "success"});')
- d = json.loads(stripped)
- self.assertEqual(d, {'status': 'success'})
-
- def test_strip_or_none(self):
- self.assertEqual(strip_or_none(' abc'), 'abc')
- self.assertEqual(strip_or_none('abc '), 'abc')
- self.assertEqual(strip_or_none(' abc '), 'abc')
- self.assertEqual(strip_or_none('\tabc\t'), 'abc')
- self.assertEqual(strip_or_none('\n\tabc\n\t'), 'abc')
- self.assertEqual(strip_or_none('abc'), 'abc')
- self.assertEqual(strip_or_none(''), '')
- self.assertEqual(strip_or_none(None), None)
- self.assertEqual(strip_or_none(42), None)
- self.assertEqual(strip_or_none([]), None)
-
- def test_uppercase_escape(self):
- self.assertEqual(uppercase_escape('aä'), 'aä')
- self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
-
- def test_lowercase_escape(self):
- self.assertEqual(lowercase_escape('aä'), 'aä')
- self.assertEqual(lowercase_escape('\\u0026'), '&')
-
- def test_limit_length(self):
- self.assertEqual(limit_length(None, 12), None)
- self.assertEqual(limit_length('foo', 12), 'foo')
- self.assertTrue(
- limit_length('foo bar baz asd', 12).startswith('foo bar'))
- self.assertTrue('...' in limit_length('foo bar baz asd', 12))
-
- def test_mimetype2ext(self):
- self.assertEqual(mimetype2ext(None), None)
- self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
- self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
- self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
- self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
- self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
- self.assertEqual(mimetype2ext('audio/x-wav'), 'wav')
- self.assertEqual(mimetype2ext('audio/x-wav;codec=pcm'), 'wav')
-
- def test_month_by_name(self):
- self.assertEqual(month_by_name(None), None)
- self.assertEqual(month_by_name('December', 'en'), 12)
- self.assertEqual(month_by_name('décembre', 'fr'), 12)
- self.assertEqual(month_by_name('desember', 'is'), 12)
- self.assertEqual(month_by_name('December'), 12)
- self.assertEqual(month_by_name('décembre'), None)
- self.assertEqual(month_by_name('Unknown', 'unknown'), None)
-
- def test_parse_codecs(self):
- self.assertEqual(parse_codecs(''), {})
- self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
- 'vcodec': 'avc1.77.30',
- 'acodec': 'mp4a.40.2',
- 'dynamic_range': None,
- })
- self.assertEqual(parse_codecs('mp4a.40.2'), {
- 'vcodec': 'none',
- 'acodec': 'mp4a.40.2',
- 'dynamic_range': None,
- })
- self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
- 'vcodec': 'avc1.42001e',
- 'acodec': 'mp4a.40.5',
- 'dynamic_range': None,
- })
- self.assertEqual(parse_codecs('avc3.640028'), {
- 'vcodec': 'avc3.640028',
- 'acodec': 'none',
- 'dynamic_range': None,
- })
- self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
- 'vcodec': 'h264',
- 'acodec': 'aac',
- 'dynamic_range': None,
- })
- self.assertEqual(parse_codecs('av01.0.05M.08'), {
- 'vcodec': 'av01.0.05M.08',
- 'acodec': 'none',
- 'dynamic_range': None,
- })
- self.assertEqual(parse_codecs('vp9.2'), {
- 'vcodec': 'vp9.2',
- 'acodec': 'none',
- 'dynamic_range': 'HDR10',
- })
- self.assertEqual(parse_codecs('vp09.02.50.10.01.09.18.09.00'), {
- 'vcodec': 'vp09.02.50.10.01.09.18.09.00',
- 'acodec': 'none',
- 'dynamic_range': 'HDR10',
- })
- self.assertEqual(parse_codecs('av01.0.12M.10.0.110.09.16.09.0'), {
- 'vcodec': 'av01.0.12M.10.0.110.09.16.09.0',
- 'acodec': 'none',
- 'dynamic_range': 'HDR10',
- })
- self.assertEqual(parse_codecs('dvhe'), {
- 'vcodec': 'dvhe',
- 'acodec': 'none',
- 'dynamic_range': 'DV',
- })
- self.assertEqual(parse_codecs('fLaC'), {
- 'vcodec': 'none',
- 'acodec': 'flac',
- 'dynamic_range': None,
- })
- self.assertEqual(parse_codecs('theora, vorbis'), {
- 'vcodec': 'theora',
- 'acodec': 'vorbis',
- 'dynamic_range': None,
- })
- self.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
- 'vcodec': 'unknownvcodec',
- 'acodec': 'unknownacodec',
- })
- self.assertEqual(parse_codecs('unknown'), {})
-
- def test_escape_rfc3986(self):
- reserved = "!*'();:@&=+$,/?#[]"
- unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
- self.assertEqual(escape_rfc3986(reserved), reserved)
- self.assertEqual(escape_rfc3986(unreserved), unreserved)
- self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
- self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
- self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
- self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
-
- def test_normalize_url(self):
- self.assertEqual(
- normalize_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
- 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4',
- )
- self.assertEqual(
- normalize_url('http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erklärt/Das-Erste/Video?documentId=22673108&bcastId=5290'),
- 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290',
- )
- self.assertEqual(
- normalize_url('http://тест.рф/фрагмент'),
- 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82',
- )
- self.assertEqual(
- normalize_url('http://тест.рф/абв?абв=абв#абв'),
- 'http://xn--e1aybc.xn--p1ai/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2',
- )
- self.assertEqual(normalize_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
-
- self.assertEqual(normalize_url('http://www.example.com/../a/b/../c/./d.html'), 'http://www.example.com/a/c/d.html')
-
- def test_remove_dot_segments(self):
- self.assertEqual(remove_dot_segments('/a/b/c/./../../g'), '/a/g')
- self.assertEqual(remove_dot_segments('mid/content=5/../6'), 'mid/6')
- self.assertEqual(remove_dot_segments('/ad/../cd'), '/cd')
- self.assertEqual(remove_dot_segments('/ad/../cd/'), '/cd/')
- self.assertEqual(remove_dot_segments('/..'), '/')
- self.assertEqual(remove_dot_segments('/./'), '/')
- self.assertEqual(remove_dot_segments('/./a'), '/a')
- self.assertEqual(remove_dot_segments('/abc/./.././d/././e/.././f/./../../ghi'), '/ghi')
- self.assertEqual(remove_dot_segments('/'), '/')
- self.assertEqual(remove_dot_segments('/t'), '/t')
- self.assertEqual(remove_dot_segments('t'), 't')
- self.assertEqual(remove_dot_segments(''), '')
- self.assertEqual(remove_dot_segments('/../a/b/c'), '/a/b/c')
- self.assertEqual(remove_dot_segments('../a'), 'a')
- self.assertEqual(remove_dot_segments('./a'), 'a')
- self.assertEqual(remove_dot_segments('.'), '')
- self.assertEqual(remove_dot_segments('////'), '////')
-
- def test_js_to_json_vars_strings(self):
- self.assertDictEqual(
- json.loads(js_to_json(
- '''{
- 'null': a,
- 'nullStr': b,
- 'true': c,
- 'trueStr': d,
- 'false': e,
- 'falseStr': f,
- 'unresolvedVar': g,
- }''',
- {
- 'a': 'null',
- 'b': '"null"',
- 'c': 'true',
- 'd': '"true"',
- 'e': 'false',
- 'f': '"false"',
- 'g': 'var',
- },
- )),
- {
- 'null': None,
- 'nullStr': 'null',
- 'true': True,
- 'trueStr': 'true',
- 'false': False,
- 'falseStr': 'false',
- 'unresolvedVar': 'var',
- },
- )
-
- self.assertDictEqual(
- json.loads(js_to_json(
- '''{
- 'int': a,
- 'intStr': b,
- 'float': c,
- 'floatStr': d,
- }''',
- {
- 'a': '123',
- 'b': '"123"',
- 'c': '1.23',
- 'd': '"1.23"',
- },
- )),
- {
- 'int': 123,
- 'intStr': '123',
- 'float': 1.23,
- 'floatStr': '1.23',
- },
- )
-
- self.assertDictEqual(
- json.loads(js_to_json(
- '''{
- 'object': a,
- 'objectStr': b,
- 'array': c,
- 'arrayStr': d,
- }''',
- {
- 'a': '{}',
- 'b': '"{}"',
- 'c': '[]',
- 'd': '"[]"',
- },
- )),
- {
- 'object': {},
- 'objectStr': '{}',
- 'array': [],
- 'arrayStr': '[]',
- },
- )
-
- def test_js_to_json_realworld(self):
- inp = '''{
- 'clip':{'provider':'pseudo'}
- }'''
- self.assertEqual(js_to_json(inp), '''{
- "clip":{"provider":"pseudo"}
- }''')
- json.loads(js_to_json(inp))
-
- inp = '''{
- 'playlist':[{'controls':{'all':null}}]
- }'''
- self.assertEqual(js_to_json(inp), '''{
- "playlist":[{"controls":{"all":null}}]
- }''')
-
- inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
- self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
-
- inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
- json_code = js_to_json(inp)
- self.assertEqual(json.loads(json_code), json.loads(inp))
-
- inp = '''{
- 0:{src:'skipped', type: 'application/dash+xml'},
- 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
- }'''
- self.assertEqual(js_to_json(inp), '''{
- "0":{"src":"skipped", "type": "application/dash+xml"},
- "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
- }''')
-
- inp = '''{"foo":101}'''
- self.assertEqual(js_to_json(inp), '''{"foo":101}''')
-
- inp = '''{"duration": "00:01:07"}'''
- self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
-
- inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
- self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
-
- def test_js_to_json_edgecases(self):
- on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
- self.assertEqual(json.loads(on), {'abc_def': "1'\\2\\'3\"4"})
-
- on = js_to_json('{"abc": true}')
- self.assertEqual(json.loads(on), {'abc': True})
-
- # Ignore JavaScript code as well
- on = js_to_json('''{
- "x": 1,
- y: "a",
- z: some.code
- }''')
- d = json.loads(on)
- self.assertEqual(d['x'], 1)
- self.assertEqual(d['y'], 'a')
-
- # Just drop ! prefix for now though this results in a wrong value
- on = js_to_json('''{
- a: !0,
- b: !1,
- c: !!0,
- d: !!42.42,
- e: !!![],
- f: !"abc",
- g: !"",
- !42: 42
- }''')
- self.assertEqual(json.loads(on), {
- 'a': 0,
- 'b': 1,
- 'c': 0,
- 'd': 42.42,
- 'e': [],
- 'f': 'abc',
- 'g': '',
- '42': 42,
- })
-
- on = js_to_json('["abc", "def",]')
- self.assertEqual(json.loads(on), ['abc', 'def'])
-
- on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
- self.assertEqual(json.loads(on), ['abc', 'def'])
-
- on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
- self.assertEqual(json.loads(on), ['abc', 'def'])
-
- on = js_to_json('{"abc": "def",}')
- self.assertEqual(json.loads(on), {'abc': 'def'})
-
- on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
- self.assertEqual(json.loads(on), {'abc': 'def'})
-
- on = js_to_json('{ 0: /* " \n */ ",]" , }')
- self.assertEqual(json.loads(on), {'0': ',]'})
-
- on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
- self.assertEqual(json.loads(on), {'0': ',]'})
-
- on = js_to_json('{ 0: // comment\n1 }')
- self.assertEqual(json.loads(on), {'0': 1})
-
- on = js_to_json(r'["x<\/p>"]')
- self.assertEqual(json.loads(on), ['
x
'])
-
- on = js_to_json(r'["\xaa"]')
- self.assertEqual(json.loads(on), ['\u00aa'])
-
- on = js_to_json("['a\\\nb']")
- self.assertEqual(json.loads(on), ['ab'])
-
- on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
- self.assertEqual(json.loads(on), ['ab'])
-
- on = js_to_json('{0xff:0xff}')
- self.assertEqual(json.loads(on), {'255': 255})
-
- on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
- self.assertEqual(json.loads(on), {'255': 255})
-
- on = js_to_json('{077:077}')
- self.assertEqual(json.loads(on), {'63': 63})
-
- on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
- self.assertEqual(json.loads(on), {'63': 63})
-
- on = js_to_json('{42:42}')
- self.assertEqual(json.loads(on), {'42': 42})
-
- on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
- self.assertEqual(json.loads(on), {'42': 42})
-
- on = js_to_json('{42:4.2e1}')
- self.assertEqual(json.loads(on), {'42': 42.0})
-
- on = js_to_json('{ "0x40": "0x40" }')
- self.assertEqual(json.loads(on), {'0x40': '0x40'})
-
- on = js_to_json('{ "040": "040" }')
- self.assertEqual(json.loads(on), {'040': '040'})
-
- on = js_to_json('[1,//{},\n2]')
- self.assertEqual(json.loads(on), [1, 2])
-
- on = js_to_json(R'"\^\$\#"')
- self.assertEqual(json.loads(on), R'^$#', msg='Unnecessary escapes should be stripped')
-
- on = js_to_json('\'"\\""\'')
- self.assertEqual(json.loads(on), '"""', msg='Unnecessary quote escape should be escaped')
-
- on = js_to_json('[new Date("spam"), \'("eggs")\']')
- self.assertEqual(json.loads(on), ['spam', '("eggs")'], msg='Date regex should match a single string')
-
- on = js_to_json('[0.077, 7.06, 29.064, 169.0072]')
- self.assertEqual(json.loads(on), [0.077, 7.06, 29.064, 169.0072])
-
- def test_js_to_json_malformed(self):
- self.assertEqual(js_to_json('42a1'), '42"a1"')
- self.assertEqual(js_to_json('42a-1'), '42"a"-1')
- self.assertEqual(js_to_json('{a: `${e("")}`}'), '{"a": "\\"e\\"(\\"\\")"}')
-
- def test_js_to_json_template_literal(self):
- self.assertEqual(js_to_json('`Hello ${name}`', {'name': '"world"'}), '"Hello world"')
- self.assertEqual(js_to_json('`${name}${name}`', {'name': '"X"'}), '"XX"')
- self.assertEqual(js_to_json('`${name}${name}`', {'name': '5'}), '"55"')
- self.assertEqual(js_to_json('`${name}"${name}"`', {'name': '5'}), '"5\\"5\\""')
- self.assertEqual(js_to_json('`${name}`', {}), '"name"')
-
- def test_js_to_json_common_constructors(self):
- self.assertEqual(json.loads(js_to_json('new Map([["a", 5]])')), {'a': 5})
- self.assertEqual(json.loads(js_to_json('Array(5, 10)')), [5, 10])
- self.assertEqual(json.loads(js_to_json('new Array(15,5)')), [15, 5])
- self.assertEqual(json.loads(js_to_json('new Map([Array(5, 10),new Array(15,5)])')), {'5': 10, '15': 5})
- self.assertEqual(json.loads(js_to_json('new Date("123")')), '123')
- self.assertEqual(json.loads(js_to_json('new Date(\'2023-10-19\')')), '2023-10-19')
-
- def test_extract_attributes(self):
- self.assertEqual(extract_attributes(''), {'x': 'y'})
- self.assertEqual(extract_attributes(""), {'x': 'y'})
- self.assertEqual(extract_attributes(''), {'x': 'y'})
- self.assertEqual(extract_attributes(''), {'x': "a 'b' c"})
- self.assertEqual(extract_attributes(''), {'x': 'a "b" c'})
- self.assertEqual(extract_attributes(''), {'x': 'y'})
- self.assertEqual(extract_attributes(''), {'x': 'y'})
- self.assertEqual(extract_attributes(''), {'x': '&'}) # XML
- self.assertEqual(extract_attributes(''), {'x': '"'})
- self.assertEqual(extract_attributes(''), {'x': '£'}) # HTML 3.2
- self.assertEqual(extract_attributes(''), {'x': 'λ'}) # HTML 4.0
- self.assertEqual(extract_attributes(''), {'x': '&foo'})
- self.assertEqual(extract_attributes(''), {'x': "'"})
- self.assertEqual(extract_attributes(''), {'x': '"'})
- self.assertEqual(extract_attributes(''), {'x': None})
- self.assertEqual(extract_attributes(''), {'x': 'y', 'a': None})
- self.assertEqual(extract_attributes(''), {'x': 'y'})
- self.assertEqual(extract_attributes(''), {'y': '2', 'x': '3'})
- self.assertEqual(extract_attributes(''), {'x': 'y'})
- self.assertEqual(extract_attributes(''), {'x': 'y'})
- self.assertEqual(extract_attributes(""), {'x': 'y'})
- self.assertEqual(extract_attributes(''), {'x': '\ny\n'})
- self.assertEqual(extract_attributes(''), {'caps': 'x'}) # Names lowercased
- self.assertEqual(extract_attributes(''), {'x': '2'})
- self.assertEqual(extract_attributes(''), {'x': '2'})
- self.assertEqual(extract_attributes(''), {'_:funny-name1': '1'})
- self.assertEqual(extract_attributes(''), {'x': 'Fáilte 世界 \U0001f600'})
- self.assertEqual(extract_attributes(''), {'x': 'décompose\u0301'})
- # "Narrow" Python builds don't support unicode code points outside BMP.
- try:
- chr(0x10000)
- supports_outside_bmp = True
- except ValueError:
- supports_outside_bmp = False
- if supports_outside_bmp:
- self.assertEqual(extract_attributes(''), {'x': 'Smile \U0001f600!'})
- # Malformed HTML should not break attributes extraction on older Python
- self.assertEqual(extract_attributes(' '), {})
-
- def test_clean_html(self):
- self.assertEqual(clean_html('a:\nb'), 'a: b')
- self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
- self.assertEqual(clean_html('a \xa0b'), 'a\nb')
-
- def test_args_to_str(self):
- self.assertEqual(
- args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
- 'foo ba/r -baz \'2 be\' \'\'' if os.name != 'nt' else 'foo ba/r -baz "2 be" ""',
- )
-
- def test_parse_filesize(self):
- self.assertEqual(parse_filesize(None), None)
- self.assertEqual(parse_filesize(''), None)
- self.assertEqual(parse_filesize('91 B'), 91)
- self.assertEqual(parse_filesize('foobar'), None)
- self.assertEqual(parse_filesize('2 MiB'), 2097152)
- self.assertEqual(parse_filesize('5 GB'), 5000000000)
- self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
- self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
- self.assertEqual(parse_filesize('1,24 KB'), 1240)
- self.assertEqual(parse_filesize('1,24 kb'), 1240)
- self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
-
- def test_parse_count(self):
- self.assertEqual(parse_count(None), None)
- self.assertEqual(parse_count(''), None)
- self.assertEqual(parse_count('0'), 0)
- self.assertEqual(parse_count('1000'), 1000)
- self.assertEqual(parse_count('1.000'), 1000)
- self.assertEqual(parse_count('1.1k'), 1100)
- self.assertEqual(parse_count('1.1 k'), 1100)
- self.assertEqual(parse_count('1,1 k'), 1100)
- self.assertEqual(parse_count('1.1kk'), 1100000)
- self.assertEqual(parse_count('1.1kk '), 1100000)
- self.assertEqual(parse_count('1,1kk'), 1100000)
- self.assertEqual(parse_count('100 views'), 100)
- self.assertEqual(parse_count('1,100 views'), 1100)
- self.assertEqual(parse_count('1.1kk views'), 1100000)
- self.assertEqual(parse_count('10M views'), 10000000)
- self.assertEqual(parse_count('has 10M views'), 10000000)
-
- def test_parse_resolution(self):
- self.assertEqual(parse_resolution(None), {})
- self.assertEqual(parse_resolution(''), {})
- self.assertEqual(parse_resolution(' 1920x1080'), {'width': 1920, 'height': 1080})
- self.assertEqual(parse_resolution('1920×1080 '), {'width': 1920, 'height': 1080})
- self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
- self.assertEqual(parse_resolution('720p'), {'height': 720})
- self.assertEqual(parse_resolution('4k'), {'height': 2160})
- self.assertEqual(parse_resolution('8K'), {'height': 4320})
- self.assertEqual(parse_resolution('pre_1920x1080_post'), {'width': 1920, 'height': 1080})
- self.assertEqual(parse_resolution('ep1x2'), {})
- self.assertEqual(parse_resolution('1920, 1080'), {'width': 1920, 'height': 1080})
- self.assertEqual(parse_resolution('1920w', lenient=True), {'width': 1920})
-
- def test_parse_bitrate(self):
- self.assertEqual(parse_bitrate(None), None)
- self.assertEqual(parse_bitrate(''), None)
- self.assertEqual(parse_bitrate('300kbps'), 300)
- self.assertEqual(parse_bitrate('1500kbps'), 1500)
- self.assertEqual(parse_bitrate('300 kbps'), 300)
-
- def test_version_tuple(self):
- self.assertEqual(version_tuple('1'), (1,))
- self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
- self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
- self.assertEqual(version_tuple('invalid', lenient=True), (-1,))
- self.assertEqual(version_tuple('1.2.3', lenient=True), (1, 2, 3))
- self.assertEqual(version_tuple('12.34-something', lenient=True), (12, 34, -1))
-
- def test_detect_exe_version(self):
- self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
-built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
-configuration: --prefix=/usr --extra-'''), '1.2.1')
- self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
-built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
- self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
-Trying to open render node...
-Success at /dev/dri/renderD128.
-ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
-
- def test_age_restricted(self):
- self.assertFalse(age_restricted(None, 10)) # unrestricted content
- self.assertFalse(age_restricted(1, None)) # unrestricted policy
- self.assertFalse(age_restricted(8, 10))
- self.assertTrue(age_restricted(18, 14))
- self.assertFalse(age_restricted(18, 18))
-
- def test_is_html(self):
- self.assertFalse(is_html(b'\x49\x44\x43\xaaa'))
- self.assertTrue(is_html( # UTF-8 with BOM
- b'\xef\xbb\xbf\xaaa'))
- self.assertTrue(is_html( # UTF-16-LE
- b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00',
- ))
- self.assertTrue(is_html( # UTF-16-BE
- b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4',
- ))
- self.assertTrue(is_html( # UTF-32-BE
- b'\x00\x00\xFE\xFF\x00\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4'))
- self.assertTrue(is_html( # UTF-32-LE
- b'\xFF\xFE\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4\x00\x00\x00'))
-
- def test_render_table(self):
- self.assertEqual(
- render_table(
- ['a', 'empty', 'bcd'],
- [[123, '', 4], [9999, '', 51]]),
- 'a empty bcd\n'
- '123 4\n'
- '9999 51')
-
- self.assertEqual(
- render_table(
- ['a', 'empty', 'bcd'],
- [[123, '', 4], [9999, '', 51]],
- hide_empty=True),
- 'a bcd\n'
- '123 4\n'
- '9999 51')
-
- self.assertEqual(
- render_table(
- ['\ta', 'bcd'],
- [['1\t23', 4], ['\t9999', 51]]),
- ' a bcd\n'
- '1 23 4\n'
- '9999 51')
-
- self.assertEqual(
- render_table(
- ['a', 'bcd'],
- [[123, 4], [9999, 51]],
- delim='-'),
- 'a bcd\n'
- '--------\n'
- '123 4\n'
- '9999 51')
-
- self.assertEqual(
- render_table(
- ['a', 'bcd'],
- [[123, 4], [9999, 51]],
- delim='-', extra_gap=2),
- 'a bcd\n'
- '----------\n'
- '123 4\n'
- '9999 51')
-
- def test_match_str(self):
- # Unary
- self.assertFalse(match_str('xy', {'x': 1200}))
- self.assertTrue(match_str('!xy', {'x': 1200}))
- self.assertTrue(match_str('x', {'x': 1200}))
- self.assertFalse(match_str('!x', {'x': 1200}))
- self.assertTrue(match_str('x', {'x': 0}))
- self.assertTrue(match_str('is_live', {'is_live': True}))
- self.assertFalse(match_str('is_live', {'is_live': False}))
- self.assertFalse(match_str('is_live', {'is_live': None}))
- self.assertFalse(match_str('is_live', {}))
- self.assertFalse(match_str('!is_live', {'is_live': True}))
- self.assertTrue(match_str('!is_live', {'is_live': False}))
- self.assertTrue(match_str('!is_live', {'is_live': None}))
- self.assertTrue(match_str('!is_live', {}))
- self.assertTrue(match_str('title', {'title': 'abc'}))
- self.assertTrue(match_str('title', {'title': ''}))
- self.assertFalse(match_str('!title', {'title': 'abc'}))
- self.assertFalse(match_str('!title', {'title': ''}))
-
- # Numeric
- self.assertFalse(match_str('x>0', {'x': 0}))
- self.assertFalse(match_str('x>0', {}))
- self.assertTrue(match_str('x>?0', {}))
- self.assertTrue(match_str('x>1K', {'x': 1200}))
- self.assertFalse(match_str('x>2K', {'x': 1200}))
- self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
- self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
- self.assertTrue(match_str('x > 1:0:0', {'x': 3700}))
-
- # String
- self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
- self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
- self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
- self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
- self.assertTrue(match_str('y^=foo', {'y': 'foobar42'}))
- self.assertFalse(match_str('y!^=foo', {'y': 'foobar42'}))
- self.assertFalse(match_str('y^=bar', {'y': 'foobar42'}))
- self.assertTrue(match_str('y!^=bar', {'y': 'foobar42'}))
- self.assertRaises(ValueError, match_str, 'x^=42', {'x': 42})
- self.assertTrue(match_str('y*=bar', {'y': 'foobar42'}))
- self.assertFalse(match_str('y!*=bar', {'y': 'foobar42'}))
- self.assertFalse(match_str('y*=baz', {'y': 'foobar42'}))
- self.assertTrue(match_str('y!*=baz', {'y': 'foobar42'}))
- self.assertTrue(match_str('y$=42', {'y': 'foobar42'}))
- self.assertFalse(match_str('y$=43', {'y': 'foobar42'}))
-
- # And
- self.assertFalse(match_str(
- 'like_count > 100 & dislike_count 50 & description',
- {'like_count': 90, 'description': 'foo'}))
- self.assertTrue(match_str(
- 'like_count > 100 & dislike_count 50 & description',
- {'like_count': 190, 'description': 'foo'}))
- self.assertFalse(match_str(
- 'like_count > 100 & dislike_count 50 & description',
- {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
- self.assertFalse(match_str(
- 'like_count > 100 & dislike_count 50 & description',
- {'like_count': 190, 'dislike_count': 10}))
-
- # Regex
- self.assertTrue(match_str(r'x~=\bbar', {'x': 'foo bar'}))
- self.assertFalse(match_str(r'x~=\bbar.+', {'x': 'foo bar'}))
- self.assertFalse(match_str(r'x~=^FOO', {'x': 'foo bar'}))
- self.assertTrue(match_str(r'x~=(?i)^FOO', {'x': 'foo bar'}))
-
- # Quotes
- self.assertTrue(match_str(r'x^="foo"', {'x': 'foo "bar"'}))
- self.assertFalse(match_str(r'x^="foo "', {'x': 'foo "bar"'}))
- self.assertFalse(match_str(r'x$="bar"', {'x': 'foo "bar"'}))
- self.assertTrue(match_str(r'x$=" \"bar\""', {'x': 'foo "bar"'}))
-
- # Escaping &
- self.assertFalse(match_str(r'x=foo & bar', {'x': 'foo & bar'}))
- self.assertTrue(match_str(r'x=foo \& bar', {'x': 'foo & bar'}))
- self.assertTrue(match_str(r'x=foo \& bar & x^=foo', {'x': 'foo & bar'}))
- self.assertTrue(match_str(r'x="foo \& bar" & x^=foo', {'x': 'foo & bar'}))
-
- # Example from docs
- self.assertTrue(match_str(
- r"!is_live & like_count>?100 & description~='(?i)\bcats \& dogs\b'",
- {'description': 'Raining Cats & Dogs'}))
-
- # Incomplete
- self.assertFalse(match_str('id!=foo', {'id': 'foo'}, True))
- self.assertTrue(match_str('x', {'id': 'foo'}, True))
- self.assertTrue(match_str('!x', {'id': 'foo'}, True))
- self.assertFalse(match_str('x', {'id': 'foo'}, False))
-
- def test_parse_dfxp_time_expr(self):
- self.assertEqual(parse_dfxp_time_expr(None), None)
- self.assertEqual(parse_dfxp_time_expr(''), None)
- self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
- self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
- self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
- self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
- self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
-
- def test_dfxp2srt(self):
- dfxp_data = '''
-
-
-
-
The following line contains Chinese characters and special symbols
-
第二行 ♪♪
-
Third Line
-
Lines with invalid timestamps are ignored
-
Ignore, two
-
Ignored, three
-
-
- '''.encode()
- srt_data = '''1
-00:00:00,000 --> 00:00:01,000
-The following line contains Chinese characters and special symbols
-
-2
-00:00:01,000 --> 00:00:02,000
-第二行
-♪♪
-
-3
-00:00:02,000 --> 00:00:03,000
-Third
-Line
-
-'''
- self.assertEqual(dfxp2srt(dfxp_data), srt_data)
-
- dfxp_data_no_default_namespace = b'''
-
-
-
-
- '''
- srt_data = '''1
-00:00:00,000 --> 00:00:01,000
-The first line
-
-'''
- self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
-
- dfxp_data_with_style = b'''
-
-
-
-
-
-
-
-
-
-
-
-
default stylecustom style
-
part 1 part 2
-
line 3 part 3
-
inner style
-
-
- '''
- srt_data = '''1
-00:00:02,080 --> 00:00:05,840
-default stylecustom style
-
-2
-00:00:02,080 --> 00:00:05,840
-part 1
- part 2
-
-3
-00:00:05,840 --> 00:00:09,560
-line 3
-part 3
-
-4
-00:00:09,560 --> 00:00:12,360
-inner
- style
-
-'''
- self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
-
- dfxp_data_non_utf8 = '''
-
-
-
-
- '''.encode('utf-16')
- srt_data = '''1
-00:00:00,000 --> 00:00:01,000
-Line 1
-
-2
-00:00:01,000 --> 00:00:02,000
-第二行
-
-'''
- self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
-
- def test_cli_option(self):
- self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
- self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
- self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
- self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
-
- def test_cli_valueless_option(self):
- self.assertEqual(cli_valueless_option(
- {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
- self.assertEqual(cli_valueless_option(
- {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
- self.assertEqual(cli_valueless_option(
- {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
- self.assertEqual(cli_valueless_option(
- {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
- self.assertEqual(cli_valueless_option(
- {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
- self.assertEqual(cli_valueless_option(
- {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
-
- def test_cli_bool_option(self):
- self.assertEqual(
- cli_bool_option(
- {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
- ['--no-check-certificate', 'true'])
- self.assertEqual(
- cli_bool_option(
- {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
- ['--no-check-certificate=true'])
- self.assertEqual(
- cli_bool_option(
- {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
- ['--check-certificate', 'false'])
- self.assertEqual(
- cli_bool_option(
- {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
- ['--check-certificate=false'])
- self.assertEqual(
- cli_bool_option(
- {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
- ['--check-certificate', 'true'])
- self.assertEqual(
- cli_bool_option(
- {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
- ['--check-certificate=true'])
- self.assertEqual(
- cli_bool_option(
- {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
- [])
-
- def test_ohdave_rsa_encrypt(self):
- N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
- e = 65537
-
- self.assertEqual(
- ohdave_rsa_encrypt(b'aa111222', e, N),
- '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
-
- def test_pkcs1pad(self):
- data = [1, 2, 3]
- padded_data = pkcs1pad(data, 32)
- self.assertEqual(padded_data[:2], [0, 2])
- self.assertEqual(padded_data[28:], [0, 1, 2, 3])
-
- self.assertRaises(ValueError, pkcs1pad, data, 8)
-
- def test_encode_base_n(self):
- self.assertEqual(encode_base_n(0, 30), '0')
- self.assertEqual(encode_base_n(80, 30), '2k')
-
- custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
- self.assertEqual(encode_base_n(0, 30, custom_table), '9')
- self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
-
- self.assertRaises(ValueError, encode_base_n, 0, 70)
- self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
-
- def test_caesar(self):
- self.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
- self.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
- self.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
- self.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
- self.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
- self.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
- self.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
- self.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
-
- def test_rot47(self):
- self.assertEqual(rot47('yt-dlp'), r'JE\5=A')
- self.assertEqual(rot47('YT-DLP'), r'*%\s{!')
-
- def test_urshift(self):
- self.assertEqual(urshift(3, 1), 1)
- self.assertEqual(urshift(-3, 1), 2147483646)
-
- GET_ELEMENT_BY_CLASS_TEST_STRING = '''
- nice
- '''
-
- def test_get_element_by_class(self):
- html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
-
- self.assertEqual(get_element_by_class('foo', html), 'nice')
- self.assertEqual(get_element_by_class('no-such-class', html), None)
-
- def test_get_element_html_by_class(self):
- html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
-
- self.assertEqual(get_element_html_by_class('foo', html), html.strip())
- self.assertEqual(get_element_by_class('no-such-class', html), None)
-
- GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING = '''
- foo
- '''
-
- def test_get_element_by_attribute(self):
- html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
-
- self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
- self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
- self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
-
- html = self.GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
-
- self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
-
- def test_get_element_html_by_attribute(self):
- html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
-
- self.assertEqual(get_element_html_by_attribute('class', 'foo bar', html), html.strip())
- self.assertEqual(get_element_html_by_attribute('class', 'foo', html), None)
- self.assertEqual(get_element_html_by_attribute('class', 'no-such-foo', html), None)
-
- html = self.GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
-
- self.assertEqual(get_element_html_by_attribute('itemprop', 'author', html), html.strip())
-
- GET_ELEMENTS_BY_CLASS_TEST_STRING = '''
- nice also nice
- '''
- GET_ELEMENTS_BY_CLASS_RES = ['nice ', 'also nice ']
-
- def test_get_elements_by_class(self):
- html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
-
- self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
- self.assertEqual(get_elements_by_class('no-such-class', html), [])
-
- def test_get_elements_html_by_class(self):
- html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
-
- self.assertEqual(get_elements_html_by_class('foo', html), self.GET_ELEMENTS_BY_CLASS_RES)
- self.assertEqual(get_elements_html_by_class('no-such-class', html), [])
-
- def test_get_elements_by_attribute(self):
- html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
-
- self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
- self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
- self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
-
- def test_get_elements_html_by_attribute(self):
- html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
-
- self.assertEqual(get_elements_html_by_attribute('class', 'foo bar', html), self.GET_ELEMENTS_BY_CLASS_RES)
- self.assertEqual(get_elements_html_by_attribute('class', 'foo', html), [])
- self.assertEqual(get_elements_html_by_attribute('class', 'no-such-foo', html), [])
-
- def test_get_elements_text_and_html_by_attribute(self):
- html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
-
- self.assertEqual(
- list(get_elements_text_and_html_by_attribute('class', 'foo bar', html)),
- list(zip(['nice', 'also nice'], self.GET_ELEMENTS_BY_CLASS_RES, strict=True)))
- self.assertEqual(list(get_elements_text_and_html_by_attribute('class', 'foo', html)), [])
- self.assertEqual(list(get_elements_text_and_html_by_attribute('class', 'no-such-foo', html)), [])
-
- self.assertEqual(list(get_elements_text_and_html_by_attribute(
- 'class', 'foo', 'nice nice ', tag='a')), [('nice', 'nice ')])
-
- GET_ELEMENT_BY_TAG_TEST_STRING = '''
- random text lorem ipsum
-
- this should be returned
-
this should also be returned
-
- this should also be returned
-
- closing tag above should not trick, so this should also be returned
-
- but this text should not be returned
- '''
- GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML = GET_ELEMENT_BY_TAG_TEST_STRING.strip()[32:276]
- GET_ELEMENT_BY_TAG_RES_OUTERDIV_TEXT = GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML[5:-6]
- GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML = GET_ELEMENT_BY_TAG_TEST_STRING.strip()[78:119]
- GET_ELEMENT_BY_TAG_RES_INNERSPAN_TEXT = GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML[6:-7]
-
- def test_get_element_text_and_html_by_tag(self):
- html = self.GET_ELEMENT_BY_TAG_TEST_STRING
-
- self.assertEqual(
- get_element_text_and_html_by_tag('div', html),
- (self.GET_ELEMENT_BY_TAG_RES_OUTERDIV_TEXT, self.GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML))
- self.assertEqual(
- get_element_text_and_html_by_tag('span', html),
- (self.GET_ELEMENT_BY_TAG_RES_INNERSPAN_TEXT, self.GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML))
- self.assertRaises(compat_HTMLParseError, get_element_text_and_html_by_tag, 'article', html)
-
- def test_iri_to_uri(self):
- self.assertEqual(
- iri_to_uri('https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b'),
- 'https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b') # Same
- self.assertEqual(
- iri_to_uri('https://www.google.com/search?q=Käsesoßenrührlöffel'), # German for cheese sauce stirring spoon
- 'https://www.google.com/search?q=K%C3%A4seso%C3%9Fenr%C3%BChrl%C3%B6ffel')
- self.assertEqual(
- iri_to_uri('https://www.google.com/search?q=lt<+gt>+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#'),
- 'https://www.google.com/search?q=lt%3C+gt%3E+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#')
- self.assertEqual(
- iri_to_uri('http://правозащита38.рф/category/news/'),
- 'http://xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
- self.assertEqual(
- iri_to_uri('http://www.правозащита38.рф/category/news/'),
- 'http://www.xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
- self.assertEqual(
- iri_to_uri('https://i❤.ws/emojidomain/👍👏🤝💪'),
- 'https://xn--i-7iq.ws/emojidomain/%F0%9F%91%8D%F0%9F%91%8F%F0%9F%A4%9D%F0%9F%92%AA')
- self.assertEqual(
- iri_to_uri('http://日本語.jp/'),
- 'http://xn--wgv71a119e.jp/')
- self.assertEqual(
- iri_to_uri('http://导航.中国/'),
- 'http://xn--fet810g.xn--fiqs8s/')
-
- def test_clean_podcast_url(self):
- self.assertEqual(clean_podcast_url('https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW7835899191.mp3'), 'https://traffic.megaphone.fm/HSW7835899191.mp3')
- self.assertEqual(clean_podcast_url('https://play.podtrac.com/npr-344098539/edge1.pod.npr.org/anon.npr-podcasts/podcast/npr/waitwait/2020/10/20201003_waitwait_wwdtmpodcast201003-015621a5-f035-4eca-a9a1-7c118d90bc3c.mp3'), 'https://edge1.pod.npr.org/anon.npr-podcasts/podcast/npr/waitwait/2020/10/20201003_waitwait_wwdtmpodcast201003-015621a5-f035-4eca-a9a1-7c118d90bc3c.mp3')
- self.assertEqual(clean_podcast_url('https://pdst.fm/e/2.gum.fm/chtbl.com/track/chrt.fm/track/34D33/pscrb.fm/rss/p/traffic.megaphone.fm/ITLLC7765286967.mp3?updated=1687282661'), 'https://traffic.megaphone.fm/ITLLC7765286967.mp3?updated=1687282661')
- self.assertEqual(clean_podcast_url('https://pdst.fm/e/https://mgln.ai/e/441/www.buzzsprout.com/1121972/13019085-ep-252-the-deep-life-stack.mp3'), 'https://www.buzzsprout.com/1121972/13019085-ep-252-the-deep-life-stack.mp3')
-
- def test_LazyList(self):
- it = list(range(10))
-
- self.assertEqual(list(LazyList(it)), it)
- self.assertEqual(LazyList(it).exhaust(), it)
- self.assertEqual(LazyList(it)[5], it[5])
-
- self.assertEqual(LazyList(it)[5:], it[5:])
- self.assertEqual(LazyList(it)[:5], it[:5])
- self.assertEqual(LazyList(it)[::2], it[::2])
- self.assertEqual(LazyList(it)[1::2], it[1::2])
- self.assertEqual(LazyList(it)[5::-1], it[5::-1])
- self.assertEqual(LazyList(it)[6:2:-2], it[6:2:-2])
- self.assertEqual(LazyList(it)[::-1], it[::-1])
-
- self.assertTrue(LazyList(it))
- self.assertFalse(LazyList(range(0)))
- self.assertEqual(len(LazyList(it)), len(it))
- self.assertEqual(repr(LazyList(it)), repr(it))
- self.assertEqual(str(LazyList(it)), str(it))
-
- self.assertEqual(list(LazyList(it, reverse=True)), it[::-1])
- self.assertEqual(list(reversed(LazyList(it))[::-1]), it)
- self.assertEqual(list(reversed(LazyList(it))[1:3:7]), it[::-1][1:3:7])
-
- def test_LazyList_laziness(self):
-
- def test(ll, idx, val, cache):
- self.assertEqual(ll[idx], val)
- self.assertEqual(ll._cache, list(cache))
-
- ll = LazyList(range(10))
- test(ll, 0, 0, range(1))
- test(ll, 5, 5, range(6))
- test(ll, -3, 7, range(10))
-
- ll = LazyList(range(10), reverse=True)
- test(ll, -1, 0, range(1))
- test(ll, 3, 6, range(10))
-
- ll = LazyList(itertools.count())
- test(ll, 10, 10, range(11))
- ll = reversed(ll)
- test(ll, -15, 14, range(15))
-
- def test_format_bytes(self):
- self.assertEqual(format_bytes(0), '0.00B')
- self.assertEqual(format_bytes(1000), '1000.00B')
- self.assertEqual(format_bytes(1024), '1.00KiB')
- self.assertEqual(format_bytes(1024**2), '1.00MiB')
- self.assertEqual(format_bytes(1024**3), '1.00GiB')
- self.assertEqual(format_bytes(1024**4), '1.00TiB')
- self.assertEqual(format_bytes(1024**5), '1.00PiB')
- self.assertEqual(format_bytes(1024**6), '1.00EiB')
- self.assertEqual(format_bytes(1024**7), '1.00ZiB')
- self.assertEqual(format_bytes(1024**8), '1.00YiB')
- self.assertEqual(format_bytes(1024**9), '1024.00YiB')
-
- def test_hide_login_info(self):
- self.assertEqual(Config.hide_login_info(['-u', 'foo', '-p', 'bar']),
- ['-u', 'PRIVATE', '-p', 'PRIVATE'])
- self.assertEqual(Config.hide_login_info(['-u']), ['-u'])
- self.assertEqual(Config.hide_login_info(['-u', 'foo', '-u', 'bar']),
- ['-u', 'PRIVATE', '-u', 'PRIVATE'])
- self.assertEqual(Config.hide_login_info(['--username=foo']),
- ['--username=PRIVATE'])
-
- def test_locked_file(self):
- TEXT = 'test_locked_file\n'
- FILE = 'test_locked_file.ytdl'
- MODES = 'war' # Order is important
-
- try:
- for lock_mode in MODES:
- with locked_file(FILE, lock_mode, False) as f:
- if lock_mode == 'r':
- self.assertEqual(f.read(), TEXT * 2, 'Wrong file content')
- else:
- f.write(TEXT)
- for test_mode in MODES:
- testing_write = test_mode != 'r'
- try:
- with locked_file(FILE, test_mode, False):
- pass
- except (BlockingIOError, PermissionError):
- if not testing_write: # FIXME: blocked read access
- print(f'Known issue: Exclusive lock ({lock_mode}) blocks read access ({test_mode})')
- continue
- self.assertTrue(testing_write, f'{test_mode} is blocked by {lock_mode}')
- else:
- self.assertFalse(testing_write, f'{test_mode} is not blocked by {lock_mode}')
- finally:
- with contextlib.suppress(OSError):
- os.remove(FILE)
-
- def test_determine_file_encoding(self):
- self.assertEqual(determine_file_encoding(b''), (None, 0))
- self.assertEqual(determine_file_encoding(b'--verbose -x --audio-format mkv\n'), (None, 0))
-
- self.assertEqual(determine_file_encoding(b'\xef\xbb\xbf'), ('utf-8', 3))
- self.assertEqual(determine_file_encoding(b'\x00\x00\xfe\xff'), ('utf-32-be', 4))
- self.assertEqual(determine_file_encoding(b'\xff\xfe'), ('utf-16-le', 2))
-
- self.assertEqual(determine_file_encoding(b'\xff\xfe# coding: utf-8\n--verbose'), ('utf-16-le', 2))
-
- self.assertEqual(determine_file_encoding(b'# coding: utf-8\n--verbose'), ('utf-8', 0))
- self.assertEqual(determine_file_encoding(b'# coding: someencodinghere-12345\n--verbose'), ('someencodinghere-12345', 0))
-
- self.assertEqual(determine_file_encoding(b'#coding:utf-8\n--verbose'), ('utf-8', 0))
- self.assertEqual(determine_file_encoding(b'# coding: utf-8 \r\n--verbose'), ('utf-8', 0))
-
- self.assertEqual(determine_file_encoding('# coding: utf-32-be'.encode('utf-32-be')), ('utf-32-be', 0))
- self.assertEqual(determine_file_encoding('# coding: utf-16-le'.encode('utf-16-le')), ('utf-16-le', 0))
-
- def test_get_compatible_ext(self):
- self.assertEqual(get_compatible_ext(
- vcodecs=[None], acodecs=[None, None], vexts=['mp4'], aexts=['m4a', 'm4a']), 'mkv')
- self.assertEqual(get_compatible_ext(
- vcodecs=[None], acodecs=[None], vexts=['flv'], aexts=['flv']), 'flv')
-
- self.assertEqual(get_compatible_ext(
- vcodecs=[None], acodecs=[None], vexts=['mp4'], aexts=['m4a']), 'mp4')
- self.assertEqual(get_compatible_ext(
- vcodecs=[None], acodecs=[None], vexts=['mp4'], aexts=['webm']), 'mkv')
- self.assertEqual(get_compatible_ext(
- vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['m4a']), 'mkv')
- self.assertEqual(get_compatible_ext(
- vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['webm']), 'webm')
- self.assertEqual(get_compatible_ext(
- vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['weba']), 'webm')
-
- self.assertEqual(get_compatible_ext(
- vcodecs=['h264'], acodecs=['mp4a'], vexts=['mov'], aexts=['m4a']), 'mp4')
- self.assertEqual(get_compatible_ext(
- vcodecs=['av01.0.12M.08'], acodecs=['opus'], vexts=['mp4'], aexts=['webm']), 'webm')
-
- self.assertEqual(get_compatible_ext(
- vcodecs=['vp9'], acodecs=['opus'], vexts=['webm'], aexts=['webm'], preferences=['flv', 'mp4']), 'mp4')
- self.assertEqual(get_compatible_ext(
- vcodecs=['av1'], acodecs=['mp4a'], vexts=['webm'], aexts=['m4a'], preferences=('webm', 'mkv')), 'mkv')
-
- def test_try_call(self):
- def total(*x, **kwargs):
- return sum(x) + sum(kwargs.values())
-
- self.assertEqual(try_call(None), None,
- msg='not a fn should give None')
- self.assertEqual(try_call(lambda: 1), 1,
- msg='int fn with no expected_type should give int')
- self.assertEqual(try_call(lambda: 1, expected_type=int), 1,
- msg='int fn with expected_type int should give int')
- self.assertEqual(try_call(lambda: 1, expected_type=dict), None,
- msg='int fn with wrong expected_type should give None')
- self.assertEqual(try_call(total, args=(0, 1, 0), expected_type=int), 1,
- msg='fn should accept arglist')
- self.assertEqual(try_call(total, kwargs={'a': 0, 'b': 1, 'c': 0}, expected_type=int), 1,
- msg='fn should accept kwargs')
- self.assertEqual(try_call(lambda: 1, expected_type=dict), None,
- msg='int fn with no expected_type should give None')
- self.assertEqual(try_call(lambda x: {}, total, args=(42, ), expected_type=int), 42,
- msg='expect first int result with expected_type int')
-
- def test_variadic(self):
- self.assertEqual(variadic(None), (None, ))
- self.assertEqual(variadic('spam'), ('spam', ))
- self.assertEqual(variadic('spam', allowed_types=dict), 'spam')
- with warnings.catch_warnings():
- warnings.simplefilter('ignore')
- self.assertEqual(variadic('spam', allowed_types=[dict]), 'spam')
-
- def test_http_header_dict(self):
- headers = HTTPHeaderDict()
- headers['ytdl-test'] = b'0'
- self.assertEqual(list(headers.items()), [('Ytdl-Test', '0')])
- self.assertEqual(list(headers.sensitive().items()), [('ytdl-test', '0')])
- headers['ytdl-test'] = 1
- self.assertEqual(list(headers.items()), [('Ytdl-Test', '1')])
- self.assertEqual(list(headers.sensitive().items()), [('ytdl-test', '1')])
- headers['Ytdl-test'] = '2'
- self.assertEqual(list(headers.items()), [('Ytdl-Test', '2')])
- self.assertEqual(list(headers.sensitive().items()), [('Ytdl-test', '2')])
- self.assertTrue('ytDl-Test' in headers)
- self.assertEqual(str(headers), str(dict(headers)))
- self.assertEqual(repr(headers), str(dict(headers)))
-
- headers.update({'X-dlp': 'data'})
- self.assertEqual(set(headers.items()), {('Ytdl-Test', '2'), ('X-Dlp', 'data')})
- self.assertEqual(set(headers.sensitive().items()), {('Ytdl-test', '2'), ('X-dlp', 'data')})
- self.assertEqual(dict(headers), {'Ytdl-Test': '2', 'X-Dlp': 'data'})
- self.assertEqual(len(headers), 2)
- self.assertEqual(headers.copy(), headers)
- headers2 = HTTPHeaderDict({'X-dlp': 'data3'}, headers, **{'X-dlP': 'data2'})
- self.assertEqual(set(headers2.items()), {('Ytdl-Test', '2'), ('X-Dlp', 'data2')})
- self.assertEqual(set(headers2.sensitive().items()), {('Ytdl-test', '2'), ('X-dlP', 'data2')})
- self.assertEqual(len(headers2), 2)
- headers2.clear()
- self.assertEqual(len(headers2), 0)
-
- # ensure we prefer latter headers
- headers3 = HTTPHeaderDict({'Ytdl-TeSt': 1}, {'Ytdl-test': 2})
- self.assertEqual(set(headers3.items()), {('Ytdl-Test', '2')})
- self.assertEqual(set(headers3.sensitive().items()), {('Ytdl-test', '2')})
- del headers3['ytdl-tesT']
- self.assertEqual(dict(headers3), {})
-
- headers4 = HTTPHeaderDict({'ytdl-test': 'data;'})
- self.assertEqual(set(headers4.items()), {('Ytdl-Test', 'data;')})
- self.assertEqual(set(headers4.sensitive().items()), {('ytdl-test', 'data;')})
-
- # common mistake: strip whitespace from values
- # https://github.com/yt-dlp/yt-dlp/issues/8729
- headers5 = HTTPHeaderDict({'ytdl-test': ' data; '})
- self.assertEqual(set(headers5.items()), {('Ytdl-Test', 'data;')})
- self.assertEqual(set(headers5.sensitive().items()), {('ytdl-test', 'data;')})
-
- # test if picklable
- headers6 = HTTPHeaderDict(a=1, b=2)
- self.assertEqual(pickle.loads(pickle.dumps(headers6)), headers6)
-
- def test_extract_basic_auth(self):
- assert extract_basic_auth('http://:foo.bar') == ('http://:foo.bar', None)
- assert extract_basic_auth('http://foo.bar') == ('http://foo.bar', None)
- assert extract_basic_auth('http://@foo.bar') == ('http://foo.bar', 'Basic Og==')
- assert extract_basic_auth('http://:pass@foo.bar') == ('http://foo.bar', 'Basic OnBhc3M=')
- assert extract_basic_auth('http://user:@foo.bar') == ('http://foo.bar', 'Basic dXNlcjo=')
- assert extract_basic_auth('http://user:pass@foo.bar') == ('http://foo.bar', 'Basic dXNlcjpwYXNz')
-
- @unittest.skipUnless(os.name == 'nt', 'Only relevant on Windows')
- def test_windows_escaping(self):
- tests = [
- 'test"&',
- '%CMDCMDLINE:~-1%&',
- 'a\nb',
- '"',
- '\\',
- '!',
- '^!',
- 'a \\ b',
- 'a \\" b',
- 'a \\ b\\',
- # We replace \r with \n
- ('a\r\ra', 'a\n\na'),
- ]
-
- def run_shell(args):
- stdout, stderr, error = Popen.run(
- args, text=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- assert not stderr
- assert not error
- return stdout
-
- for argument in tests:
- if isinstance(argument, str):
- expected = argument
- else:
- argument, expected = argument
-
- args = [sys.executable, '-c', 'import sys; print(end=sys.argv[1])', argument, 'end']
- assert run_shell(args) == expected
- assert run_shell(shell_quote(args, shell=True)) == expected
-
- def test_partial_application(self):
- assert callable(int_or_none(scale=10)), 'missing positional parameter should apply partially'
- assert int_or_none(10, scale=0.1) == 100, 'positionally passed argument should call function'
- assert int_or_none(v=10) == 10, 'keyword passed positional should call function'
- assert int_or_none(scale=0.1)(10) == 100, 'call after partial application should call the function'
-
- _JWT_KEY = '12345678'
- _JWT_HEADERS_1 = {'a': 'b'}
- _JWT_HEADERS_2 = {'typ': 'JWT', 'alg': 'HS256'}
- _JWT_HEADERS_3 = {'typ': 'JWT', 'alg': 'RS256'}
- _JWT_HEADERS_4 = {'c': 'd', 'alg': 'ES256'}
- _JWT_DECODED = {
- 'foo': 'bar',
- 'qux': 'baz',
- }
- _JWT_SIMPLE = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJxdXgiOiJiYXoifQ.fKojvTWqnjNTbsdoDTmYNc4tgYAG3h_SWRzM77iLH0U'
- _JWT_WITH_EXTRA_HEADERS = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImEiOiJiIn0.eyJmb28iOiJiYXIiLCJxdXgiOiJiYXoifQ.Ia91-B77yasfYM7jsB6iVKLew-3rO6ITjNmjWUVXCvQ'
- _JWT_WITH_REORDERED_HEADERS = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJxdXgiOiJiYXoifQ.slg-7COta5VOfB36p3tqV4MGPV6TTA_ouGnD48UEVq4'
- _JWT_WITH_REORDERED_HEADERS_AND_RS256_ALG = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIiLCJxdXgiOiJiYXoifQ.XWp496oVgQnoits0OOocutdjxoaQwn4GUWWxUsKENPM'
- _JWT_WITH_EXTRA_HEADERS_AND_ES256_ALG = 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImMiOiJkIn0.eyJmb28iOiJiYXIiLCJxdXgiOiJiYXoifQ.oM_tc7IkfrwkoRh43rFFE1wOi3J3mQGwx7_lMyKQqDg'
-
- def test_jwt_encode(self):
- def test(expected, headers={}):
- self.assertEqual(jwt_encode(self._JWT_DECODED, self._JWT_KEY, headers=headers), expected)
-
- test(self._JWT_SIMPLE)
- test(self._JWT_WITH_EXTRA_HEADERS, headers=self._JWT_HEADERS_1)
- test(self._JWT_WITH_REORDERED_HEADERS, headers=self._JWT_HEADERS_2)
- test(self._JWT_WITH_REORDERED_HEADERS_AND_RS256_ALG, headers=self._JWT_HEADERS_3)
- test(self._JWT_WITH_EXTRA_HEADERS_AND_ES256_ALG, headers=self._JWT_HEADERS_4)
-
- def test_jwt_decode_hs256(self):
- def test(inp):
- self.assertEqual(jwt_decode_hs256(inp), self._JWT_DECODED)
-
- test(self._JWT_SIMPLE)
- test(self._JWT_WITH_EXTRA_HEADERS)
- test(self._JWT_WITH_REORDERED_HEADERS)
- test(self._JWT_WITH_REORDERED_HEADERS_AND_RS256_ALG)
- test(self._JWT_WITH_EXTRA_HEADERS_AND_ES256_ALG)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_verbose_output.py b/test/test_verbose_output.py
deleted file mode 100644
index e9559d33b..000000000
--- a/test/test_verbose_output.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-import subprocess
-
-rootDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-
-
-class TestVerboseOutput(unittest.TestCase):
- def test_private_info_arg(self):
- outp = subprocess.Popen(
- [
- sys.executable, 'yt_dlp/__main__.py',
- '-v', '--ignore-config',
- '--username', 'johnsmith@gmail.com',
- '--password', 'my_secret_password',
- ], cwd=rootDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- _, serr = outp.communicate()
- self.assertTrue(b'--username' in serr)
- self.assertTrue(b'johnsmith' not in serr)
- self.assertTrue(b'--password' in serr)
- self.assertTrue(b'my_secret_password' not in serr)
-
- def test_private_info_shortarg(self):
- outp = subprocess.Popen(
- [
- sys.executable, 'yt_dlp/__main__.py',
- '-v', '--ignore-config',
- '-u', 'johnsmith@gmail.com',
- '-p', 'my_secret_password',
- ], cwd=rootDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- _, serr = outp.communicate()
- self.assertTrue(b'-u' in serr)
- self.assertTrue(b'johnsmith' not in serr)
- self.assertTrue(b'-p' in serr)
- self.assertTrue(b'my_secret_password' not in serr)
-
- def test_private_info_eq(self):
- outp = subprocess.Popen(
- [
- sys.executable, 'yt_dlp/__main__.py',
- '-v', '--ignore-config',
- '--username=johnsmith@gmail.com',
- '--password=my_secret_password',
- ], cwd=rootDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- _, serr = outp.communicate()
- self.assertTrue(b'--username' in serr)
- self.assertTrue(b'johnsmith' not in serr)
- self.assertTrue(b'--password' in serr)
- self.assertTrue(b'my_secret_password' not in serr)
-
- def test_private_info_shortarg_eq(self):
- outp = subprocess.Popen(
- [
- sys.executable, 'yt_dlp/__main__.py',
- '-v', '--ignore-config',
- '-u=johnsmith@gmail.com',
- '-p=my_secret_password',
- ], cwd=rootDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- _, serr = outp.communicate()
- self.assertTrue(b'-u' in serr)
- self.assertTrue(b'johnsmith' not in serr)
- self.assertTrue(b'-p' in serr)
- self.assertTrue(b'my_secret_password' not in serr)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_websockets.py b/test/test_websockets.py
deleted file mode 100644
index caa026f44..000000000
--- a/test/test_websockets.py
+++ /dev/null
@@ -1,517 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import time
-
-import pytest
-
-from test.helper import verify_address_availability
-from yt_dlp.networking.common import Features, DEFAULT_TIMEOUT
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-import http.client
-import http.cookiejar
-import http.server
-import json
-import random
-import ssl
-import threading
-
-from yt_dlp import socks
-from yt_dlp.cookies import YoutubeDLCookieJar
-from yt_dlp.dependencies import websockets
-from yt_dlp.networking import Request
-from yt_dlp.networking.exceptions import (
- CertificateVerifyError,
- HTTPError,
- ProxyError,
- RequestError,
- SSLError,
- TransportError,
-)
-from yt_dlp.utils.traversal import traverse_obj
-from yt_dlp.utils.networking import HTTPHeaderDict
-
-TEST_DIR = os.path.dirname(os.path.abspath(__file__))
-
-
-pytestmark = pytest.mark.handler_flaky(
- 'Websockets',
- os.name == 'nt' or sys.implementation.name == 'pypy',
- reason='segfaults',
-)
-
-
-def websocket_handler(websocket):
- for message in websocket:
- if isinstance(message, bytes):
- if message == b'bytes':
- return websocket.send('2')
- elif isinstance(message, str):
- if message == 'headers':
- return websocket.send(json.dumps(dict(websocket.request.headers.raw_items())))
- elif message == 'path':
- return websocket.send(websocket.request.path)
- elif message == 'source_address':
- return websocket.send(websocket.remote_address[0])
- elif message == 'str':
- return websocket.send('1')
- return websocket.send(message)
-
-
-def process_request(self, request):
- if request.path.startswith('/gen_'):
- status = http.HTTPStatus(int(request.path[5:]))
- if 300 <= status.value <= 300:
- return websockets.http11.Response(
- status.value, status.phrase, websockets.datastructures.Headers([('Location', '/')]), b'')
- return self.protocol.reject(status.value, status.phrase)
- elif request.path.startswith('/get_cookie'):
- response = self.protocol.accept(request)
- response.headers['Set-Cookie'] = 'test=ytdlp'
- return response
- return self.protocol.accept(request)
-
-
-def create_websocket_server(**ws_kwargs):
- import websockets.sync.server
- wsd = websockets.sync.server.serve(
- websocket_handler, '127.0.0.1', 0,
- process_request=process_request, open_timeout=2, **ws_kwargs)
- ws_port = wsd.socket.getsockname()[1]
- ws_server_thread = threading.Thread(target=wsd.serve_forever)
- ws_server_thread.daemon = True
- ws_server_thread.start()
- return ws_server_thread, ws_port
-
-
-def create_ws_websocket_server():
- return create_websocket_server()
-
-
-def create_wss_websocket_server():
- certfn = os.path.join(TEST_DIR, 'testcert.pem')
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.load_cert_chain(certfn, None)
- return create_websocket_server(ssl=sslctx)
-
-
-MTLS_CERT_DIR = os.path.join(TEST_DIR, 'testdata', 'certificate')
-
-
-def create_mtls_wss_websocket_server():
- certfn = os.path.join(TEST_DIR, 'testcert.pem')
- cacertfn = os.path.join(MTLS_CERT_DIR, 'ca.crt')
-
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.verify_mode = ssl.CERT_REQUIRED
- sslctx.load_verify_locations(cafile=cacertfn)
- sslctx.load_cert_chain(certfn, None)
-
- return create_websocket_server(ssl=sslctx)
-
-
-def create_legacy_wss_websocket_server():
- certfn = os.path.join(TEST_DIR, 'testcert.pem')
- sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
- sslctx.maximum_version = ssl.TLSVersion.TLSv1_2
- sslctx.set_ciphers('SHA1:AESCCM:aDSS:eNULL:aNULL')
- sslctx.load_cert_chain(certfn, None)
- return create_websocket_server(ssl=sslctx)
-
-
-def ws_validate_and_send(rh, req):
- rh.validate(req)
- max_tries = 3
- for i in range(max_tries):
- try:
- return rh.send(req)
- except TransportError as e:
- if i < (max_tries - 1) and 'connection closed during handshake' in str(e):
- # websockets server sometimes hangs on new connections
- continue
- raise
-
-
-@pytest.mark.skipif(not websockets, reason='websockets must be installed to test websocket request handlers')
-@pytest.mark.parametrize('handler', ['Websockets'], indirect=True)
-class TestWebsSocketRequestHandlerConformance:
- @classmethod
- def setup_class(cls):
- cls.ws_thread, cls.ws_port = create_ws_websocket_server()
- cls.ws_base_url = f'ws://127.0.0.1:{cls.ws_port}'
-
- cls.wss_thread, cls.wss_port = create_wss_websocket_server()
- cls.wss_base_url = f'wss://127.0.0.1:{cls.wss_port}'
-
- cls.bad_wss_thread, cls.bad_wss_port = create_websocket_server(ssl=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER))
- cls.bad_wss_host = f'wss://127.0.0.1:{cls.bad_wss_port}'
-
- cls.mtls_wss_thread, cls.mtls_wss_port = create_mtls_wss_websocket_server()
- cls.mtls_wss_base_url = f'wss://127.0.0.1:{cls.mtls_wss_port}'
-
- cls.legacy_wss_thread, cls.legacy_wss_port = create_legacy_wss_websocket_server()
- cls.legacy_wss_host = f'wss://127.0.0.1:{cls.legacy_wss_port}'
-
- def test_basic_websockets(self, handler):
- with handler() as rh:
- ws = ws_validate_and_send(rh, Request(self.ws_base_url))
- assert 'upgrade' in ws.headers
- assert ws.status == 101
- ws.send('foo')
- assert ws.recv() == 'foo'
- ws.close()
-
- # https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
- @pytest.mark.parametrize('msg,opcode', [('str', 1), (b'bytes', 2)])
- def test_send_types(self, handler, msg, opcode):
- with handler() as rh:
- ws = ws_validate_and_send(rh, Request(self.ws_base_url))
- ws.send(msg)
- assert int(ws.recv()) == opcode
- ws.close()
-
- def test_verify_cert(self, handler):
- with handler() as rh:
- with pytest.raises(CertificateVerifyError):
- ws_validate_and_send(rh, Request(self.wss_base_url))
-
- with handler(verify=False) as rh:
- ws = ws_validate_and_send(rh, Request(self.wss_base_url))
- assert ws.status == 101
- ws.close()
-
- def test_ssl_error(self, handler):
- with handler(verify=False) as rh:
- with pytest.raises(SSLError, match=r'ssl(?:v3|/tls) alert handshake failure') as exc_info:
- ws_validate_and_send(rh, Request(self.bad_wss_host))
- assert not issubclass(exc_info.type, CertificateVerifyError)
-
- def test_legacy_ssl_extension(self, handler):
- with handler(verify=False) as rh:
- ws = ws_validate_and_send(rh, Request(self.legacy_wss_host, extensions={'legacy_ssl': True}))
- assert ws.status == 101
- ws.close()
-
- # Ensure only applies to request extension
- with pytest.raises(SSLError):
- ws_validate_and_send(rh, Request(self.legacy_wss_host))
-
- def test_legacy_ssl_support(self, handler):
- with handler(verify=False, legacy_ssl_support=True) as rh:
- ws = ws_validate_and_send(rh, Request(self.legacy_wss_host))
- assert ws.status == 101
- ws.close()
-
- @pytest.mark.parametrize('path,expected', [
- # Unicode characters should be encoded with uppercase percent-encoding
- ('/中文', '/%E4%B8%AD%E6%96%87'),
- # don't normalize existing percent encodings
- ('/%c7%9f', '/%c7%9f'),
- ])
- def test_percent_encode(self, handler, path, expected):
- with handler() as rh:
- ws = ws_validate_and_send(rh, Request(f'{self.ws_base_url}{path}'))
- ws.send('path')
- assert ws.recv() == expected
- assert ws.status == 101
- ws.close()
-
- def test_remove_dot_segments(self, handler):
- with handler() as rh:
- # This isn't a comprehensive test,
- # but it should be enough to check whether the handler is removing dot segments
- ws = ws_validate_and_send(rh, Request(f'{self.ws_base_url}/a/b/./../../test'))
- assert ws.status == 101
- ws.send('path')
- assert ws.recv() == '/test'
- ws.close()
-
- # We are restricted to known HTTP status codes in http.HTTPStatus
- # Redirects are not supported for websockets
- @pytest.mark.parametrize('status', (200, 204, 301, 302, 303, 400, 500, 511))
- def test_raise_http_error(self, handler, status):
- with handler() as rh:
- with pytest.raises(HTTPError) as exc_info:
- ws_validate_and_send(rh, Request(f'{self.ws_base_url}/gen_{status}'))
- assert exc_info.value.status == status
-
- @pytest.mark.parametrize('params,extensions', [
- ({'timeout': sys.float_info.min}, {}),
- ({}, {'timeout': sys.float_info.min}),
- ])
- def test_read_timeout(self, handler, params, extensions):
- with handler(**params) as rh:
- with pytest.raises(TransportError):
- ws_validate_and_send(rh, Request(self.ws_base_url, extensions=extensions))
-
- def test_connect_timeout(self, handler):
- # nothing should be listening on this port
- connect_timeout_url = 'ws://10.255.255.255'
- with handler(timeout=0.01) as rh, pytest.raises(TransportError):
- now = time.time()
- ws_validate_and_send(rh, Request(connect_timeout_url))
- assert time.time() - now < DEFAULT_TIMEOUT
-
- # Per request timeout, should override handler timeout
- request = Request(connect_timeout_url, extensions={'timeout': 0.01})
- with handler() as rh, pytest.raises(TransportError):
- now = time.time()
- ws_validate_and_send(rh, request)
- assert time.time() - now < DEFAULT_TIMEOUT
-
- def test_cookies(self, handler):
- cookiejar = YoutubeDLCookieJar()
- cookiejar.set_cookie(http.cookiejar.Cookie(
- version=0, name='test', value='ytdlp', port=None, port_specified=False,
- domain='127.0.0.1', domain_specified=True, domain_initial_dot=False, path='/',
- path_specified=True, secure=False, expires=None, discard=False, comment=None,
- comment_url=None, rest={}))
-
- with handler(cookiejar=cookiejar) as rh:
- ws = ws_validate_and_send(rh, Request(self.ws_base_url))
- ws.send('headers')
- assert HTTPHeaderDict(json.loads(ws.recv()))['cookie'] == 'test=ytdlp'
- ws.close()
-
- with handler() as rh:
- ws = ws_validate_and_send(rh, Request(self.ws_base_url))
- ws.send('headers')
- assert 'cookie' not in HTTPHeaderDict(json.loads(ws.recv()))
- ws.close()
-
- ws = ws_validate_and_send(rh, Request(self.ws_base_url, extensions={'cookiejar': cookiejar}))
- ws.send('headers')
- assert HTTPHeaderDict(json.loads(ws.recv()))['cookie'] == 'test=ytdlp'
- ws.close()
-
- @pytest.mark.skip_handler('Websockets', 'Set-Cookie not supported by websockets')
- def test_cookie_sync_only_cookiejar(self, handler):
- # Ensure that cookies are ONLY being handled by the cookiejar
- with handler() as rh:
- ws_validate_and_send(rh, Request(f'{self.ws_base_url}/get_cookie', extensions={'cookiejar': YoutubeDLCookieJar()}))
- ws = ws_validate_and_send(rh, Request(self.ws_base_url, extensions={'cookiejar': YoutubeDLCookieJar()}))
- ws.send('headers')
- assert 'cookie' not in HTTPHeaderDict(json.loads(ws.recv()))
- ws.close()
-
- @pytest.mark.skip_handler('Websockets', 'Set-Cookie not supported by websockets')
- def test_cookie_sync_delete_cookie(self, handler):
- # Ensure that cookies are ONLY being handled by the cookiejar
- cookiejar = YoutubeDLCookieJar()
- with handler(verbose=True, cookiejar=cookiejar) as rh:
- ws_validate_and_send(rh, Request(f'{self.ws_base_url}/get_cookie'))
- ws = ws_validate_and_send(rh, Request(self.ws_base_url))
- ws.send('headers')
- assert HTTPHeaderDict(json.loads(ws.recv()))['cookie'] == 'test=ytdlp'
- ws.close()
- cookiejar.clear_session_cookies()
- ws = ws_validate_and_send(rh, Request(self.ws_base_url))
- ws.send('headers')
- assert 'cookie' not in HTTPHeaderDict(json.loads(ws.recv()))
- ws.close()
-
- def test_source_address(self, handler):
- source_address = f'127.0.0.{random.randint(5, 255)}'
- verify_address_availability(source_address)
- with handler(source_address=source_address) as rh:
- ws = ws_validate_and_send(rh, Request(self.ws_base_url))
- ws.send('source_address')
- assert source_address == ws.recv()
- ws.close()
-
- def test_response_url(self, handler):
- with handler() as rh:
- url = f'{self.ws_base_url}/something'
- ws = ws_validate_and_send(rh, Request(url))
- assert ws.url == url
- ws.close()
-
- def test_request_headers(self, handler):
- with handler(headers=HTTPHeaderDict({'test1': 'test', 'test2': 'test2'})) as rh:
- # Global Headers
- ws = ws_validate_and_send(rh, Request(self.ws_base_url))
- ws.send('headers')
- headers = HTTPHeaderDict(json.loads(ws.recv()))
- assert headers['test1'] == 'test'
- ws.close()
-
- # Per request headers, merged with global
- ws = ws_validate_and_send(rh, Request(
- self.ws_base_url, headers={'test2': 'changed', 'test3': 'test3'}))
- ws.send('headers')
- headers = HTTPHeaderDict(json.loads(ws.recv()))
- assert headers['test1'] == 'test'
- assert headers['test2'] == 'changed'
- assert headers['test3'] == 'test3'
- ws.close()
-
- def test_keep_header_casing(self, handler):
- with handler(headers=HTTPHeaderDict({'x-TeSt1': 'test'})) as rh:
- ws = ws_validate_and_send(rh, Request(self.ws_base_url, headers={'x-TeSt2': 'test'}, extensions={'keep_header_casing': True}))
- ws.send('headers')
- headers = json.loads(ws.recv())
- assert 'x-TeSt1' in headers
- assert 'x-TeSt2' in headers
-
- @pytest.mark.parametrize('client_cert', (
- {'client_certificate': os.path.join(MTLS_CERT_DIR, 'clientwithkey.crt')},
- {
- 'client_certificate': os.path.join(MTLS_CERT_DIR, 'client.crt'),
- 'client_certificate_key': os.path.join(MTLS_CERT_DIR, 'client.key'),
- },
- {
- 'client_certificate': os.path.join(MTLS_CERT_DIR, 'clientwithencryptedkey.crt'),
- 'client_certificate_password': 'foobar',
- },
- {
- 'client_certificate': os.path.join(MTLS_CERT_DIR, 'client.crt'),
- 'client_certificate_key': os.path.join(MTLS_CERT_DIR, 'clientencrypted.key'),
- 'client_certificate_password': 'foobar',
- },
- ))
- def test_mtls(self, handler, client_cert):
- with handler(
- # Disable client-side validation of unacceptable self-signed testcert.pem
- # The test is of a check on the server side, so unaffected
- verify=False,
- client_cert=client_cert,
- ) as rh:
- ws_validate_and_send(rh, Request(self.mtls_wss_base_url)).close()
-
- def test_request_disable_proxy(self, handler):
- for proxy_proto in handler._SUPPORTED_PROXY_SCHEMES or ['ws']:
- # Given handler is configured with a proxy
- with handler(proxies={'ws': f'{proxy_proto}://10.255.255.255'}, timeout=5) as rh:
- # When a proxy is explicitly set to None for the request
- ws = ws_validate_and_send(rh, Request(self.ws_base_url, proxies={'http': None}))
- # Then no proxy should be used
- assert ws.status == 101
- ws.close()
-
- @pytest.mark.skip_handlers_if(
- lambda _, handler: Features.NO_PROXY not in handler._SUPPORTED_FEATURES, 'handler does not support NO_PROXY')
- def test_noproxy(self, handler):
- for proxy_proto in handler._SUPPORTED_PROXY_SCHEMES or ['ws']:
- # Given the handler is configured with a proxy
- with handler(proxies={'ws': f'{proxy_proto}://10.255.255.255'}, timeout=5) as rh:
- for no_proxy in (f'127.0.0.1:{self.ws_port}', '127.0.0.1', 'localhost'):
- # When request no proxy includes the request url host
- ws = ws_validate_and_send(rh, Request(self.ws_base_url, proxies={'no': no_proxy}))
- # Then the proxy should not be used
- assert ws.status == 101
- ws.close()
-
- @pytest.mark.skip_handlers_if(
- lambda _, handler: Features.ALL_PROXY not in handler._SUPPORTED_FEATURES, 'handler does not support ALL_PROXY')
- def test_allproxy(self, handler):
- supported_proto = traverse_obj(handler._SUPPORTED_PROXY_SCHEMES, 0, default='ws')
- # This is a bit of a hacky test, but it should be enough to check whether the handler is using the proxy.
- # 0.1s might not be enough of a timeout if proxy is not used in all cases, but should still get failures.
- with handler(proxies={'all': f'{supported_proto}://10.255.255.255'}, timeout=0.1) as rh:
- with pytest.raises(TransportError):
- ws_validate_and_send(rh, Request(self.ws_base_url)).close()
-
- with handler(timeout=0.1) as rh:
- with pytest.raises(TransportError):
- ws_validate_and_send(
- rh, Request(self.ws_base_url, proxies={'all': f'{supported_proto}://10.255.255.255'})).close()
-
-
-def create_fake_ws_connection(raised):
- import websockets.sync.client
-
- class FakeWsConnection(websockets.sync.client.ClientConnection):
- def __init__(self, *args, **kwargs):
- class FakeResponse:
- body = b''
- headers = {}
- status_code = 101
- reason_phrase = 'test'
-
- self.response = FakeResponse()
-
- def send(self, *args, **kwargs):
- raise raised()
-
- def recv(self, *args, **kwargs):
- raise raised()
-
- def close(self, *args, **kwargs):
- return
-
- return FakeWsConnection()
-
-
-@pytest.mark.parametrize('handler', ['Websockets'], indirect=True)
-class TestWebsocketsRequestHandler:
- # ruff: disable[PLW0108] `websockets` may not be available
- @pytest.mark.parametrize('raised,expected', [
- # https://websockets.readthedocs.io/en/stable/reference/exceptions.html
- (lambda: websockets.exceptions.InvalidURI(msg='test', uri='test://'), RequestError),
- # Requires a response object. Should be covered by HTTP error tests.
- # (lambda: websockets.exceptions.InvalidStatus(), TransportError),
- (lambda: websockets.exceptions.InvalidHandshake(), TransportError),
- # These are subclasses of InvalidHandshake
- (lambda: websockets.exceptions.InvalidHeader(name='test'), TransportError),
- (lambda: websockets.exceptions.NegotiationError(), TransportError),
- # Catch-all
- (lambda: websockets.exceptions.WebSocketException(), TransportError),
- (TimeoutError, TransportError),
- # These may be raised by our create_connection implementation, which should also be caught
- (OSError, TransportError),
- (ssl.SSLError, SSLError),
- (ssl.SSLCertVerificationError, CertificateVerifyError),
- (socks.ProxyError, ProxyError),
- ])
- # ruff: enable[PLW0108]
- def test_request_error_mapping(self, handler, monkeypatch, raised, expected):
- import websockets.sync.client
-
- import yt_dlp.networking._websockets
- with handler() as rh:
- def fake_connect(*args, **kwargs):
- raise raised()
- monkeypatch.setattr(yt_dlp.networking._websockets, 'create_connection', lambda *args, **kwargs: None)
- monkeypatch.setattr(websockets.sync.client, 'connect', fake_connect)
- with pytest.raises(expected) as exc_info:
- rh.send(Request('ws://fake-url'))
- assert exc_info.type is expected
-
- @pytest.mark.parametrize('raised,expected,match', [
- # https://websockets.readthedocs.io/en/stable/reference/sync/client.html#websockets.sync.client.ClientConnection.send
- (lambda: websockets.exceptions.ConnectionClosed(None, None), TransportError, None),
- (RuntimeError, TransportError, None),
- (TimeoutError, TransportError, None),
- (TypeError, RequestError, None),
- (socks.ProxyError, ProxyError, None),
- # Catch-all
- # ruff: noqa: PLW0108 `websockets` may not be available
- (lambda: websockets.exceptions.WebSocketException(), TransportError, None),
- ])
- def test_ws_send_error_mapping(self, handler, monkeypatch, raised, expected, match):
- from yt_dlp.networking._websockets import WebsocketsResponseAdapter
- ws = WebsocketsResponseAdapter(create_fake_ws_connection(raised), url='ws://fake-url')
- with pytest.raises(expected, match=match) as exc_info:
- ws.send('test')
- assert exc_info.type is expected
-
- @pytest.mark.parametrize('raised,expected,match', [
- # https://websockets.readthedocs.io/en/stable/reference/sync/client.html#websockets.sync.client.ClientConnection.recv
- (lambda: websockets.exceptions.ConnectionClosed(None, None), TransportError, None),
- (RuntimeError, TransportError, None),
- (TimeoutError, TransportError, None),
- (socks.ProxyError, ProxyError, None),
- # Catch-all
- # ruff: noqa: PLW0108 `websockets` may not be available
- (lambda: websockets.exceptions.WebSocketException(), TransportError, None),
- ])
- def test_ws_recv_error_mapping(self, handler, monkeypatch, raised, expected, match):
- from yt_dlp.networking._websockets import WebsocketsResponseAdapter
- ws = WebsocketsResponseAdapter(create_fake_ws_connection(raised), url='ws://fake-url')
- with pytest.raises(expected, match=match) as exc_info:
- ws.recv()
- assert exc_info.type is expected
diff --git a/test/test_youtube_lists.py b/test/test_youtube_lists.py
deleted file mode 100644
index b3f323e21..000000000
--- a/test/test_youtube_lists.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-from test.helper import FakeYDL, is_download_test
-from yt_dlp.extractor import YoutubeIE, YoutubeTabIE
-from yt_dlp.utils import ExtractorError
-
-
-@is_download_test
-class TestYoutubeLists(unittest.TestCase):
- def assertIsPlaylist(self, info):
- """Make sure the info has '_type' set to 'playlist'"""
- self.assertEqual(info['_type'], 'playlist')
-
- def test_youtube_playlist_noplaylist(self):
- dl = FakeYDL()
- dl.params['noplaylist'] = True
- ie = YoutubeTabIE(dl)
- result = ie.extract('https://www.youtube.com/watch?v=OmJ-4B-mS-Y&list=PLydZ2Hrp_gPRJViZjLFKaBMgCQOYEEkyp&index=2')
- self.assertEqual(result['_type'], 'url')
- self.assertEqual(result['ie_key'], YoutubeIE.ie_key())
- self.assertEqual(YoutubeIE.extract_id(result['url']), 'OmJ-4B-mS-Y')
-
- def test_youtube_mix(self):
- dl = FakeYDL()
- ie = YoutubeTabIE(dl)
- result = ie.extract('https://www.youtube.com/watch?v=tyITL_exICo&list=RDCLAK5uy_kLWIr9gv1XLlPbaDS965-Db4TrBoUTxQ8')
- entries = list(result['entries'])
- self.assertTrue(len(entries) >= 50)
- original_video = entries[0]
- self.assertEqual(original_video['id'], 'tyITL_exICo')
-
- def test_youtube_flat_playlist_extraction(self):
- dl = FakeYDL()
- dl.params['extract_flat'] = True
- ie = YoutubeTabIE(dl)
- result = ie.extract('https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc')
- self.assertIsPlaylist(result)
- entries = list(result['entries'])
- self.assertTrue(len(entries) == 1)
- video = entries[0]
- self.assertEqual(video['_type'], 'url')
- self.assertEqual(video['ie_key'], 'Youtube')
- self.assertEqual(video['id'], 'BaW_jenozKc')
- self.assertEqual(video['url'], 'https://www.youtube.com/watch?v=BaW_jenozKc')
- self.assertEqual(video['title'], 'youtube-dl test video "\'/\\ä↭𝕐')
- self.assertEqual(video['duration'], 10)
- self.assertEqual(video['uploader'], 'Philipp Hagemeister')
-
- def test_youtube_channel_no_uploads(self):
- dl = FakeYDL()
- dl.params['extract_flat'] = True
- ie = YoutubeTabIE(dl)
- # no uploads
- with self.assertRaisesRegex(ExtractorError, r'no uploads'):
- ie.extract('https://www.youtube.com/channel/UC2yXPzFejc422buOIzn_0CA')
-
- # no uploads and no UCID given
- with self.assertRaisesRegex(ExtractorError, r'no uploads'):
- ie.extract('https://www.youtube.com/news')
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/test_youtube_misc.py b/test/test_youtube_misc.py
deleted file mode 100644
index 81b116217..000000000
--- a/test/test_youtube_misc.py
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/usr/bin/env python3
-
-# Allow direct execution
-import os
-import sys
-import unittest
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-from yt_dlp.extractor import YoutubeIE
-
-
-class TestYoutubeMisc(unittest.TestCase):
- def test_youtube_extract(self):
- assertExtractId = lambda url, video_id: self.assertEqual(YoutubeIE.extract_id(url), video_id)
- assertExtractId('http://www.youtube.com/watch?&v=BaW_jenozKc', 'BaW_jenozKc')
- assertExtractId('https://www.youtube.com/watch?&v=BaW_jenozKc', 'BaW_jenozKc')
- assertExtractId('https://www.youtube.com/watch?feature=player_embedded&v=BaW_jenozKc', 'BaW_jenozKc')
- assertExtractId('https://www.youtube.com/watch_popup?v=BaW_jenozKc', 'BaW_jenozKc')
- assertExtractId('http://www.youtube.com/watch?v=BaW_jenozKcsharePLED17F32AD9753930', 'BaW_jenozKc')
- assertExtractId('BaW_jenozKc', 'BaW_jenozKc')
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/test/testcert.pem b/test/testcert.pem
deleted file mode 100644
index b3e0f00c7..000000000
--- a/test/testcert.pem
+++ /dev/null
@@ -1,52 +0,0 @@
------BEGIN PRIVATE KEY-----
-MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDMF0bAzaHAdIyB
-HRmnIp4vv40lGqEePmWqicCl0QZ0wsb5dNysSxSa7330M2QeQopGfdaUYF1uTcNp
-Qx6ECgBSfg+RrOBI7r/u4F+sKX8MUXVaf/5QoBUrGNGSn/pp7HMGOuQqO6BVg4+h
-A1ySSwUG8mZItLRry1ISyErmW8b9xlqfd97uLME/5tX+sMelRFjUbAx8A4CK58Ev
-mMguHVTlXzx5RMdYcf1VScYcjlV/qA45uzP8zwI5aigfcmUD+tbGuQRhKxUhmw0J
-aobtOR6+JSOAULW5gYa/egE4dWLwbyM6b6eFbdnjlQzEA1EW7ChMPAW/Mo83KyiP
-tKMCSQulAgMBAAECggEALCfBDAexPjU5DNoh6bIorUXxIJzxTNzNHCdvgbCGiA54
-BBKPh8s6qwazpnjT6WQWDIg/O5zZufqjE4wM9x4+0Zoqfib742ucJO9wY4way6x4
-Clt0xzbLPabB+MoZ4H7ip+9n2+dImhe7pGdYyOHoNYeOL57BBi1YFW42Hj6u/8pd
-63YCXisto3Rz1YvRQVjwsrS+cRKZlzAFQRviL30jav7Wh1aWEfcXxjj4zhm8pJdk
-ITGtq6howz57M0NtX6hZnfe8ywzTnDFIGKIMA2cYHuYJcBh9bc4tCGubTvTKK9UE
-8fM+f6UbfGqfpKCq1mcgs0XMoFDSzKS9+mSJn0+5JQKBgQD+OCKaeH3Yzw5zGnlw
-XuQfMJGNcgNr+ImjmvzUAC2fAZUJLAcQueE5kzMv5Fmd+EFE2CEX1Vit3tg0SXvA
-G+bq609doILHMA03JHnV1npO/YNIhG3AAtJlKYGxQNfWH9mflYj9mEui8ZFxG52o
-zWhHYuifOjjZszUR+/eio6NPzwKBgQDNhUBTrT8LIX4SE/EFUiTlYmWIvOMgXYvN
-8Cm3IRNQ/yyphZaXEU0eJzfX5uCDfSVOgd6YM/2pRah+t+1Hvey4H8e0GVTu5wMP
-gkkqwKPGIR1YOmlw6ippqwvoJD7LuYrm6Q4D6e1PvkjwCq6lEndrOPmPrrXNd0JJ
-XO60y3U2SwKBgQDLkyZarryQXxcCI6Q10Tc6pskYDMIit095PUbTeiUOXNT9GE28
-Hi32ziLCakk9kCysNasii81MxtQ54tJ/f5iGbNMMddnkKl2a19Hc5LjjAm4cJzg/
-98KGEhvyVqvAo5bBDZ06/rcrD+lZOzUglQS5jcIcqCIYa0LHWQ/wJLxFzwKBgFcZ
-1SRhdSmDfUmuF+S4ZpistflYjC3IV5rk4NkS9HvMWaJS0nqdw4A3AMzItXgkjq4S
-DkOVLTkTI5Do5HAWRv/VwC5M2hkR4NMu1VGAKSisGiKtRsirBWSZMEenLNHshbjN
-Jrpz5rZ4H7NT46ZkCCZyFBpX4gb9NyOedjA7Via3AoGARF8RxbYjnEGGFuhnbrJB
-FTPR0vaL4faY3lOgRZ8jOG9V2c9Hzi/y8a8TU4C11jnJSDqYCXBTd5XN28npYxtD
-pjRsCwy6ze+yvYXPO7C978eMG3YRyj366NXUxnXN59ibwe/lxi2OD9z8J1LEdF6z
-VJua1Wn8HKxnXMI61DhTCSo=
------END PRIVATE KEY-----
------BEGIN CERTIFICATE-----
-MIIEEzCCAvugAwIBAgIJAK1haYi6gmSKMA0GCSqGSIb3DQEBCwUAMIGeMQswCQYD
-VQQGEwJERTEMMAoGA1UECAwDTlJXMRQwEgYDVQQHDAtEdWVzc2VsZG9yZjEbMBkG
-A1UECgwSeW91dHViZS1kbCBwcm9qZWN0MRkwFwYDVQQLDBB5b3V0dWJlLWRsIHRl
-c3RzMRIwEAYDVQQDDAlsb2NhbGhvc3QxHzAdBgkqhkiG9w0BCQEWEHBoaWhhZ0Bw
-aGloYWcuZGUwIBcNMTUwMTMwMDExNTA4WhgPMjExNTAxMDYwMTE1MDhaMIGeMQsw
-CQYDVQQGEwJERTEMMAoGA1UECAwDTlJXMRQwEgYDVQQHDAtEdWVzc2VsZG9yZjEb
-MBkGA1UECgwSeW91dHViZS1kbCBwcm9qZWN0MRkwFwYDVQQLDBB5b3V0dWJlLWRs
-IHRlc3RzMRIwEAYDVQQDDAlsb2NhbGhvc3QxHzAdBgkqhkiG9w0BCQEWEHBoaWhh
-Z0BwaGloYWcuZGUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDMF0bA
-zaHAdIyBHRmnIp4vv40lGqEePmWqicCl0QZ0wsb5dNysSxSa7330M2QeQopGfdaU
-YF1uTcNpQx6ECgBSfg+RrOBI7r/u4F+sKX8MUXVaf/5QoBUrGNGSn/pp7HMGOuQq
-O6BVg4+hA1ySSwUG8mZItLRry1ISyErmW8b9xlqfd97uLME/5tX+sMelRFjUbAx8
-A4CK58EvmMguHVTlXzx5RMdYcf1VScYcjlV/qA45uzP8zwI5aigfcmUD+tbGuQRh
-KxUhmw0JaobtOR6+JSOAULW5gYa/egE4dWLwbyM6b6eFbdnjlQzEA1EW7ChMPAW/
-Mo83KyiPtKMCSQulAgMBAAGjUDBOMB0GA1UdDgQWBBTBUZoqhQkzHQ6xNgZfFxOd
-ZEVt8TAfBgNVHSMEGDAWgBTBUZoqhQkzHQ6xNgZfFxOdZEVt8TAMBgNVHRMEBTAD
-AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCUOCl3T/J9B08Z+ijfOJAtkbUaEHuVZb4x
-5EpZSy2ZbkLvtsftMFieHVNXn9dDswQc5qjYStCC4o60LKw4M6Y63FRsAZ/DNaqb
-PY3jyCyuugZ8/sNf50vHYkAcF7SQYqOQFQX4TQsNUk2xMJIt7H0ErQFmkf/u3dg6
-cy89zkT462IwxzSG7NNhIlRkL9o5qg+Y1mF9eZA1B0rcL6hO24PPTHOd90HDChBu
-SZ6XMi/LzYQSTf0Vg2R+uMIVlzSlkdcZ6sqVnnqeLL8dFyIa4e9sj/D4ZCYP8Mqe
-Z73H5/NNhmwCHRqVUTgm307xblQaWGhwAiDkaRvRW2aJQ0qGEdZK
------END CERTIFICATE-----
diff --git a/test/testdata/certificate/ca.crt b/test/testdata/certificate/ca.crt
deleted file mode 100644
index ddf7be7ad..000000000
--- a/test/testdata/certificate/ca.crt
+++ /dev/null
@@ -1,10 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIBfDCCASOgAwIBAgIUUgngoxFpuWft8gjj3uEFoqJyoJowCgYIKoZIzj0EAwIw
-FDESMBAGA1UEAwwJeXRkbHB0ZXN0MB4XDTIyMDQxNTAzMDEwMVoXDTM4MTAxNTAz
-MDEwMVowFDESMBAGA1UEAwwJeXRkbHB0ZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0D
-AQcDQgAEcTaKMtIn2/1kgid1zXFpLm87FMT5PP3/bltKVVH3DLO//0kUslCHYxFU
-KpcCfVt9aueRyUFi1TNkkkEZ9D6fbqNTMFEwHQYDVR0OBBYEFBdY2rVNLFGM6r1F
-iuamNDaiq0QoMB8GA1UdIwQYMBaAFBdY2rVNLFGM6r1FiuamNDaiq0QoMA8GA1Ud
-EwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDRwAwRAIgXJg2jio1kow2g/iP54Qq+iI2
-m4EAvZiY0Im/Ni3PHawCIC6KCl6QcHANbeq8ckOXNGusjl6OWhvEM3uPBPhqskq1
------END CERTIFICATE-----
diff --git a/test/testdata/certificate/ca.key b/test/testdata/certificate/ca.key
deleted file mode 100644
index 38920d571..000000000
--- a/test/testdata/certificate/ca.key
+++ /dev/null
@@ -1,5 +0,0 @@
------BEGIN EC PRIVATE KEY-----
-MHcCAQEEIG2L1bHdl3PnaLiJ7Zm8aAGCj4GiVbSbXQcrJAdL+yqOoAoGCCqGSM49
-AwEHoUQDQgAEcTaKMtIn2/1kgid1zXFpLm87FMT5PP3/bltKVVH3DLO//0kUslCH
-YxFUKpcCfVt9aueRyUFi1TNkkkEZ9D6fbg==
------END EC PRIVATE KEY-----
diff --git a/test/testdata/certificate/ca.srl b/test/testdata/certificate/ca.srl
deleted file mode 100644
index de2d1eab3..000000000
--- a/test/testdata/certificate/ca.srl
+++ /dev/null
@@ -1 +0,0 @@
-4A260C33C4D34612646E6321E1E767DF1A95EF0B
diff --git a/test/testdata/certificate/client.crt b/test/testdata/certificate/client.crt
deleted file mode 100644
index 874622fae..000000000
--- a/test/testdata/certificate/client.crt
+++ /dev/null
@@ -1,9 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIBIzCBygIUSiYMM8TTRhJkbmMh4edn3xqV7wswCgYIKoZIzj0EAwIwFDESMBAG
-A1UEAwwJeXRkbHB0ZXN0MB4XDTIyMDQxNTAzMDEyN1oXDTM4MTAxNTAzMDEyN1ow
-FTETMBEGA1UEAwwKeXRkbHB0ZXN0MjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA
-BKREKVDWfLKZknzYg+BUkmTn43f2pl/LNSyKPtXo/UV7hhp6JXIq3ZuZ7rubyuMS
-XNuH+2Cl9msSpJB2LhJs5kcwCgYIKoZIzj0EAwIDSAAwRQIhAMRr46vO25/5nUhD
-aHp4L67AeSvrjvSFHfubyD3Kr5dwAiA8EfOgVxc8Qh6ozTcbXO/WnBfS48ZFRSQY
-D0dB8M1kJw==
------END CERTIFICATE-----
diff --git a/test/testdata/certificate/client.csr b/test/testdata/certificate/client.csr
deleted file mode 100644
index 2d5d7a5c1..000000000
--- a/test/testdata/certificate/client.csr
+++ /dev/null
@@ -1,7 +0,0 @@
------BEGIN CERTIFICATE REQUEST-----
-MIHQMHcCAQAwFTETMBEGA1UEAwwKeXRkbHB0ZXN0MjBZMBMGByqGSM49AgEGCCqG
-SM49AwEHA0IABKREKVDWfLKZknzYg+BUkmTn43f2pl/LNSyKPtXo/UV7hhp6JXIq
-3ZuZ7rubyuMSXNuH+2Cl9msSpJB2LhJs5kegADAKBggqhkjOPQQDAgNJADBGAiEA
-1LZ72mtPmVxhGtdMvpZ0fyA68H2RC5IMHpLq18T55UcCIQDKpkXXVTvAzS0JioCq
-6kiYq8Oxx6ZMoI+11k75/Kip1g==
------END CERTIFICATE REQUEST-----
diff --git a/test/testdata/certificate/client.key b/test/testdata/certificate/client.key
deleted file mode 100644
index e47389b51..000000000
--- a/test/testdata/certificate/client.key
+++ /dev/null
@@ -1,5 +0,0 @@
------BEGIN EC PRIVATE KEY-----
-MHcCAQEEIAW6h9hwT0Aha+JBukgmHnrKRPoqPNWYA86ic0UaKHs8oAoGCCqGSM49
-AwEHoUQDQgAEpEQpUNZ8spmSfNiD4FSSZOfjd/amX8s1LIo+1ej9RXuGGnolcird
-m5nuu5vK4xJc24f7YKX2axKkkHYuEmzmRw==
------END EC PRIVATE KEY-----
diff --git a/test/testdata/certificate/clientencrypted.key b/test/testdata/certificate/clientencrypted.key
deleted file mode 100644
index 0baee37e9..000000000
--- a/test/testdata/certificate/clientencrypted.key
+++ /dev/null
@@ -1,8 +0,0 @@
------BEGIN EC PRIVATE KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: AES-256-CBC,4B39160146F15544922E553E08299A35
-
-96A7/iBkIfTVb8r2812ued2pS49FfVY4Ppz/45OGF0uFayMtMl8/GuEBCamuhFXS
-rnOOpco96TTeeKZHqR45wnf4tgHM8IjoQ6H0EX3lVF19OHnArAgrGYtohWUGSyGn
-IgLJFdUewIjdI7XApTJprQFE5E2tETXFA95mCz88u1c=
------END EC PRIVATE KEY-----
diff --git a/test/testdata/certificate/clientwithencryptedkey.crt b/test/testdata/certificate/clientwithencryptedkey.crt
deleted file mode 100644
index f357e4c95..000000000
--- a/test/testdata/certificate/clientwithencryptedkey.crt
+++ /dev/null
@@ -1,17 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIBIzCBygIUSiYMM8TTRhJkbmMh4edn3xqV7wswCgYIKoZIzj0EAwIwFDESMBAG
-A1UEAwwJeXRkbHB0ZXN0MB4XDTIyMDQxNTAzMDEyN1oXDTM4MTAxNTAzMDEyN1ow
-FTETMBEGA1UEAwwKeXRkbHB0ZXN0MjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA
-BKREKVDWfLKZknzYg+BUkmTn43f2pl/LNSyKPtXo/UV7hhp6JXIq3ZuZ7rubyuMS
-XNuH+2Cl9msSpJB2LhJs5kcwCgYIKoZIzj0EAwIDSAAwRQIhAMRr46vO25/5nUhD
-aHp4L67AeSvrjvSFHfubyD3Kr5dwAiA8EfOgVxc8Qh6ozTcbXO/WnBfS48ZFRSQY
-D0dB8M1kJw==
------END CERTIFICATE-----
------BEGIN EC PRIVATE KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: AES-256-CBC,4B39160146F15544922E553E08299A35
-
-96A7/iBkIfTVb8r2812ued2pS49FfVY4Ppz/45OGF0uFayMtMl8/GuEBCamuhFXS
-rnOOpco96TTeeKZHqR45wnf4tgHM8IjoQ6H0EX3lVF19OHnArAgrGYtohWUGSyGn
-IgLJFdUewIjdI7XApTJprQFE5E2tETXFA95mCz88u1c=
------END EC PRIVATE KEY-----
diff --git a/test/testdata/certificate/clientwithkey.crt b/test/testdata/certificate/clientwithkey.crt
deleted file mode 100644
index 942f6e2a4..000000000
--- a/test/testdata/certificate/clientwithkey.crt
+++ /dev/null
@@ -1,14 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIBIzCBygIUSiYMM8TTRhJkbmMh4edn3xqV7wswCgYIKoZIzj0EAwIwFDESMBAG
-A1UEAwwJeXRkbHB0ZXN0MB4XDTIyMDQxNTAzMDEyN1oXDTM4MTAxNTAzMDEyN1ow
-FTETMBEGA1UEAwwKeXRkbHB0ZXN0MjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA
-BKREKVDWfLKZknzYg+BUkmTn43f2pl/LNSyKPtXo/UV7hhp6JXIq3ZuZ7rubyuMS
-XNuH+2Cl9msSpJB2LhJs5kcwCgYIKoZIzj0EAwIDSAAwRQIhAMRr46vO25/5nUhD
-aHp4L67AeSvrjvSFHfubyD3Kr5dwAiA8EfOgVxc8Qh6ozTcbXO/WnBfS48ZFRSQY
-D0dB8M1kJw==
------END CERTIFICATE-----
------BEGIN EC PRIVATE KEY-----
-MHcCAQEEIAW6h9hwT0Aha+JBukgmHnrKRPoqPNWYA86ic0UaKHs8oAoGCCqGSM49
-AwEHoUQDQgAEpEQpUNZ8spmSfNiD4FSSZOfjd/amX8s1LIo+1ej9RXuGGnolcird
-m5nuu5vK4xJc24f7YKX2axKkkHYuEmzmRw==
------END EC PRIVATE KEY-----
diff --git a/test/testdata/certificate/instructions.md b/test/testdata/certificate/instructions.md
deleted file mode 100644
index b0e3fbd48..000000000
--- a/test/testdata/certificate/instructions.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# Generate certificates for client cert tests
-
-## CA
-```sh
-openssl ecparam -name prime256v1 -genkey -noout -out ca.key
-openssl req -new -x509 -sha256 -days 6027 -key ca.key -out ca.crt -subj "/CN=ytdlptest"
-```
-
-## Client
-```sh
-openssl ecparam -name prime256v1 -genkey -noout -out client.key
-openssl ec -in client.key -out clientencrypted.key -passout pass:foobar -aes256
-openssl req -new -sha256 -key client.key -out client.csr -subj "/CN=ytdlptest2"
-openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 6027 -sha256
-cp client.crt clientwithkey.crt
-cp client.crt clientwithencryptedkey.crt
-cat client.key >> clientwithkey.crt
-cat clientencrypted.key >> clientwithencryptedkey.crt
-```
\ No newline at end of file
diff --git a/test/testdata/cookies/httponly_cookies.txt b/test/testdata/cookies/httponly_cookies.txt
deleted file mode 100644
index c46541d6b..000000000
--- a/test/testdata/cookies/httponly_cookies.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-# Netscape HTTP Cookie File
-# http://curl.haxx.se/rfc/cookie_spec.html
-# This is a generated file! Do not edit.
-
-#HttpOnly_www.foobar.foobar FALSE / TRUE 2147483647 HTTPONLY_COOKIE HTTPONLY_COOKIE_VALUE
-www.foobar.foobar FALSE / TRUE 2147483647 JS_ACCESSIBLE_COOKIE JS_ACCESSIBLE_COOKIE_VALUE
diff --git a/test/testdata/cookies/malformed_cookies.txt b/test/testdata/cookies/malformed_cookies.txt
deleted file mode 100644
index 17bc40354..000000000
--- a/test/testdata/cookies/malformed_cookies.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-# Netscape HTTP Cookie File
-# http://curl.haxx.se/rfc/cookie_spec.html
-# This is a generated file! Do not edit.
-
-# Cookie file entry with invalid number of fields - 6 instead of 7
-www.foobar.foobar FALSE / FALSE 0 COOKIE
-
-# Cookie file entry with invalid expires at
-www.foobar.foobar FALSE / FALSE 1.7976931348623157e+308 COOKIE VALUE
diff --git a/test/testdata/cookies/session_cookies.txt b/test/testdata/cookies/session_cookies.txt
deleted file mode 100644
index f6996f031..000000000
--- a/test/testdata/cookies/session_cookies.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-# Netscape HTTP Cookie File
-# http://curl.haxx.se/rfc/cookie_spec.html
-# This is a generated file! Do not edit.
-
-www.foobar.foobar FALSE / TRUE YoutubeDLExpiresEmpty YoutubeDLExpiresEmptyValue
-www.foobar.foobar FALSE / TRUE 0 YoutubeDLExpires0 YoutubeDLExpires0Value
diff --git a/test/testdata/f4m/custom_base_url.f4m b/test/testdata/f4m/custom_base_url.f4m
deleted file mode 100644
index 74e1539e8..000000000
--- a/test/testdata/f4m/custom_base_url.f4m
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
- recorded
- http://vod.livestream.com/events/0000000000673980/
- 269.293
- AAAAm2Fic3QAAAAAAAAAAQAAAAPoAAAAAAAEG+0AAAAAAAAAAAAAAAAAAQAAABlhc3J0AAAAAAAAAAABAAAAAQAAAC4BAAAAVmFmcnQAAAAAAAAD6AAAAAAEAAAAAQAAAAAAAAAAAAAXcAAAAC0AAAAAAAQHQAAAE5UAAAAuAAAAAAAEGtUAAAEYAAAAAAAAAAAAAAAAAAAAAAA=
-
- AgAKb25NZXRhRGF0YQgAAAAIAAhkdXJhdGlvbgBAcNSwIMSbpgAFd2lkdGgAQJQAAAAAAAAABmhlaWdodABAhoAAAAAAAAAJZnJhbWVyYXRlAEA4/7DoLwW3AA12aWRlb2RhdGFyYXRlAECe1DLgjcobAAx2aWRlb2NvZGVjaWQAQBwAAAAAAAAADWF1ZGlvZGF0YXJhdGUAQGSimlvaPKQADGF1ZGlvY29kZWNpZABAJAAAAAAAAAAACQ==
-
-
diff --git a/test/testdata/ism/ec-3_test.Manifest b/test/testdata/ism/ec-3_test.Manifest
deleted file mode 100644
index 45f95de73..000000000
--- a/test/testdata/ism/ec-3_test.Manifest
+++ /dev/null
@@ -1 +0,0 @@
-
\ No newline at end of file
diff --git a/test/testdata/ism/sintel.Manifest b/test/testdata/ism/sintel.Manifest
deleted file mode 100644
index 2ff8c2447..000000000
--- a/test/testdata/ism/sintel.Manifest
+++ /dev/null
@@ -1,988 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/test/testdata/m3u8/bipbop_16x9.m3u8 b/test/testdata/m3u8/bipbop_16x9.m3u8
deleted file mode 100644
index 1ce87dd04..000000000
--- a/test/testdata/m3u8/bipbop_16x9.m3u8
+++ /dev/null
@@ -1,38 +0,0 @@
-#EXTM3U
-
-#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="bipbop_audio",LANGUAGE="eng",NAME="BipBop Audio 1",AUTOSELECT=YES,DEFAULT=YES
-#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="bipbop_audio",LANGUAGE="eng",NAME="BipBop Audio 2",AUTOSELECT=NO,DEFAULT=NO,URI="alternate_audio_aac/prog_index.m3u8"
-
-
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English",DEFAULT=YES,AUTOSELECT=YES,FORCED=NO,LANGUAGE="en",CHARACTERISTICS="public.accessibility.transcribes-spoken-dialog, public.accessibility.describes-music-and-sound",URI="subtitles/eng/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English (Forced)",DEFAULT=NO,AUTOSELECT=NO,FORCED=YES,LANGUAGE="en",URI="subtitles/eng_forced/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Français",DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,LANGUAGE="fr",CHARACTERISTICS="public.accessibility.transcribes-spoken-dialog, public.accessibility.describes-music-and-sound",URI="subtitles/fra/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Français (Forced)",DEFAULT=NO,AUTOSELECT=NO,FORCED=YES,LANGUAGE="fr",URI="subtitles/fra_forced/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Español",DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,LANGUAGE="es",CHARACTERISTICS="public.accessibility.transcribes-spoken-dialog, public.accessibility.describes-music-and-sound",URI="subtitles/spa/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Español (Forced)",DEFAULT=NO,AUTOSELECT=NO,FORCED=YES,LANGUAGE="es",URI="subtitles/spa_forced/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="日本語",DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,LANGUAGE="ja",CHARACTERISTICS="public.accessibility.transcribes-spoken-dialog, public.accessibility.describes-music-and-sound",URI="subtitles/jpn/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="日本語 (Forced)",DEFAULT=NO,AUTOSELECT=NO,FORCED=YES,LANGUAGE="ja",URI="subtitles/jpn_forced/prog_index.m3u8"
-
-
-#EXT-X-STREAM-INF:BANDWIDTH=263851,CODECS="mp4a.40.2, avc1.4d400d",RESOLUTION=416x234,AUDIO="bipbop_audio",SUBTITLES="subs"
-gear1/prog_index.m3u8
-#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=28451,CODECS="avc1.4d400d",URI="gear1/iframe_index.m3u8"
-
-#EXT-X-STREAM-INF:BANDWIDTH=577610,CODECS="mp4a.40.2, avc1.4d401e",RESOLUTION=640x360,AUDIO="bipbop_audio",SUBTITLES="subs"
-gear2/prog_index.m3u8
-#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=181534,CODECS="avc1.4d401e",URI="gear2/iframe_index.m3u8"
-
-#EXT-X-STREAM-INF:BANDWIDTH=915905,CODECS="mp4a.40.2, avc1.4d401f",RESOLUTION=960x540,AUDIO="bipbop_audio",SUBTITLES="subs"
-gear3/prog_index.m3u8
-#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=297056,CODECS="avc1.4d401f",URI="gear3/iframe_index.m3u8"
-
-#EXT-X-STREAM-INF:BANDWIDTH=1030138,CODECS="mp4a.40.2, avc1.4d401f",RESOLUTION=1280x720,AUDIO="bipbop_audio",SUBTITLES="subs"
-gear4/prog_index.m3u8
-#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=339492,CODECS="avc1.4d401f",URI="gear4/iframe_index.m3u8"
-
-#EXT-X-STREAM-INF:BANDWIDTH=1924009,CODECS="mp4a.40.2, avc1.4d401f",RESOLUTION=1920x1080,AUDIO="bipbop_audio",SUBTITLES="subs"
-gear5/prog_index.m3u8
-#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=669554,CODECS="avc1.4d401f",URI="gear5/iframe_index.m3u8"
-
-#EXT-X-STREAM-INF:BANDWIDTH=41457,CODECS="mp4a.40.2",AUDIO="bipbop_audio",SUBTITLES="subs"
-gear0/prog_index.m3u8
diff --git a/test/testdata/m3u8/img_bipbop_adv_example_fmp4.m3u8 b/test/testdata/m3u8/img_bipbop_adv_example_fmp4.m3u8
deleted file mode 100644
index 620ce04c5..000000000
--- a/test/testdata/m3u8/img_bipbop_adv_example_fmp4.m3u8
+++ /dev/null
@@ -1,76 +0,0 @@
-#EXTM3U
-#EXT-X-VERSION:6
-#EXT-X-INDEPENDENT-SEGMENTS
-
-
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=2168183,BANDWIDTH=2177116,CODECS="avc1.640020,mp4a.40.2",RESOLUTION=960x540,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud1",SUBTITLES="sub1"
-v5/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=7968416,BANDWIDTH=8001098,CODECS="avc1.64002a,mp4a.40.2",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud1",SUBTITLES="sub1"
-v9/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=6170000,BANDWIDTH=6312875,CODECS="avc1.64002a,mp4a.40.2",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud1",SUBTITLES="sub1"
-v8/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=4670769,BANDWIDTH=4943747,CODECS="avc1.64002a,mp4a.40.2",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud1",SUBTITLES="sub1"
-v7/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=3168702,BANDWIDTH=3216424,CODECS="avc1.640020,mp4a.40.2",RESOLUTION=1280x720,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud1",SUBTITLES="sub1"
-v6/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=1265132,BANDWIDTH=1268994,CODECS="avc1.64001e,mp4a.40.2",RESOLUTION=768x432,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud1",SUBTITLES="sub1"
-v4/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=895755,BANDWIDTH=902298,CODECS="avc1.64001e,mp4a.40.2",RESOLUTION=640x360,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud1",SUBTITLES="sub1"
-v3/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=530721,BANDWIDTH=541052,CODECS="avc1.640015,mp4a.40.2",RESOLUTION=480x270,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud1",SUBTITLES="sub1"
-v2/prog_index.m3u8
-
-
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=2390686,BANDWIDTH=2399619,CODECS="avc1.640020,ac-3",RESOLUTION=960x540,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud2",SUBTITLES="sub1"
-v5/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=8190919,BANDWIDTH=8223601,CODECS="avc1.64002a,ac-3",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud2",SUBTITLES="sub1"
-v9/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=6392503,BANDWIDTH=6535378,CODECS="avc1.64002a,ac-3",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud2",SUBTITLES="sub1"
-v8/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=4893272,BANDWIDTH=5166250,CODECS="avc1.64002a,ac-3",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud2",SUBTITLES="sub1"
-v7/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=3391205,BANDWIDTH=3438927,CODECS="avc1.640020,ac-3",RESOLUTION=1280x720,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud2",SUBTITLES="sub1"
-v6/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=1487635,BANDWIDTH=1491497,CODECS="avc1.64001e,ac-3",RESOLUTION=768x432,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud2",SUBTITLES="sub1"
-v4/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=1118258,BANDWIDTH=1124801,CODECS="avc1.64001e,ac-3",RESOLUTION=640x360,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud2",SUBTITLES="sub1"
-v3/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=753224,BANDWIDTH=763555,CODECS="avc1.640015,ac-3",RESOLUTION=480x270,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud2",SUBTITLES="sub1"
-v2/prog_index.m3u8
-
-
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=2198686,BANDWIDTH=2207619,CODECS="avc1.640020,ec-3",RESOLUTION=960x540,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud3",SUBTITLES="sub1"
-v5/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=7998919,BANDWIDTH=8031601,CODECS="avc1.64002a,ec-3",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud3",SUBTITLES="sub1"
-v9/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=6200503,BANDWIDTH=6343378,CODECS="avc1.64002a,ec-3",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud3",SUBTITLES="sub1"
-v8/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=4701272,BANDWIDTH=4974250,CODECS="avc1.64002a,ec-3",RESOLUTION=1920x1080,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud3",SUBTITLES="sub1"
-v7/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=3199205,BANDWIDTH=3246927,CODECS="avc1.640020,ec-3",RESOLUTION=1280x720,FRAME-RATE=60.000,CLOSED-CAPTIONS="cc1",AUDIO="aud3",SUBTITLES="sub1"
-v6/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=1295635,BANDWIDTH=1299497,CODECS="avc1.64001e,ec-3",RESOLUTION=768x432,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud3",SUBTITLES="sub1"
-v4/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=926258,BANDWIDTH=932801,CODECS="avc1.64001e,ec-3",RESOLUTION=640x360,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud3",SUBTITLES="sub1"
-v3/prog_index.m3u8
-#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=561224,BANDWIDTH=571555,CODECS="avc1.640015,ec-3",RESOLUTION=480x270,FRAME-RATE=30.000,CLOSED-CAPTIONS="cc1",AUDIO="aud3",SUBTITLES="sub1"
-v2/prog_index.m3u8
-
-
-#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=183689,BANDWIDTH=187492,CODECS="avc1.64002a",RESOLUTION=1920x1080,URI="v7/iframe_index.m3u8"
-#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=132672,BANDWIDTH=136398,CODECS="avc1.640020",RESOLUTION=1280x720,URI="v6/iframe_index.m3u8"
-#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=97767,BANDWIDTH=101378,CODECS="avc1.640020",RESOLUTION=960x540,URI="v5/iframe_index.m3u8"
-#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=75722,BANDWIDTH=77818,CODECS="avc1.64001e",RESOLUTION=768x432,URI="v4/iframe_index.m3u8"
-#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=63522,BANDWIDTH=65091,CODECS="avc1.64001e",RESOLUTION=640x360,URI="v3/iframe_index.m3u8"
-#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=39678,BANDWIDTH=40282,CODECS="avc1.640015",RESOLUTION=480x270,URI="v2/iframe_index.m3u8"
-
-
-#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud1",LANGUAGE="en",NAME="English",AUTOSELECT=YES,DEFAULT=YES,CHANNELS="2",URI="a1/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud2",LANGUAGE="en",NAME="English",AUTOSELECT=YES,DEFAULT=YES,CHANNELS="6",URI="a2/prog_index.m3u8"
-#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud3",LANGUAGE="en",NAME="English",AUTOSELECT=YES,DEFAULT=YES,CHANNELS="6",URI="a3/prog_index.m3u8"
-
-
-#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS,GROUP-ID="cc1",LANGUAGE="en",NAME="English",AUTOSELECT=YES,DEFAULT=YES,INSTREAM-ID="CC1"
-
-
-#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="sub1",LANGUAGE="en",NAME="English",AUTOSELECT=YES,DEFAULT=YES,FORCED=NO,URI="s1/en/prog_index.m3u8"
diff --git a/test/testdata/mpd/float_duration.mpd b/test/testdata/mpd/float_duration.mpd
deleted file mode 100644
index 8dc1d2d5e..000000000
--- a/test/testdata/mpd/float_duration.mpd
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/test/testdata/mpd/subtitles.mpd b/test/testdata/mpd/subtitles.mpd
deleted file mode 100644
index 6f948adba..000000000
--- a/test/testdata/mpd/subtitles.mpd
+++ /dev/null
@@ -1,351 +0,0 @@
-
-
-
-
- dash/
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/test/testdata/mpd/unfragmented.mpd b/test/testdata/mpd/unfragmented.mpd
deleted file mode 100644
index 5a3720be7..000000000
--- a/test/testdata/mpd/unfragmented.mpd
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
-
- DASH_360
-
-
-
-
-
- DASH_240
-
-
-
-
-
-
-
-
- audio
-
-
-
-
-
-
-
diff --git a/test/testdata/mpd/urls_only.mpd b/test/testdata/mpd/urls_only.mpd
deleted file mode 100644
index 2b9d595d3..000000000
--- a/test/testdata/mpd/urls_only.mpd
+++ /dev/null
@@ -1,218 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/test/testdata/netrc/netrc b/test/testdata/netrc/netrc
deleted file mode 100644
index bafe92fe6..000000000
--- a/test/testdata/netrc/netrc
+++ /dev/null
@@ -1,4 +0,0 @@
-machine normal_use login user password pass
-machine empty_user login "" password pass
-machine empty_pass login user password ""
-machine both_empty login "" password ""
diff --git a/test/testdata/netrc/print_netrc.py b/test/testdata/netrc/print_netrc.py
deleted file mode 100644
index 5c25814f8..000000000
--- a/test/testdata/netrc/print_netrc.py
+++ /dev/null
@@ -1,2 +0,0 @@
-with open('./test/testdata/netrc/netrc', encoding='utf-8') as fp:
- print(fp.read())
diff --git a/test/testdata/plugin_packages/testpackage/yt_dlp_plugins/extractor/package.py b/test/testdata/plugin_packages/testpackage/yt_dlp_plugins/extractor/package.py
deleted file mode 100644
index 39020fef9..000000000
--- a/test/testdata/plugin_packages/testpackage/yt_dlp_plugins/extractor/package.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from yt_dlp.extractor.common import InfoExtractor
-
-
-class PackagePluginIE(InfoExtractor):
- _VALID_URL = 'package'
- pass
diff --git a/test/testdata/reload_plugins/yt_dlp_plugins/extractor/normal.py b/test/testdata/reload_plugins/yt_dlp_plugins/extractor/normal.py
deleted file mode 100644
index 6b927077f..000000000
--- a/test/testdata/reload_plugins/yt_dlp_plugins/extractor/normal.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from yt_dlp.extractor.common import InfoExtractor
-
-
-class NormalPluginIE(InfoExtractor):
- _VALID_URL = 'normal'
- REPLACED = True
-
-
-class _IgnoreUnderscorePluginIE(InfoExtractor):
- pass
diff --git a/test/testdata/reload_plugins/yt_dlp_plugins/postprocessor/normal.py b/test/testdata/reload_plugins/yt_dlp_plugins/postprocessor/normal.py
deleted file mode 100644
index 5e44ba2b5..000000000
--- a/test/testdata/reload_plugins/yt_dlp_plugins/postprocessor/normal.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from yt_dlp.postprocessor.common import PostProcessor
-
-
-class NormalPluginPP(PostProcessor):
- REPLACED = True
diff --git a/test/testdata/thumbnails/foo %d bar/placeholder b/test/testdata/thumbnails/foo %d bar/placeholder
deleted file mode 100644
index e69de29bb..000000000
diff --git a/test/testdata/xspf/foo_xspf.xspf b/test/testdata/xspf/foo_xspf.xspf
deleted file mode 100644
index b7f0086b3..000000000
--- a/test/testdata/xspf/foo_xspf.xspf
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
- 2018-03-09T18:01:43Z
-
-
- cd1/track%201.mp3
- Pandemonium
- Foilverb
- Visit http://bigbrother404.bandcamp.com
- Pandemonium EP
- 1
- 202416
-
-
- ../%E3%83%88%E3%83%A9%E3%83%83%E3%82%AF%E3%80%80%EF%BC%92.mp3
- Final Cartridge (Nichico Twelve Remix)
- Visit http://bigbrother404.bandcamp.com
- Foilverb
- Pandemonium EP
- 2
- 255857
-
-
- track3.mp3
- https://example.com/track3.mp3
- Rebuilding Nightingale
- Visit http://bigbrother404.bandcamp.com
- Foilverb
- Pandemonium EP
- 3
- 287915
-
-
-
diff --git a/test/testdata/yt_dlp_plugins/extractor/_ignore.py b/test/testdata/yt_dlp_plugins/extractor/_ignore.py
deleted file mode 100644
index 57faf75bb..000000000
--- a/test/testdata/yt_dlp_plugins/extractor/_ignore.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from yt_dlp.extractor.common import InfoExtractor
-
-
-class IgnorePluginIE(InfoExtractor):
- pass
diff --git a/test/testdata/yt_dlp_plugins/extractor/ignore.py b/test/testdata/yt_dlp_plugins/extractor/ignore.py
deleted file mode 100644
index dca111a37..000000000
--- a/test/testdata/yt_dlp_plugins/extractor/ignore.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from yt_dlp.extractor.common import InfoExtractor
-
-
-class IgnoreNotInAllPluginIE(InfoExtractor):
- pass
-
-
-class InAllPluginIE(InfoExtractor):
- _VALID_URL = 'inallpluginie'
- pass
-
-
-__all__ = ['InAllPluginIE']
diff --git a/test/testdata/yt_dlp_plugins/extractor/normal.py b/test/testdata/yt_dlp_plugins/extractor/normal.py
deleted file mode 100644
index 996b2936f..000000000
--- a/test/testdata/yt_dlp_plugins/extractor/normal.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from yt_dlp.extractor.common import InfoExtractor
-
-
-class NormalPluginIE(InfoExtractor):
- _VALID_URL = 'normalpluginie'
- REPLACED = False
-
-
-class _IgnoreUnderscorePluginIE(InfoExtractor):
- _VALID_URL = 'ignoreunderscorepluginie'
- pass
diff --git a/test/testdata/yt_dlp_plugins/extractor/override.py b/test/testdata/yt_dlp_plugins/extractor/override.py
deleted file mode 100644
index 766dc32e1..000000000
--- a/test/testdata/yt_dlp_plugins/extractor/override.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from yt_dlp.extractor.generic import GenericIE
-
-
-class OverrideGenericIE(GenericIE, plugin_name='override'):
- TEST_FIELD = 'override'
diff --git a/test/testdata/yt_dlp_plugins/extractor/overridetwo.py b/test/testdata/yt_dlp_plugins/extractor/overridetwo.py
deleted file mode 100644
index 826184c64..000000000
--- a/test/testdata/yt_dlp_plugins/extractor/overridetwo.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from yt_dlp.extractor.generic import GenericIE
-
-
-class _UnderscoreOverrideGenericIE(GenericIE, plugin_name='underscore-override'):
- SECONDARY_TEST_FIELD = 'underscore-override'
diff --git a/test/testdata/yt_dlp_plugins/postprocessor/normal.py b/test/testdata/yt_dlp_plugins/postprocessor/normal.py
deleted file mode 100644
index 1e94d7b8b..000000000
--- a/test/testdata/yt_dlp_plugins/postprocessor/normal.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from yt_dlp.postprocessor.common import PostProcessor
-
-
-class NormalPluginPP(PostProcessor):
- REPLACED = False
diff --git a/test/testdata/zipped_plugins/yt_dlp_plugins/extractor/zipped.py b/test/testdata/zipped_plugins/yt_dlp_plugins/extractor/zipped.py
deleted file mode 100644
index c5140bb02..000000000
--- a/test/testdata/zipped_plugins/yt_dlp_plugins/extractor/zipped.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from yt_dlp.extractor.common import InfoExtractor
-
-
-class ZippedPluginIE(InfoExtractor):
- _VALID_URL = 'zippedpluginie'
- pass
diff --git a/test/testdata/zipped_plugins/yt_dlp_plugins/postprocessor/zipped.py b/test/testdata/zipped_plugins/yt_dlp_plugins/postprocessor/zipped.py
deleted file mode 100644
index 223822bd6..000000000
--- a/test/testdata/zipped_plugins/yt_dlp_plugins/postprocessor/zipped.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from yt_dlp.postprocessor.common import PostProcessor
-
-
-class ZippedPluginPP(PostProcessor):
- pass
diff --git a/web/.dockerignore b/web/.dockerignore
new file mode 100644
index 000000000..40708b0e2
--- /dev/null
+++ b/web/.dockerignore
@@ -0,0 +1,8 @@
+web/backend/downloads/
+web/backend/cookies.txt
+__pycache__/
+*.pyc
+*.pyo
+.venv/
+.git/
+*.egg-info/
diff --git a/web/README.md b/web/README.md
new file mode 100644
index 000000000..7aaad6ab6
--- /dev/null
+++ b/web/README.md
@@ -0,0 +1,24 @@
+# yt-dlp Web UI
+
+## Setup
+
+**1. Install backend dependencies** (from the `web/backend` folder):
+```bash
+pip install -r web/backend/requirements.txt
+```
+
+**2. Install yt-dlp** (from the repo root):
+```bash
+pip install -e .
+```
+
+**3. Start the backend:**
+```bash
+uvicorn web.backend.main:app --reload --port 8000
+```
+
+**4. Open the frontend:**
+
+Just open `web/frontend/index.html` in your browser — no build step needed.
+
+> Make sure `ffmpeg` is installed and on your PATH for merging video+audio streams.
diff --git a/web/backend/main.py b/web/backend/main.py
new file mode 100644
index 000000000..7a9e90ad6
--- /dev/null
+++ b/web/backend/main.py
@@ -0,0 +1,288 @@
+import json
+import uuid
+import asyncio
+import httpx
+import urllib.parse
+from pathlib import Path
+from fastapi import FastAPI, HTTPException, Request
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import StreamingResponse, Response, JSONResponse, FileResponse
+from fastapi.staticfiles import StaticFiles
+from pydantic import BaseModel
+
+import yt_dlp
+
+app = FastAPI()
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+@app.exception_handler(Exception)
+async def global_exception_handler(request: Request, exc: Exception):
+ return JSONResponse(status_code=500, content={"detail": str(exc)})
+
+DOWNLOAD_DIR = Path(__file__).parent / "downloads"
+DOWNLOAD_DIR.mkdir(exist_ok=True)
+FRONTEND_DIR = Path(__file__).parent.parent / "frontend"
+
+FORMAT_PRESETS = {
+ "best": "bestvideo+bestaudio/bestvideo/best",
+ "1080p": "bestvideo[height<=1080]+bestaudio/bestvideo[height<=1080]/best",
+ "720p": "bestvideo[height<=720]+bestaudio/bestvideo[height<=720]/best",
+ "480p": "bestvideo[height<=480]+bestaudio/bestvideo[height<=480]/best",
+ "audio": "bestaudio/best",
+}
+
+# file_id -> { status, percent, eta, speed, filepath, ... }
+_progress: dict[str, dict] = {}
+# file_id -> asyncio.Task
+_tasks: dict[str, asyncio.Task] = {}
+
+
+class InfoRequest(BaseModel):
+ url: str
+
+class DownloadRequest(BaseModel):
+ url: str
+ preset: str = "best"
+ format_id: str | None = None
+ file_id: str | None = None
+
+
+@app.get("/")
+async def index():
+ return FileResponse(FRONTEND_DIR / "index.html")
+
+
+@app.post("/info")
+async def get_info(req: InfoRequest):
+ ydl_opts = {"quiet": True, "no_warnings": True, "skip_download": True}
+ info = None
+ try:
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
+ info = await asyncio.to_thread(ydl.extract_info, req.url, download=False)
+ except Exception:
+ pass
+ if not info:
+ try:
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
+ info = await asyncio.to_thread(ydl.extract_info, req.url, download=False)
+ except Exception as e:
+ raise HTTPException(status_code=400, detail=str(e))
+ if not info:
+ raise HTTPException(status_code=400, detail="Could not extract video info.")
+
+ thumbnails = info.get("thumbnails") or []
+ thumbnail_url = None
+ if thumbnails:
+ ranked = sorted(
+ (t for t in thumbnails if t.get("url")),
+ key=lambda t: (t.get("width") or 0) * (t.get("height") or 0),
+ reverse=True,
+ )
+ thumbnail_url = ranked[0]["url"] if ranked else None
+ thumbnail_url = thumbnail_url or info.get("thumbnail")
+
+ formats = [
+ {
+ "format_id": f.get("format_id"),
+ "ext": f.get("ext"),
+ "resolution": f.get("resolution") or f.get("format_note") or "unknown",
+ "filesize": f.get("filesize") or f.get("filesize_approx"),
+ "vcodec": f.get("vcodec"),
+ "acodec": f.get("acodec"),
+ "fps": f.get("fps"),
+ "height": f.get("height") or 0,
+ "tbr": f.get("tbr") or 0,
+ }
+ for f in (info.get("formats") or [])
+ if f.get("ext") != "mhtml"
+ and f.get("protocol") != "mhtml"
+ and (f.get("vcodec", "none") != "none" or f.get("acodec", "none") != "none")
+ ]
+ formats.sort(key=lambda f: (f["height"], f["tbr"]), reverse=True)
+
+ if not formats:
+ raise HTTPException(status_code=400, detail="No downloadable formats found.")
+
+ return {
+ "title": info.get("title"),
+ "thumbnail": f"/thumbnail?url={thumbnail_url}" if thumbnail_url else None,
+ "duration": info.get("duration"),
+ "uploader": info.get("uploader"),
+ "view_count": info.get("view_count"),
+ "like_count": info.get("like_count"),
+ "upload_date": info.get("upload_date"),
+ "formats": formats,
+ }
+
+
+@app.get("/thumbnail")
+async def proxy_thumbnail(url: str):
+ try:
+ async with httpx.AsyncClient(follow_redirects=True, timeout=10) as client:
+ r = await client.get(url, headers={"User-Agent": "Mozilla/5.0"})
+ return Response(content=r.content, media_type=r.headers.get("content-type", "image/jpeg"))
+ except Exception:
+ raise HTTPException(status_code=502, detail="Could not fetch thumbnail")
+
+
+async def _run_download(file_id: str, url: str, fmt: str, output_template: str):
+ """Runs yt-dlp in a thread and updates _progress. Cancellable via task cancellation."""
+ cancelled = asyncio.Event()
+
+ def progress_hook(d):
+ if cancelled.is_set():
+ raise yt_dlp.utils.DownloadError("Cancelled")
+ status = d.get("status")
+ if status == "downloading":
+ downloaded = d.get("downloaded_bytes", 0)
+ total = d.get("total_bytes") or d.get("total_bytes_estimate") or 0
+ pct = round((downloaded / total) * 100, 1) if total else 0
+ eta = d.get("eta")
+ speed = d.get("speed")
+ _progress[file_id].update({
+ "status": "downloading",
+ "percent": pct,
+ "eta": int(eta) if eta else None,
+ "speed": round(speed / 1024 / 1024, 2) if speed else None,
+ })
+ elif status == "finished":
+ _progress[file_id].update({"status": "finished", "percent": 100, "eta": 0})
+
+ ydl_opts = {
+ "quiet": True,
+ "no_warnings": True,
+ "format": fmt,
+ "outtmpl": output_template,
+ "merge_output_format": "mp4",
+ "progress_hooks": [progress_hook],
+ }
+
+ try:
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
+ info = await asyncio.to_thread(ydl.extract_info, url, download=True)
+ return info
+ except asyncio.CancelledError:
+ cancelled.set()
+ _progress[file_id]["status"] = "cancelled"
+ raise
+ except Exception as e:
+ _progress[file_id]["status"] = "error"
+ _progress[file_id]["error"] = str(e)
+ raise
+
+
+@app.post("/download")
+async def download_video(req: DownloadRequest):
+ file_id = req.file_id or str(uuid.uuid4())
+ output_template = str(DOWNLOAD_DIR / f"{file_id}.%(ext)s")
+ fmt = req.format_id if req.format_id else FORMAT_PRESETS.get(req.preset, FORMAT_PRESETS["best"])
+
+ _progress[file_id] = {
+ "status": "starting", "percent": 0, "eta": None, "speed": None,
+ "url": req.url, "fmt": fmt, "output_template": output_template,
+ }
+
+ task = asyncio.create_task(_run_download(file_id, req.url, fmt, output_template))
+ _tasks[file_id] = task
+
+ try:
+ info = await task
+ except asyncio.CancelledError:
+ return JSONResponse({"file_id": file_id, "status": "cancelled"})
+ except Exception as e:
+ _tasks.pop(file_id, None)
+ raise HTTPException(status_code=400, detail=_progress.get(file_id, {}).get("error", str(e)))
+
+ _tasks.pop(file_id, None)
+
+ matches = list(DOWNLOAD_DIR.glob(f"{file_id}.*"))
+ if not matches:
+ raise HTTPException(status_code=500, detail="Download failed: file not found")
+
+ filepath = matches[0]
+ title = info.get("title") or file_id
+ filename_ascii = "".join(c for c in title if c.isascii() and (c.isalnum() or c in " ._-()")).strip()
+ if not filename_ascii:
+ filename_ascii = file_id
+ filename_ascii += filepath.suffix
+ filename_encoded = urllib.parse.quote(title + filepath.suffix)
+
+ _progress[file_id].update({
+ "status": "ready",
+ "percent": 100,
+ "filepath": str(filepath),
+ "filename_ascii": filename_ascii,
+ "filename_encoded": filename_encoded,
+ })
+
+ return JSONResponse({"file_id": file_id, "status": "ready"})
+
+
+@app.post("/cancel/{file_id}")
+async def cancel_download(file_id: str):
+ task = _tasks.get(file_id)
+ if task and not task.done():
+ task.cancel()
+ # Clean up partial files
+ for f in DOWNLOAD_DIR.glob(f"{file_id}*"):
+ f.unlink(missing_ok=True)
+ _progress[file_id] = {"status": "cancelled", "percent": 0}
+ return JSONResponse({"status": "cancelled"})
+ return JSONResponse({"status": "not_found"})
+
+
+@app.get("/file/{file_id}")
+async def serve_file(file_id: str):
+ meta = _progress.get(file_id)
+ if not meta or meta.get("status") != "ready":
+ raise HTTPException(status_code=404, detail="File not ready or already downloaded")
+
+ filepath = Path(meta["filepath"])
+ if not filepath.exists():
+ raise HTTPException(status_code=404, detail="File not found")
+
+ filename_ascii = meta["filename_ascii"]
+ filename_encoded = meta["filename_encoded"]
+
+ def iterfile():
+ with open(filepath, "rb") as f:
+ yield from f
+ filepath.unlink(missing_ok=True)
+ _progress.pop(file_id, None)
+
+ return StreamingResponse(
+ iterfile(),
+ media_type="video/mp4",
+ headers={
+ "Content-Disposition": f"attachment; filename=\"{filename_ascii}\"; filename*=UTF-8''{filename_encoded}",
+ },
+ )
+
+
+@app.get("/progress/{file_id}")
+async def progress_stream(file_id: str, request: Request):
+ async def event_generator():
+ while True:
+ if await request.is_disconnected():
+ break
+ data = _progress.get(file_id)
+ if data:
+ yield f"data: {json.dumps(data)}\n\n"
+ if data.get("status") in ("ready", "cancelled", "error"):
+ break
+ await asyncio.sleep(0.5)
+
+ return StreamingResponse(
+ event_generator(),
+ media_type="text/event-stream",
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
+ )
+
+
+app.mount("/static", StaticFiles(directory=FRONTEND_DIR), name="static")
diff --git a/web/backend/requirements.txt b/web/backend/requirements.txt
new file mode 100644
index 000000000..4c611b5a7
--- /dev/null
+++ b/web/backend/requirements.txt
@@ -0,0 +1,3 @@
+fastapi>=0.110.0
+uvicorn[standard]>=0.29.0
+httpx>=0.27.0
diff --git a/web/frontend/app.js b/web/frontend/app.js
new file mode 100644
index 000000000..8b7fe2780
--- /dev/null
+++ b/web/frontend/app.js
@@ -0,0 +1,309 @@
+const API = 'http://localhost:8000';
+
+const urlInput = document.getElementById('url-input');
+const clearBtn = document.getElementById('clear-btn');
+const fetchBtn = document.getElementById('fetch-btn');
+const errorMsg = document.getElementById('error-msg');
+const preview = document.getElementById('preview');
+const thumbnail = document.getElementById('thumbnail');
+const videoTitle = document.getElementById('video-title');
+const uploaderEl = document.getElementById('uploader');
+const durationEl = document.getElementById('duration');
+const formatSection = document.getElementById('format-section');
+const formatSelect = document.getElementById('format-select');
+const downloadBtn = document.getElementById('download-btn');
+const progressWrap = document.getElementById('progress-wrap');
+const progressFill = document.getElementById('progress-fill');
+const progressLabel = document.getElementById('progress-label');
+const cancelBtn = document.getElementById('cancel-btn');
+
+let currentFileId = null;
+let currentAbort = null;
+let currentSse = null;
+
+// --- Cancel ---
+cancelBtn.addEventListener('click', async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ // Abort the pending fetch
+ if (currentAbort) { currentAbort.abort(); currentAbort = null; }
+ // Close SSE
+ if (currentSse) { currentSse.close(); currentSse = null; }
+ // Tell backend to kill the task and clean up
+ if (currentFileId) {
+ fetch(`${API}/cancel/${currentFileId}`, { method: 'POST' }).catch(() => {});
+ currentFileId = null;
+ }
+
+ progressWrap.style.display = 'none';
+ setProgress(0, '');
+ setLoading(downloadBtn, false);
+});
+
+// --- Reset UI ---
+function resetUI() {
+ urlInput.value = '';
+ clearBtn.style.display = 'none';
+ errorMsg.style.display = 'none';
+ preview.style.display = 'none';
+ formatSection.style.display = 'none';
+ downloadBtn.style.display = 'none';
+ progressWrap.style.display = 'none';
+ thumbnail.src = '';
+}
+window.addEventListener('pageshow', resetUI);
+
+// --- Helpers ---
+function showError(msg) {
+ errorMsg.textContent = msg;
+ errorMsg.style.display = 'block';
+}
+function hideError() { errorMsg.style.display = 'none'; }
+
+function setLoading(btn, loading, text) {
+ btn.disabled = loading;
+ btn.style.opacity = loading ? '0.6' : '1';
+ btn.style.cursor = loading ? 'wait' : '';
+ if (text) btn.dataset.label = btn.dataset.label || btn.textContent.trim();
+ if (loading && text) {
+ btn.textContent = text;
+ } else if (!loading && btn.dataset.label) {
+ if (btn.id === 'download-btn') {
+ btn.innerHTML = ` Download`;
+ } else {
+ btn.textContent = btn.dataset.label;
+ }
+ delete btn.dataset.label;
+ }
+}
+
+function formatDuration(secs) {
+ if (!secs) return null;
+ const h = Math.floor(secs / 3600);
+ const m = Math.floor((secs % 3600) / 60);
+ const s = secs % 60;
+ return h > 0
+ ? `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`
+ : `${m}:${String(s).padStart(2,'0')}`;
+}
+
+function formatCount(n) {
+ if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B';
+ if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
+ return n.toString();
+}
+
+function formatBytes(bytes) {
+ if (!bytes) return null;
+ if (bytes >= 1e9) return (bytes / 1e9).toFixed(1) + ' GB';
+ if (bytes >= 1e6) return (bytes / 1e6).toFixed(1) + ' MB';
+ return (bytes / 1e3).toFixed(0) + ' KB';
+}
+
+function formatLabel(f) {
+ const parts = [];
+ const res = f.resolution || '';
+ if (res && res !== 'unknown') parts.push(res);
+ if (f.ext) parts.push(f.ext.toUpperCase());
+ const hasVideo = f.vcodec && f.vcodec !== 'none';
+ const hasAudio = f.acodec && f.acodec !== 'none';
+ if (!hasVideo && hasAudio) parts.push('audio only');
+ if (f.fps && hasVideo) parts.push(`${f.fps}fps`);
+ const size = formatBytes(f.filesize);
+ if (size) parts.push(`~${size}`);
+ return parts.join(' · ') || f.format_id;
+}
+
+function setProgress(pct, label) {
+ progressFill.style.width = pct + '%';
+ progressLabel.innerHTML = label;
+}
+
+function formatEta(secs) {
+ if (secs == null || secs < 0) return '';
+ if (secs < 60) return `ETA ${secs}s`;
+ const m = Math.floor(secs / 60);
+ const s = secs % 60;
+ return `ETA ${m}m ${s}s`;
+}
+
+// --- URL input ---
+urlInput.addEventListener('input', () => {
+ clearBtn.style.display = urlInput.value ? 'flex' : 'none';
+});
+clearBtn.addEventListener('click', () => { resetUI(); urlInput.focus(); });
+urlInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') fetchBtn.click(); });
+
+// --- Fetch info ---
+fetchBtn.addEventListener('click', async () => {
+ const url = urlInput.value.trim();
+ if (!url) { showError('Please paste a video URL first.'); return; }
+
+ hideError();
+ preview.style.display = 'none';
+ formatSection.style.display = 'none';
+ downloadBtn.style.display = 'none';
+ progressWrap.style.display = 'none';
+ setLoading(fetchBtn, true, 'Fetching…');
+
+ try {
+ const res = await fetch(`${API}/info`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.detail || 'Failed to fetch video info.');
+ renderPreview(data);
+ renderFormats(data.formats || []);
+ preview.style.display = 'flex';
+ formatSection.style.display = 'flex';
+ downloadBtn.style.display = 'flex';
+ } catch (err) {
+ showError(err.message);
+ } finally {
+ setLoading(fetchBtn, false);
+ }
+});
+
+function renderPreview(info) {
+ thumbnail.src = info.thumbnail || '';
+ thumbnail.alt = info.title || 'Video thumbnail';
+ thumbnail.style.display = info.thumbnail ? 'block' : 'none';
+ videoTitle.textContent = info.title || 'Unknown title';
+ uploaderEl.textContent = info.uploader || '';
+ uploaderEl.style.display = info.uploader ? '' : 'none';
+ const dur = formatDuration(info.duration);
+ durationEl.textContent = dur || '';
+ durationEl.style.display = dur ? '' : 'none';
+
+ const viewsEl = document.getElementById('views');
+ const likesEl = document.getElementById('likes');
+ const dateEl = document.getElementById('upload-date');
+ viewsEl.textContent = info.view_count ? '👁 ' + formatCount(info.view_count) : '';
+ viewsEl.style.display = info.view_count ? '' : 'none';
+ likesEl.textContent = info.like_count ? '👍 ' + formatCount(info.like_count) : '';
+ likesEl.style.display = info.like_count ? '' : 'none';
+ if (info.upload_date && info.upload_date.length === 8) {
+ const d = info.upload_date;
+ const formatted = new Date(`${d.slice(0,4)}-${d.slice(4,6)}-${d.slice(6,8)}`).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
+ dateEl.textContent = '📅 ' + formatted;
+ dateEl.style.display = '';
+ } else {
+ dateEl.style.display = 'none';
+ }
+}
+
+function renderFormats(formats) {
+ formatSelect.innerHTML = '';
+ const sorted = [...formats].sort((a, b) =>
+ (b.height || 0) - (a.height || 0) || (b.tbr || 0) - (a.tbr || 0)
+ );
+ const combined = sorted.filter(f => f.vcodec !== 'none' && f.acodec !== 'none');
+ const videoOnly = sorted.filter(f => f.vcodec !== 'none' && f.acodec === 'none');
+ const audioOnly = sorted.filter(f => f.vcodec === 'none' && f.acodec !== 'none');
+
+ const addGroup = (label, items) => {
+ if (!items.length) return;
+ const group = document.createElement('optgroup');
+ group.label = label;
+ items.forEach(f => {
+ const opt = document.createElement('option');
+ opt.value = f.format_id;
+ opt.textContent = formatLabel(f);
+ group.appendChild(opt);
+ });
+ formatSelect.appendChild(group);
+ };
+
+ if ((videoOnly[0]?.height || 0) >= (combined[0]?.height || 0)) {
+ addGroup('Video only', videoOnly);
+ addGroup('Video + Audio', combined);
+ } else {
+ addGroup('Video + Audio', combined);
+ addGroup('Video only', videoOnly);
+ }
+ addGroup('Audio only', audioOnly);
+ if (sorted.length) formatSelect.value = sorted[0].format_id;
+}
+
+// --- Download ---
+downloadBtn.addEventListener('click', async () => {
+ const url = urlInput.value.trim();
+ if (!url) return;
+
+ hideError();
+ setLoading(downloadBtn, true, 'Downloading…');
+ progressWrap.style.display = 'block';
+ setProgress(0, 'Starting… ');
+
+ const fileId = crypto.randomUUID();
+ currentFileId = fileId;
+
+ // SSE for live progress
+ const sse = new EventSource(`${API}/progress/${fileId}`);
+ currentSse = sse;
+ sse.onmessage = (e) => {
+ const d = JSON.parse(e.data);
+ if (d.status === 'downloading') {
+ const pct = d.percent || 0;
+ const eta = d.eta != null ? formatEta(d.eta) : '';
+ const speed = d.speed != null ? `${d.speed} MB/s` : '';
+ const meta = [speed, eta].filter(Boolean).join(' · ');
+ setProgress(pct, `${pct}% ${meta ? ` ${meta} ` : ''}`);
+ } else if (d.status === 'finished') {
+ setProgress(100, '100% Processing… ');
+ } else if (d.status === 'cancelled') {
+ sse.close();
+ } else if (d.status === 'error') {
+ sse.close();
+ showError(d.error || 'Download failed.');
+ progressWrap.style.display = 'none';
+ setLoading(downloadBtn, false);
+ }
+ };
+ sse.onerror = () => sse.close();
+
+ // AbortController so cancel can kill the fetch
+ const abort = new AbortController();
+ currentAbort = abort;
+
+ try {
+ const res = await fetch(`${API}/download`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url, format_id: formatSelect.value, file_id: fileId }),
+ signal: abort.signal,
+ });
+
+ sse.close();
+ currentSse = null;
+ currentAbort = null;
+
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({ detail: 'Download failed.' }));
+ throw new Error(data.detail || 'Download failed.');
+ }
+
+ // Only trigger file download if not cancelled
+ if (currentFileId === fileId) {
+ setProgress(100, '✓ Done — saving to your downloads ');
+ // Open in new tab so current page never navigates away
+ window.open(`${API}/file/${fileId}`, '_blank');
+ setTimeout(() => { progressWrap.style.display = 'none'; }, 2500);
+ }
+ } catch (err) {
+ sse.close();
+ currentSse = null;
+ currentAbort = null;
+ if (err.name !== 'AbortError') {
+ showError(err.message);
+ progressWrap.style.display = 'none';
+ }
+ } finally {
+ if (currentFileId === fileId) currentFileId = null;
+ setLoading(downloadBtn, false);
+ }
+});
diff --git a/web/frontend/index.html b/web/frontend/index.html
new file mode 100644
index 000000000..34f682a0b
--- /dev/null
+++ b/web/frontend/index.html
@@ -0,0 +1,135 @@
+
+
+
+
+
+ yt-dlp Web
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
yt-dlp web
+
+
+
+
+ Download any video,instantly.
+ Paste a YouTube (or any supported) link below and grab your video.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Download
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/web/frontend/style.css b/web/frontend/style.css
new file mode 100644
index 000000000..81e51da49
--- /dev/null
+++ b/web/frontend/style.css
@@ -0,0 +1,380 @@
+*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
+
+:root {
+ --bg: #0a0a0f;
+ --surface: rgba(255,255,255,0.04);
+ --surface-hover: rgba(255,255,255,0.07);
+ --border: rgba(255,255,255,0.08);
+ --border-focus: rgba(99,102,241,0.6);
+ --text: #f1f1f5;
+ --text-muted: #8b8b9e;
+ --primary: #6366f1;
+ --primary-hover: #4f52e0;
+ --success: #22c55e;
+ --error: #f87171;
+ --radius: 14px;
+ --radius-sm: 8px;
+}
+
+html { font-size: 16px; }
+
+body {
+ font-family: 'Inter', system-ui, sans-serif;
+ background: var(--bg);
+ color: var(--text);
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow-x: hidden;
+}
+
+/* Ambient background orbs */
+.bg-orbs { position: fixed; inset: 0; pointer-events: none; z-index: 0; overflow: hidden; }
+.orb {
+ position: absolute;
+ border-radius: 50%;
+ filter: blur(80px);
+ opacity: 0.18;
+}
+.orb-1 { width: 500px; height: 500px; background: #6366f1; top: -150px; left: -100px; }
+.orb-2 { width: 400px; height: 400px; background: #8b5cf6; bottom: -100px; right: -80px; }
+.orb-3 { width: 300px; height: 300px; background: #06b6d4; top: 40%; left: 50%; transform: translateX(-50%); }
+
+.container {
+ position: relative;
+ z-index: 1;
+ width: 100%;
+ max-width: 640px;
+ padding: 24px 16px 48px;
+ display: flex;
+ flex-direction: column;
+ gap: 32px;
+}
+
+/* Header */
+header { display: flex; justify-content: center; }
+.logo {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ font-weight: 700;
+ font-size: 1.1rem;
+ letter-spacing: -0.02em;
+}
+
+/* Hero */
+.hero { text-align: center; }
+.hero h1 {
+ font-size: clamp(2rem, 6vw, 2.8rem);
+ font-weight: 700;
+ line-height: 1.15;
+ letter-spacing: -0.03em;
+}
+.gradient-text {
+ background: linear-gradient(135deg, #6366f1, #a78bfa, #38bdf8);
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ background-clip: text;
+}
+.subtitle {
+ margin-top: 12px;
+ color: var(--text-muted);
+ font-size: 1rem;
+ line-height: 1.6;
+}
+
+/* Card */
+.card {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ padding: 24px;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+}
+
+/* Input row */
+.input-row { display: flex; gap: 10px; }
+.input-wrap {
+ flex: 1;
+ position: relative;
+ display: flex;
+ align-items: center;
+}
+.input-icon {
+ position: absolute;
+ left: 14px;
+ color: var(--text-muted);
+ pointer-events: none;
+ flex-shrink: 0;
+}
+#url-input {
+ width: 100%;
+ background: rgba(255,255,255,0.05);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ color: var(--text);
+ font-family: inherit;
+ font-size: 0.9rem;
+ padding: 12px 40px 12px 42px;
+ outline: none;
+ transition: border-color 0.2s, box-shadow 0.2s;
+}
+#url-input::placeholder { color: var(--text-muted); }
+#url-input:focus {
+ border-color: var(--border-focus);
+ box-shadow: 0 0 0 3px rgba(99,102,241,0.15);
+}
+.clear-btn {
+ position: absolute;
+ right: 10px;
+ background: none;
+ border: none;
+ color: var(--text-muted);
+ cursor: pointer;
+ padding: 4px;
+ border-radius: 4px;
+ display: none;
+ align-items: center;
+ transition: color 0.15s;
+}
+.clear-btn:hover { color: var(--text); }
+
+/* Buttons */
+.btn-primary {
+ background: var(--primary);
+ color: #fff;
+ border: none;
+ border-radius: var(--radius-sm);
+ font-family: inherit;
+ font-size: 0.9rem;
+ font-weight: 600;
+ padding: 12px 22px;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ white-space: nowrap;
+ transition: background 0.2s, transform 0.1s;
+ flex-shrink: 0;
+}
+.btn-primary:hover { background: var(--primary-hover); }
+.btn-primary:active { transform: scale(0.97); }
+.btn-primary:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
+
+.btn-download {
+ background: linear-gradient(135deg, #6366f1, #8b5cf6);
+ color: #fff;
+ border: none;
+ border-radius: var(--radius-sm);
+ font-family: inherit;
+ font-size: 1rem;
+ font-weight: 600;
+ padding: 14px 24px;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ transition: opacity 0.2s, transform 0.1s, box-shadow 0.2s;
+ box-shadow: 0 4px 20px rgba(99,102,241,0.3);
+}
+.btn-download:hover { opacity: 0.9; box-shadow: 0 6px 28px rgba(99,102,241,0.45); }
+.btn-download:active { transform: scale(0.98); }
+.btn-download:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
+
+/* Spinner */
+.btn-spinner {
+ width: 16px;
+ height: 16px;
+ border: 2px solid rgba(255,255,255,0.3);
+ border-top-color: #fff;
+ border-radius: 50%;
+ animation: spin 0.7s linear infinite;
+ display: inline-block;
+}
+@keyframes spin { to { transform: rotate(360deg); } }
+
+/* Error */
+.error-msg {
+ background: rgba(248,113,113,0.1);
+ border: 1px solid rgba(248,113,113,0.25);
+ color: var(--error);
+ border-radius: var(--radius-sm);
+ padding: 12px 14px;
+ font-size: 0.875rem;
+ line-height: 1.5;
+}
+
+/* Preview */
+.preview {
+ display: none;
+ gap: 16px;
+ align-items: flex-start;
+ animation: fadeIn 0.3s ease;
+}
+.preview.visible { display: flex; }.thumbnail {
+ width: 140px;
+ height: 80px;
+ object-fit: cover;
+ border-radius: var(--radius-sm);
+ flex-shrink: 0;
+ background: var(--surface-hover);
+}
+.meta { flex: 1; min-width: 0; }
+.video-title {
+ font-size: 0.95rem;
+ font-weight: 600;
+ line-height: 1.4;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.meta-row { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; }
+.tag {
+ background: rgba(255,255,255,0.07);
+ border: 1px solid var(--border);
+ border-radius: 20px;
+ padding: 3px 10px;
+ font-size: 0.75rem;
+ color: var(--text-muted);
+}
+
+/* Format selector */
+.format-section { display: flex; flex-direction: column; gap: 10px; }
+.format-label { font-size: 0.8rem; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.06em; }
+.select-wrap { position: relative; }
+.select-wrap select {
+ width: 100%;
+ background: rgba(255,255,255,0.05);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ color: var(--text);
+ font-family: inherit;
+ font-size: 0.875rem;
+ padding: 11px 40px 11px 14px;
+ appearance: none;
+ -webkit-appearance: none;
+ cursor: pointer;
+ outline: none;
+ transition: border-color 0.2s, box-shadow 0.2s;
+}
+.select-wrap select:focus {
+ border-color: var(--border-focus);
+ box-shadow: 0 0 0 3px rgba(99,102,241,0.15);
+}
+.select-wrap select option { background: #1a1a2e; color: var(--text); }
+.select-arrow {
+ position: absolute;
+ right: 12px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--text-muted);
+ pointer-events: none;
+}
+
+/* Progress */
+.progress-wrap {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ animation: fadeIn 0.3s ease;
+ background: rgba(99,102,241,0.06);
+ border: 1px solid rgba(99,102,241,0.15);
+ border-radius: var(--radius-sm);
+ padding: 14px 16px;
+}
+.progress-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+.progress-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+.progress-bar {
+ flex: 1;
+ height: 6px;
+ background: rgba(255,255,255,0.07);
+ border-radius: 99px;
+ overflow: hidden;
+}
+.progress-actions { display: flex; gap: 8px; flex-shrink: 0; }
+.progress-btn {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ border: none;
+ border-radius: 6px;
+ font-family: inherit;
+ font-size: 0.75rem;
+ font-weight: 600;
+ padding: 5px 10px;
+ cursor: pointer;
+ transition: opacity 0.15s, transform 0.1s;
+}
+.progress-btn:hover { opacity: 0.8; }
+.progress-btn:active { transform: scale(0.96); }
+.progress-btn.cancel {
+ background: rgba(248,113,113,0.12);
+ border: 1px solid rgba(248,113,113,0.25);
+ color: var(--error);
+}
+.progress-bar {
+ height: 6px;
+ background: rgba(255,255,255,0.07);
+ border-radius: 99px;
+ overflow: hidden;
+}
+.progress-fill {
+ height: 100%;
+ background: linear-gradient(90deg, #6366f1, #a78bfa, #38bdf8);
+ background-size: 200% 100%;
+ border-radius: 99px;
+ width: 0%;
+ transition: width 0.5s ease;
+ animation: shimmer 2s linear infinite;
+}
+@keyframes shimmer {
+ 0% { background-position: 200% center; }
+ 100% { background-position: -200% center; }
+}
+.progress-label {
+ font-size: 0.82rem;
+ font-weight: 500;
+ color: var(--text-muted);
+ letter-spacing: 0.01em;
+ font-variant-numeric: tabular-nums;
+}
+.progress-label .pct {
+ font-size: 1rem;
+ font-weight: 700;
+ color: var(--text);
+ letter-spacing: -0.02em;
+}
+.progress-label .meta {
+ color: var(--text-muted);
+ font-size: 0.78rem;
+}
+
+/* Footer */
+footer { text-align: center; font-size: 0.8rem; color: var(--text-muted); }
+footer a { color: var(--text-muted); text-decoration: underline; text-underline-offset: 3px; }
+footer a:hover { color: var(--text); }
+
+@keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
+
+@media (max-width: 480px) {
+ .input-row { flex-direction: column; }
+ .btn-primary { width: 100%; justify-content: center; }
+ .preview { flex-direction: column; }
+ .thumbnail { width: 100%; height: 180px; }
+}