Asterisk + pjsua
Automated call testing with pjsua2 and Python
Scripted calls against Asterisk that dial, play audio, record what comes back and fail the build when something's off.
6 min readPart 2 of 2
Clicking through pjsua by hand is fine for poking at one problem. It's useless for catching regressions. After a dialplan change or an Asterisk upgrade, what you want is something that places a handful of calls, checks each one did what it should, and fails the build if it didn't.
pjsua2 is pjproject's object-oriented API, and it ships with SWIG bindings for Python. This post builds a small call-test harness on it, running against the lab from the previous post.
Building the Python module
The bindings aren't on PyPI. They're built from the same pjproject tree, which has to be compiled as position-independent code first:
sudo apt-get install -y swig python3-dev
cd pjproject
./configure CFLAGS="-fPIC"
make dep && make -j"$(nproc)"
cd pjsip-apps/src/swig/python
make
make install
python3 -c "import pjsua2; print('ok')"If that last line prints ok, you're done with the hard part. (Inside a virtualenv, the pjproject docs suggest python setup.py install instead of make install.)
How pjsua2 wants to be used from Python
pjsua2 is callback driven. You subclass Account and Call, override the callbacks you care about, and the library calls you back as things happen.
Normally the library runs its own worker threads to drive all of that. The pjsua2 documentation says that from Python you should switch them off (threadCnt = 0), because Python doesn't cope with being called from threads it didn't create. With no worker threads, your code polls the library itself with libHandleEvents(). That suits a test harness nicely: everything happens on one thread, in an order you control.
import time
import pjsua2 as pj
class Call(pj.Call):
def __init__(self, account, call_id=pj.PJSUA_INVALID_ID):
super().__init__(account, call_id)
self.confirmed = False
self.disconnected = False
self.status_code = None
self.on_media = None # set by a test: called with (call, audio_media)
def onCallState(self, prm):
info = self.getInfo()
if info.state == pj.PJSIP_INV_STATE_CONFIRMED:
self.confirmed = True
elif info.state == pj.PJSIP_INV_STATE_DISCONNECTED:
self.disconnected = True
self.status_code = info.lastStatusCode
def onCallMediaState(self, prm):
info = self.getInfo()
for i, media in enumerate(info.media):
if media.type == pj.PJMEDIA_TYPE_AUDIO and media.status == pj.PJSUA_CALL_MEDIA_ACTIVE:
if self.on_media:
self.on_media(self, self.getAudioMedia(i))
class Account(pj.Account):
def __init__(self):
super().__init__()
self.registered = False
self.incoming = []
def onRegState(self, prm):
self.registered = prm.code == 200
def onIncomingCall(self, prm):
call = Call(self, prm.callId)
self.incoming.append(call) # keep a reference, see below
answer = pj.CallOpParam()
answer.statusCode = 200
call.answer(answer)
class Lab:
def __init__(self, port=5090):
self.ep = pj.Endpoint()
self.ep.libCreate()
cfg = pj.EpConfig()
cfg.uaConfig.threadCnt = 0 # no worker threads, we poll
cfg.uaConfig.mainThreadOnly = True
cfg.logConfig.level = 1
cfg.logConfig.consoleLevel = 1
self.ep.libInit(cfg)
transport = pj.TransportConfig()
transport.port = port
self.ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, transport)
self.ep.audDevManager().setNullDev() # CI agents have no sound card
self.ep.libStart()
def account(self, user, password, server="127.0.0.1"):
cfg = pj.AccountConfig()
cfg.idUri = f"sip:{user}@{server}"
cfg.regConfig.registrarUri = f"sip:{server}"
cfg.sipConfig.authCreds.append(pj.AuthCredInfo("digest", "*", user, 0, password))
acc = Account()
acc.create(cfg)
self.wait_for(lambda: acc.registered, timeout=5)
return acc
def run(self, seconds):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
self.ep.libHandleEvents(20)
def wait_for(self, condition, timeout):
deadline = time.monotonic() + timeout
while not condition():
if time.monotonic() > deadline:
raise TimeoutError(f"gave up after {timeout}s")
self.ep.libHandleEvents(20)
def close(self):
self.ep.hangupAllCalls()
self.run(0.5)
self.ep.libDestroy()Garbage collection is the other trap. The pjsua2 documentation warns that a garbage collector delays the destruction of objects, can run destructors out of order, and may run them on a thread pjproject doesn't know about. The safe pattern is to keep an explicit reference to every pjsua2 object for as long as the library might use it, and to tear things down in a known order. That's why Account keeps incoming calls in a list, and why every test below holds on to its calls, players and recorders until it's finished with them.
The same documentation is clear that there must be exactly one Endpoint per application. That fits nicely with a session-scoped pytest fixture:
import pytest
from sipcheck import Lab
@pytest.fixture(scope="session")
def lab():
lab = Lab()
yield lab
lab.close()
@pytest.fixture(scope="session")
def alice(lab):
return lab.account("alice", "alice-lab-secret")
@pytest.fixture(scope="session")
def bob(lab):
return lab.account("bob", "bob-lab-secret")Both accounts share one UDP port. That's fine: when Asterisk sends an INVITE for bob, pjsua matches it to the right account by the user in the request URI.
Test 1: a missing extension is rejected
The simplest useful test, and a good one to write first because it proves the harness works before audio gets involved:
import pjsua2 as pj
from sipcheck import Call
def test_unknown_extension_is_rejected(lab, alice):
call = Call(alice)
call.makeCall("sip:999@127.0.0.1", pj.CallOpParam(True))
lab.wait_for(lambda: call.disconnected, timeout=5)
assert call.status_code == 404Test 2: alice can reach bob
def test_alice_reaches_bob(lab, alice, bob):
before = len(bob.incoming)
call = Call(alice)
call.makeCall("sip:bob@127.0.0.1", pj.CallOpParam(True))
lab.wait_for(lambda: call.confirmed, timeout=10)
assert len(bob.incoming) == before + 1
call.hangup(pj.CallOpParam(True))
lab.wait_for(lambda: call.disconnected, timeout=5)confirmed means the INVITE transaction finished with an ACK, so signalling worked end to end. It says nothing about audio, which is the next test's job.
Test 3: the echo test echoes
Play a known recording into extension 600, record whatever comes back, and check the recording isn't silence.
import array
import math
import wave
def rms(path):
with wave.open(path) as w:
samples = array.array("h", w.readframes(w.getnframes()))
return math.sqrt(sum(s * s for s in samples) / max(len(samples), 1))
def test_echo_returns_audio(lab, alice, tmp_path):
recording = str(tmp_path / "echo.wav")
media = [] # players and recorders must outlive the call
def connect(call, audio):
player = pj.AudioMediaPlayer()
player.createPlayer("fixtures/count-to-five.wav", pj.PJMEDIA_FILE_NO_LOOP)
recorder = pj.AudioMediaRecorder()
recorder.createRecorder(recording)
player.startTransmit(audio)
audio.startTransmit(recorder)
media.extend([player, recorder])
call = Call(alice)
call.on_media = connect
call.makeCall("sip:600@127.0.0.1", pj.CallOpParam(True))
lab.wait_for(lambda: call.confirmed, timeout=5)
lab.run(4)
call.hangup(pj.CallOpParam(True))
lab.wait_for(lambda: call.disconnected, timeout=5)
media.clear() # destroying the recorder finalizes the WAV header
assert rms(recording) > 500The recorder writes 16-bit PCM, which is why array("h") works for reading it back. And the media.clear() before reading isn't tidiness: the WAV header's length fields are only written when the recorder is destroyed. Read the file before that and Python's wave module will tell you it's empty.
An RMS threshold is crude, but it catches the failures that actually happen: no media at all, one-way audio, and a codec mismatch that produces noise or silence. Calibrate the number once against your own fixture. Record a working echo and a call to an extension that answers and stays silent, then pick a threshold comfortably between the two. If you need more than that, compare the recording against the source with a cross-correlation.
Running it in Jenkins
stage('Call tests') {
agent { label 'docker' }
options {
timeout(time: 15, unit: 'MINUTES')
lock('sip-lab')
}
steps {
sh 'docker compose -f lab/compose.yaml up -d --build'
retry(20) {
sleep 2
sh 'docker exec asterisk asterisk -rx "core waitfullybooted"'
}
sh 'python3 -m pytest tests/calls --junitxml=reports/calls.xml'
}
post {
always {
junit 'reports/calls.xml'
sh 'docker logs asterisk > reports/asterisk.log 2>&1 || true'
archiveArtifacts artifacts: 'reports/**', allowEmptyArchive: true
sh 'docker compose -f lab/compose.yaml down'
}
}
}The retry loop waits for Asterisk to finish booting before any test tries to register. Without it, the first test can easily run before Asterisk is listening and fail for no interesting reason.
The lock is there because the lab uses host networking, so two builds on the same agent would both try to own port 5060. (There's more on locks in the Jenkins pipeline tips post.) And archiving the Asterisk log with every run, pass or fail, is the cheapest debugging aid there is. When a nightly call test fails, that log is usually the whole story.
What to test next
Once these three pass reliably, the same harness stretches a long way. DTMF menus can be driven with Call.dialDtmf(). Blind transfers go through Call.xfer(). Codec negotiation can be pinned down by changing priorities with Endpoint.codecSetPriority() and asserting which codec the call ends up using. Each one is a few more lines on top of the classes above.
References
- Building PJSUA2, pjproject documentation: the SWIG prerequisites, the
-fPICbuild and installing the Python module. - PJSUA2 general concepts, pjproject documentation: disabling worker threads for Python, garbage collection, and the single
Endpoint. - PJSUA2 API reference, including
UaConfig,Call,AudioMediaPlayerandAudioMediaRecorder. - pytest fixtures: fixture scopes, including
session. - Python's wave and array modules.
- Jenkins plugins: JUnit and Lockable Resources.
#sip #pjsip #python #testing