---
title: "Testing your integration"
description: "Test the code that calls AudD without spending requests or using the network: replay recorded API responses through a fake HTTP transport in Python, Node and Go, cover a match, no match, API errors, gateway errors and timeouts, and know which few checks to run live before launch."
slug: "/resources/concepts/testing-your-integration"
section: "concepts"
keywords: [audd, testing, unit tests, mock, fixtures, recorded responses, httpx MockTransport, fetch, node:test, pytest, test token]
---

# Testing your integration

You can test the code that calls the AudD API without sending any requests to AudD. You can pass your own HTTP client to the SDK, and in a test, it can return a response that we recorded. The tests don't spend requests, and they work without the network. We'll show you where to get the responses and how to replay them in Python, Node and Go.

## Replay a recorded response in Python

The recorded responses are in the [fixtures folder](https://github.com/AudDMusic/audd-openapi/tree/main/fixtures) of our public `audd-openapi` repository, and our SDKs are tested against the same files. Download the ones the tests below use:

```bash
mkdir fixtures && cd fixtures
F=https://raw.githubusercontent.com/AudDMusic/audd-openapi/main/fixtures
for f in recognize_basic error_900_invalid_token enterprise_with_isrc_upc \
         streams_callback_with_result streams_callback_with_notification; do
  curl -sO "$F/$f.json"
done
cd ..
```

This is the code we'll test. `identify()` recognizes a clip, `scan()` sends a long file to the enterprise endpoint, and `on_callback()` reads a callback from a stream:

```python
# app.py: the code you want to test
from audd import AudD, AudDAPIError, AudDConnectionError, AudDServerError


def identify(audd: AudD, url: str) -> str:
    try:
        song = audd.recognize(url)
    except (AudDConnectionError, AudDServerError):
        return "AudD is unavailable, try again later"
    except AudDAPIError as e:
        return f"recognition failed: error {e.error_code}"
    if song is None:
        return "no match"
    return f"{song.artist} - {song.title} {song.song_link}"


def scan(audd: AudD, url: str) -> list[str]:
    matches = audd.recognize_enterprise(url, limit=10)
    return [f"{m.artist} - {m.title}" for m in matches]


def on_callback(audd: AudD, body: bytes) -> str:
    match, notification = audd.streams.parse_callback(body)
    if notification:
        return f"stream {notification.radio_id}: code {notification.notification_code}"
    return f"stream {match.radio_id}: {match.song.artist} - {match.song.title}"
```

Save the tests in `test_app.py`. You can install the SDK and pytest with `pip install audd pytest`, and then run the tests with `pytest`:

```python
# test_app.py: run with `pytest`
import json
from pathlib import Path
from urllib.parse import parse_qsl

import httpx
from audd import AudD

from app import identify, on_callback, scan

FIXTURES = Path(__file__).parent / "fixtures"
CLIP = "https://audd.tech/example.mp3"


def fixture(name: str) -> dict:
    return json.loads((FIXTURES / name).read_text())


def form(request: httpx.Request) -> dict:
    return dict(parse_qsl(request.content.decode()))  # the fields of a request with a URL


def fake_audd(*replies):
    """An AudD client that gets these replies, in order, and never uses the network.

    A reply is an httpx.Response, or an exception to raise, such as a timeout.
    Returns the client and the list of the requests it sent.
    """
    replies = list(replies)
    sent = []

    def handler(request: httpx.Request) -> httpx.Response:  # every request ends up here
        sent.append(request)
        reply = replies.pop(0)
        if isinstance(reply, Exception):
            raise reply
        return reply

    http = httpx.Client(transport=httpx.MockTransport(handler))
    # backoff_factor=0: the SDK retries without waiting, so the 502 test is instant
    return AudD("fake-token", httpx_client=http, backoff_factor=0), sent


def test_match():
    audd, sent = fake_audd(httpx.Response(200, json=fixture("recognize_basic.json")))
    assert identify(audd, CLIP) == (
        "Tears For Fears - Everybody Wants To Rule The World https://lis.tn/NbkVb"
    )
    assert sent[0].url == "https://api.audd.io/"
    assert form(sent[0])["url"] == CLIP


def test_no_match():
    audd, _ = fake_audd(httpx.Response(200, json={"status": "success", "result": None}))
    assert identify(audd, CLIP) == "no match"


def test_api_error():
    audd, _ = fake_audd(httpx.Response(200, json=fixture("error_900_invalid_token.json")))
    assert identify(audd, CLIP) == "recognition failed: error 900"


def test_gateway_error():
    page = httpx.Response(502, text="<html><body>502 Bad Gateway</body></html>")
    audd, sent = fake_audd(page, page, page)
    assert identify(audd, CLIP) == "AudD is unavailable, try again later"
    assert len(sent) == 3  # the SDK tried 3 times


def test_timeout():
    audd, sent = fake_audd(httpx.ReadTimeout("timed out"))
    assert identify(audd, CLIP) == "AudD is unavailable, try again later"
    assert len(sent) == 1  # not retried: the request may already have been counted


def test_enterprise_call_has_a_limit():
    audd, sent = fake_audd(httpx.Response(200, json=fixture("enterprise_with_isrc_upc.json")))
    assert scan(audd, CLIP) == ["Tears For Fears - Everybody Wants To Rule The World"]
    assert sent[0].url == "https://enterprise.audd.io/"
    assert form(sent[0])["limit"] == "10"


def test_stream_callbacks():
    audd = AudD("fake-token")
    result = (FIXTURES / "streams_callback_with_result.json").read_bytes()
    notification = (FIXTURES / "streams_callback_with_notification.json").read_bytes()
    assert on_callback(audd, result) == "stream 7: Alan Walker, A$AP Rocky - Live Fast (PUBGM)"
    assert on_callback(audd, notification) == "stream 3: code 650"
```

Since the requests never reach our servers, the tests work offline, and any string works as the token. You can also check the requests in `sent`: for example, to make sure that every enterprise call has a `limit`.

### Timeouts when you pass your own httpx client

If you pass your own `httpx.Client` to the SDK, the standard endpoint and the streams methods use that client's timeout, and the default timeout in httpx is 5 seconds. The enterprise endpoint keeps the SDK's own timeouts: 30 seconds to connect and an hour to read. In tests, the timeout makes no difference, but in production, create your client with the SDK's defaults:

```python
import httpx
from audd import AudD

http = httpx.Client(timeout=httpx.Timeout(connect=30.0, read=60.0, write=60.0, pool=30.0))
audd = AudD("your-api-token", httpx_client=http)
```

## The same tests in Node

In Node, the SDK takes a `fetch` function in its options, and a test can pass one that returns a `Response` without making a request. Install the SDK with `npm install @audd/sdk` (Node 20 or later), and save both files next to the `fixtures` folder:

```js
// app.mjs: the code you want to test
import { AudDAPIError, AudDConnectionError, AudDServerError, parseCallback } from "@audd/sdk";

export async function identify(audd, url) {
  let song;
  try {
    song = await audd.recognize(url);
  } catch (err) {
    if (err instanceof AudDConnectionError || err instanceof AudDServerError) {
      return "AudD is unavailable, try again later";
    }
    if (err instanceof AudDAPIError) return `recognition failed: error ${err.errorCode}`;
    throw err;
  }
  if (!song) return "no match";
  return `${song.artist} - ${song.title} ${song.songLink}`;
}

export async function scan(audd, url) {
  const matches = await audd.recognizeEnterprise(url, { limit: 10 });
  return matches.map((m) => `${m.artist} - ${m.title}`);
}

export function onCallback(body) {
  const { match, notification } = parseCallback(body);
  if (notification) {
    return `stream ${notification.radioId}: code ${notification.notificationCode}`;
  }
  return `stream ${match.radioId}: ${match.song.artist} - ${match.song.title}`;
}
```

```js
// app.test.mjs: run with `node --test`
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { AudD } from "@audd/sdk";
import { identify, onCallback, scan } from "./app.mjs";

const CLIP = "https://audd.tech/example.mp3";
const fixture = (name) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url), "utf8");
const reply = (body, status = 200) => new Response(body, { status });

// An AudD client that gets these replies, in order, and never uses the network.
function fakeAudD(...replies) {
  const sent = [];
  const fetch = async (url, init) => {
    sent.push({ url: String(url), form: init.body }); // init.body is the FormData the SDK sends
    const next = replies.shift();
    if (next instanceof Error) throw next;
    return next;
  };
  return { audd: new AudD("fake-token", { fetch, backoffFactorMs: 0 }), sent }; // 0: retry at once
}

test("match", async () => {
  const { audd, sent } = fakeAudD(reply(fixture("recognize_basic.json")));
  assert.equal(
    await identify(audd, CLIP),
    "Tears For Fears - Everybody Wants To Rule The World https://lis.tn/NbkVb",
  );
  assert.equal(sent[0].url, "https://api.audd.io/");
  assert.equal(sent[0].form.get("url"), CLIP);
});

test("no match", async () => {
  const { audd } = fakeAudD(reply('{"status":"success","result":null}'));
  assert.equal(await identify(audd, CLIP), "no match");
});

test("API error", async () => {
  const { audd } = fakeAudD(reply(fixture("error_900_invalid_token.json")));
  assert.equal(await identify(audd, CLIP), "recognition failed: error 900");
});

test("gateway error", async () => {
  const page = () => reply("<html><body>502 Bad Gateway</body></html>", 502);
  const { audd, sent } = fakeAudD(page(), page(), page());
  assert.equal(await identify(audd, CLIP), "AudD is unavailable, try again later");
  assert.equal(sent.length, 3); // the SDK tried 3 times
});

test("timeout", async () => {
  const timedOut = new DOMException("This operation was aborted", "AbortError");
  const { audd, sent } = fakeAudD(timedOut);
  assert.equal(await identify(audd, CLIP), "AudD is unavailable, try again later");
  assert.equal(sent.length, 1); // not retried: the request may already have been counted
});

test("enterprise call has a limit", async () => {
  const { audd, sent } = fakeAudD(reply(fixture("enterprise_with_isrc_upc.json")));
  assert.deepEqual(await scan(audd, CLIP), ["Tears For Fears - Everybody Wants To Rule The World"]);
  assert.equal(sent[0].url, "https://enterprise.audd.io/");
  assert.equal(sent[0].form.get("limit"), "10");
});

test("stream callbacks", () => {
  assert.equal(
    onCallback(fixture("streams_callback_with_result.json")),
    "stream 7: Alan Walker, A$AP Rocky - Live Fast (PUBGM)",
  );
  assert.equal(onCallback(fixture("streams_callback_with_notification.json")), "stream 3: code 650");
});
```

Your own `fetch` doesn't change the timeouts. By default, a request to the standard endpoint times out after 60 seconds, and a request to the enterprise endpoint after an hour. You can change this for a call with `timeoutMs`. When the time is up, the SDK aborts the request, and `fetch` rejects with an `AbortError`: the timeout test throws the same error.

## The same test in Go

In Go, you can use the `audd.WithHTTPClient` option to pass your own `http.Client`. Install the SDK with `go get github.com/AudDMusic/audd-go` in your module. In the test below, the `Transport` of the client returns a recorded body:

```go
// app_test.go: run with `go test`
package app

import (
	"bytes"
	"io"
	"net/http"
	"os"
	"testing"

	"github.com/AudDMusic/audd-go"
)

// replay answers every request with the same recorded body; no network.
type replay []byte

func (b replay) RoundTrip(r *http.Request) (*http.Response, error) {
	return &http.Response{StatusCode: 200, Header: http.Header{},
		Body: io.NopCloser(bytes.NewReader(b)), Request: r}, nil
}

func fakeAudD(body []byte) *audd.Client {
	hc := &http.Client{Transport: replay(body)}
	return audd.NewClient("fake-token", audd.WithHTTPClient(hc), audd.WithBackoffFactor(0))
}

func TestMatch(t *testing.T) {
	body, err := os.ReadFile("fixtures/recognize_basic.json")
	if err != nil {
		t.Fatal(err)
	}
	song, err := fakeAudD(body).Recognize("https://audd.tech/example.mp3", nil)
	if err != nil || song.Artist != "Tears For Fears" || song.SongLink != "https://lis.tn/NbkVb" {
		t.Fatalf("got %+v, %v", song, err)
	}
}

func TestNoMatch(t *testing.T) {
	song, err := fakeAudD([]byte(`{"status":"success","result":null}`)).
		Recognize("https://audd.tech/example.mp3", nil)
	if err != nil || song != nil {
		t.Fatalf("got %+v, %v", song, err)
	}
}
```

> **Note.** The same `http.Client` is used for the standard and the enterprise endpoint, and the SDK doesn't change it. The timeouts you set with `WithStandardTimeout` and `WithEnterpriseTimeout` are ignored. A Timeout of zero means no timeout, so in production, set a `Timeout` in `RecognizeOptions` or `EnterpriseOptions`, or use a context with a deadline.

## Other SDKs

In the other SDKs, use these options to pass your own HTTP client. The C and C++ SDKs don't have this option.

| SDK | Option |
|---|---|
| Rust | `AudD::builder(token).reqwest_client(client)` |
| PHP | `new AudD($token, httpClient: $psr18Client)` |
| Java | `AudD.builder().httpClient(okHttpClient)` |
| Kotlin | `AudD(token, engine = engine)` |
| Swift | `AudD(apiToken: token, urlSession: session)` |
| C# | `new AudD.AudD(token, httpClient: httpClient)` |

## The cases to cover

The tests above cover these cases. It's hard to get most of them from a live call, which is why they're worth a test.

### A match

`recognize_basic.json` is the response we recorded for `https://audd.tech/example.mp3`. The song is "Everybody Wants To Rule The World" by Tears For Fears, and the `song_link` is `https://lis.tn/NbkVb`. If a field is missing from a response, the SDKs leave it empty instead of raising an error, so your code should work without it.

### When `result` is null

If the server has successfully processed the request, but there are no matches, the `result` field could be `null` or an empty array, depending on the method. The SDKs return `None` (`null` in Node, `nil` in Go) for the standard endpoint, and an empty list for the enterprise endpoint. It's not an error, so your code should just show that nothing was found.

### When the API returns an error

All the responses contain the `status` field that equals either "success" if the request was successfully processed or "error" if there's been an error. On an error, the SDK raises an exception with the `error_code` from the response, and `error_900_invalid_token.json` is a recorded `900` (an invalid token). The codes are grouped by category in the [error reference](/resources/reference/errors).

### When a gateway answers instead of the API

The API itself returns errors with the `200 OK` status and a JSON body. If the status isn't 200, the response comes from the network in front of the API: for example, `413` when an upload is too large for the proxy, or `502`, `503` or `504` when a gateway can't reach the server. Such a response may have an HTML body or no body at all. In the SDKs, a recognition call that gets a `5xx` is retried, up to 3 attempts by default, and then the SDK raises a server error with the HTTP status and `error_code` `0`.

### When the request times out

If a request times out, you'll get a connection error. The SDK won't send the request again if it timed out after the file or the URL was sent: a request like that might still consume requests. Your code has to decide what to do, for example, try again later.

### Enterprise calls

We count requests to the enterprise endpoint as 1 request per 12 seconds of audio, so the bug to test for is a call without a `limit`. The test above checks that `scan()` sends one. `enterprise_with_isrc_upc.json` is a one-chunk result that we recorded with `limit=1`.

### Stream callbacks

You'll receive callbacks with results and with notifications. `streams_callback_with_result.json` is a result, and `streams_callback_with_notification.json` is a notification with the code `650`. Give your handler the bytes of the file, as it would get them from the POST body. To send them to your receiver over HTTP instead, see [Test stream callbacks locally](/resources/recipes/test-callbacks-locally).

## The other recorded responses

The fixtures folder has a few more responses that you can use in the same way:

| File | What it is |
|---|---|
| `recognize_with_metadata.json` | a match with Apple Music, Spotify and MusicBrainz blocks |
| `recognize_custom_match.json` | a match from a custom catalog: only `timecode` and `audio_id` (built to the documented shape, not recorded) |
| `enterprise_custom_match.json` | an enterprise match from a custom catalog (built to the documented shape) |
| `error_700_no_file.json` | error `700`: no file or URL received |
| `error_904_enterprise_unauthorized.json` | error `904`: a URL sent to the enterprise endpoint without a paid plan |
| `error_902_stream_limit.json` | error `902` from `addStream`: the stream limit is reached |
| `error_19_no_callback_url.json` | error `19` from `getCallbackUrl`: no callback URL is set |
| `getStreams_empty.json` | `getStreams` on an account with no streams |

## The `test` token

You can use the public `test` token for examples, but it's limited to 10 requests a day on the standard endpoint, and the streams methods and the enterprise endpoint don't accept it. So it's good for your first call by hand, like the one below, and not for tests that run on every commit:

```bash
curl https://api.audd.io/ -F url=https://audd.tech/example.mp3 -F api_token=test
```

Get your own token at [dashboard.audd.io](https://dashboard.audd.io).

## What to check live before you launch

Recorded responses show that your code handles the responses, but not that the requests you send are right. So before you launch, send a few requests with your own token:

1. Recognize `https://audd.tech/example.mp3`. You should see "Everybody Wants To Rule The World" by Tears For Fears, which means that your token and your request are fine.
2. Try a recording from your app or your users, not just the example file. If the result is null, see [Audio format and quality](/resources/concepts/audio-format-and-quality).
3. If you use the enterprise endpoint, send one file with `limit=1`. On the free trial, upload the file: sending a URL to the enterprise endpoint needs a paid plan, and the API returns error `904`.
4. If you use streams, receive one real callback on your receiver; see [Test stream callbacks locally](/resources/recipes/test-callbacks-locally).

These calls are counted like any other requests, and we count requests to the enterprise endpoint as 1 request per 12 seconds of audio. You can see your usage in the [dashboard](https://dashboard.audd.io) or with `audd usage`. When you're ready to launch, go through the [production checklist](/resources/concepts/production-checklist).

---

**Related**

- [Error codes reference](/resources/reference/errors)
- [Retries: what's safe to retry](/resources/concepts/retry-strategy)
- [Test stream callbacks locally](/resources/recipes/test-callbacks-locally)
- [Production checklist](/resources/concepts/production-checklist)
- [SDK method map](/resources/reference/sdk-method-map)
- [SDK docs](https://docs.audd.io/sdks)

## Sitemap

See the [resources sitemap](https://audd.io/resources/sitemap.md) for every guide and the [glossary](https://audd.io/resources/reference/glossary.md) for AudD terms.
