Is there a way to switch an XCTest unit test into the right-to-left mode to test Arabic version of the app where sentences are written from right to left of the screen? My app code logic behaves differently based on language direction. I would like to verify this functionality in a unit test. What I need to do is to switch the app into the right-to-left language mode from an XCTest unit test case.
One can run the app in the right-to-left mode by changing the Scheme's Application language settings to Right-to-left Pseudolanguage. Is there a way to do similar thing in a unit test?
My imperfect solution
I ended up changing semanticContentAttribute of a view under test to .ForceRightToLeft. It does what I need to do. It does not feel like a very clean approach though. Firstly, it only works in iOS 9. Secondly, it looks like I am tinkering with my app views on a low level from the unit test. Instead, I would prefer to switch the whole app's language to right-to-left if it is possible.
class MyTests: XCTestCase {
func testRightToLeft() {
if #available(iOS 9.0, *) {
let view = UIView()
view.semanticContentAttribute = .ForceRightToLeft
// Test code involving the view
}
}
}
There's no easy way to do this right now with testing/UI testing besides passing in environment flags or setting the semanticContentAttribute as you are doing now. Filing a bug to Apple is highly recommended.
You can also change the device language & region in the scheme. This means you'll need separate schemes for the various LTR/RTL tests you want to run:
Xcode even provides pseudo-languages for extra-long string & RTL testing.
You can detect the writing direction via
let writingDirection = UIApplication.sharedApplication().userInterfaceLayoutDirection
switch writingDirection {
case .LeftToRight:
//
case .RightToLeft:
//
default:
break // what now? You are obviously using iOS 11's topToBottom direction…
}
To set different languages and locales on startup this might be a proper solution.
What you are looking for is Automated UI-Testing
This example JavaScript code changes the device orientation for example:
var target = UIATarget.localTarget();
var app = target.frontMostApp();
//set orientation to landscape left
target.setDeviceOrientation(UIA_DEVICE_ORIENTATION_LANDSCAPELEFT);
UIALogger.logMessage("Current orientation now " + app.interfaceOrientation());
//reset orientation to portrait
target.setDeviceOrientation(UIA_DEVICE_ORIENTATION_PORTRAIT);
UIALogger.logMessage("Current orientation now " + app.interfaceOrientation());
For testing, if your layout has changed to RTL or LTR you could try to access specific UI Elements and check their content against an expected content. So here is another example to check the contents of a TableViewCell from the official docs:
The crux of testing is being able to verify that each test has been performed and that it has either passed or failed. This code example runs the test testName to determine whether a valid element recipe element whose name starts with “Tarte” exists in the recipe table view. First, a local variable is used to specify the cell criteria:
var cell = UIATarget.localTarget().frontMostApp().mainWindow() \
.tableViews()[0].cells().firstWithPredicate("name beginswith 'Tarte'");
Next, the script uses the isValid method to test whether a valid element matching those criteria exists in the recipe table view.
if (cell.isValid()) {
UIALogger.logPass(testName);
} else {
UIALogger.logFail(testName);
}
If a valid cell is found, the code logs a pass message for the testName test; if not, it logs a failure message.
Notice that this test specifies firstWithPredicate and "name
beginsWith 'Tarte'". These criteria yield a reference to the cell for
“Tarte aux Fraises,” which works for the default data already in the
Recipes sample app. If, however, a user adds a recipe for “Tarte aux
Framboises,” this example may or may not give the desired results.
If you want to test a specific scheme:
Executing an Automation Instrument Script in Xcode
After you have created your customized Automation template, you can execute your test script from Xcode by following these steps:
Open your project in Xcode.
From the Scheme pop-up menu (in the workspace window toolbar), select Edit Scheme for a scheme with which you would like to use your script.
Select Profile from the left column of the scheme editing dialog.
Choose your application from the Executable pop-up menu.
Choose your customized Automation Instrument template from the Instrument pop-up menu.
Click OK to approve your changes and dismiss the scheme editor dialog.
Choose Product > Profile.
Instruments launches and executes your test script.
Related
Heloo!
I am working with uitests on iOS and am using typeText method to enter a string into a textField. The application is multilingual, so the test case involves entering a string in different languages. However, the method fails for strings other than the current keyboard language (cannot switch the keyboard language to enter this string, although the simulator has a keyboard with this language).
I haven't been able to solve this problem for a week now. I did not find ways to switch the keyboard language for typeText, or otherwise solve the problem.
Please, help!
UPD (for drunkencheetah):
I use this method as XCUIElement extension:
func clearAndTypeText(_ text: String) {
let typedText = self.value as? String
focusIfNeeded()
if typedText != nil {
let deleteText = String(repeating: XCUIKeyboardKey.delete.rawValue, count: typedText!.count)
typeText(deleteText)
}
typeText(text)
}
firstTextField.clearAndTypeText("English12345") // Result - "English12345"
secontTextField.clearAndTypeText("文本123") // Chinese as example. Result -> "123"
// This will take a very long time to print.
If I manage to manually switch the keyboard language (while running the test) from English to Chinese, the text will be printed. Otherwise, only numbers
typeText() should function regardless of the current keyboard language. I've just tested typing text in Bulgarian(Cyrillic) and Chinese without issues.
Since your application is multilingual you should make sure you are locating the element respective to the current application language(if not using an accessibility identifier).
Also make sure the element has keyboard focus - use tap() on it before attempting typeText() just in case.
Make sure if running on simulator that I/O > Keyboard > Connect hardware keyboard is disabled
As Mike Collins suggests in the comments you could use the pasteboard (only on simulator!) like this:
UIPasteboard.general.string = "teststring"
textElement.doubleTap()
app.menuItems["Paste"].tap()
Note that this will not work on real devices.
I'm writing UI Tests for my application. I've an attribute named numberOfPhotos in PhotosViewController and it's value is set from another ViewController. Whenever numberOfPhotos is 2, only two photos should be displayed in my current PhotosViewController.
I was able to test if required number of images are visible or not but I'm not able to set numberOfPhotos from UITests class. Is there anyway I can set this value and proceed to tests.
Currents I'm editing the code to set value for numberOfPhotos and testing it. Is there anyway I can set this value from UITests class. Thanks.
They are different apps, that's why you can't set it directly. The UiTests use a test runner that runs your app. There is a way to do what you want using launchArguments.
From your tests:
let app = XCUIApplication()
app.launchArguments = XCUIApplication().launchArguments + ["UiTesting", "numberOfPhotos", "2"])
app.launch()
From your app:
var isUiTesting: Bool {
return ProcessInfo.processInfo.arguments.contains("UiTesting")
}
Write some code in your controller to check the isUiTesting property and set the number of photos based on the next few launchArguments. You will have to do some parsing of the launch arguments.
I am trying to pull all the options off an android spinner, using Appium. With Selenium, you can use the Select object and do something like getOptions (I forget the exact syntax). I need the text from all the options in the spinner.
Considering the spinner options are accessible through Appium. Getting all the values of the options on the spinner shall work as follows :
List<WebElement> spinnerList = driver.findElements(getBy("identifier")); //where identifier would vary on how you can access the elements
String spinnerListElementText[index]; //e.g. to store Text of all the options
for (int index = 0; index < spinnerList.size(); index++) {
String spinnerListElementText[index] = spinnerList.get(index).getText();
}
In Appium, there are test frameworks called Uiautomator, Uiautomator2 and Espresso, respectively. The thing that you were trying to get is not provided by Uiautomator or Uiautomator2 test frameworks. The only way with those frameworks is to click the spinner and get page source of spinner with visible elements. You could try to use Espresso framework. This is the reason:
Uiautomator: It is a test framework which provides a black-box testing for developers. It means that you can not get internal codes of the application.
Espresso: It is a test framework which provides a grey-box testing for developers. It means that you can get internal codes of the application, find elements which are not visible in the page (off-screen elements).
Try to use Espresso framework in Appium.
I am currently exploring the new UITest library in Xcode, and I want to test if the keyboard that pops up upon clicking inside a UITextView has the proper type (in this case it should be .PhonePad).
I don't think this is feasible with the default XCUIElement and XCUIElementAttributes (which are still a bit blurry to me concerning their actual meaning), and I don't really understand how and what I am supposed to extend in order to be able to test this.
Any help would be greatly appreciated ! :)
Below code I am using for testing the Phone number and password validation check.
let app = XCUIApplication()
let tablesQuery = app.tables
tablesQuery.cells.containingType(.StaticText, identifier:"Login Using").buttons["Icon mail"].tap()
tablesQuery.textFields["Phone Number"].tap()
tablesQuery.cells.containingType(.SecureTextField, identifier:"Password").childrenMatchingType(.TextField).element.typeText("ooo")
tablesQuery.staticTexts["Login Using"].swipeUp()
tablesQuery.secureTextFields["Password"].tap()
tablesQuery.cells.containingType(.Button, identifier:"Login").childrenMatchingType(.SecureTextField).element.typeText("eeee")
tablesQuery.buttons["Login"].tap()
app.alerts["Error"].collectionViews.buttons["OK"].pressForDuration(1.1);
I hope this will be useful for you.
I'm using Instruments for iOS automation and I can't seem to figure out how to tap options on the copy/paste menu. When I do a logElementTree(),I see that we are returning a UIEditingMenu and then three elements (which correspond to options of that menu, such as copy/paste, etc..). I am attempting to place this into a variable, and then trying to "tap" that variable but I cannot get that to work. Here is a sample of my code:
var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow();
//This generates the highlighted text
app.dragInsideWithOptions({startOffset:{x:0.45, y:0.6}, endOffset:{x:0.45, y:0.6}, duration:1.5});
var copy = app.editingMenu.elements.withName("copyButton");
copy.tap();
Instruments returns, "0) UIAElementNil". In addition to the above, I've also tried:
app.elements.withName("copyButton")
window.elements.withName("copyButton")
So, I can get the editingMenu to produce the available options, but I cannot figure out a way to tap or select one of those options. I'm not quite sure I know how to reference those options to begin with.
Does anyone have any ideas?
Thanks!
You should try app.editingMenu().elements()[index].tap() where index is the index of the option you want to tap from the array of elements returned. I got my one working this way.
Hey.
First of all, I was always using .elements() not .elements... but it is JS, so it may be invoking function that is assigned to object property..?
Anyway, maybe this edit menu is not internal window of the app, but it is system level menu, that is invoked, when you do the drag? If that is true, try:
UIATarget.localTarget().frontMostApp().elements().withName("copyButton").tap();
But as I see in apple reference your version with calling app.editingMenu() should be fine...
Maybe try calling buttons by position, and you will see which respond:
UIATarget.localTarget().frontMostApp().editingMenu().elements()[0].tap;
UIATarget.localTarget().frontMostApp().editingMenu().elements()[1].tap;
UIATarget.localTarget().frontMostApp().editingMenu().elements()[2].tap;
You should find position of correct one this way. When you have it's position you can check its properties by button.logElement();. With this inf you you should be able to switch back to .withName method instead hardcoded position.
I did this similar to yoosiba but with editingMenu element names.
Using Xcode 4.5.1 and device running iOS 6.
Using Alex Vollmer's excellent tuneup_js for target, app and vtap().
Otherwise you can use UIATarget.localTarget().frontMostApp() and tap().
NOTE: vtap() will delay and retry tapping. Without this you may need to add your own delays.
// tap in textFieldA to see editingMenu.
app.mainWindow().textFields()["textFieldA"].vtap();
app.editingMenu().elements()["Select All"].vtap();
app.editingMenu().elements()["Copy"].vtap();
// must delay before attempting next tap
target.delay(2);
// ... navigate to different section of the app
// tap in textFieldB to see editingMenu.
app.mainWindow().textFields()["textFieldB"].vtap();
// paste clipboard contents copied from textFieldA into textFieldB
app.editingMenu().elements()["Paste"].vtap();
target.delay(2);