Skip to content

Instantly share code, notes, and snippets.

@wyattowalsh
Last active August 21, 2026 14:47
Show Gist options
  • Select an option

  • Save wyattowalsh/1415d657dfad77a52319cac904399c4a to your computer and use it in GitHub Desktop.

Select an option

Save wyattowalsh/1415d657dfad77a52319cac904399c4a to your computer and use it in GitHub Desktop.
ats-jobs

"""Run the complete local release gate for the ats-jobs Gist."""

from future import annotations

import argparse import subprocess import sys import tomllib# ats-jobs

Fetch public job postings from Greenhouse, Lever, Ashby, Workable, BambooHR, and Workday using a native ATS URL or a company careers page.

Run

uvx \
  --from git+https://gist.github.com/1415d657dfad77a52319cac904399c4a.git \
  ats-jobs \
  https://jobs.ashbyhq.com/agentio/e4438c35-0766-4a03-8a3a-335514a2dc3a

Or run the script directly:

uv run \
  https://gist.githubusercontent.com/wyattowalsh/1415d657dfad77a52319cac904399c4a/raw/ats_jobs.py \
  https://jobs.ashbyhq.com/agentio

A board URL lists jobs. A posting URL fetches one job. A normal company careers URL is discovered through redirects, canonical and embedded links, provider-specific page metadata, URL-encoded ATS links, relative Workday CXS paths, and bounded board-slug probes.

Output

Interactive terminals default to a semantic Rich view that omits duplicated provider payloads:

ats-jobs JOB_URL
ats-jobs JOB_URL --pretty
ats-jobs JOB_URL --pretty --pager
ats-jobs BOARD_URL --pretty

Pipes and files default to normalized, indented JSON:

ats-jobs BOARD_URL | jq '.[].title'
ats-jobs JOB_URL --format json
ats-jobs BOARD_URL --format jsonl
ats-jobs BOARD_URL --format table
ats-jobs JOB_URL --raw --format json
ats-jobs BOARD_URL --output jobs.json

--raw preserves provider-native records. Pretty output intentionally excludes source and description_html while retaining the readable description and key metadata.

Discovery and diagnosis

ats-jobs detect https://company.com/careers
ats-jobs inspect https://company.com/careers
ats-jobs https://company.com/careers -v
ats-jobs https://company.com/careers -vv

Useful controls:

-p, --provider PROVIDER   constrain discovery to one provider
--offline                 require a native ATS URL and make no discovery request
--no-probe                inspect redirects and page links without slug probes
--documented-only         reject BambooHR and Workday browser-facing interfaces
-q, --quiet               suppress warnings and progress
-v, --verbose             show resolution and fetch summaries; repeat for HTTP details

Commands

ats-jobs URL              infer list or get
ats-jobs list URL         fetch all public postings
ats-jobs get URL          fetch one posting
ats-jobs detect URL       print the provider
ats-jobs inspect URL      print discovery provenance and parsed identifiers
ats-jobs providers        show capabilities and support tiers
ats-jobs version          print the version

Run ats-jobs -h or ats-jobs COMMAND -h for contextual Typer help.

Provider support

Provider List Get
Greenhouse documented public API documented public API
Lever documented public API documented public API
Ashby documented public feed exact local URL match
Workable documented public collection exact local shortcode or URL match
BambooHR undocumented hosted-careers JSON undocumented hosted-careers JSON
Workday undocumented hosted-careers CXS undocumented hosted-careers CXS

BambooHR and Workday may drift without notice. --documented-only rejects both.

Development

Python 3.13 and uv are required.

uv sync
uv run ruff check
uv run ruff format --check
uv run ty check
uv run pytest
uv run verify.py

The offline suite uses httpx.MockTransport: 189 tests, 98.80% combined statement and branch coverage.

MIT licensed.

from dataclasses import dataclass from pathlib import Path

ROOT = Path(file).resolve().parent

@dataclass(frozen=True, slots=True) class Gate: """One release-gate command."""

name: str
command: tuple[str, ...]

def read_inline_script_metadata(path: Path) -> dict[str, object]: """Parse the PEP 723 TOML block from a Python script.""" lines = path.read_text(encoding="utf-8").splitlines() try: start = lines.index("# /// script") + 1 end = lines.index("# ///", start) except ValueError as exc: msg = f"{path.name}: missing PEP 723 script metadata" raise RuntimeError(msg) from exc body = "\n".join(line.removeprefix("# ") for line in lines[start:end]) parsed = tomllib.loads(body) return parsed

def read_project_metadata(path: Path) -> dict[str, object]: """Read pyproject.toml.""" with path.open("rb") as handle: return tomllib.load(handle)

def normalize_dependencies(values: object) -> tuple[str, ...]: """Normalize a dependency collection for exact parity checks.""" if not isinstance(values, list) or not all(isinstance(item, str) for item in values): msg = "dependencies must be a list of strings" raise RuntimeError(msg) return tuple(sorted(values))

def verify_metadata() -> None: """Check duplicated package/script metadata that must stay synchronized.""" script = read_inline_script_metadata(ROOT / "ats_jobs.py") pyproject = read_project_metadata(ROOT / "pyproject.toml") project = pyproject.get("project") if not isinstance(project, dict): msg = "pyproject.toml is missing [project]" raise RuntimeError(msg)

script_dependencies = normalize_dependencies(script.get("dependencies"))
project_dependencies = normalize_dependencies(project.get("dependencies"))
if script_dependencies != project_dependencies:
    msg = "PEP 723 and pyproject.toml runtime dependencies differ"
    raise RuntimeError(msg)

script_python = script.get("requires-python")
project_python = project.get("requires-python")
if script_python != project_python:
    msg = "PEP 723 and pyproject.toml Python requirements differ"
    raise RuntimeError(msg)

script_tool = script.get("tool")
project_tool = pyproject.get("tool")
if not isinstance(script_tool, dict) or not isinstance(project_tool, dict):
    msg = "PEP 723 and pyproject.toml must both define [tool.uv]"
    raise RuntimeError(msg)
script_uv = script_tool.get("uv")
project_uv = project_tool.get("uv")
if not isinstance(script_uv, dict) or not isinstance(project_uv, dict):
    msg = "PEP 723 and pyproject.toml must both define [tool.uv]"
    raise RuntimeError(msg)
if script_uv.get("exclude-newer") != project_uv.get("exclude-newer"):
    msg = "PEP 723 and pyproject.toml exclude-newer values differ"
    raise RuntimeError(msg)

version = project.get("version")
source = (ROOT / "ats_jobs.py").read_text(encoding="utf-8")
if not isinstance(version, str) or f'__version__ = "{version}"' not in source:
    msg = "pyproject.toml and ats_jobs.py versions differ"
    raise RuntimeError(msg)

def run_gate(gate: Gate) -> None: """Run one command, stopping at the first failure.""" print(f"\n==> {gate.name}\n$ {' '.join(gate.command)}", flush=True) completed = subprocess.run(gate.command, cwd=ROOT, check=False) if completed.returncode: raise SystemExit(completed.returncode)

def gates() -> tuple[Gate, ...]: """Return the canonical python-conventions completion sequence.""" return ( Gate("Ruff lint", ("uv", "run", "ruff", "check")), Gate("Ruff format", ("uv", "run", "ruff", "format", "--check")), Gate("ty", ("uv", "run", "ty", "check")), Gate("pytest and coverage", ("uv", "run", "pytest")), Gate("Build package", ("uv", "build")), Gate("Package entry point", ("uvx", "--from", ".", "ats-jobs", "version")), Gate( "PEP 723 script entry point", ("uv", "run", "--no-project", "ats_jobs.py", "version"), ), )

def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description=doc) parser.add_argument( "--metadata-only", action="store_true", help="Only validate PEP 723, pyproject.toml, and version parity.", ) return parser.parse_args(argv)

def main(argv: list[str] | None = None) -> int: """Execute metadata checks and, unless disabled, every release gate.""" args = parse_args(argv) try: verify_metadata() except RuntimeError as exc: print(f"metadata check failed: {exc}", file=sys.stderr) return 1 print("metadata parity: PASS") if args.metadata_only: return 0 for gate in gates(): run_gate(gate) print("\nall release gates: PASS") return 0

if name == "main": raise SystemExit(main())

# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx>=0.28,<0.29",
# "pydantic>=2.11,<3",
# "rich>=14.1,<16",
# "typer>=0.20,<1",
# ]
# [tool.uv]
# exclude-newer = "2026-08-21T00:00:00Z"
# ///
"""Fetch public ATS job postings from one careers or job URL."""
from __future__ import annotations
import html
import ipaddress
import io
import json
import re
import sys
import tempfile
import time
import traceback
from collections.abc import Callable, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import UTC, datetime
from enum import IntEnum, StrEnum
from html.parser import HTMLParser
from pathlib import Path
from typing import Annotated, Any, Final, Iterator, Protocol, cast
from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlsplit, urlunsplit
import httpx
import typer
from pydantic import BaseModel, ConfigDict, Field, field_validator
from rich import box
from rich.console import Console, Group, RenderableType
from rich.panel import Panel
from rich.rule import Rule
from rich.table import Table
from rich.text import Text
__version__ = "0.3.0"
USER_AGENT: Final = f"ats-jobs/{__version__}"
MAX_RESPONSE_BYTES: Final = 25 * 1024 * 1024
MAX_DISCOVERY_BYTES: Final = 5 * 1024 * 1024
MAX_PAGES: Final = 10_000
MAX_REDIRECTS: Final = 5
LEVER_PAGE_SIZE: Final = 100
WORKDAY_PAGE_SIZE: Final = 20
RETRYABLE_STATUS_CODES: Final = frozenset({408, 425, 429, 500, 502, 503, 504})
TRACKING_QUERY_KEYS: Final = frozenset(
{
"gh_src",
"ref",
"referrer",
"source",
"trk",
}
)
type JsonObject = dict[str, Any]
type JsonValue = JsonObject | list[Any] | str | int | float | bool | None
type EventSink = Callable[[str], None]
class ExitCode(IntEnum):
"""Stable process exit codes."""
SUCCESS = 0
INPUT = 2
NOT_FOUND = 3
AMBIGUOUS = 4
TRANSPORT = 5
INVALID_JSON = 6
SCHEMA = 7
UNSUPPORTED = 8
PAGINATION = 9
RUNTIME = 10
PERMISSION = 11
RATE_LIMIT = 12
class Provider(StrEnum):
"""Supported ATS providers."""
GREENHOUSE = "greenhouse"
LEVER = "lever"
ASHBY = "ashby"
WORKABLE = "workable"
BAMBOOHR = "bamboohr"
WORKDAY = "workday"
class SupportTier(StrEnum):
"""Evidence level for an operation's upstream interface."""
DOCUMENTED_PUBLIC = "documented-public"
DOCUMENTED_DERIVED = "documented-derived"
UNDOCUMENTED_PUBLIC = "undocumented-public"
class Operation(StrEnum):
"""Supported fetch operations."""
LIST = "list"
GET = "get"
class OutputFormat(StrEnum):
"""CLI output formats."""
AUTO = "auto"
PRETTY = "pretty"
JSON = "json"
JSONL = "jsonl"
TABLE = "table"
class DiscoveryMethod(StrEnum):
"""How a user URL was resolved to a provider-native ATS target."""
DIRECT = "direct-host"
OVERRIDE = "provider-override"
REDIRECT = "redirect"
CANONICAL = "canonical-link"
META = "metadata-link"
EMBED = "embedded-link"
LINK = "page-link"
HTML = "html-pattern"
SLUG_PROBE = "slug-probe"
class ATSJobsError(Exception):
"""Base domain error carrying a stable exit code."""
exit_code = ExitCode.RUNTIME
def __init__(
self,
message: str,
*,
provider: Provider | None = None,
operation: Operation | None = None,
url: str | None = None,
) -> None:
super().__init__(message)
self.message = message
self.provider = provider
self.operation = operation
self.url = sanitize_url(url) if url else None
def __str__(self) -> str:
context = [
value
for value in (
self.provider.value if self.provider else None,
self.operation.value if self.operation else None,
)
if value
]
prefix = f"[{'/'.join(context)}] " if context else ""
suffix = f" ({self.url})" if self.url else ""
return f"{prefix}{self.message}{suffix}"
class InputError(ATSJobsError):
exit_code = ExitCode.INPUT
class NotFoundError(ATSJobsError):
exit_code = ExitCode.NOT_FOUND
class AmbiguousMatchError(ATSJobsError):
exit_code = ExitCode.AMBIGUOUS
class TransportError(ATSJobsError):
exit_code = ExitCode.TRANSPORT
class InvalidJSONError(ATSJobsError):
exit_code = ExitCode.INVALID_JSON
class SchemaError(ATSJobsError):
exit_code = ExitCode.SCHEMA
class UnsupportedInterfaceError(ATSJobsError):
exit_code = ExitCode.UNSUPPORTED
class PaginationError(ATSJobsError):
exit_code = ExitCode.PAGINATION
class PermissionError(ATSJobsError):
exit_code = ExitCode.PERMISSION
class RateLimitError(ATSJobsError):
exit_code = ExitCode.RATE_LIMIT
@dataclass(frozen=True, slots=True)
class CliReporter:
"""Human-friendly CLI diagnostics that never contaminate stdout."""
verbose: int = 0
quiet: bool = False
@staticmethod
def _emit(
label: str,
message: str,
*,
color: str | None = None,
bold: bool = False,
dim: bool = False,
) -> None:
typer.secho(
f"{label:<7} {message}",
fg=color,
bold=bold,
dim=dim,
err=True,
)
def warning(self, message: str) -> None:
"""Emit a warning unless quiet mode is active."""
if not self.quiet:
self._emit("WARNING", message, color=typer.colors.YELLOW)
def info(self, message: str) -> None:
"""Emit progress at ``-v`` or above."""
if self.verbose >= 1 and not self.quiet:
self._emit("INFO", message, color=typer.colors.CYAN)
def debug(self, message: str) -> None:
"""Emit request-level detail at ``-vv`` or above."""
if self.verbose >= 2 and not self.quiet:
self._emit("DEBUG", message, color=typer.colors.BLUE, dim=True)
def success(self, message: str) -> None:
"""Emit a completion summary at ``-v`` or above."""
if self.verbose >= 1 and not self.quiet:
self._emit("OK", message, color=typer.colors.GREEN, bold=True)
@contextmanager
def status(self, message: str) -> Iterator[None]:
"""Show a transient spinner only on an interactive stderr terminal."""
if self.quiet or self.verbose >= 1 or not sys.stderr.isatty():
yield
return
console = Console(stderr=True, highlight=False)
with console.status(message, spinner="dots"):
yield
def error(self, error: ATSJobsError) -> None:
"""Emit a domain error and its most useful remediation."""
self._emit("ERROR", str(error), color=typer.colors.RED, bold=True)
hint = cli_error_hint(error)
if hint:
self._emit("HINT", hint, color=typer.colors.CYAN)
def unexpected(self, error: Exception) -> None:
"""Emit a safe unexpected-error summary, with a trace only at ``-vv``."""
self._emit(
"ERROR",
f"unexpected {type(error).__name__}: {error}",
color=typer.colors.RED,
bold=True,
)
if self.verbose >= 2:
traceback.print_exc(file=sys.stderr)
else:
self._emit(
"HINT",
"Re-run with -vv for request details and a traceback.",
color=typer.colors.CYAN,
)
def cli_error_hint(error: ATSJobsError) -> str | None:
"""Return a concise next step for a CLI-facing domain error."""
if isinstance(error, UnsupportedInterfaceError):
return "Remove --documented-only to allow this best-effort public interface."
if isinstance(error, NotFoundError):
return "Verify that the board or posting is public and that the URL has not expired."
if isinstance(error, AmbiguousMatchError):
return "Use the canonical posting URL or a provider-specific posting identifier."
if isinstance(error, PermissionError):
return "Confirm that the careers page is public and does not require authentication."
if isinstance(error, InvalidJSONError):
return "The provider returned non-JSON content; retry with -vv to inspect the request path."
if isinstance(error, RateLimitError):
return "Retry later or reduce request frequency."
if isinstance(error, PaginationError):
return "Retry once; the board may have changed while pages were being collected."
if isinstance(error, SchemaError):
return "The provider response may have changed. Re-run with -vv before reporting it."
if isinstance(error, TransportError):
return "Check connectivity and the URL. Re-run with -vv for HTTP request details."
if isinstance(error, InputError):
if "unsupported ATS hostname" in error.message or "could not detect" in error.message:
return (
"Paste the public careers page or native ATS URL, keep --discover enabled, "
"or set --provider explicitly."
)
if "--raw" in error.message and "json" in error.message:
return "Use --format json or --format jsonl with --raw."
if "--quiet cannot be combined" in error.message:
return "Choose quiet mode or verbosity, not both."
if "--pretty cannot be combined" in error.message:
return "Use --pretty by itself, or choose exactly one --format value."
if "--pager cannot be combined" in error.message:
return "Choose terminal paging or file output, not both."
if "--pager requires" in error.message:
return "Use --pretty --pager, or omit --pager for machine-readable output."
if "board but not an individual posting" in error.message:
return "Use `list` for the board or paste the provider's direct posting URL."
return "Run `ats-jobs --help` or `ats-jobs <command> --help` for examples."
return None
class ProviderSpec(BaseModel):
"""Static provider capability metadata."""
model_config = ConfigDict(frozen=True)
provider: Provider
hosts: tuple[str, ...]
list_support: SupportTier
get_support: SupportTier
list_semantics: str
notes: str | None = None
verified_at: str = "2026-08-21"
class Target(BaseModel):
"""Provider-specific information parsed from a user URL."""
model_config = ConfigDict(frozen=True)
provider: Provider
original_url: str
origin: str
operation: Operation
board: str | None = None
job_id: str | None = None
region: str | None = None
tenant: str | None = None
site: str | None = None
external_path: str | None = None
class DiscoveryResult(BaseModel):
"""Resolved target plus explainable discovery provenance."""
model_config = ConfigDict(frozen=True)
requested_url: str
resolved_url: str
method: DiscoveryMethod
target: Target
visited_urls: tuple[str, ...] = ()
probed_slugs: tuple[str, ...] = ()
class FetchOptions(BaseModel):
"""Provider-independent fetch options."""
model_config = ConfigDict(frozen=True)
include_unlisted: bool = False
documented_only: bool = False
class JobPosting(BaseModel):
"""Minimal cross-provider representation with the source object retained."""
model_config = ConfigDict(extra="forbid")
provider: Provider
id: str
title: str
company: str | None = None
location: str | None = None
department: str | None = None
employment_type: str | None = None
description_html: str | None = None
description_text: str | None = None
job_url: str
apply_url: str | None = None
published_at: str | None = None
remote: bool | None = None
source: JsonObject = Field(default_factory=dict)
@field_validator("id", "title", "job_url")
@classmethod
def _non_empty(cls, value: str) -> str:
if not value.strip():
msg = "must not be empty"
raise ValueError(msg)
return value
PROVIDER_SPECS: Final[dict[Provider, ProviderSpec]] = {
Provider.GREENHOUSE: ProviderSpec(
provider=Provider.GREENHOUSE,
hosts=("boards.greenhouse.io", "job-boards.greenhouse.io", "boards-api.greenhouse.io"),
list_support=SupportTier.DOCUMENTED_PUBLIC,
get_support=SupportTier.DOCUMENTED_PUBLIC,
list_semantics="All public job posts returned by the board's Job Board API.",
),
Provider.LEVER: ProviderSpec(
provider=Provider.LEVER,
hosts=("jobs.lever.co", "jobs.eu.lever.co", "api.lever.co", "api.eu.lever.co"),
list_support=SupportTier.DOCUMENTED_PUBLIC,
get_support=SupportTier.DOCUMENTED_PUBLIC,
list_semantics="All published postings returned through explicit offset pagination.",
),
Provider.ASHBY: ProviderSpec(
provider=Provider.ASHBY,
hosts=("jobs.ashbyhq.com", "api.ashbyhq.com"),
list_support=SupportTier.DOCUMENTED_PUBLIC,
get_support=SupportTier.DOCUMENTED_DERIVED,
list_semantics=(
"Listed public postings by default; include direct-link postings on request."
),
notes="Single-job lookup is an exact local match against the documented public feed.",
),
Provider.WORKABLE: ProviderSpec(
provider=Provider.WORKABLE,
hosts=("apply.workable.com", "jobs.workable.com", "www.workable.com"),
list_support=SupportTier.DOCUMENTED_PUBLIC,
get_support=SupportTier.DOCUMENTED_DERIVED,
list_semantics="Public postings from the account endpoint with details enabled.",
notes="Single-job lookup is an exact local shortcode or URL match.",
),
Provider.BAMBOOHR: ProviderSpec(
provider=Provider.BAMBOOHR,
hosts=("*.bamboohr.com",),
list_support=SupportTier.UNDOCUMENTED_PUBLIC,
get_support=SupportTier.UNDOCUMENTED_PUBLIC,
list_semantics="Openings exposed by BambooHR's hosted-careers browser interface.",
notes="The hosted-careers JSON interface is undocumented and may change without notice.",
),
Provider.WORKDAY: ProviderSpec(
provider=Provider.WORKDAY,
hosts=("*.myworkdayjobs.com", "*.myworkdaysite.com"),
list_support=SupportTier.UNDOCUMENTED_PUBLIC,
get_support=SupportTier.UNDOCUMENTED_PUBLIC,
list_semantics="Public postings exposed by the hosted-careers CXS interface.",
notes="CXS is an undocumented browser-facing interface, not Workday Web Services.",
),
}
def sanitize_url(value: str | None) -> str | None:
"""Remove credentials, query parameters, and fragments from a diagnostic URL."""
if value is None:
return None
try:
parsed = urlsplit(value)
except ValueError:
return "<invalid-url>"
host = parsed.hostname or ""
if parsed.port:
host = f"{host}:{parsed.port}"
return urlunsplit((parsed.scheme, host, parsed.path, "", ""))
def coerce_url(value: str) -> str:
"""Accept a normal HTTP(S) URL, adding https:// to a bare hostname."""
candidate = value.strip()
if not candidate:
raise InputError("URL must not be empty")
if "://" not in candidate and "." in candidate.split("/", 1)[0]:
candidate = f"https://{candidate}"
try:
parsed = urlsplit(candidate)
except ValueError as exc:
raise InputError("URL could not be parsed", url=candidate) from exc
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
raise InputError("URL must use http or https and include a hostname", url=candidate)
if parsed.username or parsed.password:
raise InputError("embedded URL credentials are not allowed", url=candidate)
try:
parsed.hostname.encode("idna")
except UnicodeError as exc:
raise InputError("URL hostname is invalid", url=candidate) from exc
return candidate
def canonicalize_url(value: str) -> str:
"""Canonicalize a URL for exact provider-job matching."""
parsed = urlsplit(coerce_url(value))
host = cast(str, parsed.hostname).encode("idna").decode("ascii").lower()
if parsed.port:
host = f"{host}:{parsed.port}"
path = re.sub(r"/{2,}", "/", parsed.path or "/")
if path != "/":
path = path.rstrip("/")
path = quote(path, safe="/%:@~!$&'()*+,;=-._")
query = [
(key, item)
for key, item in parse_qsl(parsed.query, keep_blank_values=True)
if not key.lower().startswith("utm_") and key.lower() not in TRACKING_QUERY_KEYS
]
query.sort()
return urlunsplit((parsed.scheme.lower(), host, path, urlencode(query), ""))
def strip_html(value: str | None) -> str | None:
"""Convert provider HTML to compact plain text without evaluating it."""
if value is None:
return None
text = re.sub(r"<(br|/p|/li|/div|/h[1-6])\b[^>]*>", "\n", value, flags=re.IGNORECASE)
text = re.sub(r"<[^>]+>", " ", text)
text = html.unescape(text)
text = re.sub(r"[ \t\r\f\v]+", " ", text)
text = re.sub(r"\s+([.,;:!?])", r"\1", text)
text = re.sub(r" *\n+ *", "\n", text)
return text.strip() or None
def timestamp_to_iso(value: Any) -> str | None:
"""Normalize common epoch-millisecond or string timestamps."""
if isinstance(value, bool) or value is None:
return None
if isinstance(value, int | float):
seconds = float(value) / 1000 if value > 10_000_000_000 else float(value)
try:
return datetime.fromtimestamp(seconds, tz=UTC).isoformat().replace("+00:00", "Z")
except (OverflowError, OSError, ValueError):
return None
if isinstance(value, str):
return value.strip() or None
return None
def _segments(path: str) -> list[str]:
return [segment for segment in path.split("/") if segment]
def _is_locale(segment: str) -> bool:
return bool(re.fullmatch(r"[a-zA-Z]{2}(?:-[a-zA-Z]{2})?", segment))
def _valid_identifier(value: str | None, *, name: str) -> str:
if value is None or not re.fullmatch(r"[A-Za-z0-9._-]+", value):
raise InputError(f"could not derive a valid {name}")
return value
def _provider_matches_host(provider: Provider, host: str) -> bool:
"""Return whether a hostname belongs to a provider's native surfaces."""
lowered = host.lower()
if provider is Provider.GREENHOUSE:
return lowered in PROVIDER_SPECS[provider].hosts
if provider is Provider.LEVER:
return lowered in PROVIDER_SPECS[provider].hosts
if provider is Provider.ASHBY:
return lowered in PROVIDER_SPECS[provider].hosts
if provider is Provider.WORKABLE:
return lowered in {"apply.workable.com", "jobs.workable.com", "www.workable.com"} or (
lowered.endswith(".workable.com") and lowered.count(".") >= 2
)
if provider is Provider.BAMBOOHR:
return lowered.endswith(".bamboohr.com")
return lowered.endswith(".myworkdayjobs.com") or lowered.endswith(".myworkdaysite.com")
def detect_provider(value: str, override: Provider | None = None) -> Provider:
"""Detect the ATS provider from a URL hostname."""
if override is not None:
return override
parsed = urlsplit(coerce_url(value))
host = cast(str, parsed.hostname).lower()
for provider in Provider:
if _provider_matches_host(provider, host):
return provider
raise InputError("unsupported ATS hostname", url=value)
def parse_target(value: str, override: Provider | None = None) -> Target:
"""Parse a careers or job URL into provider-specific identifiers."""
url = coerce_url(value)
host = cast(str, urlsplit(url).hostname).lower()
if override is not None and not _provider_matches_host(override, host):
path = urlsplit(url).path
custom_workday_cxs = override is Provider.WORKDAY and path.startswith("/wday/cxs/")
if not custom_workday_cxs:
raise InputError(
"provider override needs discovery for a non-provider hostname",
url=url,
)
provider = detect_provider(url, override)
parser = TARGET_PARSERS[provider]
return parser(url)
def _parse_greenhouse(url: str) -> Target:
parsed = urlsplit(url)
host = cast(str, parsed.hostname).lower()
parts = _segments(parsed.path)
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
board: str | None = None
job_id: str | None = None
if host == "boards-api.greenhouse.io":
if len(parts) >= 4 and parts[:2] == ["v1", "boards"] and parts[3] == "jobs":
board = parts[2]
job_id = parts[4] if len(parts) >= 5 else None
elif parts[:1] == ["embed"]:
board = query.get("for")
job_id = query.get("token") or query.get("gh_jid")
elif parts:
board = parts[0]
if "jobs" in parts:
index = parts.index("jobs")
job_id = parts[index + 1] if len(parts) > index + 1 else None
if board is None:
board = query.get("for")
if job_id is None:
job_id = query.get("gh_jid")
board = _valid_identifier(board, name="Greenhouse board token")
if job_id is not None and not job_id.isdigit():
raise InputError("Greenhouse job-post ID must be numeric", url=url)
return Target(
provider=Provider.GREENHOUSE,
original_url=url,
origin="https://boards-api.greenhouse.io",
operation=Operation.GET if job_id else Operation.LIST,
board=board,
job_id=job_id,
)
def _parse_lever(url: str) -> Target:
parsed = urlsplit(url)
host = cast(str, parsed.hostname).lower()
parts = _segments(parsed.path)
region = "eu" if ".eu." in host else "global"
if host.startswith("api."):
if len(parts) < 3 or parts[:2] != ["v0", "postings"]:
raise InputError("could not derive Lever site from API URL", url=url)
site = parts[2]
job_id = parts[3] if len(parts) >= 4 else None
else:
site = parts[0] if parts else None
job_id = parts[1] if len(parts) >= 2 else None
site = _valid_identifier(site, name="Lever site")
if job_id is not None:
job_id = _valid_identifier(job_id, name="Lever posting ID")
origin = "https://api.eu.lever.co" if region == "eu" else "https://api.lever.co"
return Target(
provider=Provider.LEVER,
original_url=url,
origin=origin,
operation=Operation.GET if job_id else Operation.LIST,
board=site,
job_id=job_id,
region=region,
)
def _parse_ashby(url: str) -> Target:
parsed = urlsplit(url)
host = cast(str, parsed.hostname).lower()
parts = _segments(parsed.path)
if host == "api.ashbyhq.com":
prefix = ["posting-api", "job-board"]
if len(parts) < 3 or parts[:2] != prefix:
raise InputError("could not derive Ashby board name from API URL", url=url)
board = parts[2]
job_id = None
else:
board = parts[0] if parts else None
job_id = parts[1] if len(parts) >= 2 else None
board = _valid_identifier(board, name="Ashby board name")
return Target(
provider=Provider.ASHBY,
original_url=url,
origin="https://api.ashbyhq.com",
operation=Operation.GET if job_id else Operation.LIST,
board=board,
job_id=job_id,
)
def _parse_workable(url: str) -> Target:
parsed = urlsplit(url)
host = cast(str, parsed.hostname).lower()
parts = _segments(parsed.path)
account: str | None = None
job_id: str | None = None
if host in {"apply.workable.com", "jobs.workable.com", "www.workable.com"}:
if host == "www.workable.com" and len(parts) >= 3 and parts[:2] == ["api", "accounts"]:
account = parts[2]
return Target(
provider=Provider.WORKABLE,
original_url=url,
origin="https://www.workable.com",
operation=Operation.LIST,
board=_valid_identifier(account, name="Workable account"),
)
if host == "jobs.workable.com" and parts[:1] == ["view"]:
raise InputError(
"Workable view URLs do not expose the account; use the account careers URL",
url=url,
)
if parts[:1] in (["j"], ["view"]):
raise InputError(
"Workable short job URLs do not expose the account; use an account-bearing URL",
url=url,
)
account = parts[0] if parts else None
if len(parts) >= 3 and parts[1] in {"j", "jobs"}:
job_id = parts[2]
elif len(parts) >= 2 and parts[1] not in {"jobs"}:
job_id = parts[1]
else:
account = host.split(".", 1)[0]
if parts:
job_id = parts[-1] if parts[-1] not in {"careers", "jobs"} else None
account = _valid_identifier(account, name="Workable account")
if job_id is not None:
job_id = _valid_identifier(job_id, name="Workable shortcode")
return Target(
provider=Provider.WORKABLE,
original_url=url,
origin="https://www.workable.com",
operation=Operation.GET if job_id else Operation.LIST,
board=account,
job_id=job_id,
)
def _parse_bamboohr(url: str) -> Target:
parsed = urlsplit(url)
host = cast(str, parsed.hostname).lower()
tenant = host.removesuffix(".bamboohr.com")
tenant = _valid_identifier(tenant, name="BambooHR tenant")
parts = _segments(parsed.path)
job_id: str | None = None
if "careers" in parts:
index = parts.index("careers")
if len(parts) > index + 1 and parts[index + 1].isdigit():
job_id = parts[index + 1]
return Target(
provider=Provider.BAMBOOHR,
original_url=url,
origin=f"https://{tenant}.bamboohr.com",
operation=Operation.GET if job_id else Operation.LIST,
tenant=tenant,
job_id=job_id,
)
def _parse_workday(url: str) -> Target:
parsed = urlsplit(url)
host = cast(str, parsed.hostname).lower()
parts = _segments(parsed.path)
tenant: str | None = None
site: str | None = None
tail: list[str] = []
if len(parts) >= 4 and parts[:2] == ["wday", "cxs"]:
tenant, site = parts[2], parts[3]
tail = parts[4:]
elif host.endswith(".myworkdaysite.com"):
if len(parts) < 3 or parts[0] != "recruiting":
raise InputError("expected /recruiting/TENANT/SITE in Workday URL", url=url)
tenant, site = parts[1], parts[2]
tail = parts[3:]
else:
tenant = host.split(".", 1)[0]
if parts and _is_locale(parts[0]):
parts = parts[1:]
if parts:
site = parts[0]
tail = parts[1:]
tenant = _valid_identifier(tenant, name="Workday tenant")
site = _valid_identifier(site, name="Workday site")
external_path = f"/{'/'.join(tail)}" if tail and tail[0] == "job" else None
return Target(
provider=Provider.WORKDAY,
original_url=url,
origin=f"{parsed.scheme}://{parsed.netloc}",
operation=Operation.GET if external_path else Operation.LIST,
tenant=tenant,
site=site,
external_path=external_path,
)
TARGET_PARSERS: Final[dict[Provider, Callable[[str], Target]]] = {
Provider.GREENHOUSE: _parse_greenhouse,
Provider.LEVER: _parse_lever,
Provider.ASHBY: _parse_ashby,
Provider.WORKABLE: _parse_workable,
Provider.BAMBOOHR: _parse_bamboohr,
Provider.WORKDAY: _parse_workday,
}
@dataclass(frozen=True, slots=True)
class DiscoveryCandidate:
"""One provider-native URL discovered on a public careers page."""
url: str
method: DiscoveryMethod
score: int
provider: Provider | None = None
@dataclass(frozen=True, slots=True)
class DiscoveryPage:
"""A bounded public HTML response and its redirect history."""
final_url: str
text: str
visited_urls: tuple[str, ...]
class _ATSLinkParser(HTMLParser):
"""Extract URL-bearing HTML attributes without treating page text as trusted markup."""
def __init__(self, base_url: str) -> None:
super().__init__(convert_charrefs=True)
self.base_url = base_url
self.candidates: list[DiscoveryCandidate] = []
def _add(
self,
value: str | None,
method: DiscoveryMethod,
score: int,
provider: Provider | None = None,
) -> None:
if not value:
return
candidate = urljoin(self.base_url, html.unescape(value.strip()).replace("\\/", "/"))
try:
detected = provider or detect_provider(candidate)
parse_target(candidate, detected)
except ATSJobsError:
return
self.candidates.append(DiscoveryCandidate(candidate, method, score, detected))
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
attributes = {name.lower(): value for name, value in attrs}
lowered_tag = tag.lower()
rel = (attributes.get("rel") or "").lower().split()
if lowered_tag == "link" and "canonical" in rel:
self._add(attributes.get("href"), DiscoveryMethod.CANONICAL, 110)
if lowered_tag == "meta":
key = (attributes.get("property") or attributes.get("name") or "").lower()
if key in {"og:url", "twitter:url"}:
self._add(attributes.get("content"), DiscoveryMethod.META, 100)
method = (
DiscoveryMethod.EMBED
if lowered_tag in {"iframe", "form", "script"}
else DiscoveryMethod.LINK
)
score = 90 if method is DiscoveryMethod.EMBED else 70
for name in ("href", "src", "action", "data-url", "data-src", "data-jobs-url"):
self._add(attributes.get(name), method, score)
provider_attributes = (
(Provider.ASHBY, "data-ashby-job-board-name", "https://jobs.ashbyhq.com/{value}"),
(
Provider.GREENHOUSE,
"data-greenhouse-board",
"https://job-boards.greenhouse.io/{value}",
),
(
Provider.GREENHOUSE,
"data-greenhouse-board-token",
"https://job-boards.greenhouse.io/{value}",
),
(Provider.LEVER, "data-lever-site", "https://jobs.lever.co/{value}"),
(Provider.WORKABLE, "data-workable-account", "https://apply.workable.com/{value}"),
(
Provider.BAMBOOHR,
"data-bamboohr-tenant",
"https://{value}.bamboohr.com/careers",
),
)
for provider, attribute, template in provider_attributes:
identifier = attributes.get(attribute)
if identifier and re.fullmatch(r"[A-Za-z0-9._-]+", identifier):
self._add(
template.format(value=identifier),
DiscoveryMethod.EMBED,
95,
provider,
)
workday_tenant = attributes.get("data-workday-tenant")
workday_site = attributes.get("data-workday-site")
if (
workday_tenant
and workday_site
and re.fullmatch(r"[A-Za-z0-9._-]+", workday_tenant)
and re.fullmatch(r"[A-Za-z0-9._-]+", workday_site)
):
self._add(
f"/wday/cxs/{workday_tenant}/{workday_site}/jobs",
DiscoveryMethod.EMBED,
95,
Provider.WORKDAY,
)
ATS_URL_PATTERN: Final = re.compile(
r"https?:(?:\\?/){2}(?:[^\s\"'<>]|\\/)+",
flags=re.IGNORECASE,
)
ENCODED_ATS_URL_PATTERN: Final = re.compile(
r"https?%3A%2F%2F[A-Za-z0-9%._~:/?#\[\]@!$&'()*+,;=-]+",
flags=re.IGNORECASE,
)
WORKDAY_CXS_PATH_PATTERN: Final = re.compile(
r"/wday/cxs/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+(?:/[^\s\"'<>]*)?",
flags=re.IGNORECASE,
)
PROTOCOL_RELATIVE_ATS_PATTERN: Final = re.compile(
r"(?<!:)//(?:boards\.greenhouse\.io|job-boards\.greenhouse\.io|"
r"jobs(?:\.eu)?\.lever\.co|jobs\.ashbyhq\.com|apply\.workable\.com|"
r"[A-Za-z0-9._-]+\.bamboohr\.com|"
r"[A-Za-z0-9._-]+\.(?:myworkdayjobs|myworkdaysite)\.com)"
r"(?:/[^\s\"'<>]*)?",
flags=re.IGNORECASE,
)
GENERIC_HOST_PREFIXES: Final = frozenset(
{"www", "careers", "career", "jobs", "job", "apply", "work", "join", "hiring"}
)
MULTIPART_PUBLIC_SUFFIXES: Final = frozenset(
{
"co.uk",
"com.au",
"com.br",
"com.cn",
"com.mx",
"co.jp",
"co.nz",
"co.za",
}
)
GENERIC_PATH_SEGMENTS: Final = frozenset(
{
"about",
"career",
"careers",
"company",
"en",
"jobs",
"join",
"openings",
"positions",
"work-with-us",
}
)
def _validate_public_discovery_url(value: str) -> str:
"""Reject obviously local or non-public discovery targets."""
candidate = coerce_url(value)
host = cast(str, urlsplit(candidate).hostname).lower().rstrip(".")
if host == "localhost" or host.endswith((".localhost", ".local", ".internal")):
raise InputError("discovery URL must use a public hostname", url=candidate)
try:
address = ipaddress.ip_address(host)
except ValueError:
return candidate
if not address.is_global:
raise InputError("discovery URL must not target a private or reserved IP", url=candidate)
return candidate
class DiscoveryClient:
"""Bounded HTML/JSON client used only when hostname parsing is insufficient."""
def __init__(
self,
client: httpx.Client | None = None,
*,
retries: int = 2,
sleeper: Callable[[float], None] = time.sleep,
event_sink: EventSink | None = None,
) -> None:
self._owned = client is None
self._client = client or httpx.Client(
timeout=httpx.Timeout(20.0, connect=8.0),
headers={"User-Agent": USER_AGENT},
)
self._retries = max(retries, 1)
self._sleeper = sleeper
self._event_sink = event_sink
def _debug(self, message: str) -> None:
if self._event_sink is not None:
self._event_sink(message)
def close(self) -> None:
if self._owned:
self._client.close()
def _request(
self,
url: str,
*,
accept: str,
params: Mapping[str, Any] | None = None,
allowed_hosts: Sequence[str] | None = None,
) -> tuple[httpx.Response, tuple[str, ...]]:
initial = _validate_public_discovery_url(url)
visited: list[str] = []
last_response: httpx.Response | None = None
for attempt in range(self._retries): # pragma: no branch
request = self._client.build_request(
"GET",
initial,
params=params,
headers={"Accept": accept, "User-Agent": USER_AGENT},
)
try:
for redirect_count in range(MAX_REDIRECTS + 1):
safe_url = _validate_public_discovery_url(str(request.url))
request = self._client.build_request(
"GET",
safe_url,
headers={"Accept": accept, "User-Agent": USER_AGENT},
)
host = request.url.host or ""
if allowed_hosts is not None and not _host_allowed(host, allowed_hosts):
raise TransportError(
f"unexpected discovery destination: {host}",
url=safe_url,
)
visited.append(safe_url)
self._debug(
f"discover GET {sanitize_url(safe_url)} "
f"(attempt {attempt + 1}/{self._retries})"
)
response = self._client.send(request, follow_redirects=False)
last_response = response
if not response.is_redirect:
break
next_request = response.next_request
if next_request is None:
raise TransportError(
"discovery redirect is missing a Location header",
url=safe_url,
)
if redirect_count >= MAX_REDIRECTS:
raise TransportError(
f"discovery redirect chain exceeds {MAX_REDIRECTS} hops",
url=initial,
)
self._debug(
f"discover redirect {response.status_code} -> "
f"{sanitize_url(str(next_request.url))}"
)
request = self._client.build_request(
"GET",
str(next_request.url),
headers={"Accept": accept, "User-Agent": USER_AGENT},
)
else: # pragma: no cover - guarded above.
raise AssertionError("unreachable discovery redirect state")
except (httpx.TimeoutException, httpx.TransportError) as exc:
if attempt + 1 < self._retries:
delay = _retry_delay(None, attempt)
self._debug(f"discovery {type(exc).__name__}; retrying in {delay:.2f}s")
self._sleeper(delay)
continue
raise TransportError(
f"discovery request failed after {self._retries} attempts: {exc}",
url=initial,
) from exc
if response.status_code in RETRYABLE_STATUS_CODES and attempt + 1 < self._retries:
delay = _retry_delay(response, attempt)
self._debug(
f"discovery HTTP {response.status_code}; retrying in {delay:.2f}s"
)
self._sleeper(delay)
continue
break
response = cast(httpx.Response, last_response)
if response.status_code in {401, 403}:
raise PermissionError(
f"careers page denied discovery (HTTP {response.status_code})",
url=initial,
)
if response.status_code == 404:
raise NotFoundError("careers page was not found", url=initial)
if response.status_code == 429:
raise RateLimitError("discovery was rate limited after retries", url=initial)
if response.status_code >= 400:
raise TransportError(
f"discovery request failed (HTTP {response.status_code})",
url=initial,
)
if len(response.content) > MAX_DISCOVERY_BYTES:
raise TransportError(
f"discovery response exceeds {MAX_DISCOVERY_BYTES} bytes",
url=initial,
)
return response, tuple(dict.fromkeys(visited))
def fetch_page(self, url: str) -> DiscoveryPage:
"""Fetch one public page and retain its redirect history."""
response, visited = self._request(
url,
accept="text/html,application/xhtml+xml;q=0.9,*/*;q=0.5",
)
return DiscoveryPage(
final_url=str(response.url),
text=response.text,
visited_urls=visited,
)
def request_json(
self,
url: str,
*,
allowed_hosts: Sequence[str],
params: Mapping[str, Any] | None = None,
) -> JsonValue:
"""Request JSON from one known ATS host for a bounded slug probe."""
response, _visited = self._request(
url,
accept="application/json",
params=params,
allowed_hosts=allowed_hosts,
)
try:
return cast(JsonValue, response.json())
except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as exc:
raise InvalidJSONError("probe response is not valid JSON", url=url) from exc
def _extract_discovery_candidates(page: DiscoveryPage) -> list[DiscoveryCandidate]:
parser = _ATSLinkParser(page.final_url)
try:
parser.feed(page.text)
except Exception:
# Attribute extraction is opportunistic; independent text scans still run.
pass
candidates = list(parser.candidates)
scan_text = (
html.unescape(page.text)
.replace("\\/", "/")
.replace("\\u002F", "/")
.replace("\\u002f", "/")
.replace("\\x2F", "/")
.replace("\\x2f", "/")
)
scanned_values = [match.group(0) for match in ATS_URL_PATTERN.finditer(scan_text)]
scanned_values.extend(
unquote(match.group(0)) for match in ENCODED_ATS_URL_PATTERN.finditer(scan_text)
)
scanned_values.extend(
f"https:{match.group(0)}" for match in PROTOCOL_RELATIVE_ATS_PATTERN.finditer(scan_text)
)
for value in scanned_values:
try:
provider = detect_provider(value)
parse_target(value, provider)
except ATSJobsError:
continue
candidates.append(DiscoveryCandidate(value, DiscoveryMethod.HTML, 55, provider))
for match in WORKDAY_CXS_PATH_PATTERN.finditer(scan_text):
value = urljoin(page.final_url, match.group(0))
try:
parse_target(value, Provider.WORKDAY)
except ATSJobsError:
continue
candidates.append(
DiscoveryCandidate(value, DiscoveryMethod.HTML, 80, Provider.WORKDAY)
)
unique: dict[str, DiscoveryCandidate] = {}
for candidate in candidates:
key = canonicalize_url(candidate.url)
previous = unique.get(key)
if previous is None or candidate.score > previous.score:
unique[key] = candidate
return list(unique.values())
def _operation_hint(value: str) -> Operation:
parsed = urlsplit(coerce_url(value))
query = {key.lower(): item for key, item in parse_qsl(parsed.query)}
if any(key in query for key in {"gh_jid", "job_id", "jobid", "postingid"}):
return Operation.GET
parts = [part.lower() for part in _segments(parsed.path)]
if not parts or parts[-1] in GENERIC_PATH_SEGMENTS:
return Operation.LIST
for marker in {
"career",
"careers",
"job",
"jobs",
"opening",
"openings",
"position",
"positions",
"view",
}:
if marker in parts and parts.index(marker) + 1 < len(parts):
return Operation.GET
if re.fullmatch(r"\d+", parts[-1]) or re.fullmatch(
r"[0-9a-f]{8}-[0-9a-f-]{27,}",
parts[-1],
flags=re.IGNORECASE,
):
return Operation.GET
return Operation.LIST
def _list_target(target: Target) -> Target:
return target.model_copy(
update={
"operation": Operation.LIST,
"job_id": None,
"external_path": None,
}
)
def _apply_requested_reference(requested_url: str, target: Target) -> Target:
"""Carry explicit provider references from a custom URL onto a discovered board."""
if target.operation is not Operation.LIST or target.provider is not Provider.GREENHOUSE:
return target
query = {key.lower(): value for key, value in parse_qsl(urlsplit(requested_url).query)}
job_id = query.get("gh_jid")
if job_id and job_id.isdigit():
return target.model_copy(update={"operation": Operation.GET, "job_id": job_id})
return target
def _target_key(target: Target) -> tuple[Any, ...]:
return (
target.provider,
target.operation,
target.board,
target.tenant,
target.site,
target.region,
target.job_id if target.operation is Operation.GET else None,
target.external_path if target.operation is Operation.GET else None,
)
def _select_discovery_candidate(
requested_url: str,
candidates: Sequence[DiscoveryCandidate],
override: Provider | None,
) -> tuple[Target, DiscoveryCandidate] | None:
hint = _operation_hint(requested_url)
grouped: dict[tuple[Any, ...], list[tuple[Target, DiscoveryCandidate]]] = {}
for candidate in candidates:
try:
provider = candidate.provider or detect_provider(candidate.url)
if override is not None and provider is not override:
continue
target = parse_target(candidate.url, provider)
except ATSJobsError:
continue
if hint is Operation.LIST and target.operation is Operation.GET:
target = _list_target(target)
elif hint is Operation.GET:
target = _apply_requested_reference(requested_url, target)
grouped.setdefault(_target_key(target), []).append((target, candidate))
if not grouped:
return None
ranked: list[tuple[int, tuple[Any, ...], Target, DiscoveryCandidate]] = []
for key, values in grouped.items():
target = values[0][0]
best = max(values, key=lambda item: item[1].score)[1]
score = best.score + min(len(values), 20) * 2
if target.operation is hint:
score += 8
ranked.append((score, key, target, best))
ranked.sort(key=lambda item: item[0], reverse=True)
top_score = ranked[0][0]
top = [item for item in ranked if item[0] == top_score]
if len(top) > 1:
choices = ", ".join(
sorted({f"{item[2].provider.value}:{item[2].board or item[2].site}" for item in top})
)
raise AmbiguousMatchError(
f"multiple ATS targets were equally plausible: {choices}",
url=requested_url,
)
_score, _key, target, candidate = top[0]
return target, candidate
def _slug_candidates(value: str) -> tuple[str, ...]:
parsed = urlsplit(coerce_url(value))
labels = [label for label in cast(str, parsed.hostname).lower().split(".") if label]
while labels and labels[0] in GENERIC_HOST_PREFIXES:
labels.pop(0)
raw_values: list[str] = []
if len(labels) >= 2:
suffix = ".".join(labels[-2:])
base_index = -3 if suffix in MULTIPART_PUBLIC_SUFFIXES and len(labels) >= 3 else -2
raw_values.append(labels[base_index])
for segment in _segments(parsed.path):
lowered = segment.lower()
if (
lowered not in GENERIC_PATH_SEGMENTS
and not lowered.isdigit()
and not re.fullmatch(r"[0-9a-f]{8}-[0-9a-f-]{27,}", lowered)
):
raw_values.append(lowered)
result: list[str] = []
for raw in raw_values:
for variant in (raw, re.sub(r"[^a-z0-9]", "", raw)):
slug = re.sub(r"[^a-z0-9._-]", "", variant)
if slug and slug not in result:
result.append(slug)
return tuple(result[:4])
def _probe_slug(
slug: str,
provider: Provider,
discovery: DiscoveryClient,
) -> Target | None:
try:
if provider is Provider.GREENHOUSE:
payload = discovery.request_json(
f"https://boards-api.greenhouse.io/v1/boards/{slug}/jobs",
allowed_hosts=("boards-api.greenhouse.io",),
)
if not isinstance(payload, Mapping) or not isinstance(payload.get("jobs"), list):
return None
return parse_target(f"https://job-boards.greenhouse.io/{slug}")
if provider is Provider.LEVER:
payload = discovery.request_json(
f"https://api.lever.co/v0/postings/{slug}",
allowed_hosts=("api.lever.co",),
params={"mode": "json", "limit": 1},
)
if not isinstance(payload, list):
return None
return parse_target(f"https://jobs.lever.co/{slug}")
if provider is Provider.ASHBY:
payload = discovery.request_json(
f"https://api.ashbyhq.com/posting-api/job-board/{slug}",
allowed_hosts=("api.ashbyhq.com",),
)
if not isinstance(payload, Mapping) or not isinstance(payload.get("jobs"), list):
return None
return parse_target(f"https://jobs.ashbyhq.com/{slug}")
if provider is Provider.WORKABLE:
payload = discovery.request_json(
f"https://www.workable.com/api/accounts/{slug}",
allowed_hosts=("www.workable.com",),
params={"details": "false"},
)
if not isinstance(payload, Mapping) or not isinstance(payload.get("jobs"), list):
return None
return parse_target(f"https://apply.workable.com/{slug}")
except ATSJobsError:
return None
return None
def resolve_target(
value: str,
override: Provider | None = None,
*,
discover: bool = True,
probe: bool = True,
discovery: DiscoveryClient | None = None,
event_sink: EventSink | None = None,
) -> DiscoveryResult:
"""Resolve a direct ATS URL or discover the ATS behind a custom careers page."""
requested_url = coerce_url(value)
direct_failure: InputError | None = None
try:
target = parse_target(requested_url, override)
except InputError as exc:
direct_failure = exc
if not discover:
raise
else:
return DiscoveryResult(
requested_url=requested_url,
resolved_url=target.original_url,
method=DiscoveryMethod.OVERRIDE if override is not None else DiscoveryMethod.DIRECT,
target=target,
visited_urls=(requested_url,),
)
owned = discovery is None
client = discovery or DiscoveryClient(event_sink=event_sink)
page: DiscoveryPage | None = None
page_error: ATSJobsError | None = None
try:
try:
page = client.fetch_page(requested_url)
except ATSJobsError as exc:
page_error = exc
if page is not None:
for redirected_url in reversed(page.visited_urls[1:]):
try:
target = parse_target(redirected_url, override)
except ATSJobsError:
continue
return DiscoveryResult(
requested_url=requested_url,
resolved_url=redirected_url,
method=DiscoveryMethod.REDIRECT,
target=target,
visited_urls=page.visited_urls,
)
if canonicalize_url(page.final_url) != canonicalize_url(requested_url):
try:
target = parse_target(page.final_url, override)
except ATSJobsError:
pass
else:
return DiscoveryResult(
requested_url=requested_url,
resolved_url=page.final_url,
method=DiscoveryMethod.REDIRECT,
target=target,
visited_urls=page.visited_urls,
)
selected = _select_discovery_candidate(
requested_url,
_extract_discovery_candidates(page),
override,
)
if selected is not None:
target, candidate = selected
return DiscoveryResult(
requested_url=requested_url,
resolved_url=candidate.url,
method=candidate.method,
target=target,
visited_urls=page.visited_urls,
)
slugs = _slug_candidates(requested_url) if probe else ()
matches: list[tuple[str, Target]] = []
providers = (override,) if override is not None else (
Provider.GREENHOUSE,
Provider.LEVER,
Provider.ASHBY,
Provider.WORKABLE,
)
for slug in slugs:
for provider in providers:
target = _probe_slug(slug, provider, client)
if target is not None:
matches.append((slug, target))
deduplicated: dict[tuple[Any, ...], tuple[str, Target]] = {}
for slug, target in matches:
deduplicated.setdefault(_target_key(target), (slug, target))
if len(deduplicated) == 1:
slug, target = next(iter(deduplicated.values()))
return DiscoveryResult(
requested_url=requested_url,
resolved_url=target.original_url,
method=DiscoveryMethod.SLUG_PROBE,
target=target,
visited_urls=page.visited_urls if page is not None else (),
probed_slugs=slugs,
)
if len(deduplicated) > 1:
choices = ", ".join(
sorted(
f"{target.provider.value}:{target.board or target.site}"
for _slug, target in deduplicated.values()
)
)
raise AmbiguousMatchError(
f"slug probes found multiple plausible boards: {choices}",
url=requested_url,
)
detail = f"; page discovery failed: {page_error.message}" if page_error else ""
attempted = f"; probed slugs: {', '.join(slugs)}" if slugs else ""
raise InputError(
"could not detect a supported ATS from the hostname, redirects, or page links"
f"{attempted}{detail}",
url=requested_url,
) from direct_failure
finally:
if owned:
client.close()
def _host_allowed(host: str, allowed_hosts: Sequence[str]) -> bool:
lowered = host.lower()
return any(
lowered == allowed.lower()
or (allowed.startswith(".") and lowered.endswith(allowed.lower()))
for allowed in allowed_hosts
)
def _retry_delay(response: httpx.Response | None, attempt: int) -> float:
if response is not None:
retry_after = response.headers.get("Retry-After")
if retry_after:
try:
return min(max(float(retry_after), 0.0), 10.0)
except ValueError:
pass
return min(0.25 * (2**attempt), 2.0)
class HttpClient:
"""Small fail-closed JSON HTTP client with bounded retries."""
def __init__(
self,
client: httpx.Client | None = None,
*,
retries: int = 3,
sleeper: Callable[[float], None] = time.sleep,
event_sink: EventSink | None = None,
) -> None:
self._owned = client is None
self._client = client or httpx.Client(
timeout=httpx.Timeout(45.0, connect=10.0),
headers={"Accept": "application/json", "User-Agent": USER_AGENT},
)
self._retries = max(retries, 1)
self._sleeper = sleeper
self._event_sink = event_sink
def _debug(self, message: str) -> None:
if self._event_sink is not None:
self._event_sink(message)
def close(self) -> None:
if self._owned:
self._client.close()
def request_json(
self,
method: str,
url: str,
*,
provider: Provider,
operation: Operation,
allowed_hosts: Sequence[str],
params: Mapping[str, Any] | None = None,
json_body: JsonObject | None = None,
) -> JsonValue:
initial_host = urlsplit(url).hostname or ""
if not _host_allowed(initial_host, allowed_hosts):
raise TransportError(
f"request host is not allowed: {initial_host}",
provider=provider,
operation=operation,
url=url,
)
last_response: httpx.Response | None = None
for attempt in range(self._retries):
request = self._client.build_request(method, url, params=params, json=json_body)
started = time.perf_counter()
self._debug(
f"{method.upper()} {sanitize_url(str(request.url))} "
f"(attempt {attempt + 1}/{self._retries})"
)
try:
for redirect_count in range(MAX_REDIRECTS + 1):
response = self._client.send(request, follow_redirects=False)
last_response = response
if not response.is_redirect:
break
next_request = response.next_request
if next_request is None:
raise TransportError(
"redirect response is missing a valid Location header",
provider=provider,
operation=operation,
url=url,
)
next_host = next_request.url.host or ""
self._debug(
f"redirect {response.status_code} -> {sanitize_url(str(next_request.url))}"
)
if not _host_allowed(next_host, allowed_hosts):
raise TransportError(
f"unexpected redirect destination: {next_host}",
provider=provider,
operation=operation,
url=url,
)
if redirect_count >= MAX_REDIRECTS:
raise TransportError(
f"redirect chain exceeds {MAX_REDIRECTS} hops",
provider=provider,
operation=operation,
url=url,
)
request = next_request
else: # pragma: no cover - range exhaustion is guarded above.
raise AssertionError("unreachable redirect loop state")
except (httpx.TimeoutException, httpx.TransportError) as exc:
if attempt + 1 < self._retries:
delay = _retry_delay(None, attempt)
self._debug(
f"{type(exc).__name__}; retrying in {delay:.2f}s"
)
self._sleeper(delay)
continue
raise TransportError(
f"request failed after {self._retries} attempts: {exc}",
provider=provider,
operation=operation,
url=url,
) from exc
if response.status_code in RETRYABLE_STATUS_CODES and attempt + 1 < self._retries:
delay = _retry_delay(response, attempt)
self._debug(f"HTTP {response.status_code}; retrying in {delay:.2f}s")
self._sleeper(delay)
continue
break
response = cast(httpx.Response, last_response)
self._debug(
f"HTTP {response.status_code} {method.upper()} {sanitize_url(url)} "
f"in {time.perf_counter() - started:.2f}s"
)
if response.status_code == 404:
raise NotFoundError(
"board, site, or posting was not found",
provider=provider,
operation=operation,
url=url,
)
if response.status_code in {401, 403}:
raise PermissionError(
f"access denied (HTTP {response.status_code})",
provider=provider,
operation=operation,
url=url,
)
if response.status_code == 429:
raise RateLimitError(
"rate limited after retry budget",
provider=provider,
operation=operation,
url=url,
)
if response.status_code >= 400:
raise TransportError(
f"request failed (HTTP {response.status_code})",
provider=provider,
operation=operation,
url=url,
)
if len(response.content) > MAX_RESPONSE_BYTES:
raise TransportError(
f"response exceeds {MAX_RESPONSE_BYTES} bytes",
provider=provider,
operation=operation,
url=url,
)
try:
return cast(JsonValue, response.json())
except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as exc:
raise InvalidJSONError(
"response is not valid JSON",
provider=provider,
operation=operation,
url=url,
) from exc
class Adapter(Protocol):
"""Provider adapter contract."""
provider: Provider
def list_jobs(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> list[JsonObject]: ...
def get_job(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> JsonObject: ...
def normalize(self, raw: JsonObject, target: Target) -> JobPosting: ...
def _mapping(value: JsonValue | Any, *, provider: Provider, label: str) -> JsonObject:
if not isinstance(value, dict):
raise SchemaError(f"{label} must be an object", provider=provider)
return cast(JsonObject, value)
def _array(value: Any, *, provider: Provider, label: str) -> list[Any]:
if not isinstance(value, list):
raise SchemaError(f"{label} must be an array", provider=provider)
return value
def _string(value: Any, *, provider: Provider, label: str) -> str:
if not isinstance(value, str) or not value.strip():
raise SchemaError(f"{label} must be a non-empty string", provider=provider)
return value
def _integer(value: Any, *, provider: Provider, label: str) -> int:
if isinstance(value, bool) or not isinstance(value, int):
raise SchemaError(f"{label} must be an integer", provider=provider)
return value
def _first_string(raw: Mapping[str, Any], *keys: str) -> str | None:
for key in keys:
value = raw.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _join_location(value: Any) -> str | None:
if isinstance(value, str):
return value.strip() or None
if isinstance(value, Mapping):
direct = _first_string(value, "location_str", "name", "address")
if direct:
return direct
parts = [
item.strip()
for key in ("city", "region", "state", "country")
if isinstance((item := value.get(key)), str) and item.strip()
]
return ", ".join(dict.fromkeys(parts)) or None
return None
def _remote_from(*values: str | None) -> bool | None:
available = [value for value in values if value]
if not available:
return None
return any("remote" in value.lower() for value in available)
class GreenhouseAdapter:
provider = Provider.GREENHOUSE
def list_jobs(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> list[JsonObject]:
del options
url = f"{target.origin}/v1/boards/{target.board}/jobs"
payload = _mapping(
http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.LIST,
allowed_hosts=("boards-api.greenhouse.io",),
params={"content": "true"},
),
provider=self.provider,
label="Greenhouse response",
)
jobs = _array(payload.get("jobs"), provider=self.provider, label="Greenhouse jobs")
meta = _mapping(payload.get("meta"), provider=self.provider, label="Greenhouse meta")
total = _integer(meta.get("total"), provider=self.provider, label="Greenhouse meta.total")
if total < 0 or total != len(jobs):
raise SchemaError("Greenhouse total does not match jobs", provider=self.provider)
result: list[JsonObject] = []
for item in jobs:
job = _mapping(item, provider=self.provider, label="Greenhouse job")
if isinstance(job.get("id"), bool) or not isinstance(job.get("id"), int):
raise SchemaError("Greenhouse job.id must be an integer", provider=self.provider)
_string(job.get("title"), provider=self.provider, label="Greenhouse job.title")
result.append(job)
return result
def get_job(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> JsonObject:
del options
if target.job_id is None:
raise InputError(
"Greenhouse job URL must contain a job-post ID",
provider=self.provider,
)
url = f"{target.origin}/v1/boards/{target.board}/jobs/{target.job_id}"
job = _mapping(
http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.GET,
allowed_hosts=("boards-api.greenhouse.io",),
params={"pay_transparency": "true"},
),
provider=self.provider,
label="Greenhouse job",
)
if str(job.get("id")) != target.job_id:
raise SchemaError("Greenhouse job ID does not match request", provider=self.provider)
_string(job.get("title"), provider=self.provider, label="Greenhouse job.title")
return job
def normalize(self, raw: JsonObject, target: Target) -> JobPosting:
title = _string(raw.get("title"), provider=self.provider, label="Greenhouse job.title")
job_id = str(raw.get("id", ""))
content = _first_string(raw, "content")
location = _join_location(raw.get("location"))
department = None
departments = raw.get("departments")
if isinstance(departments, list) and departments:
department = _join_location(departments[0])
job_url = _first_string(raw, "absolute_url") or (
f"https://job-boards.greenhouse.io/{target.board}/jobs/{job_id}"
)
return JobPosting(
provider=self.provider,
id=job_id,
title=title,
location=location,
department=department,
description_html=content,
description_text=strip_html(content),
job_url=job_url,
apply_url=job_url,
published_at=timestamp_to_iso(raw.get("updated_at")),
remote=_remote_from(location),
source=raw,
)
class LeverAdapter:
provider = Provider.LEVER
def list_jobs(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> list[JsonObject]:
del options
if target.board is None:
raise InputError("Lever site is missing", provider=self.provider)
items: list[JsonObject] = []
seen: set[str] = set()
skip = 0
for _page in range(MAX_PAGES):
url = f"{target.origin}/v0/postings/{target.board}"
payload = http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.LIST,
allowed_hosts=(urlsplit(target.origin).hostname or "",),
params={"mode": "json", "skip": skip, "limit": LEVER_PAGE_SIZE},
)
page = _array(payload, provider=self.provider, label="Lever page")
if not page:
return items
for item in page:
job = _mapping(item, provider=self.provider, label="Lever posting")
job_id = _string(job.get("id"), provider=self.provider, label="Lever posting.id")
_string(job.get("text"), provider=self.provider, label="Lever posting.text")
if job_id in seen:
raise PaginationError(
"duplicate Lever posting detected during pagination",
provider=self.provider,
operation=Operation.LIST,
)
seen.add(job_id)
items.append(job)
skip += len(page)
raise PaginationError(
"Lever pagination exceeded safety limit",
provider=self.provider,
operation=Operation.LIST,
)
def get_job(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> JsonObject:
del options
if target.board is None or target.job_id is None:
raise InputError("Lever job URL must contain a posting ID", provider=self.provider)
url = f"{target.origin}/v0/postings/{target.board}/{target.job_id}"
job = _mapping(
http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.GET,
allowed_hosts=(urlsplit(target.origin).hostname or "",),
),
provider=self.provider,
label="Lever posting",
)
if job.get("id") != target.job_id:
raise SchemaError("Lever posting ID does not match request", provider=self.provider)
_string(job.get("text"), provider=self.provider, label="Lever posting.text")
return job
def normalize(self, raw: JsonObject, target: Target) -> JobPosting:
del target
categories = raw.get("categories") if isinstance(raw.get("categories"), Mapping) else {}
categories = cast(Mapping[str, Any], categories)
title = _string(raw.get("text"), provider=self.provider, label="Lever posting.text")
job_id = _string(raw.get("id"), provider=self.provider, label="Lever posting.id")
description_html = _first_string(raw, "description")
description_text = _first_string(raw, "descriptionPlain") or strip_html(description_html)
location = _first_string(categories, "location", "allLocations")
return JobPosting(
provider=self.provider,
id=job_id,
title=title,
location=location,
department=_first_string(categories, "department", "team"),
employment_type=_first_string(categories, "commitment"),
description_html=description_html,
description_text=description_text,
job_url=_string(
raw.get("hostedUrl"), provider=self.provider, label="Lever posting.hostedUrl"
),
apply_url=_first_string(raw, "applyUrl"),
published_at=timestamp_to_iso(raw.get("createdAt")),
remote=_remote_from(location, _first_string(raw, "workplaceType")),
source=raw,
)
class AshbyAdapter:
provider = Provider.ASHBY
def list_jobs(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> list[JsonObject]:
if target.board is None:
raise InputError("Ashby board name is missing", provider=self.provider)
url = f"{target.origin}/posting-api/job-board/{target.board}"
payload = _mapping(
http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.LIST,
allowed_hosts=("api.ashbyhq.com",),
params={"includeCompensation": "true"},
),
provider=self.provider,
label="Ashby response",
)
_string(payload.get("apiVersion"), provider=self.provider, label="Ashby apiVersion")
jobs = _array(payload.get("jobs"), provider=self.provider, label="Ashby jobs")
result: list[JsonObject] = []
for item in jobs:
job = _mapping(item, provider=self.provider, label="Ashby job")
_string(job.get("title"), provider=self.provider, label="Ashby job.title")
_string(job.get("jobUrl"), provider=self.provider, label="Ashby job.jobUrl")
if not options.include_unlisted and job.get("isListed") is False:
continue
result.append(job)
return result
def get_job(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> JsonObject:
all_options = options.model_copy(update={"include_unlisted": True})
jobs = self.list_jobs(target, http, all_options)
wanted = canonicalize_url(target.original_url)
matches = [
job
for job in jobs
if any(
isinstance(candidate, str) and canonicalize_url(candidate) == wanted
for candidate in (job.get("jobUrl"), job.get("applyUrl"))
)
]
if not matches:
raise NotFoundError(
"no Ashby job exactly matched that job or application URL",
provider=self.provider,
operation=Operation.GET,
url=target.original_url,
)
if len(matches) > 1:
raise AmbiguousMatchError(
"multiple Ashby jobs matched that URL",
provider=self.provider,
operation=Operation.GET,
url=target.original_url,
)
return matches[0]
def normalize(self, raw: JsonObject, target: Target) -> JobPosting:
del target
title = _string(raw.get("title"), provider=self.provider, label="Ashby job.title")
job_url = _string(raw.get("jobUrl"), provider=self.provider, label="Ashby job.jobUrl")
job_id = _first_string(raw, "id", "jobPostingId") or _segments(urlsplit(job_url).path)[-1]
location = _first_string(raw, "location")
description_html = _first_string(raw, "descriptionHtml")
return JobPosting(
provider=self.provider,
id=job_id,
title=title,
location=location,
department=_first_string(raw, "department", "team"),
employment_type=_first_string(raw, "employmentType"),
description_html=description_html,
description_text=_first_string(raw, "descriptionPlain") or strip_html(description_html),
job_url=job_url,
apply_url=_first_string(raw, "applyUrl"),
published_at=timestamp_to_iso(raw.get("publishedAt")),
remote=(
raw.get("isRemote")
if isinstance(raw.get("isRemote"), bool)
else _remote_from(location)
),
source=raw,
)
class WorkableAdapter:
provider = Provider.WORKABLE
def list_jobs(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> list[JsonObject]:
del options
if target.board is None:
raise InputError("Workable account is missing", provider=self.provider)
url = f"{target.origin}/api/accounts/{target.board}"
payload = _mapping(
http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.LIST,
allowed_hosts=("www.workable.com",),
params={"details": "true"},
),
provider=self.provider,
label="Workable response",
)
jobs = _array(payload.get("jobs"), provider=self.provider, label="Workable jobs")
result: list[JsonObject] = []
for item in jobs:
job = _mapping(item, provider=self.provider, label="Workable job")
_string(job.get("shortcode"), provider=self.provider, label="Workable job.shortcode")
_string(job.get("title"), provider=self.provider, label="Workable job.title")
result.append(job)
return result
def get_job(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> JsonObject:
jobs = self.list_jobs(target, http, options)
wanted_url = canonicalize_url(target.original_url)
matches: list[JsonObject] = []
for job in jobs:
shortcode = str(job.get("shortcode", ""))
url_match = any(
isinstance(candidate, str) and canonicalize_url(candidate) == wanted_url
for candidate in (
job.get("url"),
job.get("application_url"),
job.get("shortlink"),
)
)
if (target.job_id and shortcode == target.job_id) or url_match:
matches.append(job)
if not matches:
raise NotFoundError(
"no Workable job exactly matched that shortcode or URL",
provider=self.provider,
operation=Operation.GET,
url=target.original_url,
)
if len(matches) > 1:
raise AmbiguousMatchError(
"multiple Workable jobs matched that shortcode or URL",
provider=self.provider,
operation=Operation.GET,
url=target.original_url,
)
return matches[0]
def normalize(self, raw: JsonObject, target: Target) -> JobPosting:
shortcode = _string(
raw.get("shortcode"), provider=self.provider, label="Workable job.shortcode"
)
title = _string(raw.get("title"), provider=self.provider, label="Workable job.title")
location = _join_location(raw.get("location"))
description_html = _first_string(raw, "description", "description_html")
job_url = _first_string(raw, "url", "shortlink") or (
f"https://apply.workable.com/{target.board}/j/{shortcode}/"
)
return JobPosting(
provider=self.provider,
id=shortcode,
title=title,
location=location,
department=_first_string(raw, "department"),
employment_type=_first_string(raw, "employment_type", "type"),
description_html=description_html,
description_text=(
_first_string(raw, "description_plain") or strip_html(description_html)
),
job_url=job_url,
apply_url=_first_string(raw, "application_url", "shortlink"),
published_at=timestamp_to_iso(raw.get("created_at")),
remote=_remote_from(location, _first_string(raw, "workplace")),
source=raw,
)
class BambooHRAdapter:
provider = Provider.BAMBOOHR
def list_jobs(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> list[JsonObject]:
del options
url = f"{target.origin}/careers/list"
payload = _mapping(
http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.LIST,
allowed_hosts=(urlsplit(target.origin).hostname or "",),
),
provider=self.provider,
label="BambooHR response",
)
jobs = _array(payload.get("result"), provider=self.provider, label="BambooHR result")
meta = payload.get("meta")
if isinstance(meta, Mapping) and "totalCount" in meta:
total = _integer(
meta.get("totalCount"), provider=self.provider, label="BambooHR meta.totalCount"
)
if total != len(jobs):
raise SchemaError("BambooHR total does not match jobs", provider=self.provider)
result: list[JsonObject] = []
for item in jobs:
job = _mapping(item, provider=self.provider, label="BambooHR job")
if isinstance(job.get("id"), bool) or not isinstance(job.get("id"), int | str):
raise SchemaError(
"BambooHR job.id must be a string or integer",
provider=self.provider,
)
result.append(job)
return result
def get_job(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> JsonObject:
del options
if target.job_id is None:
raise InputError(
"BambooHR job URL must contain a numeric job ID",
provider=self.provider,
)
url = f"{target.origin}/careers/{target.job_id}/detail"
payload = _mapping(
http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.GET,
allowed_hosts=(urlsplit(target.origin).hostname or "",),
),
provider=self.provider,
label="BambooHR response",
)
result = _mapping(
payload.get("result"), provider=self.provider, label="BambooHR result"
)
job = _mapping(
result.get("jobOpening"), provider=self.provider, label="BambooHR jobOpening"
)
if str(job.get("id")) != target.job_id:
raise SchemaError("BambooHR job ID does not match request", provider=self.provider)
return job
def normalize(self, raw: JsonObject, target: Target) -> JobPosting:
job_id = str(raw.get("id", ""))
if not job_id:
raise SchemaError("BambooHR job.id is missing", provider=self.provider)
title = _first_string(raw, "jobOpeningName", "jobTitle", "title", "name")
if title is None:
raise SchemaError("BambooHR job title is missing", provider=self.provider)
location = _join_location(raw.get("location")) or _first_string(raw, "locationName")
description_html = _first_string(raw, "description", "jobDescription")
job_url = _first_string(raw, "jobUrl", "url") or f"{target.origin}/careers/{job_id}"
return JobPosting(
provider=self.provider,
id=job_id,
title=title,
location=location,
department=_first_string(raw, "department", "departmentName"),
employment_type=_first_string(raw, "employmentStatus", "employmentType"),
description_html=description_html,
description_text=strip_html(description_html),
job_url=job_url,
apply_url=_first_string(raw, "applyUrl") or job_url,
published_at=timestamp_to_iso(raw.get("datePosted")),
remote=_remote_from(location),
source=raw,
)
class WorkdayAdapter:
provider = Provider.WORKDAY
def _base(self, target: Target) -> str:
if target.tenant is None or target.site is None:
raise InputError("Workday tenant or site is missing", provider=self.provider)
return f"{target.origin}/wday/cxs/{target.tenant}/{target.site}"
def list_jobs(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> list[JsonObject]:
del options
url = f"{self._base(target)}/jobs"
allowed_host = urlsplit(target.origin).hostname or ""
items: list[JsonObject] = []
seen: set[str] = set()
expected_total: int | None = None
offset = 0
for page_index in range(MAX_PAGES):
payload = _mapping(
http.request_json(
"POST",
url,
provider=self.provider,
operation=Operation.LIST,
allowed_hosts=(allowed_host,),
json_body={
"appliedFacets": {},
"limit": WORKDAY_PAGE_SIZE,
"offset": offset,
"searchText": "",
},
),
provider=self.provider,
label="Workday response",
)
page_total = _integer(
payload.get("total"), provider=self.provider, label="Workday total"
)
if page_total < 0:
raise SchemaError("Workday total must be non-negative", provider=self.provider)
if expected_total is None:
expected_total = page_total
elif page_total not in {0, expected_total}:
raise PaginationError(
"Workday total changed during pagination",
provider=self.provider,
operation=Operation.LIST,
)
page = _array(
payload.get("jobPostings"), provider=self.provider, label="Workday jobPostings"
)
if expected_total == 0:
if page:
raise PaginationError(
"Workday returned postings with total=0",
provider=self.provider,
operation=Operation.LIST,
)
return []
if not page:
raise PaginationError(
"Workday pagination ended before the advertised total",
provider=self.provider,
operation=Operation.LIST,
)
for item in page:
job = _mapping(item, provider=self.provider, label="Workday posting")
external_path = _string(
job.get("externalPath"),
provider=self.provider,
label="Workday posting.externalPath",
)
if external_path in seen:
raise PaginationError(
"duplicate Workday externalPath detected",
provider=self.provider,
operation=Operation.LIST,
)
seen.add(external_path)
items.append(job)
offset += len(page)
if len(items) == expected_total:
return items
if len(items) > expected_total:
raise PaginationError(
"Workday returned more postings than advertised",
provider=self.provider,
operation=Operation.LIST,
)
if page_index + 1 >= MAX_PAGES:
break
raise PaginationError(
"Workday pagination exceeded safety limit",
provider=self.provider,
operation=Operation.LIST,
)
def get_job(
self,
target: Target,
http: HttpClient,
options: FetchOptions,
) -> JsonObject:
del options
if target.external_path is None:
raise InputError(
"Workday job URL must include the /job/... external path",
provider=self.provider,
)
url = f"{self._base(target)}{target.external_path}"
payload = _mapping(
http.request_json(
"GET",
url,
provider=self.provider,
operation=Operation.GET,
allowed_hosts=(urlsplit(target.origin).hostname or "",),
),
provider=self.provider,
label="Workday response",
)
return _mapping(
payload.get("jobPostingInfo"),
provider=self.provider,
label="Workday jobPostingInfo",
)
def normalize(self, raw: JsonObject, target: Target) -> JobPosting:
title = _first_string(raw, "title")
if title is None:
raise SchemaError("Workday job title is missing", provider=self.provider)
external_path = _first_string(raw, "externalPath") or target.external_path
job_id = _first_string(raw, "jobReqId", "id")
if job_id is None and external_path:
job_id = _segments(external_path)[-1]
if job_id is None:
raise SchemaError("Workday job identifier is missing", provider=self.provider)
location = _first_string(raw, "location", "locationName", "locationsText")
description_html = _first_string(raw, "jobDescription", "description")
job_url = _first_string(raw, "externalUrl")
if job_url is None and external_path:
job_url = f"{target.origin}{external_path}"
if job_url is None:
raise SchemaError("Workday job URL is missing", provider=self.provider)
return JobPosting(
provider=self.provider,
id=job_id,
title=title,
location=location,
department=_first_string(raw, "jobFamily", "department"),
employment_type=_first_string(raw, "timeType", "workerType"),
description_html=description_html,
description_text=strip_html(description_html),
job_url=job_url,
apply_url=_first_string(raw, "externalApplyUrl") or job_url,
published_at=timestamp_to_iso(raw.get("startDate") or raw.get("postedOn")),
remote=_remote_from(location, _first_string(raw, "remoteType")),
source=raw,
)
ADAPTERS: Final[dict[Provider, Adapter]] = {
Provider.GREENHOUSE: GreenhouseAdapter(),
Provider.LEVER: LeverAdapter(),
Provider.ASHBY: AshbyAdapter(),
Provider.WORKABLE: WorkableAdapter(),
Provider.BAMBOOHR: BambooHRAdapter(),
Provider.WORKDAY: WorkdayAdapter(),
}
def operation_support(provider: Provider, operation: Operation) -> SupportTier:
spec = PROVIDER_SPECS[provider]
return spec.list_support if operation is Operation.LIST else spec.get_support
def inspect_url(value: str, override: Provider | None = None) -> JsonObject:
"""Return URL parsing and support metadata without making a network request."""
target = parse_target(value, override)
data = target.model_dump(mode="json")
data["support"] = operation_support(target.provider, target.operation).value
return data
def inspect_resolution(resolution: DiscoveryResult) -> JsonObject:
"""Return discovery provenance and provider support metadata."""
data = resolution.model_dump(mode="json")
target = resolution.target
data["support"] = operation_support(target.provider, target.operation).value
return data
def _fetch_target(
target: Target,
*,
operation: Operation | None = None,
raw: bool = False,
include_unlisted: bool = False,
documented_only: bool = False,
http: HttpClient | None = None,
event_sink: EventSink | None = None,
) -> list[JsonObject] | JsonObject | list[JobPosting] | JobPosting:
selected_operation = operation or target.operation
if selected_operation is Operation.GET and target.operation is Operation.LIST:
raise InputError(
"discovery found a board but not an individual posting reference; use list or "
"provide the direct posting URL",
provider=target.provider,
operation=Operation.GET,
url=target.original_url,
)
if selected_operation is Operation.LIST and target.operation is Operation.GET:
target = _list_target(target)
support = operation_support(target.provider, selected_operation)
if documented_only and support is SupportTier.UNDOCUMENTED_PUBLIC:
raise UnsupportedInterfaceError(
"provider interface is undocumented; remove --documented-only to use it",
provider=target.provider,
operation=selected_operation,
url=target.original_url,
)
adapter = ADAPTERS[target.provider]
options = FetchOptions(
include_unlisted=include_unlisted,
documented_only=documented_only,
)
owned = http is None
client = http or (HttpClient(event_sink=event_sink) if event_sink else HttpClient())
try:
if selected_operation is Operation.LIST:
source = adapter.list_jobs(target, client, options)
if raw:
return source
return [adapter.normalize(item, target) for item in source]
source_job = adapter.get_job(target, client, options)
if raw:
return source_job
return adapter.normalize(source_job, target)
finally:
if owned:
client.close()
def fetch_jobs(
value: str,
*,
operation: Operation | None = None,
provider: Provider | None = None,
raw: bool = False,
include_unlisted: bool = False,
documented_only: bool = False,
http: HttpClient | None = None,
discover: bool = True,
probe: bool = True,
discovery: DiscoveryClient | None = None,
event_sink: EventSink | None = None,
) -> list[JsonObject] | JsonObject | list[JobPosting] | JobPosting:
"""Fetch a list or one job from a URL."""
resolution = resolve_target(
value,
provider,
discover=discover,
probe=probe,
discovery=discovery,
event_sink=event_sink,
)
return _fetch_target(
resolution.target,
operation=operation,
raw=raw,
include_unlisted=include_unlisted,
documented_only=documented_only,
http=http,
event_sink=event_sink,
)
def _jsonable(data: Any) -> JsonValue:
if isinstance(data, BaseModel):
return cast(JsonValue, data.model_dump(mode="json"))
if isinstance(data, list):
return cast(JsonValue, [_jsonable(item) for item in data])
return cast(JsonValue, data)
def render_json(data: Any) -> str:
return json.dumps(_jsonable(data), ensure_ascii=False, indent=2, sort_keys=False)
def render_jsonl(data: Any) -> str:
items = data if isinstance(data, list) else [data]
return "\n".join(
json.dumps(_jsonable(item), ensure_ascii=False, separators=(",", ":")) for item in items
)
def _truncate(value: Any, width: int) -> str:
text = "" if value is None else str(value).replace("\n", " ")
return text if len(text) <= width else f"{text[: width - 1]}…"
def _normalized_mapping(item: Any) -> JsonObject:
if isinstance(item, JobPosting):
return item.model_dump(mode="json")
if isinstance(item, Mapping) and {"title", "job_url"}.issubset(item):
return dict(item)
raise InputError("human-readable output requires normalized job records")
def _humanize(value: Any) -> str:
if value is None:
return ""
text = str(value).replace("_", " ").strip()
text = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", text)
return text[:1].upper() + text[1:] if text else ""
def _pretty_date(value: Any) -> str:
if not isinstance(value, str) or not value.strip():
return ""
candidate = value.strip().replace("Z", "+00:00")
try:
parsed = datetime.fromisoformat(candidate)
except ValueError:
return value.strip()
return parsed.strftime("%b %d, %Y").replace(" 0", " ")
def _compensation_summary(job: Mapping[str, Any]) -> str | None:
source = job.get("source")
if not isinstance(source, Mapping):
return None
compensation = source.get("compensation")
if isinstance(compensation, Mapping):
for key in ("compensationTierSummary", "scrapeableCompensationSalarySummary", "summary"):
value = compensation.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
for key in ("salary", "salaryRange", "salary_range", "compensation"):
value = source.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
if isinstance(value, Mapping):
minimum = value.get("min") or value.get("minimum") or value.get("minValue")
maximum = value.get("max") or value.get("maximum") or value.get("maxValue")
currency = value.get("currency") or value.get("currencyCode") or ""
if isinstance(minimum, int | float) or isinstance(maximum, int | float):
low = f"{minimum:,.0f}" if isinstance(minimum, int | float) else "?"
high = f"{maximum:,.0f}" if isinstance(maximum, int | float) else "?"
prefix = f"{currency} " if currency else ""
return f"{prefix}{low} – {high}"
return None
def _workplace_summary(job: Mapping[str, Any]) -> str:
remote = job.get("remote")
if remote is True:
return "Remote"
source = job.get("source")
if isinstance(source, Mapping):
for key in ("workplaceType", "workplace_type"):
value = source.get(key)
if isinstance(value, str) and value.strip():
humanized = _humanize(value)
compact = re.sub(r"[^a-z]", "", value.lower())
return {
"onsite": "On-site",
"remote": "Remote",
"hybrid": "Hybrid",
}.get(compact, humanized)
return "On-site" if remote is False else ""
def _description_renderable(value: Any) -> Text:
text = Text()
if not isinstance(value, str) or not value.strip():
text.append("No description was provided.", style="dim italic")
return text
previous_blank = True
for raw_line in value.strip().splitlines():
line = raw_line.strip()
if not line:
if not previous_blank:
text.append("\n")
previous_blank = True
continue
heading = (
len(line) <= 90
and len(line.split()) <= 12
and line.upper() == line
and any(character.isalpha() for character in line)
)
if heading:
if len(text):
text.append("\n")
text.append(_humanize(line.lower()), style="bold cyan")
text.append("\n")
elif line.startswith(("- ", "• ", "* ")):
text.append(" • ", style="cyan")
text.append(line[2:].strip())
text.append("\n")
else:
text.append(line)
text.append("\n")
previous_blank = False
return text
def _pretty_job(job: Mapping[str, Any]) -> RenderableType:
title = str(job.get("title") or "Untitled posting")
provider = _humanize(job.get("provider"))
details = Table.grid(padding=(0, 2))
details.add_column(style="bold dim", no_wrap=True)
details.add_column(ratio=1, overflow="fold")
def add(label: str, value: Any) -> None:
if value is not None and str(value).strip():
details.add_row(label, Text(str(value).strip()))
add("Provider", provider)
add("Company", job.get("company"))
add("Location", job.get("location"))
add("Workplace", _workplace_summary(job))
add("Department", job.get("department"))
add("Type", _humanize(job.get("employment_type")))
add("Compensation", _compensation_summary(job))
add("Published", _pretty_date(job.get("published_at")))
job_url = job.get("job_url")
if isinstance(job_url, str) and job_url:
details.add_row("Job", Text(job_url, style=f"cyan underline link {job_url}"))
apply_url = job.get("apply_url")
if isinstance(apply_url, str) and apply_url and apply_url != job_url:
details.add_row("Apply", Text(apply_url, style=f"green underline link {apply_url}"))
summary = Panel(
details,
title=Text(title, style="bold"),
subtitle=Text(str(job.get("id") or ""), style="dim"),
border_style="cyan",
padding=(1, 2),
)
description = _description_renderable(job.get("description_text"))
return Group(summary, Rule("Description", style="dim"), description)
def _pretty_job_list(jobs: Sequence[Mapping[str, Any]]) -> RenderableType:
if not jobs:
return Panel("No public postings found.", title="ats-jobs", border_style="yellow")
providers = sorted({_humanize(job.get("provider")) for job in jobs if job.get("provider")})
subtitle = f" · {', '.join(providers)}" if providers else ""
table = Table(
title=f"{len(jobs)} public posting{'s' if len(jobs) != 1 else ''}{subtitle}",
box=box.SIMPLE_HEAVY,
expand=True,
header_style="bold cyan",
show_lines=False,
pad_edge=False,
)
table.add_column("#", justify="right", style="dim", no_wrap=True, width=4)
table.add_column("Title", ratio=3, overflow="fold")
table.add_column("Location", ratio=2, overflow="fold")
table.add_column("Team", ratio=2, overflow="fold")
table.add_column("Type", ratio=1, overflow="fold")
table.add_column("Posted", no_wrap=True)
table.add_column("Link", no_wrap=True)
for index, job in enumerate(jobs, start=1):
job_url = str(job.get("job_url") or "")
link = Text("open", style=f"cyan underline link {job_url}") if job_url else Text("-")
table.add_row(
str(index),
str(job.get("title") or ""),
str(job.get("location") or ""),
str(job.get("department") or ""),
_humanize(job.get("employment_type")),
_pretty_date(job.get("published_at")),
link,
)
return table
def build_pretty(data: Any) -> RenderableType:
"""Build a semantic Rich view without dumping duplicated raw provider payloads."""
if isinstance(data, list):
return _pretty_job_list([_normalized_mapping(item) for item in data])
return _pretty_job(_normalized_mapping(data))
def render_pretty(data: Any, *, width: int = 100) -> str:
"""Render the semantic view as deterministic, color-free text for tests or files."""
buffer = io.StringIO()
console = Console(
file=buffer,
force_terminal=False,
color_system=None,
width=max(width, 40),
highlight=False,
)
console.print(build_pretty(data))
return buffer.getvalue().rstrip()
def render_table(data: Any) -> str:
"""Render normalized jobs as a compact dependency-free table."""
items = data if isinstance(data, list) else [data]
rows: list[dict[str, Any]] = []
for item in items:
rows.append(_normalized_mapping(item))
columns = (("TITLE", "title", 42), ("LOCATION", "location", 24), ("URL", "job_url", 60))
widths = [
min(limit, max([len(header), *(len(str(row.get(key) or "")) for row in rows)]))
for header, key, limit in columns
]
header = " ".join(
label.ljust(width)
for (label, _key, _limit), width in zip(columns, widths, strict=True)
)
separator = " ".join("-" * width for width in widths)
rendered = [header, separator]
for row in rows:
rendered.append(
" ".join(
_truncate(row.get(key), width).ljust(width)
for (_label, key, _limit), width in zip(columns, widths, strict=True)
)
)
return "\n".join(rendered)
def render_output(data: Any, output_format: OutputFormat) -> str:
if output_format is OutputFormat.AUTO:
raise InputError("auto output must be resolved before rendering")
if output_format is OutputFormat.PRETTY:
return render_pretty(data)
if output_format is OutputFormat.JSON:
return render_json(data)
if output_format is OutputFormat.JSONL:
return render_jsonl(data)
return render_table(data)
def resolve_output_format(
requested: OutputFormat,
*,
raw: bool,
output: Path | None,
stdout_is_tty: bool | None = None,
) -> OutputFormat:
"""Use semantic pretty output interactively and JSON for pipes/files."""
if requested is not OutputFormat.AUTO:
return requested
interactive = sys.stdout.isatty() if stdout_is_tty is None else stdout_is_tty
if raw or output is not None or not interactive:
return OutputFormat.JSON
return OutputFormat.PRETTY
def write_output(text: str, output: Path | None = None) -> None:
"""Write output atomically to a file or directly to stdout."""
if output is None:
typer.echo(text)
return
destination = output.expanduser().resolve()
destination.parent.mkdir(parents=True, exist_ok=True)
temporary: Path | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=destination.parent,
prefix=f".{destination.name}.",
delete=False,
) as handle:
handle.write(text)
handle.write("\n")
temporary = Path(handle.name)
temporary.replace(destination)
except OSError as exc:
if temporary is not None:
temporary.unlink(missing_ok=True)
raise TransportError(f"could not write output file: {exc}") from exc
def emit_output(
data: Any,
output_format: OutputFormat,
*,
output: Path | None = None,
no_color: bool = False,
pager: bool = False,
width: int | None = None,
) -> None:
"""Emit machine formats plainly or a semantic Rich view interactively."""
if output_format is not OutputFormat.PRETTY:
write_output(render_output(data, output_format), output)
return
if output is not None:
write_output(render_pretty(data, width=width or 100), output)
return
console = Console(
no_color=no_color,
width=width,
highlight=False,
soft_wrap=False,
)
if pager:
with console.pager(styles=not no_color):
console.print(build_pretty(data))
else:
console.print(build_pretty(data))
APP_HELP: Final = (
"[bold]Fetch public job postings from one direct ATS or company careers URL.[/bold]\n\n"
"Native ATS links resolve locally. Custom careers pages are resolved through bounded "
"redirect, canonical-link, embed-link, and board-slug discovery. Interactive terminals "
"get a semantic pretty view; pipes and files get normalized JSON."
)
APP_EPILOG: Final = """\
[bold]Examples[/bold]
[cyan]ats-jobs https://acme.com/careers[/cyan]
[cyan]ats-jobs https://jobs.lever.co/acme[/cyan]
[cyan]ats-jobs https://jobs.lever.co/acme/POSTING_ID[/cyan]
[cyan]ats-jobs JOB_URL --pretty --pager[/cyan]
[cyan]ats-jobs list https://jobs.ashbyhq.com/acme --format jsonl[/cyan]
[cyan]ats-jobs providers[/cyan]
Use [cyan]-v[/cyan] for resolution/fetch summaries and [cyan]-vv[/cyan] for HTTP details.
"""
HELP_CONTEXT: Final[dict[str, Any]] = {
"help_option_names": ["-h", "--help"],
"max_content_width": 100,
}
app = typer.Typer(
name="ats-jobs",
help=APP_HELP,
epilog=APP_EPILOG,
add_completion=False,
no_args_is_help=True,
rich_markup_mode="rich",
suggest_commands=True,
context_settings=HELP_CONTEXT,
pretty_exceptions_enable=False,
)
def _version_callback(value: bool) -> None:
if value:
typer.echo(f"ats-jobs {__version__}")
raise typer.Exit()
@app.callback()
def app_callback(
version: Annotated[
bool,
typer.Option(
"--version",
callback=_version_callback,
is_eager=True,
help="Show the version and exit.",
rich_help_panel="General",
),
] = False,
) -> None:
del version
UrlArgument = Annotated[
str,
typer.Argument(
metavar="URL",
help="Public careers-board or individual-job URL.",
),
]
ProviderOption = Annotated[
Provider | None,
typer.Option(
"--provider",
"-p",
metavar="PROVIDER",
case_sensitive=False,
help="Override automatic provider detection.",
rich_help_panel="Selection",
),
]
FormatOption = Annotated[
OutputFormat,
typer.Option(
"--format",
"-f",
metavar="FORMAT",
case_sensitive=False,
help="Output format: auto, pretty, json, jsonl, or table.",
rich_help_panel="Output",
),
]
PrettyOption = Annotated[
bool,
typer.Option(
"--pretty",
help="Force the semantic Rich view, even when stdout is not a TTY.",
rich_help_panel="Output",
),
]
OutputOption = Annotated[
Path | None,
typer.Option(
"--output",
"-o",
metavar="PATH",
help="Write output atomically instead of printing it.",
rich_help_panel="Output",
),
]
NoColorOption = Annotated[
bool,
typer.Option(
"--no-color",
help="Disable color in pretty output.",
rich_help_panel="Output",
),
]
PagerOption = Annotated[
bool,
typer.Option(
"--pager",
help="Open pretty output in the configured terminal pager.",
rich_help_panel="Output",
),
]
WidthOption = Annotated[
int | None,
typer.Option(
"--width",
min=40,
max=240,
metavar="COLUMNS",
help="Override pretty-output width (40-240 columns).",
rich_help_panel="Output",
),
]
RawOption = Annotated[
bool,
typer.Option(
"--raw",
help="Return provider-native records instead of normalized jobs.",
rich_help_panel="Output",
),
]
IncludeUnlistedOption = Annotated[
bool,
typer.Option(
"--include-unlisted",
help="Include Ashby direct-link-only postings.",
rich_help_panel="Selection",
),
]
DocumentedOnlyOption = Annotated[
bool,
typer.Option(
"--documented-only",
help="Reject undocumented BambooHR and Workday browser interfaces.",
rich_help_panel="Selection",
),
]
DiscoverOption = Annotated[
bool,
typer.Option(
"--discover/--offline",
help="Resolve custom careers pages online, or require a native ATS URL.",
rich_help_panel="Discovery",
),
]
ProbeOption = Annotated[
bool,
typer.Option(
"--probe/--no-probe",
help="Try bounded Greenhouse, Lever, Ashby, and Workable slug probes as a fallback.",
rich_help_panel="Discovery",
),
]
QuietOption = Annotated[
bool,
typer.Option(
"--quiet",
"-q",
help="Suppress warnings and progress messages; errors still print.",
rich_help_panel="Diagnostics",
),
]
VerboseOption = Annotated[
int,
typer.Option(
"--verbose",
"-v",
count=True,
metavar="",
show_default=False,
help="Show progress; repeat as -vv for HTTP request and retry details.",
rich_help_panel="Diagnostics",
),
]
def _run_fetch(
url: str,
*,
operation: Operation | None,
provider: Provider | None,
raw: bool,
include_unlisted: bool,
documented_only: bool,
discover: bool,
probe: bool,
output_format: OutputFormat,
pretty: bool,
output: Path | None,
no_color: bool,
pager: bool,
width: int | None,
quiet: bool,
verbose: int,
) -> None:
reporter = CliReporter(verbose=verbose, quiet=quiet)
started = time.perf_counter()
try:
if quiet and verbose:
raise InputError("--quiet cannot be combined with --verbose")
if pretty and output_format is not OutputFormat.AUTO:
raise InputError("--pretty cannot be combined with an explicit --format")
requested_format = OutputFormat.PRETTY if pretty else output_format
effective_format = resolve_output_format(
requested_format,
raw=raw,
output=output,
)
if raw and effective_format in {OutputFormat.TABLE, OutputFormat.PRETTY}:
raise InputError("--raw requires json or jsonl output")
if pager and output is not None:
raise InputError("--pager cannot be combined with --output")
if pager and effective_format is not OutputFormat.PRETTY:
raise InputError("--pager requires pretty output")
with reporter.status("Resolving ATS provider and target…"):
resolution = resolve_target(
url,
provider,
discover=discover,
probe=probe,
event_sink=reporter.debug if verbose >= 2 else None,
)
target = resolution.target
selected_operation = operation or target.operation
support = operation_support(target.provider, selected_operation)
if support is SupportTier.UNDOCUMENTED_PUBLIC:
reporter.warning(
f"{target.provider.value} uses an undocumented public interface that may drift"
)
reporter.info(
f"Resolved {target.provider.value} via {resolution.method.value}; fetching "
f"{selected_operation.value} through {support.value}."
)
reporter.debug(
"resolution: "
+ json.dumps(
resolution.model_dump(mode="json"),
ensure_ascii=False,
separators=(",", ":"),
)
)
with reporter.status(f"Fetching {target.provider.value} posting data…"):
data = _fetch_target(
target,
operation=operation,
raw=raw,
include_unlisted=include_unlisted,
documented_only=documented_only,
event_sink=reporter.debug if verbose >= 2 else None,
)
emit_output(
data,
effective_format,
output=output,
no_color=no_color,
pager=pager,
width=width,
)
count = len(data) if isinstance(data, list) else 1
noun = "posting" if count == 1 else "postings"
elapsed = time.perf_counter() - started
if output is None:
reporter.success(f"Fetched {count} {noun} in {elapsed:.2f}s.")
else:
reporter.success(
f"Wrote {count} {noun} to {output.expanduser()} in {elapsed:.2f}s."
)
except ATSJobsError as exc:
reporter.error(exc)
raise typer.Exit(code=int(exc.exit_code)) from exc
except Exception as exc:
reporter.unexpected(exc)
raise typer.Exit(code=int(ExitCode.RUNTIME)) from exc
@app.command("fetch", hidden=True)
def fetch_command(
url: UrlArgument,
provider: ProviderOption = None,
raw: RawOption = False,
include_unlisted: IncludeUnlistedOption = False,
documented_only: DocumentedOnlyOption = False,
discover: DiscoverOption = True,
probe: ProbeOption = True,
output_format: FormatOption = OutputFormat.AUTO,
pretty: PrettyOption = False,
output: OutputOption = None,
no_color: NoColorOption = False,
pager: PagerOption = False,
width: WidthOption = None,
quiet: QuietOption = False,
verbose: VerboseOption = 0,
) -> None:
"""Infer list versus get from the URL."""
_run_fetch(
url,
operation=None,
provider=provider,
raw=raw,
include_unlisted=include_unlisted,
documented_only=documented_only,
discover=discover,
probe=probe,
output_format=output_format,
pretty=pretty,
output=output,
no_color=no_color,
pager=pager,
width=width,
quiet=quiet,
verbose=verbose,
)
@app.command(
"list",
rich_help_panel="Fetch jobs",
short_help="Fetch all public postings from a careers board.",
epilog=(
"[bold]Example[/bold]\n\n"
" [cyan]ats-jobs list https://jobs.lever.co/acme --format jsonl -v[/cyan]"
),
)
def list_command(
url: UrlArgument,
provider: ProviderOption = None,
raw: RawOption = False,
include_unlisted: IncludeUnlistedOption = False,
documented_only: DocumentedOnlyOption = False,
discover: DiscoverOption = True,
probe: ProbeOption = True,
output_format: FormatOption = OutputFormat.AUTO,
pretty: PrettyOption = False,
output: OutputOption = None,
no_color: NoColorOption = False,
pager: PagerOption = False,
width: WidthOption = None,
quiet: QuietOption = False,
verbose: VerboseOption = 0,
) -> None:
"""Fetch every public posting exposed by a careers board."""
_run_fetch(
url,
operation=Operation.LIST,
provider=provider,
raw=raw,
include_unlisted=include_unlisted,
documented_only=documented_only,
discover=discover,
probe=probe,
output_format=output_format,
pretty=pretty,
output=output,
no_color=no_color,
pager=pager,
width=width,
quiet=quiet,
verbose=verbose,
)
@app.command(
"get",
rich_help_panel="Fetch jobs",
short_help="Fetch one posting from a public job URL.",
epilog=(
"[bold]Example[/bold]\n\n"
" [cyan]ats-jobs get https://jobs.lever.co/acme/POSTING_ID --raw[/cyan]"
),
)
def get_command(
url: UrlArgument,
provider: ProviderOption = None,
raw: RawOption = False,
documented_only: DocumentedOnlyOption = False,
discover: DiscoverOption = True,
probe: ProbeOption = True,
output_format: FormatOption = OutputFormat.AUTO,
pretty: PrettyOption = False,
output: OutputOption = None,
no_color: NoColorOption = False,
pager: PagerOption = False,
width: WidthOption = None,
quiet: QuietOption = False,
verbose: VerboseOption = 0,
) -> None:
"""Fetch one posting identified by a job URL."""
_run_fetch(
url,
operation=Operation.GET,
provider=provider,
raw=raw,
include_unlisted=True,
documented_only=documented_only,
discover=discover,
probe=probe,
output_format=output_format,
pretty=pretty,
output=output,
no_color=no_color,
pager=pager,
width=width,
quiet=quiet,
verbose=verbose,
)
def _exit_domain_error(error: ATSJobsError, reporter: CliReporter | None = None) -> None:
active_reporter = reporter or CliReporter()
active_reporter.error(error)
raise typer.Exit(code=int(error.exit_code)) from error
def _resolve_for_cli(
url: str,
*,
provider: Provider | None,
discover: bool,
probe: bool,
quiet: bool,
verbose: int,
) -> DiscoveryResult:
reporter = CliReporter(verbose=verbose, quiet=quiet)
try:
if quiet and verbose:
raise InputError("--quiet cannot be combined with --verbose")
with reporter.status("Resolving ATS provider and target…"):
resolution = resolve_target(
url,
provider,
discover=discover,
probe=probe,
event_sink=reporter.debug if verbose >= 2 else None,
)
reporter.info(
f"Resolved {resolution.target.provider.value} via {resolution.method.value}: "
f"{sanitize_url(resolution.resolved_url)}"
)
return resolution
except ATSJobsError as exc:
_exit_domain_error(exc, reporter)
@app.command(
"detect",
rich_help_panel="Inspect and diagnose",
short_help="Detect the ATS behind a native or custom careers URL.",
)
def detect_command(
url: UrlArgument,
provider: ProviderOption = None,
discover: DiscoverOption = True,
probe: ProbeOption = True,
quiet: QuietOption = False,
verbose: VerboseOption = 0,
) -> None:
"""Print the detected provider, discovering custom careers pages when needed."""
resolution = _resolve_for_cli(
url,
provider=provider,
discover=discover,
probe=probe,
quiet=quiet,
verbose=verbose,
)
typer.echo(resolution.target.provider.value)
@app.command(
"inspect",
rich_help_panel="Inspect and diagnose",
short_help="Explain URL discovery, parsed identifiers, and support metadata.",
)
def inspect_command(
url: UrlArgument,
provider: ProviderOption = None,
discover: DiscoverOption = True,
probe: ProbeOption = True,
quiet: QuietOption = False,
verbose: VerboseOption = 0,
) -> None:
"""Print discovery provenance, parsed identifiers, and support metadata."""
resolution = _resolve_for_cli(
url,
provider=provider,
discover=discover,
probe=probe,
quiet=quiet,
verbose=verbose,
)
typer.echo(render_json(inspect_resolution(resolution)))
@app.command(
"providers",
rich_help_panel="Inspect and diagnose",
short_help="Show supported providers and interface stability.",
)
def providers_command(
output_format: Annotated[
OutputFormat,
typer.Option(
"--format",
"-f",
metavar="FORMAT",
case_sensitive=False,
help="Output format: json, jsonl, or table.",
rich_help_panel="Output",
),
] = OutputFormat.TABLE,
) -> None:
"""Show provider capabilities and support tiers."""
records = [spec.model_dump(mode="json") for spec in PROVIDER_SPECS.values()]
if output_format is OutputFormat.JSONL:
typer.echo(render_jsonl(records))
elif output_format is OutputFormat.JSON:
typer.echo(render_json(records))
else:
headers = ("PROVIDER", "LIST", "GET", "VERIFIED")
rows = [
(
spec.provider.value,
spec.list_support.value,
spec.get_support.value,
spec.verified_at,
)
for spec in PROVIDER_SPECS.values()
]
widths = [
max(len(headers[index]), *(len(row[index]) for row in rows))
for index in range(len(headers))
]
typer.echo(
" ".join(headers[index].ljust(widths[index]) for index in range(len(headers)))
)
typer.echo(" ".join("-" * widths[index] for index in range(len(headers))))
for row in rows:
typer.echo(
" ".join(row[index].ljust(widths[index]) for index in range(len(headers)))
)
@app.command(
"version",
rich_help_panel="Inspect and diagnose",
short_help="Print the installed ats-jobs version.",
)
def version_command() -> None:
"""Print the ats-jobs version."""
typer.echo(f"ats-jobs {__version__}")
COMMAND_NAMES: Final = frozenset(
{"fetch", "list", "get", "detect", "inspect", "providers", "version"}
)
def _looks_like_target(value: str) -> bool:
"""Return whether a token resembles a URL accepted by the shorthand CLI."""
if "://" in value:
return True
head = value.split("/", 1)[0]
return "." in head and not head.startswith(".")
def rewrite_argv(argv: Sequence[str]) -> list[str]:
"""Turn `ats-jobs URL` into `ats-jobs fetch URL` while preserving options."""
args = list(argv)
if not args or args[0] in COMMAND_NAMES or args[0] in {"-h", "--help", "--version"}:
return args
if any(_looks_like_target(arg) for arg in args if not arg.startswith("-")):
return ["fetch", *args]
return args
def main(argv: Sequence[str] | None = None) -> None:
"""Console-script and PEP 723 entry point."""
args = rewrite_argv(sys.argv[1:] if argv is None else argv)
app(args=args, prog_name="ats-jobs")
if __name__ == "__main__":
main()
[build-system]
requires = ["setuptools>=80"]
build-backend = "setuptools.build_meta"
[project]
name = "ats-jobs"
version = "0.3.0"
description = "Fetch public job postings from common applicant-tracking systems using one URL."
readme = "README.md"
requires-python = ">=3.13"
license = "MIT"
authors = [
{ name = "Wyatt Walsh", email = "wyattowalsh@gmail.com" },
]
keywords = ["ats", "jobs", "greenhouse", "lever", "ashby", "workable", "bamboohr", "workday"]
classifiers = [
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.13",
]
dependencies = [
"httpx>=0.28,<0.29",
"pydantic>=2.11,<3",
"rich>=14.1,<16",
"typer>=0.20,<1",
]
[project.scripts]
ats-jobs = "ats_jobs:main"
[project.urls]
Homepage = "https://gist.github.com/wyattowalsh/1415d657dfad77a52319cac904399c4a"
[dependency-groups]
dev = [
"pytest>=9,<10",
"pytest-cov>=7,<8",
"ruff>=0.16,<1",
"ty>=0.0.64,<1",
]
[tool.uv]
exclude-newer = "2026-08-21T00:00:00Z"
[tool.setuptools]
py-modules = ["ats_jobs"]
[tool.ruff]
target-version = "py313"
line-length = 100
include = ["ats_jobs.py", "test_ats_jobs.py", "verify.py"]
[tool.ruff.lint]
select = ["B", "E", "F", "I", "RUF", "UP"]
ignore = [
"B008", # Typer intentionally constructs Argument/Option metadata in signatures.
]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
line-ending = "lf"
[tool.ty.environment]
python-version = "3.13"
[tool.ty.src]
include = ["ats_jobs.py", "verify.py"]
[tool.pytest.ini_options]
addopts = [
"--strict-config",
"--strict-markers",
"--cov=ats_jobs",
"--cov-branch",
"--cov-report=term-missing:skip-covered",
"--cov-report=json:coverage.json",
"--cov-fail-under=96",
]
testpaths = ["test_ats_jobs.py"]
[tool.coverage.run]
branch = true
source = ["ats_jobs"]
[tool.coverage.report]
fail_under = 96
show_missing = true
skip_covered = true
exclude_also = [
"if TYPE_CHECKING:",
"if __name__ == .__main__.:",
"raise NotImplementedError",
]
"""Deterministic tests for the self-contained ats-jobs Gist module."""
from __future__ import annotations
import json
from collections.abc import Callable
from pathlib import Path
from typing import Any
import httpx
import pytest
from pydantic import ValidationError
from typer.testing import CliRunner
import ats_jobs
from ats_jobs import (
ADAPTERS,
MAX_RESPONSE_BYTES,
ATSJobsError,
AmbiguousMatchError,
AshbyAdapter,
BambooHRAdapter,
DiscoveryClient,
DiscoveryMethod,
ExitCode,
FetchOptions,
GreenhouseAdapter,
HttpClient,
InputError,
InvalidJSONError,
JobPosting,
LeverAdapter,
NotFoundError,
Operation,
OutputFormat,
PaginationError,
PermissionError,
Provider,
RateLimitError,
SchemaError,
SupportTier,
Target,
TransportError,
UnsupportedInterfaceError,
WorkableAdapter,
WorkdayAdapter,
app,
canonicalize_url,
coerce_url,
detect_provider,
emit_output,
fetch_jobs,
inspect_url,
inspect_resolution,
operation_support,
parse_target,
render_json,
render_jsonl,
render_output,
render_pretty,
render_table,
resolve_output_format,
resolve_target,
rewrite_argv,
sanitize_url,
strip_html,
timestamp_to_iso,
write_output,
)
runner = CliRunner()
GREENHOUSE_JOB: dict[str, Any] = {
"id": 101,
"title": "Data Engineer",
"content": "<p>Build <strong>pipelines</strong>.</p>",
"location": {"name": "New York, NY"},
"departments": [{"name": "Engineering"}],
"absolute_url": "https://job-boards.greenhouse.io/acme/jobs/101",
"updated_at": "2026-08-20T12:00:00Z",
}
LEVER_JOB: dict[str, Any] = {
"id": "lever-1",
"text": "ML Engineer",
"description": "<p>Build models.</p>",
"descriptionPlain": "Build models.",
"categories": {
"location": "Remote - US",
"department": "AI",
"commitment": "Full-time",
},
"hostedUrl": "https://jobs.lever.co/acme/lever-1",
"applyUrl": "https://jobs.lever.co/acme/lever-1/apply",
"createdAt": 1_777_000_000_000,
"workplaceType": "remote",
}
ASHBY_LISTED: dict[str, Any] = {
"id": "ashby-1",
"title": "Platform Engineer",
"location": "New York, NY",
"department": "Platform",
"employmentType": "Full-time",
"descriptionHtml": "<p>Build systems.</p>",
"descriptionPlain": "Build systems.",
"jobUrl": "https://jobs.ashbyhq.com/acme/ashby-1",
"applyUrl": "https://jobs.ashbyhq.com/acme/ashby-1/application",
"publishedAt": "2026-08-20T12:00:00Z",
"isListed": True,
"isRemote": False,
"workplaceType": "OnSite",
"compensation": {
"compensationTierSummary": "$195K – $350K • Offers Equity",
},
}
ASHBY_UNLISTED: dict[str, Any] = {
**ASHBY_LISTED,
"id": "ashby-2",
"title": "Secret Engineer",
"jobUrl": "https://jobs.ashbyhq.com/acme/ashby-2",
"applyUrl": "https://jobs.ashbyhq.com/acme/ashby-2/application",
"isListed": False,
}
WORKABLE_JOB: dict[str, Any] = {
"shortcode": "WK1",
"title": "Backend Engineer",
"location": {"city": "New York", "state": "NY", "country": "US"},
"department": "Engineering",
"employment_type": "Full-time",
"description": "<div>Build APIs.</div>",
"url": "https://apply.workable.com/acme/j/WK1/",
"application_url": "https://apply.workable.com/acme/j/WK1/apply/",
"created_at": "2026-08-19T10:00:00Z",
}
BAMBOO_JOB: dict[str, Any] = {
"id": 42,
"jobOpeningName": "Analytics Engineer",
"location": {"city": "New York", "state": "NY"},
"departmentName": "Data",
"employmentStatus": "Full-time",
"description": "<p>Model data.</p>",
"datePosted": "2026-08-18",
}
WORKDAY_LIST_JOB: dict[str, Any] = {
"title": "Software Engineer",
"externalPath": "/job/New-York/Software-Engineer_R-1",
"locationsText": "New York, NY",
"postedOn": "Posted Today",
}
WORKDAY_DETAIL: dict[str, Any] = {
"title": "Software Engineer",
"jobReqId": "R-1",
"location": "New York, NY",
"jobFamily": "Engineering",
"timeType": "Full time",
"jobDescription": "<p>Ship software.</p>",
"externalPath": "/job/New-York/Software-Engineer_R-1",
"startDate": "2026-08-21",
}
def json_response(request: httpx.Request, payload: Any, status: int = 200) -> httpx.Response:
return httpx.Response(status, json=payload, request=request)
def mock_http(
handler: Callable[[httpx.Request], httpx.Response],
*,
retries: int = 1,
sleeps: list[float] | None = None,
) -> HttpClient:
sleeper = (sleeps.append if sleeps is not None else lambda _delay: None)
return HttpClient(
httpx.Client(transport=httpx.MockTransport(handler)),
retries=retries,
sleeper=sleeper,
)
def mock_discovery(
handler: Callable[[httpx.Request], httpx.Response],
*,
retries: int = 1,
sleeps: list[float] | None = None,
events: list[str] | None = None,
) -> DiscoveryClient:
sleeper = (sleeps.append if sleeps is not None else lambda _delay: None)
return DiscoveryClient(
httpx.Client(transport=httpx.MockTransport(handler)),
retries=retries,
sleeper=sleeper,
event_sink=events.append if events is not None else None,
)
def normalized_job(**updates: Any) -> JobPosting:
values: dict[str, Any] = {
"provider": Provider.GREENHOUSE,
"id": "1",
"title": "Engineer",
"location": "New York",
"job_url": "https://example.com/job/1",
"source": {"id": 1},
}
values.update(updates)
return JobPosting(**values)
@pytest.mark.parametrize(
("value", "expected"),
[
("example.com/jobs", "https://example.com/jobs"),
(" https://example.com/jobs ", "https://example.com/jobs"),
],
)
def test_coerce_url_success(value: str, expected: str) -> None:
assert coerce_url(value) == expected
@pytest.mark.parametrize(
"value",
["", "ftp://example.com/jobs", "https:///jobs", "https://u:p@example.com/jobs"],
)
def test_coerce_url_rejects_invalid_values(value: str) -> None:
with pytest.raises(InputError):
coerce_url(value)
def test_coerce_url_rejects_bad_idna(monkeypatch: pytest.MonkeyPatch) -> None:
class BadHost(str):
def encode(self, *_args: Any, **_kwargs: Any) -> bytes:
raise UnicodeError
class ParsedURL:
scheme = "https"
hostname = BadHost("example.com")
username = None
password = None
port = None
path = ""
monkeypatch.setattr(ats_jobs, "urlsplit", lambda _value: ParsedURL())
with pytest.raises(InputError, match="hostname is invalid"):
coerce_url("https://example.com")
def test_coerce_url_rejects_parse_failure(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(ats_jobs, "urlsplit", lambda _value: (_ for _ in ()).throw(ValueError()))
with pytest.raises(InputError, match="could not be parsed"):
coerce_url("https://example.com")
def test_canonicalize_url_removes_tracking_and_normalizes() -> None:
value = "HTTPS://Example.COM//jobs/1/?utm_source=x&b=2&a=1#section"
assert canonicalize_url(value) == "https://example.com/jobs/1?a=1&b=2"
assert canonicalize_url("https://example.com:8443") == "https://example.com:8443/"
@pytest.mark.parametrize(
("value", "expected"),
[
(None, None),
("", None),
("<p>Hello <strong>world</strong></p>", "Hello world"),
("A<br>B&amp;C", "A\nB&C"),
],
)
def test_strip_html(value: str | None, expected: str | None) -> None:
assert strip_html(value) == expected
def test_join_location_string_and_empty() -> None:
assert ats_jobs._join_location(" New York ") == "New York"
assert ats_jobs._join_location(" ") is None
@pytest.mark.parametrize(
("value", "expected"),
[
(None, None),
(True, None),
("", None),
("2026-01-01", "2026-01-01"),
(0, "1970-01-01T00:00:00Z"),
(1_700_000_000_000, "2023-11-14T22:13:20Z"),
(object(), None),
(10**30, None),
],
)
def test_timestamp_to_iso(value: Any, expected: str | None) -> None:
assert timestamp_to_iso(value) == expected
def test_sanitize_url() -> None:
assert sanitize_url(None) is None
assert (
sanitize_url("https://user:secret@example.com:8443/jobs?id=1#x")
== "https://example.com:8443/jobs"
)
assert sanitize_url("https://[bad") == "<invalid-url>"
@pytest.mark.parametrize(
("url", "provider"),
[
("https://job-boards.greenhouse.io/acme", Provider.GREENHOUSE),
("https://jobs.eu.lever.co/acme", Provider.LEVER),
("https://jobs.ashbyhq.com/acme", Provider.ASHBY),
("https://apply.workable.com/acme", Provider.WORKABLE),
("https://acme.workable.com/jobs", Provider.WORKABLE),
("https://acme.bamboohr.com/careers", Provider.BAMBOOHR),
("https://acme.wd5.myworkdayjobs.com/External", Provider.WORKDAY),
("https://acme.myworkdaysite.com/recruiting/acme/External", Provider.WORKDAY),
],
)
def test_detect_provider(url: str, provider: Provider) -> None:
assert detect_provider(url) is provider
def test_detect_provider_override_and_unknown() -> None:
assert detect_provider("https://example.com", Provider.LEVER) is Provider.LEVER
with pytest.raises(InputError, match="unsupported ATS"):
detect_provider("https://example.com")
@pytest.mark.parametrize(
("url", "provider", "operation", "fields"),
[
(
"https://boards-api.greenhouse.io/v1/boards/acme/jobs/101",
Provider.GREENHOUSE,
Operation.GET,
{"board": "acme", "job_id": "101"},
),
(
"https://job-boards.greenhouse.io/acme",
Provider.GREENHOUSE,
Operation.LIST,
{"board": "acme"},
),
(
"https://boards.greenhouse.io/embed/job_board?for=acme",
Provider.GREENHOUSE,
Operation.LIST,
{"board": "acme"},
),
(
"https://boards.greenhouse.io/embed/job_app?for=acme&token=101",
Provider.GREENHOUSE,
Operation.GET,
{"board": "acme", "job_id": "101"},
),
(
"https://api.eu.lever.co/v0/postings/acme/lever-1",
Provider.LEVER,
Operation.GET,
{"board": "acme", "job_id": "lever-1", "region": "eu"},
),
(
"https://jobs.lever.co/acme",
Provider.LEVER,
Operation.LIST,
{"board": "acme", "region": "global"},
),
(
"https://api.ashbyhq.com/posting-api/job-board/acme",
Provider.ASHBY,
Operation.LIST,
{"board": "acme"},
),
(
"https://jobs.ashbyhq.com/acme/ashby-1",
Provider.ASHBY,
Operation.GET,
{"board": "acme", "job_id": "ashby-1"},
),
(
"https://apply.workable.com/acme/j/WK1/",
Provider.WORKABLE,
Operation.GET,
{"board": "acme", "job_id": "WK1"},
),
(
"https://apply.workable.com/acme/WK1",
Provider.WORKABLE,
Operation.GET,
{"board": "acme", "job_id": "WK1"},
),
(
"https://acme.workable.com/careers",
Provider.WORKABLE,
Operation.LIST,
{"board": "acme"},
),
(
"https://www.workable.com/api/accounts/acme?details=true",
Provider.WORKABLE,
Operation.LIST,
{"board": "acme"},
),
(
"https://acme.bamboohr.com/careers/42",
Provider.BAMBOOHR,
Operation.GET,
{"tenant": "acme", "job_id": "42"},
),
(
"https://acme.wd5.myworkdayjobs.com/en-US/External/job/New-York/Role_R-1",
Provider.WORKDAY,
Operation.GET,
{"tenant": "acme", "site": "External", "external_path": "/job/New-York/Role_R-1"},
),
(
"https://acme.myworkdaysite.com/recruiting/acme/External",
Provider.WORKDAY,
Operation.LIST,
{"tenant": "acme", "site": "External"},
),
(
"https://acme.wd5.myworkdayjobs.com/wday/cxs/acme/External/jobs",
Provider.WORKDAY,
Operation.LIST,
{"tenant": "acme", "site": "External"},
),
(
"https://acme.wd5.myworkdayjobs.com/wday/cxs/acme/External/job/NY/Role_R-1",
Provider.WORKDAY,
Operation.GET,
{"tenant": "acme", "site": "External", "external_path": "/job/NY/Role_R-1"},
),
],
)
def test_parse_target(
url: str,
provider: Provider,
operation: Operation,
fields: dict[str, str],
) -> None:
target = parse_target(url)
assert target.provider is provider
assert target.operation is operation
for field, value in fields.items():
assert getattr(target, field) == value
def test_parse_target_override_requires_native_or_discovered_url() -> None:
with pytest.raises(InputError, match="needs discovery"):
parse_target("https://acme.com/careers", Provider.ASHBY)
@pytest.mark.parametrize(
"url",
[
"https://job-boards.greenhouse.io/",
"https://boards-api.greenhouse.io/nope",
"https://job-boards.greenhouse.io/acme/jobs/not-numeric",
"https://api.lever.co/wrong/path",
"https://jobs.lever.co/",
"https://api.ashbyhq.com/nope",
"https://jobs.ashbyhq.com/",
"https://jobs.workable.com/view/WK1",
"https://apply.workable.com/j/WK1",
"https://.bamboohr.com/careers",
"https://acme.myworkdaysite.com/not-recruiting/acme/External",
"https://acme.wd5.myworkdayjobs.com/",
],
)
def test_parse_target_rejects_bad_provider_urls(url: str) -> None:
with pytest.raises(InputError):
parse_target(url)
def test_inspect_and_support() -> None:
data = inspect_url("https://jobs.ashbyhq.com/acme/ashby-1")
assert data["provider"] == "ashby"
assert data["support"] == "documented-derived"
assert operation_support(Provider.GREENHOUSE, Operation.LIST) is SupportTier.DOCUMENTED_PUBLIC
assert operation_support(Provider.WORKDAY, Operation.GET) is SupportTier.UNDOCUMENTED_PUBLIC
def test_resolve_target_direct_is_offline_and_explainable() -> None:
def unexpected(_request: httpx.Request) -> httpx.Response:
raise AssertionError("direct ATS URLs must not trigger discovery")
resolution = resolve_target(
"https://jobs.ashbyhq.com/acme/ashby-1",
discovery=mock_discovery(unexpected),
)
assert resolution.method is DiscoveryMethod.DIRECT
assert resolution.target.provider is Provider.ASHBY
assert resolution.target.operation is Operation.GET
assert inspect_resolution(resolution)["support"] == "documented-derived"
def test_resolve_target_follows_redirect_to_native_ats() -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.url.host == "acme.com":
return httpx.Response(
302,
headers={"Location": "https://jobs.lever.co/acme"},
request=request,
)
return httpx.Response(200, text="<html></html>", request=request)
resolution = resolve_target(
"https://acme.com/careers",
discovery=mock_discovery(handler),
probe=False,
)
assert resolution.method is DiscoveryMethod.REDIRECT
assert resolution.target.provider is Provider.LEVER
assert resolution.target.board == "acme"
assert len(resolution.visited_urls) == 2
def test_resolve_target_scans_canonical_embed_and_page_links() -> None:
html_body = """
<html><head>
<meta property="og:url" content="https://example.com/careers">
<script src="https://boards.greenhouse.io/embed/job_board/js?for=ignored"></script>
</head><body>
<a href="https://jobs.ashbyhq.com/acme/job-1">One</a>
<a href="https://jobs.ashbyhq.com/acme/job-2">Two</a>
</body></html>
"""
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, text=html_body, request=request)
resolution = resolve_target(
"https://acme.com/careers",
Provider.ASHBY,
discovery=mock_discovery(handler),
probe=False,
)
assert resolution.method is DiscoveryMethod.LINK
assert resolution.target.provider is Provider.ASHBY
assert resolution.target.operation is Operation.LIST
assert resolution.target.board == "acme"
def test_resolve_target_custom_job_page_prefers_canonical_job() -> None:
job_url = "https://jobs.ashbyhq.com/acme/e4438c35-0766-4a03-8a3a-335514a2dc3a"
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
text=f'<link rel="canonical" href="{job_url}">',
request=request,
)
resolution = resolve_target(
"https://acme.com/careers/data-scientist",
discovery=mock_discovery(handler),
probe=False,
)
assert resolution.method is DiscoveryMethod.CANONICAL
assert resolution.target.operation is Operation.GET
assert resolution.target.job_id == "e4438c35-0766-4a03-8a3a-335514a2dc3a"
def test_resolve_target_extracts_embedded_board_attribute_and_escaped_url() -> None:
page = """
<div data-ashby-job-board-name="acme"></div>
<script>window.board = "https:\\/\\/jobs.ashbyhq.com\\/acme";</script>
"""
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, text=page, request=request)
resolution = resolve_target(
"https://acme.com/jobs",
discovery=mock_discovery(handler),
probe=False,
)
assert resolution.target.provider is Provider.ASHBY
assert resolution.target.board == "acme"
assert resolution.method is DiscoveryMethod.EMBED
def test_resolve_target_uses_bounded_slug_probe() -> None:
events: list[str] = []
def handler(request: httpx.Request) -> httpx.Response:
if request.url.host == "acme.com":
return httpx.Response(200, text="<html>No ATS links</html>", request=request)
if request.url.host == "api.ashbyhq.com":
return json_response(request, {"apiVersion": "1", "jobs": []})
return httpx.Response(404, request=request)
resolution = resolve_target(
"https://careers.acme.com/jobs",
discovery=mock_discovery(handler, events=events),
)
assert resolution.method is DiscoveryMethod.SLUG_PROBE
assert resolution.target.provider is Provider.ASHBY
assert resolution.probed_slugs == ("acme",)
assert any("api.ashbyhq.com" in event for event in events)
def test_resolve_target_rejects_ambiguous_probes_and_supports_offline_mode() -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.url.host == "acme.com":
return httpx.Response(200, text="<html></html>", request=request)
if request.url.host == "boards-api.greenhouse.io":
return json_response(request, {"jobs": []})
if request.url.host == "api.lever.co":
return json_response(request, [])
return httpx.Response(404, request=request)
with pytest.raises(AmbiguousMatchError, match="multiple plausible"):
resolve_target("https://acme.com/careers", discovery=mock_discovery(handler))
with pytest.raises(InputError, match="unsupported ATS"):
resolve_target("https://acme.com/careers", discover=False)
@pytest.mark.parametrize(
"url",
["http://localhost/jobs", "http://127.0.0.1/jobs", "http://10.0.0.1/jobs"],
)
def test_discovery_rejects_non_public_targets(url: str) -> None:
with pytest.raises(InputError, match="public|private"):
resolve_target(
url,
discovery=mock_discovery(
lambda request: httpx.Response(200, request=request)
),
)
def test_resolve_target_reports_page_failure_and_attempted_slug() -> None:
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(403 if request.url.host == "acme.com" else 404, request=request)
with pytest.raises(InputError, match="probed slugs: acme") as captured:
resolve_target("https://acme.com/careers", discovery=mock_discovery(handler))
assert "denied discovery" in captured.value.message
def test_job_posting_validation() -> None:
with pytest.raises(ValidationError):
normalized_job(title="")
with pytest.raises(ValidationError):
JobPosting(
provider=Provider.GREENHOUSE,
id="1",
title="x",
job_url="https://x",
extra="not-allowed",
)
def test_domain_error_string() -> None:
error = SchemaError(
"bad shape",
provider=Provider.LEVER,
operation=Operation.LIST,
url="https://u:p@example.com/jobs?q=secret",
)
assert str(error) == "[lever/list] bad shape (https://example.com/jobs)"
assert ATSJobsError("plain").exit_code is ExitCode.RUNTIME
@pytest.mark.parametrize(
("status", "error"),
[
(404, NotFoundError),
(401, PermissionError),
(403, PermissionError),
(429, RateLimitError),
(500, TransportError),
],
)
def test_http_status_mapping(status: int, error: type[ATSJobsError]) -> None:
def handler(request: httpx.Request) -> httpx.Response:
return json_response(request, {"error": True}, status)
http = mock_http(handler)
with pytest.raises(error):
http.request_json(
"GET",
"https://api.example.com/x",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
)
def test_http_retries_status_and_honors_retry_after() -> None:
calls = 0
sleeps: list[float] = []
def handler(request: httpx.Request) -> httpx.Response:
nonlocal calls
calls += 1
if calls == 1:
return httpx.Response(503, headers={"Retry-After": "0.1"}, request=request)
return json_response(request, {"ok": True})
http = mock_http(handler, retries=2, sleeps=sleeps)
assert http.request_json(
"GET",
"https://api.example.com/x",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
) == {"ok": True}
assert calls == 2
assert sleeps == [0.1]
def test_http_retries_transport_then_raises() -> None:
calls = 0
sleeps: list[float] = []
def handler(request: httpx.Request) -> httpx.Response:
nonlocal calls
calls += 1
raise httpx.ConnectError("offline", request=request)
http = mock_http(handler, retries=2, sleeps=sleeps)
with pytest.raises(TransportError, match="2 attempts"):
http.request_json(
"GET",
"https://api.example.com/x",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
)
assert calls == 2
assert sleeps
def test_http_invalid_retry_after_uses_backoff() -> None:
calls = 0
sleeps: list[float] = []
def handler(request: httpx.Request) -> httpx.Response:
nonlocal calls
calls += 1
if calls == 1:
return httpx.Response(503, headers={"Retry-After": "later"}, request=request)
return json_response(request, [])
http = mock_http(handler, retries=2, sleeps=sleeps)
assert http.request_json(
"GET",
"https://api.example.com/x",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
) == []
assert sleeps == [0.25]
def test_http_rejects_redirect_host_invalid_json_and_large_body(
monkeypatch: pytest.MonkeyPatch,
) -> None:
requested_hosts: list[str] = []
def redirected(request: httpx.Request) -> httpx.Response:
requested_hosts.append(request.url.host)
return httpx.Response(
302,
headers={"Location": "https://evil.example/x"},
request=request,
)
with pytest.raises(TransportError, match="redirect"):
mock_http(redirected).request_json(
"GET",
"https://api.example.com/x",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
)
assert requested_hosts == ["api.example.com"]
def invalid(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, content=b"not-json", request=request)
with pytest.raises(InvalidJSONError):
mock_http(invalid).request_json(
"GET",
"https://api.example.com/x",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
)
monkeypatch.setattr(ats_jobs, "MAX_RESPONSE_BYTES", 2)
with pytest.raises(TransportError, match="exceeds"):
mock_http(lambda request: json_response(request, {"ok": True})).request_json(
"GET",
"https://api.example.com/x",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
)
monkeypatch.setattr(ats_jobs, "MAX_RESPONSE_BYTES", MAX_RESPONSE_BYTES)
def test_http_follows_only_allowed_redirects_and_bounds_the_chain(
monkeypatch: pytest.MonkeyPatch,
) -> None:
def allowed(request: httpx.Request) -> httpx.Response:
if request.url.path == "/start":
return httpx.Response(
302,
headers={"Location": "/final"},
request=request,
)
return json_response(request, {"ok": True})
assert mock_http(allowed).request_json(
"GET",
"https://api.example.com/start",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
) == {"ok": True}
with pytest.raises(TransportError, match="not allowed"):
mock_http(allowed).request_json(
"GET",
"https://api.example.com/start",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("different.example.com",),
)
def missing_location(request: httpx.Request) -> httpx.Response:
return httpx.Response(302, request=request)
with pytest.raises(TransportError, match="Location"):
mock_http(missing_location).request_json(
"GET",
"https://api.example.com/start",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
)
monkeypatch.setattr(ats_jobs, "MAX_REDIRECTS", 1)
def loop(request: httpx.Request) -> httpx.Response:
return httpx.Response(
302,
headers={"Location": "/again"},
request=request,
)
with pytest.raises(TransportError, match="exceeds 1"):
mock_http(loop).request_json(
"GET",
"https://api.example.com/start",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
)
def test_http_client_owned_close(monkeypatch: pytest.MonkeyPatch) -> None:
class FakeClient:
closed = False
def close(self) -> None:
self.closed = True
fake = FakeClient()
monkeypatch.setattr(httpx, "Client", lambda **_kwargs: fake)
client = HttpClient()
client.close()
assert fake.closed is True
def test_greenhouse_list_get_normalize_and_fetch() -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/jobs/101"):
assert request.url.params["pay_transparency"] == "true"
return json_response(request, GREENHOUSE_JOB)
assert request.url.params["content"] == "true"
return json_response(request, {"jobs": [GREENHOUSE_JOB], "meta": {"total": 1}})
http = mock_http(handler)
listed = fetch_jobs("https://job-boards.greenhouse.io/acme", http=http)
assert isinstance(listed, list)
assert listed[0].provider is Provider.GREENHOUSE
assert listed[0].department == "Engineering"
assert listed[0].description_text == "Build pipelines."
got = fetch_jobs("https://job-boards.greenhouse.io/acme/jobs/101", http=http)
assert isinstance(got, JobPosting)
assert got.id == "101"
raw = fetch_jobs(
"https://job-boards.greenhouse.io/acme/jobs/101",
raw=True,
http=http,
)
assert raw == GREENHOUSE_JOB
@pytest.mark.parametrize(
"payload",
[
[],
{"jobs": [], "meta": {}},
{"jobs": [], "meta": {"total": 1}},
{"jobs": [{"id": True, "title": "x"}], "meta": {"total": 1}},
{"jobs": [{"id": 1, "title": ""}], "meta": {"total": 1}},
],
)
def test_greenhouse_list_schema_errors(payload: Any) -> None:
adapter = GreenhouseAdapter()
target = parse_target("https://job-boards.greenhouse.io/acme")
with pytest.raises(SchemaError):
adapter.list_jobs(
target,
mock_http(lambda request: json_response(request, payload)),
FetchOptions(),
)
def test_greenhouse_get_errors_and_normalize_fallback() -> None:
adapter = GreenhouseAdapter()
board = parse_target("https://job-boards.greenhouse.io/acme")
with pytest.raises(InputError):
adapter.get_job(
board,
mock_http(lambda request: json_response(request, {})),
FetchOptions(),
)
target = parse_target("https://job-boards.greenhouse.io/acme/jobs/101")
with pytest.raises(SchemaError):
adapter.get_job(
target,
mock_http(lambda request: json_response(request, {"id": 999, "title": "x"})),
FetchOptions(),
)
fallback = adapter.normalize({"id": 101, "title": "X"}, target)
assert fallback.job_url.endswith("/acme/jobs/101")
def test_lever_list_get_normalize_and_pagination() -> None:
calls: list[int] = []
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/lever-1"):
return json_response(request, LEVER_JOB)
skip = int(request.url.params["skip"])
calls.append(skip)
return json_response(request, [LEVER_JOB] if skip == 0 else [])
http = mock_http(handler)
listed = fetch_jobs("https://jobs.lever.co/acme", http=http)
assert isinstance(listed, list)
assert listed[0].remote is True
assert listed[0].published_at is not None
assert calls == [0, 1]
got = fetch_jobs("https://jobs.lever.co/acme/lever-1", http=http)
assert isinstance(got, JobPosting)
assert got.employment_type == "Full-time"
def test_lever_pagination_and_schema_errors(monkeypatch: pytest.MonkeyPatch) -> None:
adapter = LeverAdapter()
target = parse_target("https://jobs.lever.co/acme")
with pytest.raises(SchemaError):
adapter.list_jobs(
target,
mock_http(lambda request: json_response(request, {})),
FetchOptions(),
)
with pytest.raises(SchemaError):
adapter.list_jobs(
target,
mock_http(lambda request: json_response(request, [{"id": "1", "text": ""}])),
FetchOptions(),
)
with pytest.raises(PaginationError, match="duplicate"):
adapter.list_jobs(
target,
mock_http(lambda request: json_response(request, [LEVER_JOB])),
FetchOptions(),
)
monkeypatch.setattr(ats_jobs, "MAX_PAGES", 1)
with pytest.raises(PaginationError, match="safety"):
adapter.list_jobs(
target,
mock_http(lambda request: json_response(request, [LEVER_JOB])),
FetchOptions(),
)
def test_lever_get_errors() -> None:
adapter = LeverAdapter()
board = parse_target("https://jobs.lever.co/acme")
with pytest.raises(InputError):
adapter.get_job(
board,
mock_http(lambda request: json_response(request, {})),
FetchOptions(),
)
target = parse_target("https://jobs.lever.co/acme/lever-1")
with pytest.raises(SchemaError):
adapter.get_job(
target,
mock_http(lambda request: json_response(request, {**LEVER_JOB, "id": "other"})),
FetchOptions(),
)
def test_ashby_list_visibility_get_and_normalize() -> None:
payload = {"apiVersion": "1", "jobs": [ASHBY_LISTED, ASHBY_UNLISTED]}
http = mock_http(lambda request: json_response(request, payload))
listed = fetch_jobs("https://jobs.ashbyhq.com/acme", http=http)
assert isinstance(listed, list)
assert len(listed) == 1
all_jobs = fetch_jobs(
"https://jobs.ashbyhq.com/acme",
include_unlisted=True,
http=http,
)
assert isinstance(all_jobs, list)
assert len(all_jobs) == 2
got = fetch_jobs(
"https://jobs.ashbyhq.com/acme/ashby-1?utm_source=x",
http=http,
)
assert isinstance(got, JobPosting)
assert got.id == "ashby-1"
assert got.remote is False
def test_ashby_schema_not_found_ambiguous_and_id_fallback() -> None:
adapter = AshbyAdapter()
board = parse_target("https://jobs.ashbyhq.com/acme")
with pytest.raises(SchemaError):
adapter.list_jobs(
board,
mock_http(lambda request: json_response(request, {"jobs": []})),
FetchOptions(),
)
with pytest.raises(SchemaError):
adapter.list_jobs(
board,
mock_http(
lambda request: json_response(
request,
{"apiVersion": "1", "jobs": [{"title": "x"}]},
)
),
FetchOptions(),
)
target = parse_target("https://jobs.ashbyhq.com/acme/missing")
no_match_http = mock_http(
lambda request: json_response(request, {"apiVersion": "1", "jobs": [ASHBY_LISTED]})
)
with pytest.raises(NotFoundError):
adapter.get_job(target, no_match_http, FetchOptions())
duplicate = {**ASHBY_LISTED, "id": "other"}
ambiguous_http = mock_http(
lambda request: json_response(
request,
{"apiVersion": "1", "jobs": [ASHBY_LISTED, duplicate]},
)
)
matching = parse_target("https://jobs.ashbyhq.com/acme/ashby-1")
with pytest.raises(AmbiguousMatchError):
adapter.get_job(matching, ambiguous_http, FetchOptions())
raw = {key: value for key, value in ASHBY_LISTED.items() if key != "id"}
assert adapter.normalize(raw, matching).id == "ashby-1"
def test_workable_list_get_normalize_and_fallback() -> None:
payload = {"name": "Acme", "jobs": [WORKABLE_JOB]}
http = mock_http(lambda request: json_response(request, payload))
listed = fetch_jobs("https://apply.workable.com/acme", http=http)
assert isinstance(listed, list)
assert listed[0].location == "New York, NY, US"
got = fetch_jobs("https://apply.workable.com/acme/j/WK1/", http=http)
assert isinstance(got, JobPosting)
assert got.id == "WK1"
adapter = WorkableAdapter()
target = parse_target("https://apply.workable.com/acme/j/WK1")
fallback_raw = {"shortcode": "WK1", "title": "X"}
assert adapter.normalize(fallback_raw, target).job_url.endswith("/acme/j/WK1/")
def test_workable_schema_not_found_and_ambiguous() -> None:
adapter = WorkableAdapter()
board = parse_target("https://apply.workable.com/acme")
with pytest.raises(SchemaError):
adapter.list_jobs(
board,
mock_http(lambda request: json_response(request, [])),
FetchOptions(),
)
with pytest.raises(SchemaError):
adapter.list_jobs(
board,
mock_http(
lambda request: json_response(
request,
{"jobs": [{"shortcode": "", "title": "x"}]},
)
),
FetchOptions(),
)
missing = parse_target("https://apply.workable.com/acme/j/MISSING")
http = mock_http(lambda request: json_response(request, {"jobs": [WORKABLE_JOB]}))
with pytest.raises(NotFoundError):
adapter.get_job(missing, http, FetchOptions())
duplicate = {**WORKABLE_JOB, "url": "https://apply.workable.com/acme/j/WK1/"}
http2 = mock_http(lambda request: json_response(request, {"jobs": [WORKABLE_JOB, duplicate]}))
target = parse_target("https://apply.workable.com/acme/j/WK1")
with pytest.raises(AmbiguousMatchError):
adapter.get_job(target, http2, FetchOptions())
def test_bamboohr_list_get_normalize_and_documented_only() -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/detail"):
return json_response(request, {"result": {"jobOpening": BAMBOO_JOB}})
return json_response(request, {"result": [BAMBOO_JOB], "meta": {"totalCount": 1}})
http = mock_http(handler)
listed = fetch_jobs("https://acme.bamboohr.com/careers", http=http)
assert isinstance(listed, list)
assert listed[0].title == "Analytics Engineer"
got = fetch_jobs("https://acme.bamboohr.com/careers/42", http=http)
assert isinstance(got, JobPosting)
assert got.job_url.endswith("/careers/42")
with pytest.raises(UnsupportedInterfaceError):
fetch_jobs(
"https://acme.bamboohr.com/careers",
documented_only=True,
http=http,
)
def test_bamboohr_schema_and_get_errors() -> None:
adapter = BambooHRAdapter()
board = parse_target("https://acme.bamboohr.com/careers")
with pytest.raises(SchemaError):
adapter.list_jobs(
board,
mock_http(lambda request: json_response(request, {})),
FetchOptions(),
)
with pytest.raises(SchemaError):
adapter.list_jobs(
board,
mock_http(
lambda request: json_response(
request,
{"result": [], "meta": {"totalCount": 1}},
)
),
FetchOptions(),
)
with pytest.raises(SchemaError):
adapter.list_jobs(
board,
mock_http(lambda request: json_response(request, {"result": [{"id": True}]})),
FetchOptions(),
)
with pytest.raises(InputError):
adapter.get_job(
board,
mock_http(lambda request: json_response(request, {})),
FetchOptions(),
)
target = parse_target("https://acme.bamboohr.com/careers/42")
with pytest.raises(SchemaError):
adapter.get_job(
target,
mock_http(
lambda request: json_response(
request,
{"result": {"jobOpening": {**BAMBOO_JOB, "id": 99}}},
)
),
FetchOptions(),
)
with pytest.raises(SchemaError, match="title"):
adapter.normalize({"id": 42}, target)
with pytest.raises(SchemaError, match="id"):
adapter.normalize({"jobOpeningName": "X"}, target)
def test_workday_list_get_normalize_both_host_families() -> None:
calls: list[int] = []
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "GET":
return json_response(request, {"jobPostingInfo": WORKDAY_DETAIL})
body = json.loads(request.content)
offset = body["offset"]
calls.append(offset)
if offset == 0:
return json_response(request, {"total": 2, "jobPostings": [WORKDAY_LIST_JOB]})
second = {**WORKDAY_LIST_JOB, "title": "Second", "externalPath": "/job/X/Second_R-2"}
return json_response(request, {"total": 0, "jobPostings": [second]})
http = mock_http(handler)
listed = fetch_jobs(
"https://acme.wd5.myworkdayjobs.com/en-US/External",
http=http,
)
assert isinstance(listed, list)
assert len(listed) == 2
assert calls == [0, 1]
got = fetch_jobs(
(
"https://acme.myworkdaysite.com/recruiting/acme/External/job/"
"New-York/Software-Engineer_R-1"
),
http=http,
)
assert isinstance(got, JobPosting)
assert got.id == "R-1"
assert got.description_text == "Ship software."
def test_workday_empty_board() -> None:
adapter = WorkdayAdapter()
target = parse_target("https://acme.wd5.myworkdayjobs.com/External")
jobs = adapter.list_jobs(
target,
mock_http(lambda request: json_response(request, {"total": 0, "jobPostings": []})),
FetchOptions(),
)
assert jobs == []
@pytest.mark.parametrize(
"responses,match",
[
([{"total": -1, "jobPostings": []}], "non-negative"),
([{"total": 1, "jobPostings": []}], "ended before"),
(
[
{"total": 2, "jobPostings": [WORKDAY_LIST_JOB]},
{"total": 3, "jobPostings": [{**WORKDAY_LIST_JOB, "externalPath": "/job/X/2"}]},
],
"total changed",
),
(
[
{"total": 2, "jobPostings": [WORKDAY_LIST_JOB]},
{"total": 0, "jobPostings": [WORKDAY_LIST_JOB]},
],
"duplicate",
),
(
[
{
"total": 1,
"jobPostings": [
WORKDAY_LIST_JOB,
{**WORKDAY_LIST_JOB, "externalPath": "/job/X/2"},
],
}
],
"more postings",
),
([{"total": 0, "jobPostings": [WORKDAY_LIST_JOB]}], "total=0"),
],
)
def test_workday_pagination_errors(responses: list[dict[str, Any]], match: str) -> None:
iterator = iter(responses)
adapter = WorkdayAdapter()
target = parse_target("https://acme.wd5.myworkdayjobs.com/External")
http = mock_http(lambda request: json_response(request, next(iterator)))
with pytest.raises((SchemaError, PaginationError), match=match):
adapter.list_jobs(target, http, FetchOptions())
def test_workday_schema_get_and_normalize_errors(monkeypatch: pytest.MonkeyPatch) -> None:
adapter = WorkdayAdapter()
target = parse_target("https://acme.wd5.myworkdayjobs.com/External")
with pytest.raises(SchemaError):
adapter.list_jobs(
target,
mock_http(lambda request: json_response(request, {})),
FetchOptions(),
)
with pytest.raises(SchemaError):
adapter.list_jobs(
target,
mock_http(lambda request: json_response(request, {"total": 1, "jobPostings": [{}]})),
FetchOptions(),
)
with pytest.raises(InputError):
adapter.get_job(
target,
mock_http(lambda request: json_response(request, {})),
FetchOptions(),
)
job_target = parse_target(
"https://acme.wd5.myworkdayjobs.com/External/job/New-York/Software-Engineer_R-1"
)
with pytest.raises(SchemaError):
adapter.get_job(
job_target,
mock_http(lambda request: json_response(request, {})),
FetchOptions(),
)
with pytest.raises(SchemaError, match="title"):
adapter.normalize({}, target)
with pytest.raises(SchemaError, match="identifier"):
adapter.normalize({"title": "X"}, target)
with pytest.raises(SchemaError, match="URL"):
adapter.normalize({"title": "X", "id": "1"}, target)
monkeypatch.setattr(ats_jobs, "MAX_PAGES", 1)
with pytest.raises(PaginationError, match="safety"):
adapter.list_jobs(
target,
mock_http(
lambda request: json_response(
request,
{"total": 2, "jobPostings": [WORKDAY_LIST_JOB]},
)
),
FetchOptions(),
)
def test_fetch_jobs_explicit_operation_and_closes_owned_client(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class FakeAdapter:
provider = Provider.GREENHOUSE
def list_jobs(self, *_args: Any) -> list[dict[str, Any]]:
return [GREENHOUSE_JOB]
def get_job(self, *_args: Any) -> dict[str, Any]:
return GREENHOUSE_JOB
def normalize(self, raw: dict[str, Any], target: Target) -> JobPosting:
return GreenhouseAdapter().normalize(raw, target)
class FakeHttp:
closed = False
def close(self) -> None:
self.closed = True
fake_http = FakeHttp()
monkeypatch.setitem(ADAPTERS, Provider.GREENHOUSE, FakeAdapter())
monkeypatch.setattr(ats_jobs, "HttpClient", lambda **_kwargs: fake_http)
result = fetch_jobs(
"https://job-boards.greenhouse.io/acme/jobs/101",
operation=Operation.LIST,
)
assert isinstance(result, list)
assert fake_http.closed is True
raw_result = fetch_jobs(
"https://job-boards.greenhouse.io/acme",
operation=Operation.LIST,
raw=True,
http=fake_http,
)
assert raw_result == [GREENHOUSE_JOB]
def test_renderers() -> None:
job = normalized_job(
provider=Provider.ASHBY,
employment_type="FullTime",
remote=False,
description_text="ABOUT YOU\n\n - Build things\n - Be kind",
source={
"workplaceType": "OnSite",
"compensation": {"compensationTierSummary": "$195K – $350K • Offers Equity"},
},
)
assert json.loads(render_json(job))["title"] == "Engineer"
assert json.loads(render_json([job]))[0]["id"] == "1"
assert json.loads(render_jsonl(job))["provider"] == "ashby"
assert len(render_jsonl([job, job]).splitlines()) == 2
table = render_table(job)
assert "TITLE" in table and "Engineer" in table
table_from_mapping = render_table(job.model_dump(mode="json"))
assert "New York" in table_from_mapping
assert render_output(job, OutputFormat.JSON) == render_json(job)
assert render_output(job, OutputFormat.JSONL) == render_jsonl(job)
assert render_output(job, OutputFormat.TABLE) == render_table(job)
pretty = render_pretty(job)
assert "Engineer" in pretty
assert "$195K – $350K" in pretty
assert "About you" in pretty
assert "description_html" not in pretty
assert render_output(job, OutputFormat.PRETTY) == pretty
with pytest.raises(InputError, match="auto output"):
render_output(job, OutputFormat.AUTO)
with pytest.raises(InputError):
render_table({"title": "missing URL"})
def test_render_table_truncates_and_empty_list() -> None:
job = normalized_job(title="X" * 100, job_url="https://example.com/" + "x" * 100)
assert "…" in render_table(job)
empty = render_table([])
assert "TITLE" in empty
assert "No public postings" in render_pretty([])
def test_output_format_resolution_and_pretty_emission(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
job = normalized_job(description_text="A readable description")
assert (
resolve_output_format(
OutputFormat.AUTO,
raw=False,
output=None,
stdout_is_tty=True,
)
is OutputFormat.PRETTY
)
assert (
resolve_output_format(
OutputFormat.AUTO,
raw=False,
output=None,
stdout_is_tty=False,
)
is OutputFormat.JSON
)
assert (
resolve_output_format(
OutputFormat.AUTO,
raw=True,
output=None,
stdout_is_tty=True,
)
is OutputFormat.JSON
)
assert (
resolve_output_format(
OutputFormat.AUTO,
raw=False,
output=tmp_path / "jobs.json",
stdout_is_tty=True,
)
is OutputFormat.JSON
)
assert (
resolve_output_format(
OutputFormat.TABLE,
raw=False,
output=None,
stdout_is_tty=True,
)
is OutputFormat.TABLE
)
emit_output(job, OutputFormat.PRETTY, no_color=True, width=80)
assert "Engineer" in capsys.readouterr().out
destination = tmp_path / "pretty.txt"
emit_output(job, OutputFormat.PRETTY, output=destination, width=80)
assert "A readable description" in destination.read_text()
def test_write_output_stdout_and_atomic_file(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
write_output("hello")
assert capsys.readouterr().out == "hello\n"
destination = tmp_path / "nested" / "out.json"
write_output("{}", destination)
assert destination.read_text() == "{}\n"
def test_write_output_error(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
def fail_replace(self: Path, target: Path) -> Path:
del self, target
raise OSError("nope")
monkeypatch.setattr(Path, "replace", fail_replace)
with pytest.raises(TransportError, match="write"):
write_output("x", tmp_path / "out")
def test_rewrite_argv() -> None:
assert rewrite_argv(["https://jobs.lever.co/acme"]) == [
"fetch",
"https://jobs.lever.co/acme",
]
assert rewrite_argv(["list", "https://x"]) == ["list", "https://x"]
assert rewrite_argv(["--help"]) == ["--help"]
assert rewrite_argv([]) == []
def test_cli_detect_inspect_providers_version() -> None:
result = runner.invoke(app, ["detect", "https://jobs.lever.co/acme"])
assert result.exit_code == 0
assert result.stdout.strip() == "lever"
result = runner.invoke(app, ["inspect", "https://jobs.ashbyhq.com/acme"])
assert result.exit_code == 0
inspected = json.loads(result.stdout)
assert inspected["target"]["board"] == "acme"
assert inspected["method"] == "direct-host"
result = runner.invoke(app, ["providers"])
assert result.exit_code == 0
assert "greenhouse" in result.stdout
result = runner.invoke(app, ["providers", "--format", "json"])
assert json.loads(result.stdout)[0]["provider"] == "greenhouse"
result = runner.invoke(app, ["providers", "--format", "jsonl"])
assert len(result.stdout.strip().splitlines()) == 6
result = runner.invoke(app, ["version"])
assert result.exit_code == 0
assert result.stdout.strip() == f"ats-jobs {ats_jobs.__version__}"
def test_cli_fetch_success_options_and_file(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
calls: list[dict[str, Any]] = []
def fake_fetch(target: Target, **kwargs: Any) -> JobPosting:
calls.append({"target": target, **kwargs})
return normalized_job()
monkeypatch.setattr(ats_jobs, "_fetch_target", fake_fetch)
result = runner.invoke(
app,
[
"fetch",
"https://jobs.lever.co/acme/1",
"--format",
"jsonl",
"--output",
str(tmp_path / "job.jsonl"),
"--quiet",
],
)
assert result.exit_code == 0
assert (tmp_path / "job.jsonl").exists()
assert calls[0]["operation"] is None
result = runner.invoke(app, ["list", "https://jobs.lever.co/acme", "--raw"])
assert result.exit_code == 0
assert calls[-1]["operation"] is Operation.LIST
result = runner.invoke(app, ["get", "https://jobs.lever.co/acme/1"])
assert result.exit_code == 0
assert calls[-1]["operation"] is Operation.GET
def test_cli_pretty_output_and_conflicting_output_options(
monkeypatch: pytest.MonkeyPatch,
) -> None:
job = normalized_job(
provider=Provider.ASHBY,
title="Data Scientist",
employment_type="FullTime",
description_text="ABOUT YOU\n\n - Build useful models",
source={
"workplaceType": "OnSite",
"compensation": {"compensationTierSummary": "$195K – $350K • Offers Equity"},
},
)
monkeypatch.setattr(ats_jobs, "_fetch_target", lambda *_args, **_kwargs: job)
result = runner.invoke(
app,
[
"get",
"https://jobs.ashbyhq.com/acme/job-1",
"--pretty",
"--no-color",
"--width",
"80",
],
)
assert result.exit_code == 0
assert "Data Scientist" in result.stdout
assert "$195K – $350K" in result.stdout
assert "Build useful models" in result.stdout
assert '"source"' not in result.stdout
result = runner.invoke(
app,
["get", "https://jobs.ashbyhq.com/acme/job-1", "--pretty", "--format", "json"],
)
assert result.exit_code == ExitCode.INPUT
result = runner.invoke(
app,
["get", "https://jobs.ashbyhq.com/acme/job-1", "--raw", "--pretty"],
)
assert result.exit_code == ExitCode.INPUT
result = runner.invoke(
app,
["get", "https://jobs.ashbyhq.com/acme/job-1", "--format", "json", "--pager"],
)
assert result.exit_code == ExitCode.INPUT
def test_cli_warnings_documented_only_and_errors(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(ats_jobs, "_fetch_target", lambda *_args, **_kwargs: normalized_job())
result = runner.invoke(app, ["fetch", "https://acme.bamboohr.com/careers/42"])
assert result.exit_code == 0
assert "undocumented" in result.stderr
result = runner.invoke(
app,
["fetch", "https://acme.bamboohr.com/careers/42", "--raw", "--format", "table"],
)
assert result.exit_code == ExitCode.INPUT
assert "requires json" in result.stderr
def fail(*_args: Any, **_kwargs: Any) -> None:
raise NotFoundError("gone", provider=Provider.LEVER, operation=Operation.GET)
monkeypatch.setattr(ats_jobs, "_fetch_target", fail)
result = runner.invoke(app, ["get", "https://jobs.lever.co/acme/1"])
assert result.exit_code == ExitCode.NOT_FOUND
assert "gone" in result.stderr
def test_cli_detect_and_inspect_errors() -> None:
result = runner.invoke(app, ["detect", "https://example.com", "--offline"])
assert result.exit_code == ExitCode.INPUT
result = runner.invoke(app, ["inspect", "https://example.com", "--offline"])
assert result.exit_code == ExitCode.INPUT
def test_main_rewrites_url(monkeypatch: pytest.MonkeyPatch) -> None:
received: dict[str, Any] = {}
def fake_app(*, args: list[str], prog_name: str) -> None:
received["args"] = args
received["prog_name"] = prog_name
monkeypatch.setattr(ats_jobs, "app", fake_app)
ats_jobs.main(["https://jobs.lever.co/acme"])
assert received == {
"args": ["fetch", "https://jobs.lever.co/acme"],
"prog_name": "ats-jobs",
}
@pytest.mark.parametrize(
"error,expected",
[
(UnsupportedInterfaceError("x"), "--documented-only"),
(NotFoundError("x"), "public"),
(AmbiguousMatchError("x"), "canonical"),
(PermissionError("x"), "authentication"),
(InvalidJSONError("x"), "non-JSON"),
(RateLimitError("x"), "Retry later"),
(PaginationError("x"), "changed"),
(SchemaError("x"), "provider response"),
(TransportError("x"), "connectivity"),
(InputError("unsupported ATS hostname"), "native ATS"),
(InputError("--raw requires json or jsonl output"), "jsonl"),
(InputError("--quiet cannot be combined with --verbose"), "not both"),
(InputError("--pretty cannot be combined with an explicit --format"), "exactly one"),
(InputError("--pager requires pretty output"), "--pretty --pager"),
(InputError("discovery found a board but not an individual posting"), "direct posting"),
(InputError("other"), "--help"),
],
)
def test_cli_error_hints(error: ATSJobsError, expected: str) -> None:
assert expected in (ats_jobs.cli_error_hint(error) or "")
assert ats_jobs.cli_error_hint(ATSJobsError("x")) is None
def test_cli_reporter_levels_and_quiet(capsys: pytest.CaptureFixture[str]) -> None:
reporter = ats_jobs.CliReporter(verbose=2)
reporter.warning("warn")
reporter.info("info")
reporter.debug("debug")
reporter.success("done")
reporter.error(ATSJobsError("plain"))
stderr = capsys.readouterr().err
assert all(label in stderr for label in ("WARNING", "INFO", "DEBUG", "OK", "ERROR"))
quiet = ats_jobs.CliReporter(verbose=2, quiet=True)
quiet.warning("warn")
quiet.info("info")
quiet.debug("debug")
quiet.success("done")
assert capsys.readouterr().err == ""
normal = ats_jobs.CliReporter()
normal.info("hidden")
normal.debug("hidden")
normal.success("hidden")
assert capsys.readouterr().err == ""
def test_http_debug_events_cover_request_retry_redirect_and_success() -> None:
calls = 0
events: list[str] = []
def handler(request: httpx.Request) -> httpx.Response:
nonlocal calls
calls += 1
if calls == 1:
return httpx.Response(503, request=request)
if request.url.path == "/start":
return httpx.Response(302, headers={"Location": "/final"}, request=request)
return json_response(request, {"ok": True})
client = HttpClient(
httpx.Client(transport=httpx.MockTransport(handler)),
retries=3,
sleeper=lambda _delay: None,
event_sink=events.append,
)
assert client.request_json(
"GET",
"https://api.example.com/start?secret=nope",
provider=Provider.LEVER,
operation=Operation.LIST,
allowed_hosts=("api.example.com",),
) == {"ok": True}
assert any("attempt 1/3" in event for event in events)
assert any("retrying" in event for event in events)
assert any("redirect 302" in event for event in events)
assert any("HTTP 200" in event for event in events)
assert all("secret" not in event for event in events)
def test_cli_help_version_suggestions_and_bare_url_rewrite() -> None:
result = runner.invoke(app, ["--help"])
assert result.exit_code == 0
assert "Fetch jobs" in result.stdout
assert "Inspect and diagnose" in result.stdout
assert "-vv" in result.stdout
assert "fetch" not in result.stdout.split("Fetch jobs", 1)[-1].split("Inspect", 1)[0]
result = runner.invoke(app, ["list", "-h"])
assert result.exit_code == 0
assert "Diagnostics" in result.stdout
assert "--include-unlisted" in result.stdout
assert "--verbose" in result.stdout
result = runner.invoke(app, ["--version"])
assert result.exit_code == 0
assert result.stdout.strip() == f"ats-jobs {ats_jobs.__version__}"
result = runner.invoke(app, ["lis"])
assert result.exit_code == ExitCode.INPUT
assert "Did you mean" in result.stderr
assert rewrite_argv(["jobs.lever.co/acme"]) == ["fetch", "jobs.lever.co/acme"]
assert rewrite_argv(["-v", "jobs.lever.co/acme"]) == [
"fetch",
"-v",
"jobs.lever.co/acme",
]
assert rewrite_argv(["lis"]) == ["lis"]
def test_cli_verbose_quiet_success_and_unexpected_error(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
def verbose_fetch(_url: str, **kwargs: Any) -> list[JobPosting]:
event_sink = kwargs.get("event_sink")
assert callable(event_sink)
event_sink("GET https://api.example.com/jobs (attempt 1/3)")
return [normalized_job(), normalized_job(id="2")]
monkeypatch.setattr(ats_jobs, "_fetch_target", verbose_fetch)
result = runner.invoke(
app,
[
"list",
"https://jobs.lever.co/acme",
"-vv",
"--output",
str(tmp_path / "jobs.json"),
],
)
assert result.exit_code == 0
assert result.stdout == ""
assert "INFO" in result.stderr
assert "DEBUG" in result.stderr
assert "OK" in result.stderr
assert "2 postings" in result.stderr
result = runner.invoke(
app,
["list", "https://jobs.lever.co/acme", "--quiet", "--verbose"],
)
assert result.exit_code == ExitCode.INPUT
assert "HINT" in result.stderr
assert "not both" in result.stderr
monkeypatch.setattr(ats_jobs, "_fetch_target", lambda *_args, **_kwargs: 1 / 0)
result = runner.invoke(app, ["list", "https://jobs.lever.co/acme"])
assert result.exit_code == ExitCode.RUNTIME
assert "unexpected ZeroDivisionError" in result.stderr
assert "Re-run with -vv" in result.stderr
result = runner.invoke(app, ["list", "https://jobs.lever.co/acme", "-vv"])
assert result.exit_code == ExitCode.RUNTIME
assert "Traceback" in result.stderr
def test_cli_domain_error_hints_are_actionable(monkeypatch: pytest.MonkeyPatch) -> None:
def fail(*_args: Any, **_kwargs: Any) -> None:
raise NotFoundError(
"gone",
provider=Provider.LEVER,
operation=Operation.GET,
url="https://jobs.lever.co/acme/1?token=secret",
)
monkeypatch.setattr(ats_jobs, "_fetch_target", fail)
result = runner.invoke(app, ["get", "https://jobs.lever.co/acme/1"])
assert result.exit_code == ExitCode.NOT_FOUND
assert "ERROR" in result.stderr
assert "HINT" in result.stderr
assert "token" not in result.stderr
def test_all_adapters_registered() -> None:
assert set(ADAPTERS) == set(Provider)
def test_cli_reporter_interactive_status(monkeypatch: pytest.MonkeyPatch) -> None:
events: list[str] = []
class FakeStderr:
@staticmethod
def isatty() -> bool:
return True
class FakeConsole:
def __init__(self, **_kwargs: Any) -> None:
pass
def status(self, message: str, *, spinner: str):
@ats_jobs.contextmanager
def active():
events.append(f"start:{message}:{spinner}")
yield
events.append("stop")
return active()
monkeypatch.setattr(ats_jobs.sys, "stderr", FakeStderr())
monkeypatch.setattr(ats_jobs, "Console", FakeConsole)
with ats_jobs.CliReporter().status("Discovering"):
events.append("body")
assert events == ["start:Discovering:dots", "body", "stop"]
def test_additional_native_url_variants() -> None:
workable = parse_target("https://acme.workable.com/openings/WK1")
assert workable.operation is Operation.GET
assert workable.board == "acme"
assert workable.job_id == "WK1"
bamboo = parse_target("https://acme.bamboohr.com/careers")
assert bamboo.operation is Operation.LIST
workday = parse_target(
"https://careers.acme.com/wday/cxs/acme/External/jobs",
Provider.WORKDAY,
)
assert workday.provider is Provider.WORKDAY
assert workday.tenant == "acme"
assert workday.site == "External"
def test_discovery_html_fingerprints_cover_encoded_relative_and_data_attributes() -> None:
encoded = "https%3A%2F%2Fjobs.ashbyhq.com%2Facme"
page = ats_jobs.DiscoveryPage(
final_url="https://careers.acme.com/jobs",
visited_urls=("https://careers.acme.com/jobs",),
text=f"""
<meta property="og:url" content="https://jobs.lever.co/acme">
<div
data-ashby-job-board-name="ashby-co"
data-greenhouse-board="greenhouse-co"
data-lever-site="lever-co"
data-workable-account="workable-co"
data-bamboohr-tenant="bamboo-co"
data-workday-tenant="wdtenant"
data-workday-site="External"
></div>
<script>const encoded = "{encoded}";</script>
<script>fetch("/wday/cxs/acme/External/jobs")</script>
""",
)
candidates = ats_jobs._extract_discovery_candidates(page)
providers = {candidate.provider for candidate in candidates}
assert providers == set(Provider)
assert any(candidate.method is DiscoveryMethod.META for candidate in candidates)
assert any(candidate.url.endswith("/wday/cxs/acme/External/jobs") for candidate in candidates)
assert any(candidate.url == "https://jobs.ashbyhq.com/acme" for candidate in candidates)
def test_discovery_candidate_scan_survives_html_parser_failure(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
ats_jobs._ATSLinkParser,
"feed",
lambda *_args, **_kwargs: (_ for _ in ()).throw(ValueError("bad html")),
)
page = ats_jobs.DiscoveryPage(
final_url="https://acme.com/careers",
text='"https:\\/\\/jobs.lever.co\\/acme"',
visited_urls=("https://acme.com/careers",),
)
candidates = ats_jobs._extract_discovery_candidates(page)
assert candidates[0].provider is Provider.LEVER
@pytest.mark.parametrize(
("url", "expected"),
[
("https://example.com/careers?gh_jid=1", Operation.GET),
("https://example.com/careers/123", Operation.GET),
(
"https://example.com/e4438c35-0766-4a03-8a3a-335514a2dc3a",
Operation.GET,
),
("https://example.com/careers", Operation.LIST),
("https://example.com/random", Operation.LIST),
],
)
def test_operation_hint(url: str, expected: Operation) -> None:
assert ats_jobs._operation_hint(url) is expected
def test_discovery_candidate_selection_rejects_invalid_and_ambiguous() -> None:
invalid = ats_jobs.DiscoveryCandidate("https://example.com/nope", DiscoveryMethod.LINK, 70)
valid = ats_jobs.DiscoveryCandidate(
"https://jobs.ashbyhq.com/acme",
DiscoveryMethod.LINK,
70,
Provider.ASHBY,
)
selected = ats_jobs._select_discovery_candidate(
"https://acme.com/careers",
[invalid, valid],
None,
)
assert selected is not None
assert selected[0].provider is Provider.ASHBY
with pytest.raises(AmbiguousMatchError, match="equally plausible"):
ats_jobs._select_discovery_candidate(
"https://acme.com/careers",
[
ats_jobs.DiscoveryCandidate(
"https://job-boards.greenhouse.io/acme",
DiscoveryMethod.LINK,
70,
Provider.GREENHOUSE,
),
ats_jobs.DiscoveryCandidate(
"https://jobs.lever.co/acme",
DiscoveryMethod.LINK,
70,
Provider.LEVER,
),
],
None,
)
def test_slug_candidates_use_domain_and_meaningful_path() -> None:
assert ats_jobs._slug_candidates("https://com") == ()
slugs = ats_jobs._slug_candidates("https://careers.vendor.co.uk/acme-inc/jobs")
assert slugs == ("vendor", "acme-inc", "acmeinc")
@pytest.mark.parametrize(
("provider", "payload"),
[
(Provider.GREENHOUSE, {}),
(Provider.LEVER, {}),
(Provider.ASHBY, []),
(Provider.WORKABLE, []),
],
)
def test_slug_probe_rejects_invalid_provider_shapes(provider: Provider, payload: Any) -> None:
class StubDiscovery:
def request_json(self, *_args: Any, **_kwargs: Any) -> Any:
return payload
assert ats_jobs._probe_slug("acme", provider, StubDiscovery()) is None
def test_slug_probe_swallows_domain_errors_and_ignores_unsupported_provider() -> None:
class FailingDiscovery:
def request_json(self, *_args: Any, **_kwargs: Any) -> Any:
raise TransportError("offline")
discovery = FailingDiscovery()
assert ats_jobs._probe_slug("acme", Provider.GREENHOUSE, discovery) is None
assert ats_jobs._probe_slug("acme", Provider.BAMBOOHR, discovery) is None
def test_resolve_target_finds_native_url_inside_redirect_chain() -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.url.host == "acme.com":
return httpx.Response(
302,
headers={"Location": "https://jobs.lever.co/acme"},
request=request,
)
if request.url.host == "jobs.lever.co":
return httpx.Response(
302,
headers={"Location": "https://careers.acme.com/final"},
request=request,
)
return httpx.Response(200, text="<html></html>", request=request)
resolution = resolve_target(
"https://acme.com/careers",
discovery=mock_discovery(handler),
probe=False,
)
assert resolution.method is DiscoveryMethod.REDIRECT
assert resolution.target.provider is Provider.LEVER
def test_resolve_target_closes_owned_discovery_client(
monkeypatch: pytest.MonkeyPatch,
) -> None:
state = {"closed": False}
class FakeDiscovery:
def __init__(self, **_kwargs: Any) -> None:
pass
def fetch_page(self, url: str) -> ats_jobs.DiscoveryPage:
return ats_jobs.DiscoveryPage(url, "<html></html>", (url,))
def request_json(self, *_args: Any, **_kwargs: Any) -> Any:
raise NotFoundError("no board")
def close(self) -> None:
state["closed"] = True
monkeypatch.setattr(ats_jobs, "DiscoveryClient", FakeDiscovery)
with pytest.raises(InputError, match="could not detect"):
resolve_target("https://acme.com/careers", probe=False)
assert state["closed"] is True
def test_discovery_client_owned_close(monkeypatch: pytest.MonkeyPatch) -> None:
state = {"closed": False}
class FakeClient:
def close(self) -> None:
state["closed"] = True
monkeypatch.setattr(ats_jobs.httpx, "Client", lambda **_kwargs: FakeClient())
client = DiscoveryClient()
client.close()
assert state["closed"] is True
def test_discovery_client_retries_transport_and_retryable_status() -> None:
transport_calls = 0
sleeps: list[float] = []
def transport_handler(request: httpx.Request) -> httpx.Response:
nonlocal transport_calls
transport_calls += 1
if transport_calls == 1:
raise httpx.ConnectError("reset", request=request)
return httpx.Response(200, text="<html></html>", request=request)
page = mock_discovery(transport_handler, retries=2, sleeps=sleeps).fetch_page(
"https://acme.com/careers"
)
assert page.final_url == "https://acme.com/careers"
assert transport_calls == 2
assert sleeps
status_calls = 0
sleeps.clear()
def status_handler(request: httpx.Request) -> httpx.Response:
nonlocal status_calls
status_calls += 1
if status_calls == 1:
return httpx.Response(503, request=request)
return httpx.Response(200, text="ok", request=request)
mock_discovery(status_handler, retries=2, sleeps=sleeps).fetch_page(
"https://acme.com/careers"
)
assert status_calls == 2
assert sleeps
def test_discovery_client_transport_failure_after_budget() -> None:
def handler(request: httpx.Request) -> httpx.Response:
raise httpx.ReadTimeout("slow", request=request)
with pytest.raises(TransportError, match="after 2 attempts"):
mock_discovery(handler, retries=2).fetch_page("https://acme.com/careers")
@pytest.mark.parametrize(
("status", "error"),
[
(401, PermissionError),
(403, PermissionError),
(404, NotFoundError),
(429, RateLimitError),
(500, TransportError),
],
)
def test_discovery_client_status_mapping(status: int, error: type[ATSJobsError]) -> None:
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(status, request=request)
with pytest.raises(error):
mock_discovery(handler).fetch_page("https://acme.com/careers")
def test_discovery_client_redirect_guards_and_host_allowlist(
monkeypatch: pytest.MonkeyPatch,
) -> None:
def missing_location(request: httpx.Request) -> httpx.Response:
return httpx.Response(302, request=request)
with pytest.raises(TransportError, match="Location"):
mock_discovery(missing_location).fetch_page("https://acme.com/careers")
monkeypatch.setattr(ats_jobs, "MAX_REDIRECTS", 1)
def endless(request: httpx.Request) -> httpx.Response:
return httpx.Response(302, headers={"Location": "/again"}, request=request)
with pytest.raises(TransportError, match="exceeds"):
mock_discovery(endless).fetch_page("https://acme.com/careers")
client = mock_discovery(lambda request: httpx.Response(200, json={}, request=request))
with pytest.raises(TransportError, match="unexpected discovery destination"):
client.request_json(
"https://api.lever.co/v0/postings/acme",
allowed_hosts=("api.ashbyhq.com",),
)
def test_discovery_client_response_size_and_invalid_json(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(ats_jobs, "MAX_DISCOVERY_BYTES", 1)
with pytest.raises(TransportError, match="exceeds"):
mock_discovery(
lambda request: httpx.Response(200, content=b"xx", request=request)
).fetch_page("https://acme.com/careers")
monkeypatch.setattr(ats_jobs, "MAX_DISCOVERY_BYTES", 1024)
with pytest.raises(InvalidJSONError):
mock_discovery(
lambda request: httpx.Response(200, text="not-json", request=request)
).request_json(
"https://api.lever.co/v0/postings/acme",
allowed_hosts=("api.lever.co",),
)
def test_global_ip_is_allowed_for_discovery_validation() -> None:
assert ats_jobs._validate_public_discovery_url("https://8.8.8.8/jobs") == (
"https://8.8.8.8/jobs"
)
def test_adapter_missing_target_identifiers() -> None:
options = FetchOptions()
http = mock_http(lambda request: json_response(request, {}))
targets = [
(
LeverAdapter(),
Target(
provider=Provider.LEVER,
original_url="https://jobs.lever.co/x",
origin="https://api.lever.co",
operation=Operation.LIST,
),
),
(
AshbyAdapter(),
Target(
provider=Provider.ASHBY,
original_url="https://jobs.ashbyhq.com/x",
origin="https://api.ashbyhq.com",
operation=Operation.LIST,
),
),
(
WorkableAdapter(),
Target(
provider=Provider.WORKABLE,
original_url="https://apply.workable.com/x",
origin="https://www.workable.com",
operation=Operation.LIST,
),
),
(
WorkdayAdapter(),
Target(
provider=Provider.WORKDAY,
original_url="https://x.wd1.myworkdayjobs.com",
origin="https://x.wd1.myworkdayjobs.com",
operation=Operation.LIST,
),
),
]
for adapter, target in targets:
with pytest.raises(InputError):
adapter.list_jobs(target, http, options)
def test_workday_pagination_safety_limit(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(ats_jobs, "MAX_PAGES", 1)
def handler(request: httpx.Request) -> httpx.Response:
return json_response(
request,
{"total": 2, "jobPostings": [WORKDAY_LIST_JOB]},
)
target = parse_target("https://acme.wd5.myworkdayjobs.com/External")
with pytest.raises(PaginationError, match="safety limit"):
WorkdayAdapter().list_jobs(target, mock_http(handler), FetchOptions())
def test_fetch_target_rejects_get_without_posting_reference() -> None:
target = parse_target("https://jobs.ashbyhq.com/acme")
with pytest.raises(InputError, match="board but not an individual"):
ats_jobs._fetch_target(target, operation=Operation.GET)
def test_pretty_helpers_cover_compensation_workplace_and_lists() -> None:
assert ats_jobs._normalized_mapping(normalized_job())["title"] == "Engineer"
assert ats_jobs._normalized_mapping({"title": "X", "job_url": "https://x.com"})["title"] == "X"
with pytest.raises(InputError):
ats_jobs._normalized_mapping({"title": "missing url"})
assert ats_jobs._pretty_date("not-a-date") == "not-a-date"
assert ats_jobs._pretty_date("2026-01-02T00:00:00Z") == "Jan 2, 2026"
assert ats_jobs._compensation_summary({"source": None}) is None
assert ats_jobs._compensation_summary({"source": {"salary": "$200K"}}) == "$200K"
assert ats_jobs._compensation_summary(
{"source": {"salaryRange": {"min": 100000, "max": 150000, "currency": "USD"}}}
) == "USD 100,000 – 150,000"
assert ats_jobs._compensation_summary(
{"source": {"salaryRange": {"minValue": 100000}}}
) == "100,000 – ?"
assert ats_jobs._workplace_summary({"remote": True}) == "Remote"
assert ats_jobs._workplace_summary(
{"remote": None, "source": {"workplace_type": "Hybrid"}}
) == "Hybrid"
assert ats_jobs._workplace_summary({"remote": False, "source": {}}) == "On-site"
assert ats_jobs._workplace_summary({"remote": None}) == ""
no_description = ats_jobs._description_renderable(None)
assert "No description" in no_description.plain
description = ats_jobs._description_renderable("Intro\n\nABOUT YOU\n- Build things")
assert "About you" in description.plain
assert "• Build things" in description.plain
rendered = render_pretty(
[
normalized_job(title="One", published_at="bad-date"),
normalized_job(
id="2",
title="Two",
provider=Provider.ASHBY,
job_url="https://example.com/job/2",
published_at="2026-01-02",
),
]
)
assert "2 public postings" in rendered
assert "One" in rendered and "Two" in rendered
def test_pretty_job_without_urls_and_description() -> None:
rendered = ats_jobs.render_pretty(
{
"provider": "ashby",
"id": "x",
"title": "Untethered",
"job_url": "",
"apply_url": "",
"description_text": None,
"source": {},
}
)
assert "Untethered" in rendered
assert "No description" in rendered
def test_emit_output_uses_pager(monkeypatch: pytest.MonkeyPatch) -> None:
events: list[str] = []
class FakeConsole:
def __init__(self, **_kwargs: Any) -> None:
pass
def pager(self, *, styles: bool):
@ats_jobs.contextmanager
def active():
events.append(f"pager:{styles}")
yield
return active()
def print(self, _renderable: Any) -> None:
events.append("print")
monkeypatch.setattr(ats_jobs, "Console", FakeConsole)
emit_output(normalized_job(), OutputFormat.PRETTY, pager=True, no_color=True)
assert events == ["pager:False", "print"]
def test_write_output_error_before_temporary_file_exists(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
def fail(*_args: Any, **_kwargs: Any) -> Any:
raise OSError("cannot create")
monkeypatch.setattr(ats_jobs.tempfile, "NamedTemporaryFile", fail)
with pytest.raises(TransportError, match="could not write"):
write_output("x", tmp_path / "out")
def test_resolve_custom_workday_cxs_and_path_slug_probe() -> None:
def workday_handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
text='<script>fetch("/wday/cxs/acme/External/jobs")</script>',
request=request,
)
workday = resolve_target(
"https://careers.acme.com/jobs",
Provider.WORKDAY,
discovery=mock_discovery(workday_handler),
probe=False,
)
assert workday.target.provider is Provider.WORKDAY
assert workday.target.origin == "https://careers.acme.com"
assert workday.target.tenant == "acme"
assert workday.target.site == "External"
def slug_handler(request: httpx.Request) -> httpx.Response:
if request.url.host == "careers.vendor.com":
return httpx.Response(200, text="<html></html>", request=request)
if request.url.host == "api.ashbyhq.com" and request.url.path.endswith("/acme-inc"):
return json_response(request, {"apiVersion": "1", "jobs": []})
return httpx.Response(404, request=request)
ashby = resolve_target(
"https://careers.vendor.com/acme-inc/jobs",
Provider.ASHBY,
discovery=mock_discovery(slug_handler),
)
assert ashby.method is DiscoveryMethod.SLUG_PROBE
assert ashby.target.board == "acme-inc"
def test_workplace_pretty_name_normalization() -> None:
assert ats_jobs._workplace_summary(
{"remote": False, "source": {"workplaceType": "OnSite"}}
) == "On-site"
def test_custom_greenhouse_gh_jid_is_carried_onto_discovered_board() -> None:
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
text='<div data-greenhouse-board="acme"></div>',
request=request,
)
resolution = resolve_target(
"https://careers.acme.com/jobs?gh_jid=12345",
discovery=mock_discovery(handler),
probe=False,
)
assert resolution.target.provider is Provider.GREENHOUSE
assert resolution.target.operation is Operation.GET
assert resolution.target.board == "acme"
assert resolution.target.job_id == "12345"
def test_cli_rejects_output_conflicts_before_discovery(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
monkeypatch.setattr(
ats_jobs,
"resolve_target",
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("networked")),
)
result = runner.invoke(
app,
[
"get",
"https://jobs.ashbyhq.com/acme/job-1",
"--raw",
"--pretty",
],
)
assert result.exit_code == ExitCode.INPUT
assert "networked" not in result.stderr
result = runner.invoke(
app,
[
"get",
"https://jobs.ashbyhq.com/acme/job-1",
"--pretty",
"--pager",
"--output",
str(tmp_path / "job.txt"),
],
)
assert result.exit_code == ExitCode.INPUT
assert "terminal paging or file output" in result.stderr
def test_discovery_scans_protocol_relative_and_unicode_escaped_urls() -> None:
page = ats_jobs.DiscoveryPage(
final_url="https://careers.acme.com/jobs",
visited_urls=("https://careers.acme.com/jobs",),
text=(
'<script>const a="//jobs.lever.co/acme"; '
'const b="https:\\u002F\\u002Fjobs.ashbyhq.com\\u002Facme"; '
'fetch("\\/wday\\/cxs\\/acme\\/External\\/jobs");</script>'
),
)
candidates = ats_jobs._extract_discovery_candidates(page)
urls = {candidate.url for candidate in candidates}
assert "https://jobs.lever.co/acme" in urls
assert "https://jobs.ashbyhq.com/acme" in urls
assert "https://careers.acme.com/wday/cxs/acme/External/jobs" in urls
def test_cli_detect_inspect_verbose_and_quiet_validation() -> None:
detected = runner.invoke(
app,
["detect", "https://jobs.ashbyhq.com/acme", "-v"],
)
assert detected.exit_code == 0
assert detected.stdout.strip() == "ashby"
assert "Resolved ashby via direct-host" in detected.stderr
inspected = runner.invoke(
app,
["inspect", "https://jobs.lever.co/acme", "-v"],
)
assert inspected.exit_code == 0
assert json.loads(inspected.stdout)["target"]["provider"] == "lever"
assert "Resolved lever via direct-host" in inspected.stderr
conflict = runner.invoke(
app,
["detect", "https://jobs.lever.co/acme", "-q", "-v"],
)
assert conflict.exit_code == ExitCode.INPUT
assert "not both" in conflict.stderr
"""Run the complete local release gate for the ats-jobs Gist."""
from __future__ import annotations
import argparse
import subprocess
import sys
import tomllib
from dataclasses import dataclass
from pathlib import Path
ROOT = Path(__file__).resolve().parent
@dataclass(frozen=True, slots=True)
class Gate:
"""One release-gate command."""
name: str
command: tuple[str, ...]
def read_inline_script_metadata(path: Path) -> dict[str, object]:
"""Parse the PEP 723 TOML block from a Python script."""
lines = path.read_text(encoding="utf-8").splitlines()
try:
start = lines.index("# /// script") + 1
end = lines.index("# ///", start)
except ValueError as exc:
msg = f"{path.name}: missing PEP 723 script metadata"
raise RuntimeError(msg) from exc
body = "\n".join(line.removeprefix("# ") for line in lines[start:end])
parsed = tomllib.loads(body)
return parsed
def read_project_metadata(path: Path) -> dict[str, object]:
"""Read pyproject.toml."""
with path.open("rb") as handle:
return tomllib.load(handle)
def normalize_dependencies(values: object) -> tuple[str, ...]:
"""Normalize a dependency collection for exact parity checks."""
if not isinstance(values, list) or not all(isinstance(item, str) for item in values):
msg = "dependencies must be a list of strings"
raise RuntimeError(msg)
return tuple(sorted(values))
def verify_metadata() -> None:
"""Check duplicated package/script metadata that must stay synchronized."""
script = read_inline_script_metadata(ROOT / "ats_jobs.py")
pyproject = read_project_metadata(ROOT / "pyproject.toml")
project = pyproject.get("project")
if not isinstance(project, dict):
msg = "pyproject.toml is missing [project]"
raise RuntimeError(msg)
script_dependencies = normalize_dependencies(script.get("dependencies"))
project_dependencies = normalize_dependencies(project.get("dependencies"))
if script_dependencies != project_dependencies:
msg = "PEP 723 and pyproject.toml runtime dependencies differ"
raise RuntimeError(msg)
script_python = script.get("requires-python")
project_python = project.get("requires-python")
if script_python != project_python:
msg = "PEP 723 and pyproject.toml Python requirements differ"
raise RuntimeError(msg)
script_tool = script.get("tool")
project_tool = pyproject.get("tool")
if not isinstance(script_tool, dict) or not isinstance(project_tool, dict):
msg = "PEP 723 and pyproject.toml must both define [tool.uv]"
raise RuntimeError(msg)
script_uv = script_tool.get("uv")
project_uv = project_tool.get("uv")
if not isinstance(script_uv, dict) or not isinstance(project_uv, dict):
msg = "PEP 723 and pyproject.toml must both define [tool.uv]"
raise RuntimeError(msg)
if script_uv.get("exclude-newer") != project_uv.get("exclude-newer"):
msg = "PEP 723 and pyproject.toml exclude-newer values differ"
raise RuntimeError(msg)
version = project.get("version")
source = (ROOT / "ats_jobs.py").read_text(encoding="utf-8")
if not isinstance(version, str) or f'__version__ = "{version}"' not in source:
msg = "pyproject.toml and ats_jobs.py versions differ"
raise RuntimeError(msg)
def run_gate(gate: Gate) -> None:
"""Run one command, stopping at the first failure."""
print(f"\n==> {gate.name}\n$ {' '.join(gate.command)}", flush=True)
completed = subprocess.run(gate.command, cwd=ROOT, check=False)
if completed.returncode:
raise SystemExit(completed.returncode)
def gates() -> tuple[Gate, ...]:
"""Return the canonical python-conventions completion sequence."""
return (
Gate("Ruff lint", ("uv", "run", "ruff", "check")),
Gate("Ruff format", ("uv", "run", "ruff", "format", "--check")),
Gate("ty", ("uv", "run", "ty", "check")),
Gate("pytest and coverage", ("uv", "run", "pytest")),
Gate("Build package", ("uv", "build")),
Gate("Package entry point", ("uvx", "--from", ".", "ats-jobs", "version")),
Gate(
"PEP 723 script entry point",
("uv", "run", "--no-project", "ats_jobs.py", "version"),
),
)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--metadata-only",
action="store_true",
help="Only validate PEP 723, pyproject.toml, and version parity.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute metadata checks and, unless disabled, every release gate."""
args = parse_args(argv)
try:
verify_metadata()
except RuntimeError as exc:
print(f"metadata check failed: {exc}", file=sys.stderr)
return 1
print("metadata parity: PASS")
if args.metadata_only:
return 0
for gate in gates():
run_gate(gate)
print("\nall release gates: PASS")
return 0
if __name__ == "__main__":
raise SystemExit(main())
MIT License
Copyright (c) 2026 Wyatt Walsh
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment