Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
sysotad_test.go 2.46 KiB
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Huawei Inc.
package cmdsysotad_test

import (
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"booting.oniroproject.org/distro/components/sysota/cmd/sysotad/cmdsysotad"
	"booting.oniroproject.org/distro/components/sysota/dbusutil/dbustest"

	. "gopkg.in/check.v1"
)

func Test(t *testing.T) { TestingT(t) }

type sysotadSuite struct {
	dbustest.Suite

	stdout bytes.Buffer
	stderr bytes.Buffer
}

var _ = Suite(&sysotadSuite{})

func (s *sysotadSuite) SetUpSuite(c *C) {
	s.Suite.SetUpSuite(c)

	cmdsysotad.Stdout = &s.stdout
	cmdsysotad.Stderr = &s.stderr
}

func (s *sysotadSuite) TearDownSuite(c *C) {
	cmdsysotad.Stdout = os.Stdout
	cmdsysotad.Stderr = os.Stderr

	s.Suite.TearDownSuite(c)
}

func (s *sysotadSuite) SetUpTest(c *C) {
	s.stdout.Reset()
	s.stderr.Reset()
}

func (s *sysotadSuite) TestStartupAndIdleShutdown(c *C) {
	opts := cmdsysotad.DefaultOptions()
	opts.IdleDuration = time.Second
	opts.StateFile = filepath.Join(c.MkDir(), "non-existent/state.ini")

	err := cmdsysotad.Run(opts)

	c.Assert(err, IsNil)
	c.Check(s.stdout.String(), Equals, ""+
		"Listening ...\n"+
		"Exiting due to inactivity\n")
	c.Check(s.stderr.String(), Equals, "")
}

func (s *sysotadSuite) TestStateFileSavedOnExit(c *C) {
	d := c.MkDir()
	stateFile := filepath.Join(d, "state.ini")

	opts := cmdsysotad.DefaultOptions()
	opts.IdleDuration = time.Second
	opts.StateFile = stateFile
	err := cmdsysotad.Run(opts)

	c.Assert(err, IsNil)
	c.Check(s.stdout.String(), Equals, ""+
		"Listening ...\n"+
		"Exiting due to inactivity\n"+
		"System state saved to "+stateFile+"\n")
	c.Check(s.stderr.String(), Equals, "")

	// The zero value is an empty state file but it gets created.
	fi, err := os.Stat(stateFile)
	c.Assert(err, IsNil)
	c.Check(fi.Size(), Equals, int64(0))
}

func (s *sysotadSuite) TestStateLoadSaveDance(c *C) {
	d := c.MkDir()
	stateFile := filepath.Join(d, "state.ini")
	err := ioutil.WriteFile(stateFile, []byte("[System]\nBootMode=try\n"), 0600)
	c.Assert(err, IsNil)

	opts := cmdsysotad.DefaultOptions()
	opts.IdleDuration = time.Second
	opts.StateFile = stateFile

	err = cmdsysotad.Run(opts)
	c.Assert(err, IsNil)

	c.Check(s.stdout.String(), Equals, ""+
		"Listening ...\n"+
		"Exiting due to inactivity\n"+
		"System state saved to "+stateFile+"\n")
	c.Check(s.stderr.String(), Equals, "")

	data, err := ioutil.ReadFile(stateFile)
	c.Assert(err, IsNil)
	c.Check(data, DeepEquals, []byte("[System]\nBootMode=try\n"))
}