moonvader
moonvader

Reputation: 21111

Execute shell script before UI Test for iOS app starts

I have UI test (for an iOS app) that opens iOS photo gallery and taps on specific image. I want to have custom script that will copy this image to simulator's photo gallery at the beginning of the test of even right before it will start.

I have sh script that works when I manually run it after simulator is launched, but I want it to be executed during test run on Xcode Cloud.

This is script code

#!/bin/bash

# Get the UDID of the simulator (adjust for your target simulator)
SIMULATOR_UDID=$(xcrun simctl list devices | grep "Booted" | awk -F '[()]' '{print $2}')

# Path to the image
IMAGE_PATH="./myImage.jpg"

# Add the image to the simulator gallery
xcrun simctl addmedia $SIMULATOR_UDID $IMAGE_PATH

I already tried to add it to pre-test actions for Test Scheme and to Build Phases of UI test target - no luck, I even wasn't able to find logs related to this script execution.

Upvotes: 0

Views: 205

Answers (2)

Herlandro Hermogenes
Herlandro Hermogenes

Reputation: 1111

Try this script code:

#!/bin/bash

# Ensure the script logs output for debugging
set -x

# Path to the image (adjust if necessary)
IMAGE_PATH="$SRCROOT/myImage.jpg"

# Get the UDID from environment variable
SIMULATOR_UDID="$TARGET_DEVICE_IDENTIFIER"

# Wait until the simulator is booted
boot_status=$(xcrun simctl bootstatus "$SIMULATOR_UDID" -b)
if [ $? -ne 0 ]; then
  echo "Simulator failed to boot"
  exit 1
fi

# Add the image to the simulator gallery
xcrun simctl addmedia "$SIMULATOR_UDID" "$IMAGE_PATH"

Steps to Implement

Script

  • Go to Edit Scheme > Test > Pre-Actions.
  • Click the “+” button and select New Run Script Action.
  • In the script editor, paste the fixed script above.
  • Check the Provide build settings from option and select your app target. This makes TARGET_DEVICE_IDENTIFIER available and you avoid parsing and potential errors from xcrun simctl list.

Logging

  • The set -x command enables a mode of the shell where all executed commands are printed to the terminal.
  • You can redirect the script output to a file if needed for debugging.

Image Path

  • Make sure myImage.jpg is included in your project directory.
  • Adjust IMAGE_PATH if the image is located elsewhere.

Simulator Boot

  • The xcrun simctl bootstatus command waits until the simulator is fully booted.
  • The -b flag makes the command block until boot is complete.
  • Waiting for the simulator to boot ensures that addmedia doesn’t fail due to the simulator not being ready.

When running on Xcode Cloud, make sure that your image file is included in the build artifacts or accessible at the specified path.

Upvotes: 1

Kostiantyn Bilyk
Kostiantyn Bilyk

Reputation: 61

Here is detailed answer on the matter of scripts for Xcode Cloud. And this is related apple documentation page. Please, let me know if it helped.

Upvotes: 0

Related Questions