$ cat job-board-api/part-27.md
Building a Job Board API, Part 27: Testing the Azure Path

Where we are
Hi, I’m Reza. In my newsletter, Root Access, I am sharing one of my projects from the very beginning, step by step. It’s a Job Board API built with Django, Django REST Framework, PostgreSQL and Docker Compose, with S3 and SQS (through LocalStack), Redis, and a background worker.
I’m a junior engineer looking for my first role in DevOps, SRE or Cloud. That’s why I build projects like this and write about them in public. It shows how I think, and writing it down helps me really understand it.
In the last four parts, the app learned to run on Azure. One setting, CLOUD_PROVIDER, now picks the storage, the queue and the public file links. In Part 23, I chose Azure Blob Storage for files. In Part 24, I set up Azure Service Bus locally. In Part 25, I wrote the ServiceBusQueue, and tested it by hand. In Part 26, I ran the real API and the real worker on Azure, and fixed what broke.
But a check by hand is done once. My automatic test suite still only knew about AWS. In this part, I add tests for the Azure path. I use two different methods, because the two services need different tools:
- Blob Storage has Azurite, a real local server. So the tests talk to it for real, and Azurite checks every signature.
- Service Bus has no library like moto. There is no moto for AMQP. So I wrote small fake classes in Python that act like the Azure SDK. They prove that my code makes the right decisions.
The emulator still did an important job. In Step 2, it showed me how the real broker behaves.

The two left boxes run on every test run. The right box was a one-time check by hand, and its findings shaped the fakes.
Part A: Storage tests against a real Azurite
Azurite becomes a test dependency
The test service in docker-compose.yml now starts Azurite, the same way it starts Postgres:
depends_on:
db:
condition: service_healthy
azurite:
condition: service_started
- service_started, not service_healthy. My Azurite service has no healthcheck. So Compose can only wait for the container to start, not for Azurite to be ready. The fixture has to check that itself, as you will see below.
- The test service still does not need LocalStack, Redis or the Service Bus emulator. moto fakes AWS, and Service Bus is faked in Python, so they are not needed. They still run as separate services when I test by hand.
The azure_blob fixture
This fixture switches one test to Azure Blob Storage and gives it a fresh, empty container. Here is how it works, in six steps:
1. It reads the Azure values from the environment.
account = os.environ["AZURE_ACCOUNT_NAME"]
key = os.environ["AZURE_ACCOUNT_KEY"]
endpoint = os.environ["AZURE_BLOB_ENDPOINT"]
Why not settings.AZURE_ACCOUNT_NAME? Because the test process runs with CLOUD_PROVIDER=aws. The Azure settings are empty there, so the fixture reads the values straight from the environment. It sets the Django settings itself, in the next step.
2. It makes a new container for every test.
container = f"test-{uuid.uuid4().hex[:12]}"
This is like moto’s fresh bucket per test. A test only sees its own files, so it can check “exactly one blob” without other tests getting in the way.
3. It switches Django to Azure, for this test only.
settings.CLOUD_PROVIDER = "azure"
settings.AZURE_ACCOUNT_NAME = account
settings.AZURE_ACCOUNT_KEY = key
settings.AZURE_BLOB_ENDPOINT = endpoint
settings.AZURE_PUBLIC_BLOB_ENDPOINT = endpoint
settings.STORAGES = {
**settings.STORAGES,
"default": {"BACKEND": "storages.backends.azure_storage.AzureStorage"},
}
- These are exactly the settings that the Azure branch of settings.py would create. So the app code runs the same way it would in the real Azure stack.
- settings is pytest-django’s fixture. It undoes every change after the test, so the next test is back on AWS.
- AZURE_PUBLIC_BLOB_ENDPOINT = endpoint. In the dev stack, SAS links point at localhost:10000 for my browser, and at azurite:10000 inside Docker. Here the tests run on the host, so the public endpoint is the same as the internal one.
- Assigning STORAGES sends Django’s setting_changed signal. Django throws away its cached storage, and the next call to default_storage builds a fresh AzureStorage.
4. It builds its own client, with no retries.
client = BlobServiceClient.from_connection_string(
connection_string, retry_total=0, connection_timeout=2
)
This client creates, checks and deletes the test container. It is separate from the app’s storage, and it must not wait. The SDK’s default retries would turn a 2-second check into a long wait, as you will see in Problem 1 below.
5. It waits up to 15 seconds for Azurite to answer.
deadline = time.monotonic() + 15
while True:
try:
client.create_container()
break
except Exception:
if time.monotonic() > deadline:
pytest.fail("Azurite did not start in 15 seconds")
time.sleep(0.5)
- service_started only means the container started. Azurite may not be listening yet.
- create_container() is both the readiness check and the setup. Once it works, Azurite answers and the container exists.
- pytest.fail, not pytest.skip. A skip would let the suite go green with the Azure path untested. That is worse than a failure.
6. After the test, it deletes the container.
yield SimpleNamespace(container=client, name=container)
client.delete_container()
I checked: after the full run, Azurite has only [‘resumes’]. No test-… containers are left behind.
Five storage tests
All five tests go through the real API, the same way a user does: permissions, serializer, validator, storage, then the response. Here they are:
1. Upload: the resume lands in Blob Storage.
assert application.resume.storage.__class__.__name__ == "AzureStorage"
assert re.fullmatch(rf"resume/job-{job.id}/[0-9a-f]{32}\.pdf", key)
- The first line proves the file went through Azure, not S3. Without it, a broken fixture could make the test pass on S3 and I would never know.
- Why .__class__ and not type()? default_storage is a LazyObject, a wrapper. It forwards attribute access to the real storage, but type() sees the wrapper. .__class__ sees through it. This is the same lesson as Problem 2 below, and I learned it the hard way.
- Then the same three checks as the S3 test: the key has the right shape, it is the only blob, and the file bytes match the upload.
2. A rejected upload stores nothing. A cv.txt gets a 400, and the container stays empty. Validation runs before storage, on both clouds.
3. Privacy: the plain blob URL does not work.
assert status == 403
assert headers["x-ms-error-code"] == "AuthorizationFailure"
Resumes are personal data. So I open the blob’s URL with no SAS and no key, like a stranger would. My S3 test did the same, and the answer is the same: 403. The container is private, and only a signed link opens it.
4. The SAS link really downloads the file.
assert parsed.path == f"/{settings.AZURE_ACCOUNT_NAME}/{azure_blob.name}/{key}"
assert query["sp"] == ["r"]
assert "sig" in query
- sp=r means read only. A link that could also write or delete would be a security bug.
- sig is the signature. se is the expiry time, and it must be 290 to 300 seconds from now: the same 5 minutes I set in Part 23.
- Then a plain HTTP GET, like a browser, with no SDK and no key. My S3 test could not do this, because a presigned S3 URL needs the AWS signature. With Azurite, the SAS link is a real URL, and a plain GET downloads the file.
- Content-Disposition makes the browser save the file as resume-<id>.pdf, not under the random key.
5. A tampered link is rejected. I replace the signature with sig=AAAA, and Azurite answers 403. This is the same idea as the S3 test, but the answer comes from Azurite, not moto.
Each cloud must start on its own
In Step 2, I fixed settings.py so each cloud only needs its own variables. Now three tests in config/test_settings.py prove it, by starting a fresh Python process for each cloud:
There is a problem: settings.py runs once, when Django starts. The test process has already started Django with CLOUD_PROVIDER=aws, so I cannot just change the environment and import settings again. So each test starts a new process, with a clean environment, and checks what that process prints.
def load_settings(provider, remove):
env = {k: v for k, v in os.environ.items() if k not in remove}
env["CLOUD_PROVIDER"] = provider
The child process loads Django and prints three words: the storage backend, whether the SQS setting is set, and whether the Service Bus setting is set.
- Azure without any AWS variable prints AzureStorage False True.
- AWS without any Azure variable prints S3Storage True False.
- Azure without SERVICE_BUS_CONNECTION_STRING must fail, and the error must name that variable.
The third test is the negative twin. Without it, the first test could pass just because settings ignores a missing variable instead of failing. Now a missing variable is a loud error, on both clouds.
Part B: Service Bus tests with fake SDK objects
For Service Bus, I replace the Azure SDK’s ServiceBusClient with a fake. Each test controls how the fake behaves, then checks that my code did the right thing. The fake is small, and it is written by hand, not generated by a mocking library.
One idea is important here: these tests prove my decisions, not Service Bus behaviour. Locks that expire, errors that close a sender, a ping that times out – those are my code’s decisions, and the fake lets me check them. The real broker was already checked by hand, in Step 2.
Only the network parts are fake
- The real ServiceBusError is used. My code raises it, so the tests use the real class.
- The real ServiceBusMessage is used too. send() builds real message objects, and the tests read their body and message_id from them.
- Only the client, the sender and the receiver are fake.
A fake received message
class FakeReceived:
def __init__(self, body, message_id="m-1", lock_token="lt-1", sequence_number=1):
self.body = body
self.message_id = message_id
self.lock_token = lock_token
self.sequence_number = sequence_number
It has exactly the four things receive() reads, and nothing else. This is on purpose. If my code ever reads a fifth thing, the test will fail with an AttributeError, and I will know the fake is out of date.
The world: a remote control for the fake broker
The sb fixture creates one object called world. Tests flip its switches to put the “broker” in a certain state:
- clients: every fake client created, in order, so tests can look inside them.
- inbox: a list of batches. Each receive call gets the next batch.
- send_error, receive_error, open_error: raise this error on send, on receive, or when opening a receiver.
- close_error: raise this error when something is closed.
- hang_send, hang_open: freeze that operation, like a paused broker.
- release: a threading.Event that unfreezes it. It is the in-process version of docker compose pause and unpause.
Here is the fake sender:
class FakeSender:
def __init__(self):
self.sent = []
self.closed = False
def send_messages(self, message):
if world.hang_send:
world.release.wait(5)
if world.send_error:
raise world.send_error
self.sent.append(message)
def close(self):
if world.close_error:
raise world.close_error
self.closed = True
- It freezes if asked, fails if asked, and otherwise records the message.
- Hang first, then error. This order allows “freeze, then finish normally after release”, which is the same test as in Step 2.
- release.wait(5) has a limit. Even if a test forgets to release, a fake can never block the suite for more than 5 seconds.
The fake receiver records the arguments of every receive call, so a test can check that receive(max_message_count=10, max_wait_time=20) was really used.
The receiver can also freeze when it is opened:
def __enter__(self): # used by ping(): opening = connect + login + attach
if world.hang_open:
world.release.wait(5)
if world.open_error:
raise world.open_error
return self
The freeze is in __enter__ because that is where the real SDK froze. In Step 2, a faulthandler dump showed the real client stuck in open(), not in receive(). So the fake freezes in the same place.
The fake client records every sender and receiver it makes, and it saves its kwargs, so tests can check that ping() used a third client with no retries.
monkeypatch.setattr(queue_module, "ServiceBusClient", FakeClient)
yield world
world.release.set()
I patch the name where it is used, in cloud.queue, not in azure.servicebus. That is the rule I learned in Part 12: patch where it is looked up, not where it is defined.
The 17 tests
Every test builds a fresh queue with a small helper, make_queue(), after the fixture has patched the client. The queue is built with the same settings as the real worker, so the tests check the real configuration, not a test-only one.
Construction (test 1)
assert q.url == "sb://servicebus/job-board-status"
assert "SAS_KEY_VALUE" not in q.url
- The worker logs url at startup, so the key must never be in it.
- There are exactly two clients, each with its own budget. If someone changed the send client back to a shared client, this test would fail.
- Creating the object opens no sender and no receiver, so it makes no network call. That is a lesson from Step 2: the real client froze on open, so construction must not open anything.
Sending (tests 2 to 6)
- 2. One sender is reused. Two sends use one sender, with two different message IDs, and send() returns the message ID.
- 3. A send error throws the sender away. The same error reaches the caller, the broken sender is closed, and the next send opens a new one.
- 4. An error while closing does not hide the real error. The caller sees “broker down”, not “close failed”.
- 5. Send gives up after SEND_SECONDS. The test sets q.SEND_SECONDS = 0.2 on this one object, so it waits a short time, then raises a queue error.
- 6. A stuck send makes the next send fail fast. The second send waits between 0.9 and 2 seconds, then raises a queue error, without waiting for the full SEND_SECONDS.
Receiving and deleting (tests 7 to 11)
- 7. Receive maps messages, and delete completes on the same receiver. One message has no message_id, so it is skipped, and the other is deleted.
- 8. One receiver is reused, with the same defaults as SQS: 10 messages and a 20-second long poll.
- 9. A new receive forgets old lock tokens. Deleting an old message fails with “No lock held for message”, because the new receiver has no record of it.
- 10. Delete without a receive raises a queue error, not a KeyError. A KeyError would crash the worker, and the message would stay in the queue.
- 11. A receive error throws the receiver away. The next receive opens a new one. This is the worker’s recovery path.
Ping (tests 12 to 14)
ping_client = sb.clients[2]
assert ping_client.kwargs == {"retry_total": 0, "try_timeout": q.PING_TIMEOUT}
- 12. Ping uses its own third client, with no retries, closes everything, and only opens a receiver. It does not send or receive a message.
- 13. A ping error reaches the caller, and the lock is released. Without that, one failed ping would make every later ping fail.
- 14. Frozen broker. The first ping times out in under 1 second. The second fails with “Previous ping still running”, and the lock is released after the first one finishes.
Choosing the cloud (tests 15 to 17)
- 15. With azure, get_queue() returns a ServiceBusQueue, and the same object every time, so the process has one queue.
- 16. With aws, it returns an SQSQueue.
- 17. issubclass(ServiceBusError, QUEUE_ERRORS). This is the contract with the worker and the publisher: they catch QUEUE_ERRORS, and a Service Bus error must be one of them.
Results
After Part A (storage):
- The whole suite: 211 passed in 8.33 seconds, coverage 90.14%. jobs/storage.py is at 100%.
- With Azurite stopped: 5 errors in 76.81s. So the tests really use Azurite, and they fail, not skip, when it is down.
- A break on purpose. I changed the SAS permission to read=False, write=True. The download test failed, and the other four still passed.
- Leftover containers after the run: only [‘resumes’].
After Part B (Service Bus):
- The whole suite: 228 passed in 9.94 seconds, coverage 98.63%. cloud/queue.py is at 100%: the ServiceBusQueue is fully tested, with fakes.
- Two breaks on purpose. Ping with retry_total=3 failed only test 12. _pending.update(…) instead of _pending[lock_token] = … failed only test 9. Each test guards one clear thing.
- Three runs in a row: 17 passed in 1.81, 1.82 and 1.81 seconds. The threaded tests are stable, not flaky.
One honest note about coverage. config/settings.py still shows lines 35 and 57 to 76 as missing. Lines 57 to 76 are the Azure branch, and they are tested, but in the subprocess tests. Coverage only measures the test process, not its child processes. Line 35 is the error for an invalid CLOUD_PROVIDER, which I checked by hand in Step 1. So the number is lower than what is really tested.
Problems I hit
1.
With Azurite stopped, the 5 tests took 428.77 seconds to fail. That is more than 7 minutes. One create_container() call waited a long time because the SDK retried inside itself, and my loop added its own 15-second wait on top. The fix: retry_total=0 and connection_timeout=2 on the fixture client, so a dead Azurite fails fast. Now the same run takes 76.81 seconds, which is 5 tests times 15 seconds, plus a little.
2.
assert ‘DefaultStorage’ == ‘AzureStorage’. I used type() on a LazyObject. The fix was .__class__.__name__, which sees through the wrapper to the real storage.
3.
KeyError: ‘Content-Disposition’. My first http_get returned dict(response.headers), which is case-sensitive. The fix was to read the header with response.headers.get(“Content-Disposition”), which is case-insensitive.
For problems 2 and 3, I did not change anything until I had read the actual error lines. Both causes were clear once I looked.
4.
Four DeprecationWarnings from django-storages. Its AzureStorage calls datetime.utcnow(), which is deprecated in Python 3.12. I silenced only that one call, in pyproject.toml:
filterwarnings = [
"ignore:datetime.datetime.utcnow:DeprecationWarning:storages.backends.azure_storage",
]
The same call in my code would still warn. I did not use a blanket ignore::DeprecationWarning, because that would hide my own mistakes too.
5.
Part of the output was missing from my first run. I ran the checks again inside { … } | tee to save the full output to a file, so I could read it after the run.
Part B had no problems. Every check matched on the first run.
What I learned
- Test each part where its truth lives. Azurite is a real server, so it can prove a SAS link works and a bad signature fails. A fake can only prove what I already decided.
- Fail, don’t skip, when a test dependency is down. A green suite with the Azure path untested is a false green.
- Turn off the SDK’s retries when my own loop owns the waiting. Otherwise my deadline means nothing.
- Measure first, then pin. I measured Azurite’s real 403 before writing the exact assertion.
- Hand-written fakes are stricter than mocks. A Mock accepts any call, so a typo would pass. A small fake class only accepts what I wrote.
- Shrink deadlines on one object, not on the class. q.SEND_SECONDS = 0.2 makes the test fast and keeps the real value for the worker.
- A break on purpose should make exactly one test fail. That shows each test guards one clear thing.
What is next
This completes item 3 of my Phase 6 checklist: the Azure path is now tested on every run, for storage and for the queue. In the next part, I continue with Phase 6.