Created
July 2, 2021 15:14
-
-
Save Pash237/083bdb623e17dd85625cbd4a9fbcf300 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import XCTest | |
class MyalarmUITests: XCTestCase { | |
override func setUpWithError() throws { | |
continueAfterFailure = false | |
} | |
override func tearDownWithError() throws { | |
let screenshot = XCUIScreen.main.screenshot() | |
let attachment = XCTAttachment(screenshot: screenshot) | |
attachment.lifetime = .deleteOnSuccess | |
add(attachment) | |
} | |
private func logIn(using phoneNumber: String) { | |
let app = XCUIApplication() | |
// вводим номер телефона | |
app.textFields["PhoneNumberTextField"].typeText(phoneNumber) | |
app.buttons["Продолжить".localized].tap() | |
// ждём SMS с кодом — сообщение покажется сверху в красной всплывайке | |
XCTAssertTrue(app.staticTexts["ErrorAlert"].waitForExistence(timeout: 5)) | |
// вычленяем код из полученного SMS | |
let sms = app.staticTexts["ErrorAlert"].label | |
let code = sms.substring(from: sms.count - 4) | |
// вводим код (через pasteboard, потому что клавиатура в симуляторе может быть выключена) | |
app.textFields["CodeTextField"].typeTextUsingPasteboard(code) | |
// убеждаемся, что объект загрузился проверяя, что кнопка переключения объектов появилась в течение 5 секунд | |
XCTAssertTrue(app.buttons["SelectObjectButton"].waitForExistence(timeout: 5)) | |
} | |
/** | |
* Проверяет, что пользователь может ввести номер телефона, код из SMS и залогиниться. | |
* Тест так называется, чтобы выполнится самым первым | |
* Сервер не даёт логиниться чаще чем раз в 60 секунд, поэтому придётся один раз залогиниться и дальше не сбрасывать сессию | |
*/ | |
func test001LogIn() throws { | |
let app = XCUIApplication() | |
app.launchArguments = ["-reset-session", "-show-sms", "-domainURL", "https://myalarm.pc.cnord.net/api/"] | |
app.launch() | |
logIn(using: "+79602471544") | |
} | |
/** | |
* Проверяет, что | |
*/ | |
func testArmDisarm() throws { | |
let app = XCUIApplication() | |
app.launchArguments = ["-domainURL", "https://myalarm.pc.cnord.net/api/"] | |
app.launch() | |
// ждём пока объект загрузится в течение 5 секунд | |
XCTAssertTrue(app.buttons["SelectObjectButton"].waitForExistence(timeout: 5)) | |
// показываем выбиралку объектов | |
Thread.sleep(forTimeInterval: 0.5) | |
app.buttons["SelectObjectButton"].tap() | |
// выбираем из спика объект Мобильный офис | |
let scrollViewsQuery = app.scrollViews | |
scrollViewsQuery.otherElements.staticTexts["Мобильный офис"].tap() | |
// находим первую кнопку раздела и запоминаем состояние раздела | |
let objectPartButton = app.otherElements["ObjectPartButton"].firstMatch | |
let initialPartState = objectPartButton.label | |
// ставим под охрану и убеждаемся что состояние поменялось | |
objectPartButton.tap() | |
app.textFields["CodeTextField"].typeTextUsingPasteboard("111111") | |
Thread.sleep(forTimeInterval: 4.0) | |
XCTAssertTrue(initialPartState != objectPartButton.label) | |
// снимаем с охраны и убеждаемся что состояние вернулось | |
objectPartButton.tap() | |
app.textFields["CodeTextField"].typeTextUsingPasteboard("111111") | |
Thread.sleep(forTimeInterval: 4.0) | |
XCTAssertTrue(initialPartState == objectPartButton.label) | |
} | |
func testRequestFrequency() throws { | |
let app = XCUIApplication() | |
app.launchArguments = ["-test-request-frequency", "-domainURL", "https://myalarm.pc.cnord.net/api/"] | |
app.launch() | |
Thread.sleep(forTimeInterval: 5.0) | |
// выбираем объект Мобильный офис | |
app.buttons["SelectObjectButton"].tap(at: CGPoint(x: 1, y: 1)) | |
let scrollViewsQuery = app.scrollViews | |
scrollViewsQuery.otherElements.staticTexts["Мобильный офис"].tap() | |
// смотрим заявки | |
let myTechTasksButton = app.otherElements["Заявки".localized].firstMatch | |
myTechTasksButton.tap() | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeDown(velocity: .fast) | |
app.swipeDown(velocity: .fast) | |
app.swipeDown(distance: 0.6) | |
// смотрим пользователей | |
let usersButton = app.buttons["Пользователи".localized].firstMatch | |
usersButton.tap() | |
Thread.sleep(forTimeInterval: 1.0) | |
app.swipeDown(distance: 0.6) | |
// гуляем по ленте | |
let eventsButton = app.otherElements["События".localized].firstMatch | |
eventsButton.tap() | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeDown(velocity: .fast) | |
app.swipeDown(velocity: .fast) | |
app.swipeDown(velocity: .fast) | |
app.swipeDown(velocity: .fast) | |
app.swipeDown(distance: 0.6) | |
// ставим и снимаем с охраны | |
let objectPartButton = app.otherElements["ObjectPartButton"].firstMatch | |
objectPartButton.tap() | |
let key = app.keys["1"] | |
key.tap() | |
key.tap() | |
key.tap() | |
key.tap() | |
key.tap() | |
key.tap() | |
objectPartButton.tap() | |
key.tap() | |
key.tap() | |
key.tap() | |
key.tap() | |
key.tap() | |
key.tap() | |
// тыкаем в устройство | |
let deviceButton = app.otherElements.matching(identifier: "DeviceButton").lastMatch | |
deviceButton.press(forDuration: 1.6); | |
Thread.sleep(forTimeInterval: 7.0) | |
deviceButton.press(forDuration: 1.5); | |
Thread.sleep(forTimeInterval: 7.0) | |
// тыкаем в камеру и скроллим там | |
var cameraButton = app.otherElements["CameraButton"].firstMatch | |
cameraButton.tap() | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeDown(velocity: .fast) | |
app.swipeDown(distance: 0.6) | |
// открываем объект с видео | |
app.buttons["SelectObjectButton"].tap(at: CGPoint(x: 1, y: 1)) | |
scrollViewsQuery.otherElements.staticTexts["#9099 им. Николая и Василия для отладки видео"].tap() | |
// тыкаем в камеру и скроллим там | |
cameraButton = app.otherElements["CameraButton"].firstMatch | |
cameraButton.tap() | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeUp(velocity: .fast) | |
app.swipeDown(velocity: .fast) | |
} | |
func testLaunchPerformance() throws { | |
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { | |
// This measures how long it takes to launch your application. | |
measure(metrics: [XCTApplicationLaunchMetric()]) { | |
XCUIApplication().launch() | |
} | |
} | |
} | |
} | |
extension XCUIElement { | |
func swipe(from startVector: CGVector, to stopVector: CGVector) { | |
let pt1 = coordinate(withNormalizedOffset: startVector) | |
let pt2 = coordinate(withNormalizedOffset: stopVector) | |
pt1.press(forDuration: 0.05, thenDragTo: pt2) | |
} | |
func swipeDown(distance: CGFloat) { | |
swipe(from: CGVector(dx: 0.1, dy: 0.1), to: CGVector(dx: 0.1, dy: 0.1 + distance)) | |
} | |
func swipeUp(distance: CGFloat) { | |
swipe(from: CGVector(dx: 0.1, dy: 0.1), to: CGVector(dx: 0.1, dy: 0.1 - distance)) | |
} | |
func tap(at position: CGPoint) { | |
let cooridnate = coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0)) | |
.withOffset(CGVector(dx: position.x, dy: position.y)) | |
cooridnate.tap() | |
} | |
/** | |
* Если клавиатура в симуляторе выключена: | |
* I/O -> Keyboard -> Toggle Software Keyboard, | |
* то просто typeText(...) может не работать. | |
* В таких случаях можно использовать костыль с вставкой из Pasteboard | |
*/ | |
func typeTextUsingPasteboard(_ text: String) { | |
UIPasteboard.general.string = text | |
tap() | |
if XCUIApplication().menuItems.element(boundBy: 0).waitForExistence(timeout: 2) { | |
XCUIApplication().menuItems.element(boundBy: 0).tap() | |
} else { | |
// если не вышло, пробуем так | |
typeText(text) | |
} | |
} | |
} | |
extension XCUIElementQuery { | |
var lastMatch: XCUIElement { element(boundBy: count - 1) } | |
} | |
class XCUITestDummyClass {} | |
extension String { | |
var localized: Self { | |
NSLocalizedString(self, bundle: Bundle(for: XCUITestDummyClass.self), comment: "") | |
} | |
func localized(_ arguments: CVarArg...) -> Self { | |
return String(format: localized, arguments: arguments.map {"\($0)"}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment