How to mock resource request limits in Python

A Python class that simulates CPU and memory limit checks for resource requests, returning clear acceptance or rejection messages.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 14 views 0 copies

Python code

23 lines
Python 3.9+
class ResourceLimits:
    def __init__(self, cpu_limit, memory_limit):
        self.cpu_limit = cpu_limit
        self.memory_limit = memory_limit

    def check_request(self, cpu, memory):
        if cpu > self.cpu_limit:
            return "CPU limit exceeded: {cpu} > {limit}".format(cpu=cpu, limit=self.cpu_limit)
        if memory > self.memory_limit:
            return "Memory limit exceeded: {memory} > {limit}".format(memory=memory, limit=self.memory_limit)
        return "Request accepted: {cpu} CPU, {memory} MB".format(cpu=cpu, memory=memory)


if __name__ == "__main__":
    limits = ResourceLimits(cpu_limit=4, memory_limit=1024)
    test_requests = [
        (2, 512),
        (3, 2048),
        (5, 512),
        (2, 1024)
    ]
    for cpu, memory in test_requests:
        print(limits.check_request(cpu, memory))

Output

stdout
Request accepted: 2 CPU, 512 MB
Memory limit exceeded: 2048 > 1024
CPU limit exceeded: 5 > 4
Request accepted: 2 CPU, 1024 MB

How it works

The ResourceLimits class stores the configured CPU and memory caps in its constructor. Each call to check_request compares the requested CPU and memory against those caps in order. The first exceeded limit triggers an immediate return message, so CPU is checked before memory. The formatted strings use the .format() method for clean output. This pattern is a simple, deterministic way to mock resource admission checks before real infrastructure enforces them.

Common mistakes

  • Checking memory before CPU, which changes the order of failure messages.
  • Using `>` instead of `>=`, letting a request exactly at the limit pass.
  • Assuming the class mutates external state instead of being pure validation logic.

Variations

  1. Return a boolean along with a message tuple (e.g., `(False, "CPU limit exceeded")`) for programmatic handling.
  2. Use dataclasses to store the limits for simpler attribute access.

Real-world use cases

  • Simulating Kubernetes resource requests in unit tests before deploying to a cluster.
  • Validating user-submitted resource configurations in a CLI tool that provisions cloud instances.
  • Serving as a lightweight local mock in development when the real scheduler is unavailable.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.