Introducing The Sweep: OX’s New Live Security Research Series
Register Now
Breaking: The 2026 Vulnpocalypse Hits PHP: Four Critical RCEs, but How Dangerous Are They?
Read the Report
Are you exposed? Connect your apps in minutes.
Scan your apps free

declarative-mocks

Latest version: v0.5.0

Overview

Last scanned
26 Nov 2026
Published
26 Nov 2026
PyPI package Publisher: MDx3R
1 Stars
0 Forks
6 Versions
263 Downloads
Python Repo language

Scan summary

declarative-mocks was last scanned on 26 Nov 2026 at version 0.5.0. Risk score 0 of 100. No malicious behavior was detected.

  • Releases: 6 versions; the latest was published on 26 Nov 2026.
  • Findings: No rules fired in version 0.5.0.
  • Downloads: 263 downloads.

Versions

6 versions published
Versions and the rules that fired in each
VersionPublishedStatus
0.5.0 LATEST 26 Nov 2026 No rules fired
0.4.2 31 Oct 2026 No rules fired
0.4.1 31 Oct 2026 No rules fired
0.4.0 23 Oct 2026 Not shown
0.3.0 18 Oct 2026 Not shown

No rules fired in 0.5.0

Findings

Findings for v0.5.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.

The score describes 0.5.0; other versions have their own rules, not their own score.

README

The publisher’s own README, as collected from the registry.

Checks PyPI Python 3.11+ License: MIT

declarative-mocks

Declare mock behavior as ordered expectations. Write readable and maintainable tests with explicit call patterns, return sequences, and side effects using dmock.

It is fully documented. Public methods and matchers ship with docstring examples, and pretty much everything about API and behavior is described in REFERENCE.md and SPEC.md.

Installation

pip install declarative-mocks

dmock requires Python 3.11+.

Usage

Normally you would set a return value, then check the object field by field and assert the call separately:

from dataclasses import dataclass, field
from datetime import datetime
from unittest.mock import Mock

@dataclass
class User:
    id: int
    name: str
    email: str
    created_at: datetime = field(default_factory=datetime.now)

class Directory:
    def lookup(self, name: str) -> User: ...

service = Mock(spec=Directory)
service.lookup.return_value = User(id=1, name="Ada", email="ada@example.com")

user = service.lookup("ada")
assert user.id == 1
assert user.name == "Ada"
assert user.email == "ada@example.com"
assert abs((datetime.now() - user.created_at).total_seconds()) < 5
name = service.lookup.call_args.args[0]
assert isinstance(name, str)
assert name.startswith("a")

Here's an example of how dmock improves your tests:

from dmock import DeclarativeMock
from dmock.matchers import IsNow, StartsWith

service = DeclarativeMock(Directory)
service.expect(Directory.lookup, StartsWith("a")).returns(
    User(id=1, name="Ada", email="ada@example.com")
)

assert service.lookup("ada") == User(
    id=1,
    name="Ada",
    email="ada@example.com",
    created_at=IsNow(),
)

# verify is automatic with pytest
service.verify()

That's not all! dmock can do so much more than that, for example:

Successive outcomes apply to the next matching call, in order:

from dmock import DeclarativeMock

api = DeclarativeMock(ApiClient)
# Using `ApiClient.next_page` helps a type checker to check
# the `expect` arguments and the values passed to `.returns` and `.runs`
api.expect(ApiClient.next_page).returns({"items": [1], "cursor": "a"})
# or you could use the string form to produce a lenient expectation: any arguments, any outcome
api.expect("next_page").returns({"items": [2], "cursor": None})
# first call → first dict; second call → second dict
# Same args → registration order; different args → matched by args.
# Chain .expect(...) or use in_order(...) to enforce strict order across different calls:
api.expect("next_page", limit=5).returns({"items": []}).once().expect("close").raises(TimeoutError)

calc = DeclarativeMock(Calculator)
calc.expect("price", 100).runs(lambda x: x - 1).returns(99)
assert calc.price(100) == 99  # from the lambda
assert calc.price(100) == 99  # from .returns(99)

expect(...) with no further arguments matches a call with no arguments. A keyword matches only that keyword:

from dmock import DeclarativeMock
from dmock.matchers import Anything

m = DeclarativeMock(Worker)
m.expect("run")  # called with no arguments
m.expect("run", Anything()).returns(0)  # any single positional arg
m.expect("run", job_id=123).returns("queued")  # this is keyword only

ANY_ARGS and ANY_KWARGS match any positional and keyword arguments, including none:

from dmock import DeclarativeMock
from dmock.matchers import ANY_ARGS, ANY_KWARGS

m = DeclarativeMock(Worker)
m.expect("run", ANY_ARGS, ANY_KWARGS).returns(0)  # any positional and keyword args, including none

Only one quantifier per expectation is allowed. The last outcome repeats when the count allows more calls, and verify() checks the counts:

from dmock import DeclarativeMock

calc = DeclarativeMock(Calculator)
calc.expect("price", 100).returns(99).once()
assert calc.price(100) == 99

calc.expect("price", 200).returns(99, repeat=2).times(3)  # last outcome repeats for the extra calls
assert [calc.price(200) for _ in range(3)] == [99, 99, 99]

calc.expect("price", 300).returns(99).between(1, 3)
assert calc.price(300) == 99

calc.expect("price", 400).never()
calc.verify()

Async methods use the same DSL. runs() accepts a sync or an async function:

from dmock import DeclarativeMock
from dmock.matchers import Anything

mock = DeclarativeMock(MyService)
mock.expect(MyService.aprocess_order, Anything()).returns("ok")
assert await mock.aprocess_order(1) == "ok"

mock.expect(MyService.aprocess_order, Anything()).runs(
    lambda order_id: f"sync-{order_id}"
)
assert await mock.aprocess_order(7) == "sync-7"

async def async_fn(order_id: int) -> str:
    return f"async-{order_id}"

mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
assert await mock.aprocess_order(9) == "async-9"

The matcher set is rich enough that even the most complicated call stays as one declarative expectation. Prefixes, partial mappings, lengths, order, and formats compose in place:

from typing import Any
from dmock import DeclarativeMock
from dmock.matchers import (
    AnyOrder,
    Equals,
    GreaterThan,
    HasLen,
    IsUUID,
    PartialMapping,
    StartsWith,
)

class EventBus:
    def publish(
        self, *, topic: str, headers: dict[str, Any], payload: dict[str, Any]
    ) -> bool: ...

bus = DeclarativeMock(EventBus)
bus.expect(
    "publish",
    topic=StartsWith("orders.events."),
    headers=PartialMapping(
        {
            "x-correlation-id": IsUUID(),
            "x-origin-service": Equals("checkout-service"),
        }
    ),
    payload=PartialMapping(
        {
            "order_id": GreaterThan(0),
            "items": (
                HasLen(GreaterThan(0))
                & AnyOrder(
                    [
                        PartialMapping({"sku": "SKU-AAA", "qty": 1}),
                        PartialMapping({"sku": "SKU-BBB", "qty": 2}),
                    ]
                )
            ),
        }
    ),
).returns(True)

assert bus.publish(
    topic="orders.events.completed",
    headers={
        "x-correlation-id": "12345678-1234-4234-8234-123456789abc",
        "x-origin-service": "checkout-service",
        "x-extra": "ignored",
    },
    payload={
        "order_id": 884,
        "items": [
            {"sku": "SKU-BBB", "qty": 2, "note": "second"},
            {"sku": "SKU-AAA", "qty": 1},
        ],
        "currency": "USD",
    },
)

bus.verify()

dmock also supports pass-through spies using the same declarative DSL:

from dmock import DeclarativeSpy
from dmock.checks import Check

class Store:
    def __init__(self) -> None:
        self.items: dict[str, str] = {}
        self.dirty = False

    def save(self, key: str, value: str) -> bool:
        self.items[key] = value
        self.dirty = False
        return True

    def fetch(self, key: str) -> str:
        return self.items[key]

store = Store()
spy = DeclarativeSpy(store)

(
    spy.observe(Store.save, "a", "A")
    .returns(
        True,
        condition=Check[bool](
            lambda _: store.items.get("a") == "A",
            lambda _: not store.dirty,
        ),
    )
    .once()
    .observe(Store.fetch, "a")
    .returns("A")
    .once()
)

assert spy.save("a", "A") is True
assert spy.fetch("a") == "A"
spy.verify()

dmock is built on unittest.mock, has zero runtime dependencies, and doesn't patch anything. Unregistered mock calls fail immediately. Nothing on live modules or instances is rewritten.

Look up the dmock source code and tests yourself, it's full of examples!

Limitations & non-goals

  • No signature binding at runtime. expect("method", …) and observe("method", …) check that method exists on the spec or object, not that the argument list matches the real signature at runtime.
  • No automatic verify() outside pytest. The pytest plugin checks every mock and spy when the test finishes. Other runners still need an explicit verify().
  • No global patching. The library does not patch modules or instances. Construct a DeclarativeMock or wrap a live instance with DeclarativeSpy and pass it in.
  • Not thread-safe. Concurrent use of one mock or spy from multiple threads is out of scope.

Roadmap

Nothing is planned for 0.5.0, feel free to suggest!

  • Other test runners (low priority) - unittest and similar runners do not verify mocks on teardown the way the pytest plugin does.

Other ideas belong in GitHub Issues.

Development

poetry install
ruff check .
ruff format --check .
mypy src tests
pytest
coverage run -m pytest
coverage report

See CONTRIBUTING.md for setup, commits, and tests. Agents follow AGENTS.md.

License

MIT

OX Radar and Response Center

Find threats in your stack.

OX Radar can check high-priority threats, like critical package CVEs, against your context.

Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.

Where it’s listed

The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).

  • pypi-releases declarative-mocks

References

The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.

Powered by Read the latest findings

Scan your whole stack

Group 1261154050 1
Group 1261154050
 

From OX Research Newsroom

Cry2Wolf: How to Tell a Real Bug from a Nothingburger
AI & VibeSec

Cry2Wolf: Not Every Branded Bug Deserves a Fire Drill

Vulnerability Insights

Compromised Claude Code extensions (versions 2.1.312 & 2.1.313) in Cursor try to install a backdoor

Plug and Pray: Your AI Agents Are Taking Orders From Strangers
Research

Plug and Pray: Your AI Agents Are Taking Orders From Strangers

Frame 2085668439 (1)
Group 1261154229