Testing your code

Fake Home Assistant above the wire or at it.

You can test code that uses the library without a Home Assistant, at two levels.

Above the wire: fake the transport

Implement entity.Transport and entity.Link and pass your fake to any domain package. These two interfaces do not gain methods within a major version.

At the wire: a fake REST API

api/apitest is an HTTP server that answers as you script it and records each request. A real api.Client talks to it.

package apitest_test

import (
	"context"
	"fmt"
	"testing"

	"github.com/taumatix/homeassistant-go/api/apitest"
)

func Example() {
	t := &testing.T{} // in a real test, use the *testing.T you are given
	server := apitest.New(t)
	server.HandleJSON(t, "GET", "/api/states", []map[string]any{{"entity_id": "switch.lamp", "state": "off"}})

	states, err := server.Client().GetStates(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Println(states[0].EntityID, states[0].State)
	// Output: switch.lamp off
}

At the wire: a real MQTT broker

mqtt/mqtttest starts a broker inside the test process. A real mqtt.Client connects to it, and the broker can publish commands, refuse or stall subscriptions, and drop a connection.

package mqtttest_test

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/taumatix/homeassistant-go/domains/switches"
	"github.com/taumatix/homeassistant-go/mqtt"
	"github.com/taumatix/homeassistant-go/mqtt/mqtttest"
)

// Example fakes Home Assistant at the broker: a real mqtt.Client serves a switch,
// and the test reads what reached the broker and sends a command back.
func Example() {
	t := &testing.T{} // in a real test, use the *testing.T you are given
	broker := mqtttest.New(t)
	defer broker.Stop() // a real *testing.T would do this for you

	ctx := context.Background()
	client := mqtt.NewClient(mqtt.WithBroker(broker.URL()), mqtt.WithClientID("lamp-service"))
	if err := client.Connect(ctx, nil); err != nil {
		panic(err)
	}
	defer func() { _ = client.Close(ctx) }()

	lamp, err := switches.NewDevice(ctx, client, "lamp")
	if err != nil {
		panic(err)
	}
	if err := lamp.ReportState(ctx, true); err != nil {
		panic(err)
	}

	// The broker records a publish just after acknowledging it, so wait for it
	// (in a real test, broker.AwaitPayload does this).
	var state string
	for deadline := time.Now().Add(5 * time.Second); state == "" && time.Now().Before(deadline); {
		state, _ = broker.Published(*lamp.Config().StateTopic)
		time.Sleep(5 * time.Millisecond)
	}
	fmt.Println(state)
	// Output: ON
}

Neither fake behaves like Home Assistant. For that, run your code against a real one, for example from its container image.