Skip to content

Commit

Permalink
journal: add proper StderrIsJournalStream test
Browse files Browse the repository at this point in the history
To ensure that StderrIsJournalStream properly works in real conditions,
this test re-executes itself with systemd-run, and observes exit code
and logged entries.
  • Loading branch information
WGH- committed Nov 7, 2022
1 parent fe8fac5 commit 4ca6222
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion journal/journal_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ package journal_test
import (
"fmt"
"os"
"os/exec"
"syscall"
"testing"

"github.com/coreos/go-systemd/v22/journal"
)

func TestStderrIsJournalStream(t *testing.T) {
func TestJournalStreamParsing(t *testing.T) {
if _, ok := os.LookupEnv("JOURNAL_STREAM"); ok {
t.Fatal("unset JOURNAL_STREAM before running this test")
}
Expand Down Expand Up @@ -84,6 +85,51 @@ func TestStderrIsJournalStream(t *testing.T) {
})
}

func TestStderrIsJournalStream(t *testing.T) {
const (
message = "TEST_MESSAGE"
)

userOrSystem := "--user"
if os.Getuid() == 0 {
userOrSystem = "--system"
}

if _, ok := os.LookupEnv("JOURNAL_STREAM"); !ok {
// Re-execute this test under systemd (see the else branch),
// and observe its exit code.
args := []string{
"systemd-run",
userOrSystem,
"--wait",
"--quiet",
"--",
os.Args[0],
"-test.run=TestStderrIsJournalStream",
"-test.count=1", // inhibit caching
}

cmd := exec.Command(args[0], args[1:]...)
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
} else {
ok, err := journal.StderrIsJournalStream()
if err != nil {
t.Fatal(err)
}
if !ok {
t.Fatal("StderrIsJournalStream should've returned true")
}

err = journal.Send(message, journal.PriInfo, nil)
if err != nil {
t.Fatal(err)
}
}
}

func ExampleStderrIsJournalStream() {
// NOTE: this is just an example. Production code
// will likely use this to setup a logging library
Expand Down

0 comments on commit 4ca6222

Please sign in to comment.