From aba821da8bbe5533a1dbebc1704ca79f155a929a Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Wed, 18 Nov 2026 21:23:20 -0700 Subject: [PATCH] fix: keep usage reporting off once it is turned off FISHE_USAGE_REPORTING_ENABLED was off only for 0/false/no/off: an empty value or any other value (a typo, "disabled") left reporting on. Once set, it is now read through the trace client's allows_reporting and fails closed: only true/on/yes/1 keeps reporting on. Unset still means on. Re-vendors trace-client-python 0.5.0, whose TRACE_USAGE_REPORTING / DO_NOT_TRACK checks fail closed too; the vendored tests are updated to the new rules. Docs updated. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 ++- src/config/config.py | 30 +++---- src/trace_client.py | 163 ++++++++++++++++++++++++++++-------- src/usageReporting.py | 2 +- tests/config/test_config.py | 15 ++-- tests/test_trace_client.py | 41 +++++++-- 6 files changed, 198 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index 718a346..7db8590 100644 --- a/README.md +++ b/README.md @@ -194,20 +194,22 @@ To turn it off, set any of these in the environment the game runs in: - `TRACE_USAGE_REPORTING=off` (also `false`, `0`, `no`) — turns off every program that reports to trace - `DO_NOT_TRACK=1` (also `true`, `yes`) — the [console DNT convention](https://consoledonottrack.com), honoured the same way +Every switch fails closed, so an opt-out is never read as "on": `FISHE_USAGE_REPORTING_ENABLED`, once set, keeps reporting on only for `true`, `on`, `yes` or `1` (any case) and turns it off for anything else, an empty value or a typo included; `TRACE_USAGE_REPORTING` set to anything but blank or one of those values turns it off; `DO_NOT_TRACK` set to anything but blank, `0`, `false`, `off` or `no` turns it off. + ```bash FISHE_USAGE_REPORTING_ENABLED=false python3 src/fishE.py ``` | Variable | Default | What it does | |---|---|---| -| `FISHE_USAGE_REPORTING_ENABLED` | `true` | `false`, `0`, `no` or `off` turns reporting off. | +| `FISHE_USAGE_REPORTING_ENABLED` | `true` | `false`, `0`, `no` or `off` turns reporting off — so does any value but `true`, `on`, `yes` or `1`, empty included. | | `FISHE_USAGE_REPORTING_ENDPOINT` | `https://trace.danielstephenson.dev` | Where events are sent — a self-hosted trace, or a local stub. | | `FISHE_USAGE_REPORTING_KEY` | the key issued to FishE | The program key sent with each event. | -| `TRACE_USAGE_REPORTING` | unset | `off`, `false`, `0` or `no` turns reporting off, for FishE and every other trace client. | -| `DO_NOT_TRACK` | unset | `1`, `true` or `yes` turns reporting off the same way. | +| `TRACE_USAGE_REPORTING` | unset | `off`, `false`, `0` or `no` (any value but blank, `true`, `on`, `yes` or `1`) turns reporting off, for FishE and every other trace client. | +| `DO_NOT_TRACK` | unset | `1`, `true` or `yes` (any value but blank, `0`, `false`, `off` or `no`) turns reporting off the same way. | | `TRACE_INSTALL_ID` | unset | Sent as the installation ID instead of the one in `trace-install-id`, which is then left alone — to pin one for a container or service. | -The test suite switches reporting off for every test (`tests/conftest.py`), and the tests that exercise it point at a loopback stub server, so running the tests never reports anything either. The client is `src/trace_client.py`, vendored as one standard-library file from [trace-client-python](https://github.com/Stephenson-Software/trace-client-python) (0.4.1); the wiring is `src/usageReporting.py`. +The test suite switches reporting off for every test (`tests/conftest.py`), and the tests that exercise it point at a loopback stub server, so running the tests never reports anything either. The client is `src/trace_client.py`, vendored as one standard-library file from [trace-client-python](https://github.com/Stephenson-Software/trace-client-python) (0.5.0); the wiring is `src/usageReporting.py`. Details: https://danielstephenson.dev/usage-reporting diff --git a/src/config/config.py b/src/config/config.py index e73724e..0d7b5dc 100644 --- a/src/config/config.py +++ b/src/config/config.py @@ -1,5 +1,7 @@ import os +from trace_client import allows_reporting + # Usage reporting (see src/usageReporting.py). The key is the program key the # trace service issued to FishE; it identifies the program, not the player, # and is bundled so an install that never sets FISHE_USAGE_REPORTING_KEY still @@ -7,18 +9,17 @@ USAGE_REPORTING_ENDPOINT_DEFAULT = "https://trace.danielstephenson.dev" USAGE_REPORTING_KEY_DEFAULT = "_zbWO4qi0bhg9RoKxYXCCy93D36R5dF0Sa5xCiR180E" -# Values that switch a FISHE_* boolean off. Anything else - including unset -# and empty - leaves the default in place, matching FISHE_SAVE_DIR above. -_FALSE_VALUES = ("0", "false", "no", "off") - -def _environmentFlag(name, default): - """Read a boolean FISHE_* variable, falling back to default when it is - unset or empty so a compose file with `NAME=` doesn't flip the switch.""" - value = os.environ.get(name, "").strip().lower() - if not value: - return default - return value not in _FALSE_VALUES +def _usageReportingEnabled(name): + """Read FishE's own usage-reporting switch. Unset means the default, on. + Once set, it fails closed: it is read through the trace client's + allows_reporting, so only true, on, yes or 1 (any case) keeps reporting + on, and anything else - false, off, no, 0, empty, a typo - turns it off. + An opt-out is never read as on.""" + value = os.environ.get(name) + if value is None: + return True + return allows_reporting(value) # @author Daniel McCoy Stephenson @@ -41,11 +42,12 @@ def __init__(self): # Usage reporting: one startup event (and one when a save is opened) # to the trace service, program name and version only. On by default; - # FISHE_USAGE_REPORTING_ENABLED=false is the opt-out. The endpoint and + # FISHE_USAGE_REPORTING_ENABLED=false is the opt-out, and anything but + # true/on/yes/1 counts as one (see _usageReportingEnabled). The endpoint and # key overrides exist so a self-hosted trace can be pointed at, and so # tests can aim the client at a loopback stub instead of production. - self.usageReportingEnabled = _environmentFlag( - "FISHE_USAGE_REPORTING_ENABLED", True + self.usageReportingEnabled = _usageReportingEnabled( + "FISHE_USAGE_REPORTING_ENABLED" ) self.usageReportingEndpoint = ( os.environ.get("FISHE_USAGE_REPORTING_ENDPOINT", "").strip() diff --git a/src/trace_client.py b/src/trace_client.py index 4ea4431..18c77d5 100644 --- a/src/trace_client.py +++ b/src/trace_client.py @@ -1,4 +1,4 @@ -"""trace-client 0.4.1 -- https://github.com/Stephenson-Software/trace-client-python +"""trace-client 0.5.0 -- https://github.com/Stephenson-Software/trace-client-python One call to report that a program was used. Copy this file into a project as is, or vendor the package; either way there is nothing else to add. Standard @@ -10,8 +10,10 @@ """ from __future__ import annotations +import decimal import json import logging +import numbers import os import queue import re @@ -21,27 +23,31 @@ import uuid from typing import Dict, Mapping, Optional, Union -__version__ = "0.4.1" +__version__ = "0.5.0" _LOG = logging.getLogger("trace") #: Environment variables that turn reporting off for every program using a -#: trace client, checked before the program's own setting. Set -#: ``TRACE_USAGE_REPORTING=off`` (also ``false``, ``0``, ``no``; case does not -#: matter) or ``DO_NOT_TRACK=1`` (also ``true``, ``yes``; see -#: https://consoledonottrack.com). +#: trace client, checked before the program's own setting. Both fail closed: +#: ``TRACE_USAGE_REPORTING`` set to anything but blank, ``true``, ``on``, +#: ``yes`` or ``1`` turns reporting off (so ``off``, ``false``, ``0``, ``no``, +#: ``disabled``, a typo, ...), and so does ``DO_NOT_TRACK`` set to anything +#: but blank, ``0``, ``false``, ``off`` or ``no`` (so ``1``, ``true``, +#: ``yes``, ...; see https://consoledonottrack.com). Case and surrounding +#: space do not matter. ENV_TRACE_USAGE_REPORTING = "TRACE_USAGE_REPORTING" ENV_DO_NOT_TRACK = "DO_NOT_TRACK" -_OFF_VALUES = frozenset(("off", "false", "0", "no")) -_DO_NOT_TRACK_VALUES = frozenset(("1", "true", "yes")) +_ON_VALUES = frozenset(("true", "on", "yes", "1")) +_NEGATIVE_VALUES = frozenset(("false", "off", "no", "0")) #: The values :attr:`TraceClient.disabled_reason` can take. First match wins. REASON_ENVIRONMENT = "environment" REASON_CONFIG = "config" REASON_NO_KEY = "no key" -#: The longest a program version may be, after trimming: the trace server's -#: limit on a tag value. +#: The longest a tag value the client sets itself -- the program version, the +#: installation ID -- may be, after trimming: the trace server's limit on a +#: tag value. MAX_TAG_LENGTH = 255 #: The most tags one event carries: the trace server's limit. The ``install`` @@ -54,18 +60,58 @@ # What install_id_from_file accepts as an ID on a line of its file. _INSTALL_ID_LINE = re.compile(r"^[A-Za-z0-9_.-]{1,%d}$" % MAX_TAG_LENGTH) +# What the User-Agent header cannot carry: everything but printable Latin-1. +_NOT_IN_A_HEADER = re.compile(r"[^\x20-\x7e\xa0-\xff]") + + +class _RedirectsNotFollowed(urllib.request.HTTPRedirectHandler): + """Declines every redirect, so the redirect itself is the answer. Following + one would re-send the key to whatever host ``Location`` names, and a 301, + 302 or 303 would turn the POST into an empty GET that loses the event + anyway. trace-client-java does not follow redirects either.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +# Every report goes through this opener rather than urlopen: urlopen follows +# redirects, and install_opener would change the host program's urlopen too. +_OPENER = urllib.request.build_opener(_RedirectsNotFollowed) + def environment_opts_out(environ: Optional[Mapping[str, str]] = None) -> bool: - """Whether the environment asks for usage reporting to be off, via - ``TRACE_USAGE_REPORTING=off`` or ``DO_NOT_TRACK=1``. Only the listed - values count; anything else (including an empty value) leaves the - program's own setting in charge.""" - env = os.environ if environ is None else environ - if env.get(ENV_TRACE_USAGE_REPORTING, "").strip().lower() in _OFF_VALUES: + """Whether the environment asks for usage reporting to be off. Fails + closed: ``TRACE_USAGE_REPORTING`` set to anything but blank or a clear + "on" (``true``, ``on``, ``yes``, ``1``), or ``DO_NOT_TRACK`` set to + anything but blank or a clear "no" (``0``, ``false``, ``off``, ``no``), + opts out; case and surrounding space do not matter. An environment that + cannot be read -- or a value that is not a string -- opts out too: it may + hold ``DO_NOT_TRACK=1``. Never raises.""" + try: + env = os.environ if environ is None else environ + usage_reporting = (env.get(ENV_TRACE_USAGE_REPORTING) or "").strip().lower() + if usage_reporting and usage_reporting not in _ON_VALUES: + return True + do_not_track = (env.get(ENV_DO_NOT_TRACK) or "").strip().lower() + return bool(do_not_track) and do_not_track not in _NEGATIVE_VALUES + except Exception: # noqa: BLE001 - an environment that cannot be read counts as opting out return True - if env.get(ENV_DO_NOT_TRACK, "").strip().lower() in _DO_NOT_TRACK_VALUES: - return True - return False + + +def allows_reporting(setting: object) -> bool: + """Whether a program's own reporting setting, as read from its + configuration, allows reporting -- for ``enabled=``. Fails closed: only + ``True``, or a string reading ``true``, ``on``, ``yes`` or ``1`` (any + case, surrounding space ignored), allows it. Anything else turns + reporting off: ``False``, ``"false"``, ``"off"``, ``"no"``, a typo, a + number, ``None`` (a missing setting), a quoted ``'"false"'``. + + Pass the raw value, e.g. ``settings.get("usage_reporting")``, rather than + ``bool(...)`` of it: ``bool("false")`` is ``True``. The constructor reads + ``enabled=`` through this function too, so ``enabled="false"`` is off.""" + if isinstance(setting, bool): + return setting + return isinstance(setting, str) and setting.strip().lower() in _ON_VALUES class TraceClient: @@ -89,7 +135,10 @@ class TraceClient: does nothing and costs nothing. So does the environment: the constructor checks ``TRACE_USAGE_REPORTING=off`` and ``DO_NOT_TRACK=1`` before it looks at ``enabled``, so a user can switch off every trace-reporting - program at once. :attr:`disabled_reason` says which of those applied + program at once. Every switch fails closed: a value that does not clearly + mean "on" turns reporting off (see :func:`environment_opts_out` and + :func:`allows_reporting`), and nothing in this client turns a switch + back on. :attr:`disabled_reason` says which of those applied (``"environment"``, ``"config"`` or ``"no key"``; ``None`` when on) so the program can say so in its notice. Programs that run on other people's machines should expose that switch in their settings and say @@ -113,7 +162,8 @@ class TraceClient: :: trace = TraceClient("https://trace.example.org", "roam", __version__, - key=settings.usage_key, enabled=settings.usage_reporting) + key=settings.usage_key, + enabled=allows_reporting(settings.usage_reporting)) trace.report("startup") ... trace.close() # on shutdown @@ -123,7 +173,7 @@ class TraceClient: TIMEOUT_SECONDS = 5.0 def __init__(self, base_url: str, application: str, version: str, *, key: Optional[str] = None, - enabled: bool = True, install_id: Optional[str] = None, + enabled: Union[bool, str, None] = True, install_id: Optional[str] = None, install_id_file: Optional[Union[str, "os.PathLike[str]"]] = None) -> None: """A client for the program named ``application``, at ``version``, reporting to the trace server at ``base_url``. The version is sent as @@ -137,7 +187,18 @@ def __init__(self, base_url: str, application: str, version: str, *, key: Option longer than :data:`MAX_TAG_LENGTH` characters is a :class:`ValueError`. ``install_id_file`` is a path to load it from (or create it in) with :meth:`install_id_from_file`, only when the - client is enabled; an explicit ``install_id`` wins over it.""" + client is enabled; an explicit ``install_id`` wins over it. + + A value that is not a string for ``base_url``, ``application``, + ``version``, ``key`` or ``install_id`` is a :class:`ValueError` naming + the argument, even on a client that would be disabled: a settings + file that reads ``version: 1.4`` as a number should say so. An empty + one (``0``, ``False``, ``[]``) still means no value, as it did before + that check: no key, no ID, or " is required".""" + for argument, given in (("base_url", base_url), ("application", application), ("version", version), + ("key", key), ("install_id", install_id)): + if given and not isinstance(given, str): + raise ValueError("%s must be a string, not %s" % (argument, type(given).__name__)) if not base_url or not base_url.strip(): raise ValueError("base_url is required") if not application or not application.strip(): @@ -157,12 +218,13 @@ def __init__(self, base_url: str, application: str, version: str, *, key: Option self._thread: Optional[threading.Thread] = None #: Why this client reports nothing: ``"environment"`` (the #: ``TRACE_USAGE_REPORTING`` / ``DO_NOT_TRACK`` variables), - #: ``"config"`` (``enabled=False``) or ``"no key"``; ``None`` when it + #: ``"config"`` (``enabled`` not ``True`` or an "on" string -- see + #: :func:`allows_reporting`) or ``"no key"``; ``None`` when it #: reports. Decided once, here, in that order of precedence. self.disabled_reason: Optional[str] = None if environment_opts_out(): self.disabled_reason = REASON_ENVIRONMENT - elif not enabled: + elif not allows_reporting(enabled): self.disabled_reason = REASON_CONFIG elif not self._key: self.disabled_reason = REASON_NO_KEY @@ -245,7 +307,10 @@ def enabled(self) -> bool: def report(self, name: str, value: Optional[float] = None, tags: Optional[Mapping[str, str]] = None) -> None: """Report that ``name`` happened, with an optional numeric value and - optional string tags. Returns immediately; see the class docstring.""" + optional string tags. Returns immediately; see the class docstring. + A blank ``name`` sends nothing. A ``value`` that is NaN, infinite or + not a real number (a string, a bool), and any tag whose key or value + is ``None``, is left out of the event; the event is still sent.""" if self._queue is None: return try: @@ -265,8 +330,13 @@ def close(self, timeout: float = TIMEOUT_SECONDS) -> None: and then exits within milliseconds -- a CLI, a short script -- would otherwise lose its one event to the race between queueing it and the sender thread picking it up. The bound still holds: an unreachable - server costs at most ``timeout``, never a hang. Safe to call more than - once, and on a disabled client.""" + server costs at most ``timeout``, never a hang. Reports still queued + when ``timeout`` runs out are not discarded: the daemon thread keeps + sending them after ``close()`` returns, then stops, and whatever it + has not sent when the program exits is lost. On a full queue the + oldest queued report is dropped (logged at DEBUG) to make room for + the signal that stops the thread. Safe to call more than once, and + on a disabled client.""" if self._queue is None or self._thread is None: return q, thread = self._queue, self._thread @@ -278,7 +348,8 @@ def close(self, timeout: float = TIMEOUT_SECONDS) -> None: # the 257th. Drop the oldest to make room -- one lost report beats a # thread that never stops. try: - q.get_nowait() + dropped = q.get_nowait() + _LOG.debug("[trace] queue full at close, dropped %s", dropped) q.put_nowait(None) except (queue.Empty, queue.Full): pass @@ -307,9 +378,9 @@ def _send(self, body: bytes) -> None: headers={ "Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + self._key, - "User-Agent": "trace-client-python/%s (%s)" % (__version__, self._application), + "User-Agent": _user_agent(self._application), }) - with urllib.request.urlopen(request, timeout=self.TIMEOUT_SECONDS) as response: + with _OPENER.open(request, timeout=self.TIMEOUT_SECONDS) as response: status = response.status response.read() except urllib.error.HTTPError as answered: @@ -325,6 +396,14 @@ def _send(self, body: bytes) -> None: _LOG.debug("[trace] trace server answered %s for %s", status, body) +def _user_agent(application: str) -> str: + """The ``User-Agent`` for ``application``. A header carries printable + Latin-1 and nothing else, and one it cannot carry stops the request, so + any other character becomes ``?`` here. The event itself keeps the exact + name: what a program is called must not cost it every report.""" + return "trace-client-python/%s (%s)" % (__version__, _NOT_IN_A_HEADER.sub("?", application)) + + def _with_version(tags: Optional[Mapping[str, str]], version: str) -> Dict[str, str]: """The event's own tags plus ``version``, unless the event already carries one. A copy; the caller's mapping is never modified.""" @@ -348,10 +427,28 @@ def _with_install(tags: Dict[str, str], install_id: Optional[str]) -> Dict[str, return merged +def _number(value: object) -> Optional[float]: + """``value`` as a number JSON can carry, or ``None`` for one it cannot: + anything that is not a real number (a string, a bool), NaN and infinity. + A ``Decimal`` or ``Fraction`` becomes a float rather than costing the + event its place: ``json.dumps`` would refuse it, and the event with it.""" + if isinstance(value, bool) or not isinstance(value, (numbers.Real, decimal.Decimal)): + return None + if type(value) not in (int, float): + try: + value = float(value) + except (OverflowError, ValueError): + return None + if value != value or value in (float("inf"), float("-inf")): + return None + return value # type: ignore[return-value] + + def _json(application: str, name: str, value: Optional[float], tags: Optional[Mapping[str, str]]) -> bytes: payload: Dict[str, object] = {"application": application, "name": name} - if value is not None and value == value and value not in (float("inf"), float("-inf")): - payload["value"] = value + number = _number(value) + if number is not None: + payload["value"] = number if tags: clean = {str(k): str(v) for k, v in tags.items() if k is not None and v is not None} if clean: diff --git a/src/usageReporting.py b/src/usageReporting.py index bfa8663..23f821e 100644 --- a/src/usageReporting.py +++ b/src/usageReporting.py @@ -13,7 +13,7 @@ Reporting is on by default and switched off with ``FISHE_USAGE_REPORTING_ENABLED=false`` in the environment (see -config.Config), or with the two variables every trace client honours, +config.Config; once set, anything but true/on/yes/1 is off), or with the two variables every trace client honours, ``TRACE_USAGE_REPORTING=off`` and ``DO_NOT_TRACK=1``. Those two are checked by the client itself, in its constructor, before FishE's own setting - so they win even when the setting says on. The first time an install reports, one diff --git a/tests/config/test_config.py b/tests/config/test_config.py index 7f371eb..1c22619 100644 --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -66,17 +66,20 @@ def test_usage_reporting_is_on_by_default_and_aimed_at_the_trace_service( assert config.usageReportingKey == config.usageReportingKey.strip() -@pytest.mark.parametrize("value", ["false", "FALSE", "0", "no", "off", " False "]) -def test_usage_reporting_can_be_switched_off(monkeypatch, value): +@pytest.mark.parametrize( + "value", + ["false", "FALSE", "0", "no", "off", " False ", "", " ", "disabled", "anything", '"false"'], +) +def test_usage_reporting_fails_closed(monkeypatch, value): + # Once set, only a clear "on" keeps reporting on: an opt-out, an empty + # value or a typo is never read as on. monkeypatch.setenv("FISHE_USAGE_REPORTING_ENABLED", value) assert createConfig().usageReportingEnabled is False -@pytest.mark.parametrize("value", ["", " ", "true", "1", "yes", "anything"]) -def test_only_a_clear_no_switches_usage_reporting_off(monkeypatch, value): - # An unset-but-present variable (a compose file with - # FISHE_USAGE_REPORTING_ENABLED=) leaves the default on, like FISHE_SAVE_DIR. +@pytest.mark.parametrize("value", ["true", "TRUE", " true ", "1", "yes", "on"]) +def test_only_a_clear_on_keeps_usage_reporting_on(monkeypatch, value): monkeypatch.setenv("FISHE_USAGE_REPORTING_ENABLED", value) assert createConfig().usageReportingEnabled is True diff --git a/tests/test_trace_client.py b/tests/test_trace_client.py index 7763c31..d9e6b27 100644 --- a/tests/test_trace_client.py +++ b/tests/test_trace_client.py @@ -13,7 +13,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest import mock -from trace_client import MAX_TAG_LENGTH, MAX_TAGS, TraceClient, environment_opts_out +from trace_client import MAX_TAG_LENGTH, MAX_TAGS, TraceClient, allows_reporting, environment_opts_out _ENV_VARS = ("TRACE_USAGE_REPORTING", "DO_NOT_TRACK") @@ -175,10 +175,13 @@ def test_DO_NOT_TRACK_disables_reporting_for_every_accepted_value(self): self._assert_environment_disables("DO_NOT_TRACK", value) def test_other_environment_values_leave_the_program_setting_in_charge(self): + # 0.5.0 fails closed: only blank, or a value that clearly means "keep + # reporting", leaves the program's own setting in charge. for variable, value in (("TRACE_USAGE_REPORTING", "on"), ("TRACE_USAGE_REPORTING", ""), - ("TRACE_USAGE_REPORTING", "disabled"), ("TRACE_USAGE_REPORTING", "1"), + ("TRACE_USAGE_REPORTING", "1"), ("TRACE_USAGE_REPORTING", "TRUE"), + ("TRACE_USAGE_REPORTING", "yes"), ("DO_NOT_TRACK", "0"), ("DO_NOT_TRACK", ""), ("DO_NOT_TRACK", "false"), - ("DO_NOT_TRACK", "off")): + ("DO_NOT_TRACK", "off"), ("DO_NOT_TRACK", "no")): with mock.patch.dict(os.environ, {variable: value}): self.assertFalse(environment_opts_out(), "%s=%r is not an opt-out" % (variable, value)) client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") @@ -187,6 +190,34 @@ def test_other_environment_values_leave_the_program_setting_in_charge(self): client.close() self.assertFalse(environment_opts_out(), "an unset variable is not an opt-out") + def test_unclear_environment_values_fail_closed(self): + for variable, value in (("TRACE_USAGE_REPORTING", "disabled"), ("TRACE_USAGE_REPORTING", "nope"), + ("TRACE_USAGE_REPORTING", "of"), ("DO_NOT_TRACK", "anything"), + ("DO_NOT_TRACK", "2")): + self._assert_environment_disables(variable, value) + + def test_an_environment_that_cannot_be_read_opts_out(self): + class Unreadable(dict): + def get(self, *args, **kwargs): + raise RuntimeError("no environment") + self.assertTrue(environment_opts_out(Unreadable())) + + def test_allows_reporting_fails_closed(self): + for setting in (True, "true", "TRUE", " on ", "yes", "1"): + self.assertTrue(allows_reporting(setting), "%r allows reporting" % (setting,)) + for setting in (False, None, "", " ", "false", "off", "no", "0", "disabled", '"false"', 0, 1, [], {}): + self.assertFalse(allows_reporting(setting), "%r must not allow reporting" % (setting,)) + + def test_enabled_is_read_through_allows_reporting(self): + for enabled in ("false", "off", "", None, 1, "disabled"): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled=enabled) + self.assertFalse(client.enabled, "enabled=%r must not enable the client" % (enabled,)) + self.assertEqual("config", client.disabled_reason) + client.close() + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled="yes") + self.assertTrue(client.enabled) + client.close() + def test_environment_wins_over_the_config_flag_and_over_the_key(self): # enabled=True with a key, and the environment still says no. with mock.patch.dict(os.environ, {"TRACE_USAGE_REPORTING": "off"}): @@ -214,12 +245,12 @@ def test_environment_opts_out_accepts_an_explicit_mapping(self): def test_user_agent_names_the_client_version(self): from trace_client import __version__ - self.assertEqual("0.4.1", __version__) + self.assertEqual("0.5.0", __version__) client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") client.report("startup") self.assertTrue(self.capture.arrived.wait(5)) client.close() - self.assertEqual("trace-client-python/0.4.1 (MyGame)", self.capture.requests[0]["user_agent"]) + self.assertEqual("trace-client-python/0.5.0 (MyGame)", self.capture.requests[0]["user_agent"]) def test_report_ignores_a_blank_name(self): client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k")