Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Support for Parsing .xctestrun file and use it to start xctest #525

Merged
merged 26 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
4bcc386
Add Support for Parsing .xctestrun file and use it to Start XCTest
bahrimootaz Dec 6, 2024
8e6375b
Add Support for Parsing .xctestrun file and use it to Start XCTest
bahrimootaz Dec 6, 2024
f1f4734
Add Support for Parsing .xctestrun file and use it to Start XCTest
bahrimootaz Dec 6, 2024
8451b6b
Add Support for Parsing .xctestrun file and use it to Start XCTest
bahrimootaz Dec 6, 2024
77167b8
Read all test configs from xctestrun file.
bahrimootaz Dec 6, 2024
6716cf6
Read all test configs from xctestrun file
bahrimootaz Dec 10, 2024
c088386
Merge pull request #1 from bahrimootaz/parse_all_test_config
bahrimootaz Dec 10, 2024
2df460e
fix parsing of the testingEnvVars
bahrimootaz Dec 10, 2024
5b61d8d
use a SchemeData while parsing xctestrun file to host the test configs
bahrimootaz Dec 11, 2024
5d7b9d0
Read all test configs from xctestrun file
bahrimootaz Dec 11, 2024
567570d
Read all test configs from xctestrun file
bahrimootaz Dec 11, 2024
11c4fba
optimize building the TestConfig from the parsed xctestrun file
bahrimootaz Dec 11, 2024
97319ec
Read all test configs from xctestrun file
bahrimootaz Dec 11, 2024
25364bd
Encapsulate the construction of the test config to 'xctestrun' parser…
bahrimootaz Dec 11, 2024
0d94d11
Resolve threads and add unit tests
bahrimootaz Dec 12, 2024
ca2e4f1
refactor testing to make it easy to read
bahrimootaz Dec 12, 2024
c85454c
Read all test configs from xctestrun file
bahrimootaz Dec 12, 2024
a80601d
resolve comments
bahrimootaz Dec 12, 2024
262b817
update comment
bahrimootaz Dec 12, 2024
ad2f45b
update class description
bahrimootaz Dec 12, 2024
4ba1cde
Merge branch 'main' into main
bahrimootaz Dec 12, 2024
6578be9
update variable names for clarity
bahrimootaz Dec 12, 2024
6e3d856
Add unit test for parsing IsUITestBundle from xctestrun file
bahrimootaz Dec 16, 2024
3e1b3d8
Add unit test for parsing IsUITestBundle from xctestrun file
bahrimootaz Dec 17, 2024
9194d63
Add unit test for parsing IsUITestBundle from xctestrun file
bahrimootaz Dec 18, 2024
c584aa8
Merge branch 'danielpaulus:main' into main
bahrimootaz Dec 19, 2024
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
129 changes: 129 additions & 0 deletions ios/testmanagerd/xctestrunnerutils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package testmanagerd

import (
"fmt"
"os"
"testing"

"github.com/stretchr/testify/assert"
)

func TestParseXCTestRun(t *testing.T) {
// Arrange: Create a temporary .xctestrun file with mock data
tempFile, err := os.CreateTemp("", "testfile*.xctestrun")
assert.NoError(t, err, "Failed to create temp file")
defer os.Remove(tempFile.Name()) // Cleanup after test

mockData := `
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>RunnerTests</key>
<dict>
<key>BlueprintName</key>
<string>RunnerTests</string>
<key>BlueprintProviderName</key>
<string>Runner</string>
<key>BlueprintProviderRelativePath</key>
<string>Runner.xcodeproj</string>
<key>BundleIdentifiersForCrashReportEmphasis</key>
<array>
<string>com.example.myApp</string>
<string>com.example.myApp.RunnerTests</string>
</array>
<key>CommandLineArguments</key>
<array/>
<key>DefaultTestExecutionTimeAllowance</key>
<integer>600</integer>
<key>DependentProductPaths</key>
<array>
<string>__TESTROOT__/Release-iphoneos/Runner.app</string>
<string>__TESTROOT__/Release-iphoneos/Runner.app/PlugIns/RunnerTests.xctest</string>
</array>
<key>DiagnosticCollectionPolicy</key>
<integer>1</integer>
<key>EnvironmentVariables</key>
<dict>
<key>APP_DISTRIBUTOR_ID_OVERRIDE</key>
<string>com.apple.AppStore</string>
<key>OS_ACTIVITY_DT_MODE</key>
<string>YES</string>
<key>SQLITE_ENABLE_THREAD_ASSERTIONS</key>
<string>1</string>
<key>TERM</key>
<string>dumb</string>
</dict>
<key>IsAppHostedTestBundle</key>
<true/>
<key>ParallelizationEnabled</key>
<true/>
<key>PreferredScreenCaptureFormat</key>
<string>screenRecording</string>
<key>ProductModuleName</key>
<string>RunnerTests</string>
<key>RunOrder</key>
<integer>0</integer>
<key>SystemAttachmentLifetime</key>
<string>deleteOnSuccess</string>
<key>TestBundlePath</key>
<string>__TESTHOST__/PlugIns/RunnerTests.xctest</string>
<key>TestHostBundleIdentifier</key>
<string>com.example.myApp</string>
<key>TestHostPath</key>
<string>__TESTROOT__/Release-iphoneos/Runner.app</string>
<key>TestLanguage</key>
<string></string>
<key>TestRegion</key>
<string></string>
<key>TestTimeoutsEnabled</key>
<false/>
<key>TestingEnvironmentVariables</key>
<dict>
<key>DYLD_INSERT_LIBRARIES</key>
<string>__TESTHOST__/Frameworks/libXCTestBundleInject.dylib</string>
<key>XCInjectBundleInto</key>
<string>unused</string>
</dict>
<key>ToolchainsSettingValue</key>
<array/>
<key>UserAttachmentLifetime</key>
<string>deleteOnSuccess</string>
</dict>
<key>__xctestrun_metadata__</key>
<dict>
<key>ContainerInfo</key>
<dict>
<key>ContainerName</key>
<string>Runner</string>
<key>SchemeName</key>
<string>Runner</string>
</dict>
<key>FormatVersion</key>
<integer>1</integer>
</dict>
</dict>
</plist>
`
_, err = tempFile.WriteString(mockData)
assert.NoError(t, err, "Failed to write mock data to temp file")
tempFile.Close()

// Act: Use the codec to parse the temp file
codec := NewXCTestRunCodec()
data, err := codec.ParseFile(tempFile.Name())

// Print the parsed data before asserting
fmt.Printf("Parsed Data: %+v\n", data)

// Assert: Verify the parsed data
assert.NoError(t, err, "Failed to parse .xctestrun file")
assert.NotNil(t, data, "Parsed data should not be nil")

// Check specific fields in the parsed data
assert.Equal(t, "com.example.myApp", data.RunnerTests.TestHostBundleIdentifier, "TestHostBundleIdentifier mismatch")
assert.Equal(t, "__TESTHOST__/PlugIns/RunnerTests.xctest", data.RunnerTests.TestBundlePath, "TestBundlePath mismatch")

// Assert XCTestRunMetadata values
assert.Equal(t, 1, data.XCTestRunMetadata.FormatVersion, "FormatVersion mismatch")
}
64 changes: 64 additions & 0 deletions ios/testmanagerd/xctestrunutils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package testmanagerd

import (
"bytes"
"errors"
"fmt"
"io"
"os"

log "github.com/sirupsen/logrus"
"howett.net/plist"
)

type XCTestRunData struct {
RunnerTests struct {
TestHostBundleIdentifier string `plist:"TestHostBundleIdentifier"`
TestBundlePath string `plist:"TestBundlePath"`
} `plist:"RunnerTests"`
XCTestRunMetadata struct {
FormatVersion int `plist:"FormatVersion"`
} `plist:"__xctestrun_metadata__"`
}

// XCTestRunCodec handles encoding and decoding operations for .xctestrun files
type XCTestRunCodec struct{}
bahrimootaz marked this conversation as resolved.
Show resolved Hide resolved

// NewXCTestRunCodec creates a new instance of XCTestRunCodec
func NewXCTestRunCodec() XCTestRunCodec {
return XCTestRunCodec{}
}

// ParseFile reads the .xctestrun file and decodes it into a map
func (codec XCTestRunCodec) ParseFile(filePath string) (XCTestRunData, error) {
file, err := os.Open(filePath)
if err != nil {
return XCTestRunData{}, fmt.Errorf("failed to open xctestrun file: %w", err)
}
defer file.Close()

return codec.Decode(file)
}

// Decode reads and decodes the binary xctestrun content from a reader
func (codec XCTestRunCodec) Decode(r io.Reader) (XCTestRunData, error) {
if r == nil {
return XCTestRunData{}, errors.New("reader was nil")
}

var result XCTestRunData
buf := new(bytes.Buffer)
_, err := io.Copy(buf, r) // Read the entire file content
if err != nil {
return XCTestRunData{}, fmt.Errorf("failed to read file content: %w", err)
}

// Decode the xctestrun content into the struct
_, err = plist.Unmarshal(buf.Bytes(), &result)
if err != nil {
return XCTestRunData{}, fmt.Errorf("failed to decode xctestrun content: %w", err)
}

log.Tracef("Successfully parsed .xctestrun file: %v", result)
return result, nil
}
46 changes: 42 additions & 4 deletions ios/testmanagerd/xcuitestrunner.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"maps"
"path"
"path/filepath"
"strings"

"github.com/Masterminds/semver"
Expand Down Expand Up @@ -249,6 +250,40 @@ type TestConfig struct {
Listener *TestListener
}

func StartXCTestWithConfig(ctx context.Context, xctestrunFilePath string, testsToSkip []string, testsToRun []string, testArgs []string, testEnv map[string]interface{}, device ios.DeviceEntry, listener *TestListener) ([]TestSuite, error) {
// Parse the .xctestrun file to get the necessary details for TestConfig
codec := NewXCTestRunCodec()
result, err := codec.ParseFile(xctestrunFilePath)
if err != nil {
log.Errorf("Error parsing xctestrun file: %v", err)
return nil, err
}

// Verify that the FormatVersion is 1
if result.XCTestRunMetadata.FormatVersion != 1 {
log.Errorf("Invalid FormatVersion in .xctestrun file: got %d, expected 1", result.XCTestRunMetadata.FormatVersion)
return nil, fmt.Errorf("invalid FormatVersion in .xctestrun file: %d (expected 1)", result.XCTestRunMetadata.FormatVersion)
}

// Extract only the file name
var testBundlePath = filepath.Base(result.RunnerTests.TestBundlePath)

// Build the TestConfig object from parsed data
testConfig := TestConfig{
TestRunnerBundleId: result.RunnerTests.TestHostBundleIdentifier,
XctestConfigName: testBundlePath,
Args: testArgs,
Env: testEnv,
TestsToRun: testsToRun,
TestsToSkip: testsToSkip,
XcTest: true,
Device: device,
Listener: listener,
}
bahrimootaz marked this conversation as resolved.
Show resolved Hide resolved

return RunTestWithConfig(ctx, testConfig)
}

func RunTestWithConfig(ctx context.Context, testConfig TestConfig) ([]TestSuite, error) {
if len(testConfig.TestRunnerBundleId) == 0 {
return nil, fmt.Errorf("RunTestWithConfig: testConfig.TestRunnerBundleId can not be empty")
Expand Down Expand Up @@ -461,11 +496,14 @@ func startTestRunner17(appserviceConn *appservice.Connection, bundleID string, s
log.Debugf("adding extra env %s=%s", key, value)
}
}
var opts = map[string]interface{}{}

opts := map[string]interface{}{
"ActivateSuspended": uint64(1),
"StartSuspendedKey": uint64(0),
"__ActivateSuspended": uint64(1),
if !isXCTest {
opts = map[string]interface{}{
"ActivateSuspended": uint64(1),
"StartSuspendedKey": uint64(0),
"__ActivateSuspended": uint64(1),
}
}

appLaunch, err := appserviceConn.LaunchAppWithStdIo(
Expand Down
51 changes: 51 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ Usage:
ios kill (<bundleID> | --pid=<processID> | --process=<processName>) [options]
ios memlimitoff (--process=<processName>) [options]
ios runtest [--bundle-id=<bundleid>] [--test-runner-bundle-id=<testrunnerbundleid>] [--xctest-config=<xctestconfig>] [--log-output=<file>] [--xctest] [--test-to-run=<tests>]... [--test-to-skip=<tests>]... [--env=<e>]... [options]
ios runxctest [--xctestrun-file-path=<xctestrunFilePath>] [--log-output=<file>] [--test-to-run=<tests>]... [--test-to-skip=<tests>]... [--env=<e>]... [options]
bahrimootaz marked this conversation as resolved.
Show resolved Hide resolved
ios runwda [--bundleid=<bundleid>] [--testrunnerbundleid=<testbundleid>] [--xctestconfig=<xctestconfig>] [--log-output=<file>] [--arg=<a>]... [--env=<e>]... [options]
ios ax [--font=<fontSize>] [options]
ios debug [options] [--stop-at-entry] <app_path>
Expand Down Expand Up @@ -232,6 +233,10 @@ The commands work as following:
> If you provide '-' as log output, it prints resuts to stdout.
> To be able to filter for tests to run or skip, use one argument per test selector. Example: runtest --test-to-run=(TestTarget.)TestClass/testMethod --test-to-run=(TestTarget.)TestClass/testMethod (the value for 'TestTarget' is optional)
> The method name can also be omitted and in this case all tests of the specified class are run
ios runxctest [--xctestrun-file-path=<xctestrunFilePath>] [--log-output=<file>] [--test-to-run=<tests>]... [--test-to-skip=<tests>]... [--env=<e>]... [options] Run a XCTest. The --xctestrun-file-path specifies the path to the .xctestrun file to configure the test execution.
bahrimootaz marked this conversation as resolved.
Show resolved Hide resolved
> If you provide '-' as log output, it prints resuts to stdout.
> To be able to filter for tests to run or skip, use one argument per test selector. Example: runxctest --test-to-run=(TestTarget.)TestClass/testMethod --test-to-run=(TestTarget.)TestClass/testMethod (the value for 'TestTarget' is optional)
bahrimootaz marked this conversation as resolved.
Show resolved Hide resolved
> The method name can also be omitted and in this case all tests of the specified class are run
ios runwda [--bundleid=<bundleid>] [--testrunnerbundleid=<testbundleid>] [--xctestconfig=<xctestconfig>] [--log-output=<file>] [--arg=<a>]... [--env=<e>]...[options] runs WebDriverAgents
> specify runtime args and env vars like --env ENV_1=something --env ENV_2=else and --arg ARG1 --arg ARG2
ios ax [--font=<fontSize>] [options] Access accessibility inspector features.
Expand Down Expand Up @@ -1001,6 +1006,52 @@ The commands work as following:
return
}

b, _ = arguments.Bool("runxctest")
if b {
xctestrunFilePath, _ := arguments.String("--xctestrun-file-path")

testsToRunArg := arguments["--test-to-run"]
var testsToRun []string
if testsToRunArg != nil && len(testsToRunArg.([]string)) > 0 {
testsToRun = testsToRunArg.([]string)
}

testsToSkipArg := arguments["--test-to-skip"]
var testsToSkip []string
testsToSkip = nil
if testsToSkipArg != nil && len(testsToSkipArg.([]string)) > 0 {
testsToSkip = testsToSkipArg.([]string)
}

rawTestlog, rawTestlogErr := arguments.String("--log-output")
env := splitKeyValuePairs(arguments["--env"].([]string), "=")

if rawTestlogErr == nil {
var writer *os.File = os.Stdout
if rawTestlog != "-" {
file, err := os.Create(rawTestlog)
exitIfError("Cannot open file "+rawTestlog, err)
writer = file
}
defer writer.Close()
var listener = testmanagerd.NewTestListener(writer, writer, os.TempDir())

testResults, err := testmanagerd.StartXCTestWithConfig(context.TODO(), xctestrunFilePath, testsToSkip, testsToRun, []string{}, env, device, listener)
if err != nil {
log.WithFields(log.Fields{"error": err}).Info("Failed running Xctest")
}

log.Info(fmt.Printf("%+v", testResults))
} else {
var listener = testmanagerd.NewTestListener(io.Discard, io.Discard, os.TempDir())
_, err := testmanagerd.StartXCTestWithConfig(context.TODO(), xctestrunFilePath, testsToSkip, testsToRun, []string{}, env, device, listener)
if err != nil {
log.WithFields(log.Fields{"error": err}).Info("Failed running Xctest")
}
}
return
}

if runWdaCommand(device, arguments) {
return
}
Expand Down
Loading