package control import ( "archive/tar" "bytes" "compress/gzip" "os" "path/filepath" "testing" ) func TestExtractTarGz(t *testing.T) { // Create a test tar.gz with a text file and a binary-like file var buf bytes.Buffer gw := gzip.NewWriter(&buf) tw := tar.NewWriter(gw) // Add a directory tw.WriteHeader(&tar.Header{ Name: "testdir/", Typeflag: tar.TypeDir, Mode: 0755, }) // Add a text file content := []byte("hello world") tw.WriteHeader(&tar.Header{ Name: "testdir/hello.txt", Size: int64(len(content)), Mode: 0644, }) tw.Write(content) // Add a binary file (fake ELF header) binContent := []byte{0x7f, 0x45, 0x4c, 0x46, 0x01, 0x02} tw.WriteHeader(&tar.Header{ Name: "testdir/edge-agent", Size: int64(len(binContent)), Mode: 0755, }) tw.Write(binContent) tw.Close() gw.Close() // Extract to temp dir dest, _ := os.MkdirTemp("", "ota-test-*") defer os.RemoveAll(dest) if err := extractTarGz(bytes.NewReader(buf.Bytes()), dest); err != nil { t.Fatalf("extractTarGz failed: %v", err) } // Verify extracted files helloPath := filepath.Join(dest, "testdir", "hello.txt") data, err := os.ReadFile(helloPath) if err != nil { t.Fatalf("hello.txt not found: %v", err) } if string(data) != "hello world" { t.Errorf("hello.txt content: got %q want %q", string(data), "hello world") } binPath := filepath.Join(dest, "testdir", "edge-agent") data, err = os.ReadFile(binPath) if err != nil { t.Fatalf("edge-agent not found: %v", err) } if !bytes.Equal(data, binContent) { t.Errorf("edge-agent content mismatch") } } func TestExtractTarGzInvalid(t *testing.T) { dest, _ := os.MkdirTemp("", "ota-test-*") defer os.RemoveAll(dest) if err := extractTarGz(bytes.NewReader([]byte("not a gzip")), dest); err == nil { t.Error("expected error for invalid gzip") } } func TestCopyFile(t *testing.T) { src, _ := os.CreateTemp("", "src-*") src.Write([]byte("test data")) src.Close() defer os.Remove(src.Name()) dst := src.Name() + ".copy" defer os.Remove(dst) if err := copyFile(src.Name(), dst); err != nil { t.Fatalf("copyFile failed: %v", err) } data, _ := os.ReadFile(dst) if string(data) != "test data" { t.Errorf("copy content: got %q want %q", string(data), "test data") } } func TestCopyFileNotFound(t *testing.T) { if err := copyFile("/nonexistent/file", "/tmp/dst"); err == nil { t.Error("expected error for nonexistent source") } }