Skip to content

Commit

Permalink
Use import typing as t convetion
Browse files Browse the repository at this point in the history
  • Loading branch information
n8henrie committed May 13, 2024
1 parent c3b47ae commit ac0c817
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 19 deletions.
14 changes: 7 additions & 7 deletions src/pycookiecheat/firefox.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
import sqlite3
import sys
import tempfile
import typing as t
import urllib.error
import urllib.parse
from pathlib import Path
from typing import Dict, List, Optional, Union

from pycookiecheat.common import (
BrowserType,
Expand Down Expand Up @@ -51,7 +51,7 @@
This makes the common.Cookie class simpler.
"""

FIREFOX_OS_PROFILE_DIRS: Dict[str, Dict[str, str]] = {
FIREFOX_OS_PROFILE_DIRS: dict[str, dict[str, str]] = {
"linux": {
BrowserType.FIREFOX: "~/.mozilla/firefox",
},
Expand Down Expand Up @@ -121,7 +121,7 @@ def _find_firefox_default_profile(firefox_dir: Path) -> str:
raise Exception("no profiles found at {}".format(firefox_dir))


def _copy_if_exists(src: List[Path], dest: Path) -> None:
def _copy_if_exists(src: list[Path], dest: Path) -> None:
for file in src:
try:
shutil.copy2(file, dest)
Expand All @@ -132,7 +132,7 @@ def _copy_if_exists(src: List[Path], dest: Path) -> None:
def _load_firefox_cookie_db(
profiles_dir: Path,
tmp_dir: Path,
profile_name: Optional[str] = None,
profile_name: t.Optional[str] = None,
) -> Path:
"""
Return a file path to the selected browser profile's cookie database.
Expand Down Expand Up @@ -177,11 +177,11 @@ def _load_firefox_cookie_db(

def firefox_cookies(
url: str,
profile_name: Optional[str] = None,
profile_name: t.Optional[str] = None,
browser: BrowserType = BrowserType.FIREFOX,
curl_cookie_file: Optional[str] = None,
curl_cookie_file: t.Optional[str] = None,
as_cookies: bool = False,
) -> Union[dict, list[Cookie]]:
) -> t.Union[dict, list[Cookie]]:
"""Retrieve cookies from Firefox on MacOS or Linux.
Args:
Expand Down
26 changes: 14 additions & 12 deletions tests/test_firefox.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Tests for Firefox cookies & helper functions."""

import re
import typing as t
from datetime import datetime, timedelta
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from textwrap import dedent
from threading import Thread
from typing import Any, cast, Iterator, Optional
from unittest.mock import patch
from urllib.error import URLError

Expand Down Expand Up @@ -103,7 +103,7 @@

def _make_test_profiles(
tmp_path: Path, profiles_ini_content: str, populate: bool = True
) -> Iterator[Path]:
) -> t.Iterator[Path]:
"""Create a Firefox data dir with profile & (optionally) populate it.
All of the fixtures using this function use the pytest builtin `tmp_path`
Expand All @@ -126,7 +126,7 @@ def _make_test_profiles(


@pytest.fixture(scope="module")
def profiles(tmp_path_factory: TempPathFactory) -> Iterator[Path]:
def profiles(tmp_path_factory: TempPathFactory) -> t.Iterator[Path]:
"""Create a Firefox data dir with profiles & cookie DBs."""
yield from _make_test_profiles(
tmp_path_factory.mktemp("_"), PROFILES_INI_VERSION2
Expand All @@ -144,7 +144,7 @@ def profiles(tmp_path_factory: TempPathFactory) -> Iterator[Path]:
)
def profiles_ini_versions(
tmp_path_factory: TempPathFactory, request: FixtureRequest
) -> Iterator[Path]:
) -> t.Iterator[Path]:
"""Create a Firefox data dir using varius `profiles.ini` types.
Use different file format versions and contents.
Expand All @@ -153,7 +153,7 @@ def profiles_ini_versions(


@pytest.fixture(scope="module")
def no_profiles(tmp_path_factory: TempPathFactory) -> Iterator[Path]:
def no_profiles(tmp_path_factory: TempPathFactory) -> t.Iterator[Path]:
"""Create a Firefox data dir with a `profiles.ini` with no profiles."""
yield from _make_test_profiles(
tmp_path_factory.mktemp("_"), PROFILES_INI_EMPTY
Expand All @@ -163,7 +163,7 @@ def no_profiles(tmp_path_factory: TempPathFactory) -> Iterator[Path]:
# TODO: Making this fixture module-scoped breaks the tests using the `profiles`
# fixture. Find out why.
@pytest.fixture
def profiles_unpopulated(tmp_path: Path) -> Iterator[Path]:
def profiles_unpopulated(tmp_path: Path) -> t.Iterator[Path]:
"""Create a Firefox data dir with valid but upopulated `profiles.ini` file.
"Unpopulated" means never actually used to launch Firefox with.
Expand All @@ -174,7 +174,7 @@ def profiles_unpopulated(tmp_path: Path) -> Iterator[Path]:


@pytest.fixture(scope="session")
def cookie_server() -> Iterator[int]:
def cookie_server() -> t.Iterator[int]:
"""Start an `HTTPServer` on localhost which sets a cookie.
Replies to GET requests by setting a "foo: bar" cookie.
Expand All @@ -201,7 +201,7 @@ def do_GET(self) -> None: # noqa: N802, must be named with HTTP verb
self.send_header("Set-Cookie", cookie["foo"].OutputString())
self.end_headers()

def log_message(self, *_: Any) -> None:
def log_message(self, *_: t.Any) -> None:
pass # Suppress logging

with HTTPServer(("localhost", 0), CookieSetter) as server:
Expand All @@ -211,7 +211,7 @@ def log_message(self, *_: Any) -> None:


@pytest.fixture
def set_cookie(profiles: Path, cookie_server: int) -> Iterator[None]:
def set_cookie(profiles: Path, cookie_server: int) -> t.Iterator[None]:
"""Launch Firefox and visit the cookie-setting server.
The cookie is set, saved to the DB and the browser closes. Ideally the
Expand Down Expand Up @@ -304,7 +304,7 @@ def test_load_firefox_cookie_db_populated(
@pytest.mark.parametrize("profile_name", [TEST_PROFILE_DIR, None])
def test_load_firefox_cookie_db_unpopulated(
tmp_path: Path,
profile_name: Optional[str],
profile_name: t.Optional[str],
profiles_unpopulated: Path,
) -> None:
"""Test loading Firefox cookies DB from an unpopulated profile."""
Expand Down Expand Up @@ -336,7 +336,9 @@ def test_load_firefox_cookie_db_copy_error(

def test_firefox_cookies(set_cookie: None) -> None:
"""Test getting Firefox cookies after visiting a site with cookies."""
cookies = cast(dict, firefox_cookies("http://localhost", TEST_PROFILE_DIR))
cookies = t.cast(
dict, firefox_cookies("http://localhost", TEST_PROFILE_DIR)
)
assert len(cookies) > 0
assert cookies["foo"] == "bar"

Expand All @@ -349,7 +351,7 @@ def test_warns_for_string_browser(set_cookie: None) -> None:
"Please pass `browser` as a `BrowserType` " "instead of `str`."
),
):
cookies = cast(
cookies = t.cast(
dict,
firefox_cookies(
"http://localhost",
Expand Down

0 comments on commit ac0c817

Please sign in to comment.