Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions e2etests/cvd/common/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.

load("@rules_go//go:def.bzl", "go_library")
load("@rules_go//go:def.bzl", "go_library", "go_test")

go_library(
name = "common",
srcs = ["common.go"],
srcs = [
"common.go",
"cvd.go",
],
importpath = "github.com/google/android-cuttlefish/e2etests/cvd/common",
visibility = ["//visibility:public"],
deps = [
"@rules_go//go/runfiles",
],
)
)

go_test(
name = "common_test",
srcs = ["cvd_test.go"],
embed = [":common"],
)
69 changes: 50 additions & 19 deletions e2etests/cvd/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
"strings"
"syscall"
"testing"
"time"

"github.com/bazelbuild/rules_go/go/runfiles"
)
Expand Down Expand Up @@ -118,19 +119,42 @@ func (tc *TestContext) RunCmdWithEnv(command []string, envvars map[string]string

// Waits for a device to be available via adb.
func (tc *TestContext) RunAdbWaitForDevice() error {
adbCommand := []string{
"timeout",
"--kill-after=30s",
"29s",
"adb",
"wait-for-device",
}
if _, err := tc.RunCmd(adbCommand...); err != nil {
ctx, cancel := context.WithTimeout(tc.context, 30*time.Second)
defer cancel()
if _, err := runCmdWithContextEnv(ctx, []string{"adb", "wait-for-device"}, map[string]string{}); err != nil {
return fmt.Errorf("timed out waiting for Cuttlefish device to connect to adb: %w", err)
}
return nil
}

// Waits for a specific device serial to be available via adb.
func (tc *TestContext) RunAdbWaitForDeviceSerial(serial string) error {
ctx, cancel := context.WithTimeout(tc.context, 30*time.Second)
defer cancel()
if _, err := runCmdWithContextEnv(ctx, []string{"adb", "-s", serial, "wait-for-device"}, map[string]string{}); err != nil {
return fmt.Errorf("timed out waiting for device %s to connect to adb: %w", serial, err)
}
return nil
}

// Checks if adb shell is reachable for a given device serial.
func (tc *TestContext) IsAdbShellReachable(serial string) bool {
ctx, cancel := context.WithTimeout(tc.context, 5*time.Second)
defer cancel()
res, err := runCmdWithContextEnv(ctx, []string{"adb", "-s", serial, "shell", "echo", "ping"}, map[string]string{})
return err == nil && strings.Contains(res.Stdout, "ping")
}

// Waits for a device serial to disconnect from adb within the given timeout.
func (tc *TestContext) WaitForDeviceOffline(serial string, timeoutSeconds int) error {
ctx, cancel := context.WithTimeout(tc.context, time.Duration(timeoutSeconds)*time.Second)
defer cancel()
if _, err := runCmdWithContextEnv(ctx, []string{"adb", "-s", serial, "wait-for-disconnect"}, map[string]string{}); err != nil {
return fmt.Errorf("device %s did not disconnect within %d seconds: %w", serial, timeoutSeconds, err)
}
return nil
}

// Runs the given command with the existing envvars.
func (tc *TestContext) RunCmd(args ...string) (CommandOutput, error) {
command := []string{}
Expand Down Expand Up @@ -191,7 +215,7 @@ func (tc *TestContext) CVDFetch(args FetchArgs) (CommandOutput, error) {
if credentialArg != "" {
fetchCmd = append(fetchCmd, fmt.Sprintf("--credential_source=%s", credentialArg))
}
res, err := tc.RunCmd(fetchCmd...);
res, err := tc.RunCmd(fetchCmd...)
if err != nil {
log.Printf("Failed to fetch: %w", err)
return res, err
Expand Down Expand Up @@ -233,19 +257,13 @@ func (tc *TestContext) CVDCreate(args CreateArgs) (CommandOutput, error) {
return res, nil
}

// Performs `cvd stop`.
func (tc *TestContext) CVDStop() error {
// Runs a cvd command with the test environment (HOME=tempdir).
func (tc *TestContext) RunCVD(args ...string) (CommandOutput, error) {
tempdirEnv := map[string]string{
"HOME": tc.tempdir,
}

stopCmd := []string{tc.TargetBin(), "stop"}
if _, err := tc.RunCmdWithEnv(stopCmd, tempdirEnv); err != nil {
log.Printf("Failed to stop instance(s): %w", err)
return err
}

return nil
cvdCmd := append([]string{tc.TargetBin()}, args...)
return tc.RunCmdWithEnv(cvdCmd, tempdirEnv)
}

// Performs `HOME=<testdir> bin/launch_cvd <args>`.
Expand Down Expand Up @@ -363,6 +381,14 @@ func (tc *TestContext) GetSyspropString(key string) (string, error) {
return strings.TrimSpace(res.Stdout), nil
}

func (tc *TestContext) GetSyspropStringForDevice(serial, key string) (string, error) {
res, err := tc.RunCmd("adb", "-s", serial, "shell", "getprop", key)
if err != nil {
return "", fmt.Errorf("failed to get sysprop %s on device %s: %w", key, serial, err)
}
return strings.TrimSpace(res.Stdout), nil
}

// Creates a standard environment for an e2etests.
func (tc *TestContext) SetUp(t *testing.T) {
tc.t = t
Expand All @@ -379,6 +405,11 @@ func (tc *TestContext) SetUp(t *testing.T) {
}
log.Printf("Finished cleaning up any pre-existing instances!")

log.Printf("Starting adb server...")
if _, err := tc.RunCmd("adb", "start-server"); err != nil {
log.Printf("Failed to start adb server: %v", err)
}

tc.tempdir = tc.t.TempDir()

log.Printf("Chdir to %s", tc.tempdir)
Expand Down
204 changes: 204 additions & 0 deletions e2etests/cvd/common/cvd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
// Copyright (C) 2026 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package e2etests

import (
"encoding/json"
"fmt"
"log"
"strings"
)

// CVDInstanceStatusEntry represents a single instance's status in `cvd status --print` JSON output.
type CVDInstanceStatusEntry struct {
AdbPort int `json:"adb_port"`
AdbSerial string `json:"adb_serial"`
AssemblyDir string `json:"assembly_dir"`
InstanceDir string `json:"instance_dir"`
InstanceName string `json:"instance_name"`
Status string `json:"status"`
WebAccess string `json:"web_access"`
WebRtcDeviceID string `json:"webrtc_device_id"`
}

// ParseCVDStatusJSON parses the JSON output returned by `cvd status --print`.
// It handles single-instance object, multi-instance array `[...]`, and group object `{"instances": [...]}` formats.
func ParseCVDStatusJSON(output string) ([]CVDInstanceStatusEntry, error) {
// 1. Try group object format: {"instances": [...]}
startObj := strings.Index(output, "{")
endObj := strings.LastIndex(output, "}")
if startObj != -1 && endObj > startObj {
jsonStr := strings.TrimSpace(output[startObj : endObj+1])
var group struct {
Instances *[]CVDInstanceStatusEntry `json:"instances"`
}
if err := json.Unmarshal([]byte(jsonStr), &group); err == nil && group.Instances != nil {
return *group.Instances, nil
}
}

// 2. Try array format: [...]
// Sift past any potential leading bracketed log prefixes (e.g. "[INFO ...]")
for idx := strings.Index(output, "["); idx != -1; {
endArray := strings.LastIndex(output, "]")
if endArray > idx {
jsonStr := strings.TrimSpace(output[idx : endArray+1])
var entries []CVDInstanceStatusEntry
if err := json.Unmarshal([]byte(jsonStr), &entries); err == nil && len(entries) > 0 {
return entries, nil
}
}
next := strings.Index(output[idx+1:], "[")
if next == -1 {
break
}
idx += 1 + next
}

// 3. Try single instance object format: {"instance_name": ..., "status": ...}
if startObj != -1 && endObj > startObj {
jsonStr := strings.TrimSpace(output[startObj : endObj+1])
var single CVDInstanceStatusEntry
if err := json.Unmarshal([]byte(jsonStr), &single); err == nil && (single.InstanceName != "" || single.Status != "") {
return []CVDInstanceStatusEntry{single}, nil
}
}

return nil, fmt.Errorf("failed to parse cvd status json from output: %s", output)
}

// CVDStop performs `cvd stop <args>`.
func (tc *TestContext) CVDStop(args ...string) error {
stopCmd := append([]string{"stop"}, args...)
if _, err := tc.RunCVD(stopCmd...); err != nil {
log.Printf("Failed to stop instance(s): %v", err)
return err
}
return nil
}

// CVDStart performs `cvd start <args>`.
func (tc *TestContext) CVDStart(args ...string) error {
startCmd := append([]string{"start"}, args...)
if _, err := tc.RunCVD(startCmd...); err != nil {
log.Printf("Failed to start instance(s): %v", err)
return err
}
return nil
}

// CVDRestart performs `cvd restart <args>`.
func (tc *TestContext) CVDRestart(args ...string) error {
restartCmd := append([]string{"restart"}, args...)
if _, err := tc.RunCVD(restartCmd...); err != nil {
log.Printf("Failed to restart instance(s): %v", err)
return err
}
return nil
}

// CVDStatus performs `cvd status --print <args>` and parses the status JSON.
func (tc *TestContext) CVDStatus(args ...string) ([]CVDInstanceStatusEntry, error) {
statusCmd := append([]string{"status", "--print"}, args...)
out, err := tc.RunCVD(statusCmd...)
if err != nil {
return nil, fmt.Errorf("cvd status failed: %w", err)
}
return ParseCVDStatusJSON(out.Stdout)
}

// CVDInstanceStop performs `cvd --instance_name=<instanceName> stop <args>`.
func (tc *TestContext) CVDInstanceStop(instanceName string, args ...string) error {
cmd := []string{fmt.Sprintf("--instance_name=%s", instanceName), "stop"}
cmd = append(cmd, args...)
if _, err := tc.RunCVD(cmd...); err != nil {
log.Printf("Failed to stop instance %s: %v", instanceName, err)
return err
}
return nil
}

// CVDInstanceStart performs `cvd --instance_name=<instanceName> start <args>`.
func (tc *TestContext) CVDInstanceStart(instanceName string, args ...string) error {
cmd := []string{fmt.Sprintf("--instance_name=%s", instanceName), "start"}
cmd = append(cmd, args...)
if _, err := tc.RunCVD(cmd...); err != nil {
log.Printf("Failed to start instance %s: %v", instanceName, err)
return err
}
return nil
}

// CVDInstanceRestart performs `cvd --instance_name=<instanceName> restart <args>`.
func (tc *TestContext) CVDInstanceRestart(instanceName string, args ...string) error {
cmd := []string{fmt.Sprintf("--instance_name=%s", instanceName), "restart"}
cmd = append(cmd, args...)
if _, err := tc.RunCVD(cmd...); err != nil {
log.Printf("Failed to restart instance %s: %v", instanceName, err)
return err
}
return nil
}

// CVDInstanceStatus performs `cvd --instance_name=<instanceName> status --print <args>` and parses the status JSON.
func (tc *TestContext) CVDInstanceStatus(instanceName string, args ...string) ([]CVDInstanceStatusEntry, error) {
cmd := []string{fmt.Sprintf("--instance_name=%s", instanceName), "status", "--print"}
cmd = append(cmd, args...)
out, err := tc.RunCVD(cmd...)
if err != nil {
return nil, fmt.Errorf("cvd status failed for instance %s: %w", instanceName, err)
}
return ParseCVDStatusJSON(out.Stdout)
}

// CVDStop performs `cvd stop <args>` on the given TestContext.
func CVDStop(tc *TestContext, args ...string) error {
return tc.CVDStop(args...)
}

// CVDStart performs `cvd start <args>` on the given TestContext.
func CVDStart(tc *TestContext, args ...string) error {
return tc.CVDStart(args...)
}

// CVDRestart performs `cvd restart <args>` on the given TestContext.
func CVDRestart(tc *TestContext, args ...string) error {
return tc.CVDRestart(args...)
}

// CVDStatus performs `cvd status --print <args>` and parses the status JSON on the given TestContext.
func CVDStatus(tc *TestContext, args ...string) ([]CVDInstanceStatusEntry, error) {
return tc.CVDStatus(args...)
}

// CVDInstanceStop performs `cvd --instance_name=<instanceName> stop <args>` on the given TestContext.
func CVDInstanceStop(tc *TestContext, instanceName string, args ...string) error {
return tc.CVDInstanceStop(instanceName, args...)
}

// CVDInstanceStart performs `cvd --instance_name=<instanceName> start <args>` on the given TestContext.
func CVDInstanceStart(tc *TestContext, instanceName string, args ...string) error {
return tc.CVDInstanceStart(instanceName, args...)
}

// CVDInstanceRestart performs `cvd --instance_name=<instanceName> restart <args>` on the given TestContext.
func CVDInstanceRestart(tc *TestContext, instanceName string, args ...string) error {
return tc.CVDInstanceRestart(instanceName, args...)
}

// CVDInstanceStatus performs `cvd --instance_name=<instanceName> status --print <args>` and parses the status JSON on the given TestContext.
func CVDInstanceStatus(tc *TestContext, instanceName string, args ...string) ([]CVDInstanceStatusEntry, error) {
return tc.CVDInstanceStatus(instanceName, args...)
}
Loading
Loading