stillya / testcontainers-keycloak

A Testcontainers implementation for Keycloak SSO.
MIT License
4 stars 4 forks source link
golang keycloak testcontainers

Keycloak Testcontainer - testcontainers implementation for Keycloak SSO.

Build Status Coverage Go Reference

Installation

go get github.com/stillya/testcontainers-keycloak

Usage

package main

import (
    "context"
    "fmt"
    keycloak "github.com/stillya/testcontainers-keycloak"
    "github.com/testcontainers/testcontainers-go"
    "github.com/testcontainers/testcontainers-go/wait"
    "os"
    "testing"
)

var keycloakContainer *keycloak.KeycloakContainer

func Test_Example(t *testing.T) {
    ctx := context.Background()

    authServerURL, err := keycloakContainer.GetAuthServerURL(ctx)
    if err != nil {
        t.Errorf("GetAuthServerURL() error = %v", err)
        return
    }

    fmt.Println(authServerURL)
    // Output:
    // http://localhost:32768/auth
}

func TestMain(m *testing.M) {
    defer func() {
        if r := recover(); r != nil {
            shutDown()
            fmt.Println("Panic")
        }
    }()
    setup()
    code := m.Run()
    shutDown()
    os.Exit(code)
}

func setup() {
    var err error
    ctx := context.Background()
    keycloakContainer, err = RunContainer(ctx)
    if err != nil {
        panic(err)
    }
}

func shutDown() {
    ctx := context.Background()
    err := keycloakContainer.Terminate(ctx)
    if err != nil {
        panic(err)
    }
}

func RunContainer(ctx context.Context) (*keycloak.KeycloakContainer, error) {
    return keycloak.RunContainer(ctx,
        "quay.io/keycloak/keycloak:24.0",
        keycloak.WithContextPath("/auth"),
        keycloak.WithRealmImportFile("../testdata/realm-export.json"),
        keycloak.WithAdminUsername("admin"),
        keycloak.WithAdminPassword("admin"),
    )
}