text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```ruby # frozen_string_literal: true # Lanes related to the Release Process (Code Freeze, Betas, Final Build, App Store Submission) platform :ios do lane :code_freeze do |skip_confirm: false| ensure_git_status_clean Fastlane::Helper::GitHelper.checkout_and_pull(DEFAULT_BRANCH) check_pods_references computed_release_branch_name = release_branch_name(release_version: release_version_next) message = <<~MESSAGE Code Freeze: New release branch from #{DEFAULT_BRANCH}: #{computed_release_branch_name} Current release version and build code: #{release_version_current} (#{build_code_current}). New release version and build code: #{release_version_next} (#{build_code_code_freeze}). MESSAGE UI.important(message) UI.user_error!('Aborted by user request') unless skip_confirm || UI.confirm('Do you want to continue?') UI.message 'Creating release branch...' Fastlane::Helper::GitHelper.create_branch(computed_release_branch_name, from: DEFAULT_BRANCH) UI.success "Done! New release branch is: #{git_branch}" UI.message 'Bumping release version and build code...' PUBLIC_VERSION_FILE.write( version_short: release_version_next, version_long: build_code_code_freeze ) UI.success "Done! New release version: #{release_version_current}. New build code: #{build_code_current}." commit_version_and_build_files new_version = release_version_current extract_release_notes_for_version( version: new_version, release_notes_file_path: File.join(PROJECT_ROOT_FOLDER, 'RELEASE-NOTES.txt'), extracted_notes_file_path: File.join(PROJECT_ROOT_FOLDER, 'Simplenote', 'Resources', 'release_notes.txt') ) ios_update_release_notes(new_version: new_version) generate_strings_file_for_glotpress UI.important('Pushing changes to remote, configuring the release on GitHub, and triggering the beta build...') UI.user_error!("Terminating as requested. Don't forget to run the remainder of this automation manually.") unless skip_confirm || UI.confirm('Do you want to continue?') push_to_git_remote(tags: false) copy_branch_protection( repository: GITHUB_REPO, from_branch: DEFAULT_BRANCH, to_branch: computed_release_branch_name ) set_milestone_frozen_marker( repository: GITHUB_REPO, milestone: new_version ) trigger_beta_build(branch_to_build: computed_release_branch_name) # TODO: Switch to working branch and open back-merge PR end lane :new_beta_release do |skip_confirm: false| ensure_git_status_clean ensure_git_branch_is_release_branch new_build_code = build_code_next UI.important <<~MESSAGE New beta: Current build code: #{build_code_current} New build code: #{new_build_code} MESSAGE UI.user_error!("Terminating as requested. Don't forget to run the remainder of this automation manually.") unless skip_confirm || UI.confirm('Do you want to continue?') download_localized_strings_and_metadata_from_glotpress lint_localizations UI.message "Bumping build code to #{new_build_code}..." PUBLIC_VERSION_FILE.write( version_long: new_build_code ) commit_version_and_build_files # Uses build_code_current let user double-check result. UI.success "Done! Release version: #{release_version_current}. New build code: #{build_code_current}." UI.important('Pushing changes to remote and triggering the beta build...') UI.user_error!("Terminating as requested. Don't forget to run the remainder of this automation manually.") unless skip_confirm || UI.confirm('Do you want to continue?') push_to_git_remote(tags: false) trigger_beta_build(branch_to_build: release_branch_name) # TODO: Switch to working branch and open back-merge PR end lane :trigger_beta_build do |branch_to_build:| trigger_buildkite_release_build(branch: branch_to_build, beta: true) end lane :trigger_release_build do |branch_to_build:| trigger_buildkite_release_build(branch: branch_to_build, beta: false) end end def commit_version_and_build_files git_commit( path: [VERSION_FILE_PATH], message: 'Bump version number', allow_nothing_to_commit: false ) end def check_pods_references # This will also print the result to STDOUT result = ios_check_beta_deps(lockfile: File.join(PROJECT_ROOT_FOLDER, 'Podfile.lock')) style = result[:pods].nil? || result[:pods].empty? ? 'success' : 'warning' message = "### Checking Internal Dependencies are all on a **stable** version\n\n#{result[:message]}" buildkite_annotate(context: 'pods-check', style: style, message: message) if is_ci end def trigger_buildkite_release_build(branch:, beta:) buildkite_trigger_build( buildkite_organization: BUILDKITE_ORGANIZATION, buildkite_pipeline: BUILDKITE_PIPELINE, branch: branch, environment: { BETA_RELEASE: beta }, pipeline_file: 'release-build.yml' ) end ```
/content/code_sandbox/fastlane/lanes/release.rb
ruby
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,134
```swift /// Simplenote credentials for screenshots generation via UI tests /// struct ScreenshotsCredentials { static let testUserEmail = "test@example.com" static let testUserPassword = "password" } ```
/content/code_sandbox/SimplenoteScreenshots/ScreenshotsCredentials-demo.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
42
```swift import UITestsFoundation import XCTest import XCUITestHelpers class SimplenoteScreenshots: XCTestCase { override func setUp() { continueAfterFailure = false UIPasteboard.general.strings = [] } func testScreenshots() throws { let app = XCUIApplication() setupSnapshot(app) app.launch() // The tests have been known to fail in the passcode screen inconsistently. // // This becomes a problem when running the screenshots automation through Fastlane because // it retries three times. A failure in the passcode screen results in the PIN screen not // being disabled, which in turn would result in the passcode screen being presented at // launch, preventing the test from proceeding. dismissPasscodeScreenIfNeeded(using: app) dismissVerifyEmailIfNeeded(using: app) let login = app.buttons["Log In"] if login.waitForExistence(timeout: 3) == false { logout(using: app) } XCTAssertTrue(login.waitForExistence(timeout: 10)) login.tap() let loginViaEmail = app.buttons["Log in with email"] XCTAssertTrue(loginViaEmail.waitForExistence(timeout: 10)) loginViaEmail.tap() let email = app.textFields["Email"] XCTAssertTrue(email.waitForExistence(timeout: 10)) email.typeText(ScreenshotsCredentials.testUserEmail) let password = app.secureTextFields["Password"] XCTAssertTrue(password.waitForExistence(timeout: 10)) password.typeSecureText(ScreenshotsCredentials.testUserPassword, using: app) // Need to check for the login button again, otherwise we'll attempt to press the one from // the previous screen. let newLogin = app.buttons["Log In"] XCTAssertTrue(newLogin.waitForExistence(timeout: 10)) newLogin.tap() dismissVerifyEmailIfNeeded(using: app) let firstNote = app.cells[noteForDetailScreenshot] // Super long timeout in case the test user has many notes and the connection is a bit slow XCTAssertTrue(firstNote.waitForExistence(timeout: 20)) firstNote.tap() takeScreenshot("1-note") goBackFromEditor(using: app) // Before taking a screenshot of the notes, make sure the review prompt header is not on // screen. let reviewPromptButton = app.buttons["I like it"] if reviewPromptButton.waitForExistence(timeout: 3) { reviewPromptButton.tap() let dismissReviewButton = app.buttons["No thanks"] XCTAssertTrue(dismissReviewButton.waitForExistence(timeout: 3)) dismissReviewButton.tap() // also wait for dismiss animation, just in case XCTAssertFalse(dismissReviewButton.waitForExistence(timeout: 3)) } takeScreenshot("2-all-notes") let interlinkingNote = app.cells[noteForInterlinkingScreenshot] XCTAssertTrue(interlinkingNote.waitForExistence(timeout: 5)) interlinkingNote.tap() let noteTextView = app.textViews.firstMatch XCTAssertTrue(noteTextView.waitForExistence(timeout: 1)) // We need to add text at the end of the note. There is no dedicated API to do so. Our best // bet is to try to scroll the text view to the bottom and tap there. There are no APIs for // that either, so our next best bet is to 1) swipe up real fast to simulate a scroll to the // bottom; 2) tap in the bottom right corner of the text view. // // Fun (?) fact worth tracking here for future reference. On the iPad Simulator^, tapping on // the `noteTextView` `XCUIElement` doesn't work. Luckily, tapping on the `XCUICoordinate` // works. Another option could have been to call `tap()` on the `XCUIApplication` itself, // but that might result in tapping in the middle of the text on a small screen. // // ^: iPad Pro 12.9" 2nd and 3rd generation Simulator on Xcode 12.3. noteTextView.swipeUp(velocity: .fast) let lowerRightCorner = noteTextView.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.9)) lowerRightCorner.tap() let interlinkingTriggerString = "\n[L" noteTextView.typeText(interlinkingTriggerString) // Before taking the screenshot, let's make sure the inter note liking window appeared by // checking the text of one of its notes is on screen XCTAssertTrue(app.staticTexts["Blueberry Recipes"].firstMatch.waitForExistence(timeout: 1)) takeScreenshot("3-interlinking") // Reset for the next test (0 ..< interlinkingTriggerString.count).forEach { _ in noteTextView.typeText(XCUIKeyboardKey.delete.rawValue) } goBackFromEditor(using: app) openMenu(using: app) let allNotesMenuInput = app.cells.matching(identifier: "all-notes").firstMatch XCTAssertTrue(allNotesMenuInput.waitForExistence(timeout: 3)) takeScreenshot("4-menu") allNotesMenuInput.tap() let searchBar = app.otherElements["search-bar"] XCTAssertTrue(searchBar.waitForExistence(timeout: 3)) searchBar.tap() searchBar.typeText("Recipe") let searchCancelButton = app.buttons["Cancel"] XCTAssertTrue(searchCancelButton.waitForExistence(timeout: 3)) takeScreenshot("5-search") searchCancelButton.tap() openMenu(using: app) let passcodeScreen = try loadPasscodeScreen(using: app) // Set the passcode // Writing the value here in clear because one can see it being typed anyways. passcodeScreen.type(passcode: 1234) // Confirm it passcodeScreen.type(passcode: 1234) // Kill the app and relaunch it so we can take a screenshot of the lock screen app.terminate() app.launch() // The screenshot for the passcode should have only 3 characters inserted. // (Typing in the passcode screen also ensures it's visible first) passcodeScreen.type(passcode: 123) takeScreenshot("6-passcode") passcodeScreen.type(passcode: 4) dismissVerifyEmailIfNeeded(using: app) // Now, disable the passcode so we're not blocked by it on next launch. openMenu(using: app) try loadPasscodeScreen(using: app).type(passcode: 1234) } func dismissVerifyEmailIfNeeded(using app: XCUIApplication) { guard app.staticTexts["Verify Your Email"].waitForExistence(timeout: 10) else { return } app.buttons["icon cross"].tap() } func logout(using app: XCUIApplication) { getMenuButtonElement(from: app).tap() let settings = app.staticTexts["Settings"] XCTAssertTrue(settings.waitForExistence(timeout: 3)) settings.tap() let logOut = app.staticTexts["Log Out"] XCTAssertTrue(logOut.waitForExistence(timeout: 3)) logOut.tap() } func goBackFromEditor(using app: XCUIApplication) { let backButton = app.buttons.matching(NSPredicate(format: "label = %@", "All Notes")).firstMatch XCTAssertTrue(backButton.waitForExistence(timeout: 3)) backButton.tap() } func openMenu(using app: XCUIApplication) { getMenuButtonElement(from: app).tap() } func getMenuButtonElement(from app: XCUIApplication) -> XCUIElement { let menu = app.buttons.matching(identifier: "menu").firstMatch XCTAssertTrue(menu.waitForExistence(timeout: 10)) return menu } func loadPasscodeScreen(using app: XCUIApplication) throws -> PasscodeScreen { let settingsMenuInput = app.cells["settings"] XCTAssertTrue(settingsMenuInput.waitForExistence(timeout: 3)) settingsMenuInput.tap() let passcodeCell = app.cells["passcode-cell"] XCTAssertTrue(passcodeCell.waitForExistence(timeout: 3)) passcodeCell.tap() return try PasscodeScreen(app: app) } func dismissPasscodeScreenIfNeeded(using app: XCUIApplication) { guard PasscodeScreen.isLoaded(in: app) else { return } do { try PasscodeScreen(app: app).type(passcode: 1234) } catch { XCTFail("Expected passcode screen to exist but it did not.") } } func takeScreenshot(_ title: String) { let mode = XCUIDevice.inDarkMode ? "dark" : "light" snapshot("\(title)-\(mode)") } let noteForDetailScreenshot = "Lemon Cake & Blueberry" let noteForInterlinkingScreenshot = "Colors" } extension XCUIElement { /// Workaround to type text into secure text fields due to the different behaviors across /// Simulators. func typeSecureText(_ text: String, using app: XCUIApplication) { tap() // At the time of writing, typing in a secure text field didn't work in some of the // Simulators on which we want to take screenshots. On top of that, the workaround to type // in the secure text field doesn't work in some other Simulators. Therefore, we need to // know which approach to use at runtime. if requiresSecureTextFieldWorkaround(using: app) { paste(text: text) } else { typeText(text) } } private func requiresSecureTextFieldWorkaround(using app: XCUIApplication) -> Bool { // At the time of writing, these tests run on the following iOS 14.3 Simulators as defined // in the Fastfile. // // - iPhone 8 Plus // - iPhone Xs // - iPad Pro 12.9" 2nd generation // - iPad Pro 12.9" 3rd generation // // Of those, the only one requiring the secure text field workaround is the iPhone 8 Plus // one. return app.isDeviceIPhone8Plus() } } ```
/content/code_sandbox/SimplenoteScreenshots/SimplenoteScreenshots.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,160
```swift // // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- import Foundation import XCTest var deviceLanguage = "" var locale = "" func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations) } func snapshot(_ name: String, waitForLoadingIndicator: Bool) { if waitForLoadingIndicator { Snapshot.snapshot(name) } else { Snapshot.snapshot(name, timeWaitingForIdle: 0) } } /// - Parameters: /// - name: The name of the snapshot /// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { Snapshot.snapshot(name, timeWaitingForIdle: timeout) } enum SnapshotError: Error, CustomDebugStringConvertible { case cannotFindSimulatorHomeDirectory case cannotRunOnPhysicalDevice var debugDescription: String { switch self { case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case .cannotRunOnPhysicalDevice: return "Can't use Snapshot on a physical device." } } } @objcMembers open class Snapshot: NSObject { static var app: XCUIApplication? static var waitForAnimations = true static var cacheDirectory: URL? static var screenshotsDirectory: URL? { return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.app = app Snapshot.waitForAnimations = waitForAnimations do { let cacheDir = try getCacheDirectory() Snapshot.cacheDirectory = cacheDir setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { NSLog(error.localizedDescription) } } class func setLanguage(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { NSLog("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { NSLog("Couldn't detect/set locale...") } if locale.isEmpty && !deviceLanguage.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } if !locale.isEmpty { app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } } class func setLaunchArguments(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { NSLog("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { if timeout > 0 { waitForLoadingIndicatorToDisappear(within: timeout) } NSLog("snapshot: \(name)") // more information about this, check out path_to_url#how-does-it-work if Snapshot.waitForAnimations { sleep(1) // Waiting for the animation to be finished (kind of) } #if os(OSX) guard let app = self.app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else guard self.app != nil else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let screenshot = XCUIScreen.main.screenshot() #if os(iOS) let image = XCUIDevice.shared.orientation.isLandscape ? fixLandscapeOrientation(image: screenshot.image) : screenshot.image #else let image = screenshot.image #endif guard var simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } do { // The simulator name contains "Clone X of " inside the screenshot file when running parallelized UI Tests on concurrent devices let regex = try NSRegularExpression(pattern: "Clone [0-9]+ of ") let range = NSRange(location: 0, length: simulator.count) simulator = regex.stringByReplacingMatches(in: simulator, range: range, withTemplate: "") let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") #if swift(<5.0) UIImagePNGRepresentation(image)?.write(to: path, options: .atomic) #else try image.pngData()?.write(to: path, options: .atomic) #endif } catch let error { NSLog("Problem writing screenshot: \(name) to \(screenshotsDir)/\(simulator)-\(name).png") NSLog(error.localizedDescription) } #endif } class func fixLandscapeOrientation(image: UIImage) -> UIImage { let format = UIGraphicsImageRendererFormat() format.scale = image.scale let renderer = UIGraphicsImageRenderer(size: image.size, format: format) return renderer.image { context in image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) } } class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { #if os(tvOS) return #endif guard let app = self.app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) } class func getCacheDirectory() throws -> URL { let cachePath = "Library/Caches/tools.fastlane" // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) let homeDir = URL(fileURLWithPath: NSHomeDirectory()) return homeDir.appendingPathComponent(cachePath) #elseif arch(i386) || arch(x86_64) || arch(arm64) guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } let homeDir = URL(fileURLWithPath: simulatorHostHome) return homeDir.appendingPathComponent(cachePath) #else throw SnapshotError.cannotRunOnPhysicalDevice #endif } } private extension XCUIElementAttributes { var isNetworkLoadingIndicator: Bool { if hasAllowListedIdentifier { return false } let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize } var hasAllowListedIdentifier: Bool { let allowListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] return allowListedIdentifiers.contains(identifier) } func isStatusBar(_ deviceWidth: CGFloat) -> Bool { if elementType == .statusBar { return true } guard frame.origin == .zero else { return false } let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) let newStatusBarSize = CGSize(width: deviceWidth, height: 44) return [oldStatusBarSize, newStatusBarSize].contains(frame.size) } } private extension XCUIElementQuery { var networkLoadingIndicators: XCUIElementQuery { let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isNetworkLoadingIndicator } return self.containing(isNetworkLoadingIndicator) } var deviceStatusBars: XCUIElementQuery { guard let app = Snapshot.app else { fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") } let deviceWidth = app.windows.firstMatch.frame.width let isStatusBar = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isStatusBar(deviceWidth) } return self.containing(isStatusBar) } } private extension CGFloat { func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { return numberA...numberB ~= self } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.25] ```
/content/code_sandbox/SimplenoteScreenshots/SnapshotHelper.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,335
```swift import XCTest @testable import Simplenote // MARK: - NSString Simplenote Tests // class NSStringSimplenoteTests: XCTestCase { /// Verifies that `byEncodingAsTagHash` effectively escapes all of the non alphanumeric characters /// func your_sha256_hashnTheReceiver() { let sample = "1234567890!@#$%^&*()-_+[]';./,qwertyuiopasdfghjkl;'zxcvbnm,./" let encoded = sample.byEncodingAsTagHash let escapedSet = CharacterSet(charactersIn: encoded) let expectedSet = CharacterSet(charactersIn: "%").union(.alphanumerics) XCTAssertTrue(expectedSet.isSuperset(of: escapedSet)) } /// Verifies that `byEncodingAsTagHash` effectively escapes special characters /// func testByEncodingAsTagHashEncodesAllOfSpecialCharacters() { let string = String("Tv@#$%^&*+-=_`~/?., ><{}[]\\()\"|':;") let hash = string.byEncodingAsTagHash let expected = "t%C3%A1%C3%9Fv%C4%93%D1%91%D0%B8%E5%85%94%E5%AD%90%40%23%24%25%5E%26%2A%2B%2D%3D%5F%60%7E%2F%3F%2E%2C%20%3E%3C%7B%7D%5B%5D%5C%28%29%22%7C%27%3A%3B" XCTAssertEqual(hash, expected) } /// Verifies that `byEncodingAsTagHash` allows us to properly compare Unicode Strings that would otherwise evaluate as not equal. /// Although our (three) sample strings yield the exact same character``, regular `isEqualString` API returns `false`. /// /// By relying on `byEncodingAsTagHash` we can properly identify matching strings. /// /// - Note: When using the `Swift.String` class, the same comparison is actually correct. /// func testNonEqualStringsCreateSameHash() { let differentStringsOneHashSamples = [ ["\u{0073}\u{0323}\u{0307}", "\u{0073}\u{0307}\u{0323}", "\u{1E69}"], // ["\u{0065}\u{0301}", "\u{00E9}"] // ] for sample in differentStringsOneHashSamples { testNonEqualStringsCreateSameHash(sample) } } } extension NSStringSimplenoteTests { private func testNonEqualStringsCreateSameHash(_ samples: [String]) { let sampleToTest = samples[0] for i in 1..<samples.count { XCTAssertNotEqual((sampleToTest as NSString), (samples[i] as NSString)) XCTAssertEqual(sampleToTest.byEncodingAsTagHash, samples[i].byEncodingAsTagHash) } } } ```
/content/code_sandbox/SimplenoteTests/NSStringSimplenoteTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
668
```swift import XCTest @testable import Simplenote // MARK: - InterlinkResultsController Tests // class InterlinkResultsControllerTests: XCTestCase { /// InMemory Storage! /// private let storage = MockupStorageManager() /// InterlinkResultsController /// private var resultsController: InterlinkResultsController! // MARK: - Overridden Methods override func setUp() { super.setUp() resultsController = InterlinkResultsController(viewContext: storage.viewContext) } override func tearDown() { super.tearDown() storage.reset() } // MARK: - Tests: Filtering /// Verifies that only Notes with matching keywords in their title are returned by `searchNotes:byTitleKeyword:` /// func your_sha256_hashKeywordInTheirTitle() { let (matching, _) = insertSampleEntities() guard let results = resultsController.searchNotes(byTitleKeyword: Settings.sampleMatchingKeyword, excluding: nil) else { XCTFail() return } XCTAssertEqual(matching, Set(results)) } /// Verifies that `searchNotes:byTitleKeyword:` limits the output count to the value defined by `maximumNumberOfResults` /// func testSearchNotesByKeywordsRespectsTheMaximumNumberOfResultsLimit() { let (_, _) = insertSampleEntities() resultsController.maximumNumberOfResults = 1 guard let results = resultsController.searchNotes(byTitleKeyword: Settings.sampleMatchingKeyword, excluding: nil) else { XCTFail() return } XCTAssertEqual(results.count, resultsController.maximumNumberOfResults) } /// Verifies that `searchNotes:byTitleKeyword:` excludes the specified entity /// func testSearchNotesByKeywordsExcludesTheSpecifiedObjectID() { let (matching, _) = insertSampleEntities() let excluded = matching.randomElement()! guard let results = resultsController.searchNotes(byTitleKeyword: Settings.sampleMatchingKeyword, excluding: excluded.objectID) else { XCTFail() return } XCTAssertFalse(results.contains(excluded)) XCTAssertEqual(results.count, matching.count - 1) } /// Verifies that `searchNotes:byTitleKeyword:` is diacritic insensitive with regards of the Note Content /// func testSearchNotesByKeywordsIsDicriticAndCaseInsensitive() { let matching = [ storage.insertSampleNote(contents: "DcrtIcs"), ] storage.save() guard let results = resultsController.searchNotes(byTitleKeyword: "diacritics", excluding: nil) else { XCTFail() return } XCTAssertEqual(results.count, matching.count) } /// Verifies that `searchNotes:byTitleKeyword:` is diacritic insensitive with a special keyword /// func your_sha512_hash() { let matching = [ storage.insertSampleNote(contents: "diacritics"), ] storage.save() guard let results = resultsController.searchNotes(byTitleKeyword: "DcrtIcs", excluding: nil) else { XCTFail() return } XCTAssertEqual(results.count, matching.count) } } // MARK: - Private // private extension InterlinkResultsControllerTests { /// Inserts a collection of sample entities. /// func insertSampleEntities() -> (matching: Set<Note>, irrelevant: Set<Note>) { let notesWithKeyword = Set(arrayLiteral: storage.insertSampleNote(contents: Settings.sampleMatchingKeyword.uppercased() + "Match \n nope"), storage.insertSampleNote(contents: "Another " + Settings.sampleMatchingKeyword + " \n nope"), storage.insertSampleNote(contents: "Yet Another " + Settings.sampleMatchingKeyword + " \n nope") ) let notesWithoutKeyword = Set(arrayLiteral: storage.insertSampleNote(contents: "nope"), storage.insertSampleNote(contents: "neither this one \n " + Settings.sampleMatchingKeyword) ) storage.save() return (notesWithKeyword, notesWithoutKeyword) } } // MARK: - Constants // private enum Settings { static let sampleMatchingKeyword: String = "match" } ```
/content/code_sandbox/SimplenoteTests/InterlinkResultsControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
865
```swift import XCTest @testable import Simplenote // MARK: - NoteContentPreviewTests Tests // class NoteContentPreviewTests: XCTestCase { /// InMemory Storage! /// private let storage = MockupStorageManager() /// Verifies that Markdown Title Markers are stripped from the title /// func testTrimsLeadingMarkdown() { let sample = "# Title" let note = storage.insertSampleNote(contents: sample) note.createPreview() XCTAssertEqual(note.titlePreview, "Title") } /// Verifies that newlines and multiple spaces in body are replaced with a single space /// func testReplacesNewlinesWithSingleSpace() { let sample = "\n\r\n# Title\n\n\n\nLINE1\n\n\r\n\nLINE2\n\nLINE3\n\r\n\n" let note = storage.insertSampleNote(contents: sample) note.createPreview() XCTAssertEqual(note.titlePreview, "Title") XCTAssertEqual(note.bodyPreview, "LINE1 LINE2 LINE3") } } ```
/content/code_sandbox/SimplenoteTests/NoteContentPreviewTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
216
```swift import XCTest @testable import Simplenote // MARK: - UIImage+Simplenote Unit Tests // class UIImageSimplenoteTests: XCTestCase { /// Verify every single UIColorName in existance yields a valid UIColor instancce /// func testEverySingleUIImageNameEffectivelyYieldsSomeUIImageInstance() { for imageName in UIImageName.allCases { XCTAssertNotNil(UIImage.image(name: imageName)) } } } ```
/content/code_sandbox/SimplenoteTests/UIImageSimplenoteTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
93
```swift import XCTest @testable import Simplenote // MARK: - NoteContentHelperTests Tests // class NoteContentHelperTests: XCTestCase { /// Empty title and body when content is nil /// func testEmptyTitleAndBodyRangeWhenContentIsNil() { let content: String? = nil let structure = NoteContentHelper.structure(of: content) XCTAssertNil(structure.title) XCTAssertNil(structure.body) XCTAssertNil(structure.trimmedBody) } /// Empty title and body when content is empty /// func testEmptyTitleAndBodyRangeWhenContentIsEmpty() { let content = "" let structure = NoteContentHelper.structure(of: content) XCTAssertNil(structure.title) XCTAssertNil(structure.body) XCTAssertNil(structure.trimmedBody) } /// Test title and empty body when content has only one line /// func testTitleAndEmptyBodyRangeWhenContentHasOnlyOneLine() { let content = "A lala lala long long le long long long YEAH!" let structure = NoteContentHelper.structure(of: content) XCTAssertEqual(structure.title, content.startIndex..<content.endIndex) XCTAssertNil(structure.body) XCTAssertNil(structure.trimmedBody) } /// Test title and body /// func testTitleAndBodyRange() { let content = "Title!\n\nBody" let structure = NoteContentHelper.structure(of: content) XCTAssertEqual(structure.title, content.range(of: "Title!")) XCTAssertEqual(structure.body, content.range(of: "\nBody")) XCTAssertEqual(structure.trimmedBody, content.range(of: "Body")) } /// Test title doesn't include leading and trailing whitespaces and newlines /// func testTitleTrimsLeadingAndTrailingWhitespacesAndNewlines() { let content = " \n\n \n Title! \n\n\n \n " let structure = NoteContentHelper.structure(of: content) XCTAssertEqual(structure.title, content.range(of: "Title!")) XCTAssertEqual(structure.body, content.range(of: "\n\n \n ")) XCTAssertNil(structure.trimmedBody) } /// Test body doesn't include leading and trailing whitespaces and newlines /// func testBodyTrimsLeadingAndTrailingWhitespacesAndNewlines() { let content = "\n\r\n# Title!\n\n\n\nLINE1\n\n\r\n\nLINE2\n\nLINE3\n\r\n\n" let structure = NoteContentHelper.structure(of: content) XCTAssertEqual(structure.title, content.range(of: "# Title!")) XCTAssertEqual(structure.body, content.range(of: "\n\n\nLINE1\n\n\r\n\nLINE2\n\nLINE3\n\r\n\n")) XCTAssertEqual(structure.trimmedBody, content.range(of: "LINE1\n\n\r\n\nLINE2\n\nLINE3")) } } ```
/content/code_sandbox/SimplenoteTests/NoteContentHelperTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
621
```swift import XCTest @testable import Simplenote class PublishControllerTests: XCTestCase { private let publishController = PublishController() private let storage = MockupStorageManager() private var logger = PublishLogger() private var mockAppDelegate: MockAppDelegate? override func setUpWithError() throws { publishController.onUpdate = { note in self.logger.lastUpdateNote = note self.logger.actions.append(note.publishState) } mockAppDelegate = MockAppDelegate(publishController: publishController) } func testUpdatePublishStateExitsIfStateUnchanged() { let note = storage.insertSampleNote(published: true) publishController.updatePublishState(for: note, to: true) XCTAssertTrue(logger.actions.isEmpty) XCTAssertNil(logger.lastUpdateNote) } func testUpdatePublishStateSetsNoteStateToPublished() { let note = storage.insertSampleNote(published: false) publishController.updatePublishState(for: note, to: true) let expectedActions: [PublishState] = [.publishing] XCTAssertTrue(note.published) testExpectations(with: note, expectedActions: expectedActions) } func testUpdatePublishStateSetsNoteStateToUnpublished() { let note = storage.insertSampleNote(published: true, publishURL: TestConstants.publishURL) publishController.updatePublishState(for: note, to: false) let expectedActions: [PublishState] = [.unpublishing] XCTAssertFalse(note.published) testExpectations(with: note, expectedActions: expectedActions) } func testDidReceiveUpdateNotificationUpdatesPublishState() { let note = storage.insertSampleNote(simperiumKey: TestConstants.simperiumKey, published: false) publishController.updatePublishState(for: note, to: true) var expectedActions: [PublishState] = [.publishing] mockAppDelegate?.updateNotification(for: note, withURL: TestConstants.publishURL) expectedActions.append(.published) testExpectations(with: note, expectedActions: expectedActions) } func testDidReceiveUpdateIgnoresNonObservedUpdates() { let note = storage.insertSampleNote(simperiumKey: TestConstants.simperiumKey) let noteB = storage.insertSampleNote(simperiumKey: TestConstants.altSimperiumKey) mockAppDelegate?.updateNotification(for: note, withURL: TestConstants.publishURL) mockAppDelegate?.updateNotification(for: noteB, withURL: TestConstants.publishURL, observedProperty: TestConstants.altObservedProperty) XCTAssertNil(logger.lastUpdateNote) XCTAssertTrue(logger.actions.isEmpty) } func testListenerRemovedAfterDidReceiUpdateCalled() { let note = storage.insertSampleNote(simperiumKey: TestConstants.simperiumKey) publishController.updatePublishState(for: note, to: true) var expectedActions: [PublishState] = [.publishing] mockAppDelegate?.updateNotification(for: note, withURL: TestConstants.publishURL) expectedActions.append(.published) mockAppDelegate?.updateNotification(for: note, withURL: TestConstants.removeURL) testExpectations(with: note, expectedActions: expectedActions) } func testDidReceiveDeleteNotificationRemovesListener() { let note = storage.insertSampleNote(simperiumKey: TestConstants.simperiumKey) publishController.updatePublishState(for: note, to: true) let expectedActions: [PublishState] = [.publishing] mockAppDelegate?.deleteNotification(for: note) mockAppDelegate?.updateNotification(for: note, withURL: TestConstants.removeURL) testExpectations(with: note, expectedActions: expectedActions) } func testDidReceiveDeleteNotificationIgnoredWithUnobservedKey() { let note = storage.insertSampleNote(simperiumKey: TestConstants.simperiumKey) let noteB = storage.insertSampleNote(simperiumKey: TestConstants.altSimperiumKey) publishController.updatePublishState(for: note, to: true) var expectedActions: [PublishState] = [.publishing] mockAppDelegate?.deleteNotification(for: noteB) mockAppDelegate?.updateNotification(for: note, withURL: TestConstants.publishURL) expectedActions.append(.published) testExpectations(with: note, expectedActions: expectedActions) } private func testExpectations(with note: Note, expectedActions: [PublishState]) { XCTAssertEqual(note, logger.lastUpdateNote) XCTAssertEqual(expectedActions, logger.actions) } } private struct TestConstants { static let publishURL = "abc123" static let removeURL = "" static let simperiumKey = "qwfpgj123456" static let altSimperiumKey = "abcdef67890" static let observedProperty = "publishURL" static let altObservedProperty = "content" } private class PublishLogger { var lastUpdateNote: Note? var actions = [PublishState]() } private class MockAppDelegate { let publishController: PublishController init(publishController: PublishController) { self.publishController = publishController } func updateNotification(for note: Note, withURL url: String, observedProperty: String = TestConstants.observedProperty) { note.publishURL = url publishController.didReceiveUpdateNotification(for: note.simperiumKey, with: [observedProperty]) } func deleteNotification(for note: Note) { publishController.didReceiveDeleteNotification(for: note.simperiumKey) } } ```
/content/code_sandbox/SimplenoteTests/PublishControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,167
```swift import Foundation @testable import Simplenote // MARK: - MockApplication // class MockApplication: ApplicationStateProvider { var applicationState: UIApplication.State = .active } ```
/content/code_sandbox/SimplenoteTests/MockApplication.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
38
```swift import Foundation @testable import Simplenote // MARK: - MockupStorage Sample Entity Insertion Methods // extension MockupStorageManager { /// Inserts a new (Sample) Note into the receiver's Main MOC /// @discardableResult func insertSampleNote(contents: String = "", simperiumKey: String = UUID().uuidString, published: Bool = false, publishURL: String? = "") -> Note { guard let note = NSEntityDescription.insertNewObject(forEntityName: Note.entityName, into: viewContext) as? Note else { fatalError() } note.modificationDate = Date() note.creationDate = Date() note.content = contents note.published = published note.publishURL = publishURL note.simperiumKey = simperiumKey return note } /// Inserts a new (Sample) Tag into the receiver's Main MOC /// @discardableResult func insertSampleTag(name: String = "") -> Tag { guard let tag = NSEntityDescription.insertNewObject(forEntityName: Tag.entityName, into: viewContext) as? Tag else { fatalError() } tag.name = name return tag } } ```
/content/code_sandbox/SimplenoteTests/MockupStorage+Sample.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
267
```swift import XCTest @testable import Simplenote // MARK: - Note+Extension Tests // class NoteLinkTests: XCTestCase { /// InMemory Storage! /// private let storage = MockupStorageManager() func testNoteInterlinkReferenceCount() { let (referencedNote, referencing) = insertSampleEntitiesWithInterlinkReferences() let noReference = referencing[0] let oneReference = referencing[1] let twoReference = referencing[2] let emptyContent = referencing[3] XCTAssertEqual(noReference.instancesOfReference(to: referencedNote), 0) XCTAssertEqual(oneReference.instancesOfReference(to: referencedNote), 1) XCTAssertEqual(twoReference.instancesOfReference(to: referencedNote), 2) XCTAssertEqual(emptyContent.instancesOfReference(to: referencedNote), 0) } } // MARK: - Private // private extension NoteLinkTests { /// Inserts a collection of sample entities. /// func insertSampleEntitiesWithInterlinkReferences() -> (referenced: Note, samles: Array<Note>) { let referencedNote = storage.insertSampleNote(contents: "This note will be referenced to") var notesReferencing = Array<Note>() if let link = referencedNote.plainInternalLink { notesReferencing.append(storage.insertSampleNote(contents: "Does not contain reference")) notesReferencing.append(storage.insertSampleNote(contents: "This note contains one reference to note \(link)")) notesReferencing.append(storage.insertSampleNote(contents: "This note contains two reference \(link) to note \(link)")) notesReferencing.append(storage.insertSampleNote(contents: "")) } storage.save() return (referencedNote, notesReferencing) } } ```
/content/code_sandbox/SimplenoteTests/NoteLinkTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
361
```swift import XCTest @testable import Simplenote // MARK: - AuthenticationValidator Tests // class AuthenticationValidatorTests: XCTestCase { /// Testing Validator /// let validator = AuthenticationValidator() /// Verifies that `performUsernameValidation` returns `true` when the input string is valid /// func your_sha256_hashd() { let results = [ validator.performUsernameValidation(username: "j@j.com"), validator.performUsernameValidation(username: "something@simplenote.blog"), validator.performUsernameValidation(username: "something@simplenote.blog"), validator.performUsernameValidation(username: "something@simplenote.blog.ar") ] for result in results { XCTAssertEqual(result, .success) } } /// Verifies that `performPasswordValidation` returns `passwordTooShort` whenever the password doesn't meet the length requirement. /// func your_sha256_hashorterThanExpected() { guard case .passwordTooShort = validator.performPasswordValidation(username: "", password: "") else { XCTFail() return } // We can't really perform a straightforward comparison, because of the associated value! } /// Verifies that `performPasswordValidation` returns `passwordMatchesUsername` whenever the password matches the username. /// func your_sha256_hashUsername() { let result = validator.performPasswordValidation(username: "somethinghere", password: "somethinghere") XCTAssertEqual(result, .passwordMatchesUsername) } /// Verifies that `performPasswordValidation` returns `passwordContainsInvalidCharacter` whenever the password contains /// either Tabs or Newlines. /// func your_sha256_hashsInvalidCharacters() { let results = [ validator.performPasswordValidation(username: "somethinghere", password: "\t12345678"), validator.performPasswordValidation(username: "somethinghere", password: "\n12345678"), validator.performPasswordValidation(username: "somethinghere", password: "1234\n5678\t"), validator.performPasswordValidation(username: "somethinghere", password: "12345678\t") ] for result in results { XCTAssertEqual(result, .passwordContainsInvalidCharacter) } } } ```
/content/code_sandbox/SimplenoteTests/AuthenticationValidatorTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
457
```swift import Foundation import XCTest @testable import Simplenote // MARK: - NSPredicate+Email Unit Tests // class NSPredicateEmailTests: XCTestCase { /// Verifies that `predicateForEmailValidation` evaluates false whenever the input string is empty /// func testPredicateForEmailValidationEvaluatesFalseOnEmptyStrings() { let predicate = NSPredicate.predicateForEmailValidation() XCTAssertFalse(predicate.evaluate(with: "")) } /// Verifies that `predicateForEmailValidation` evaluates false whenever the input string doesn't contain `@` /// func your_sha256_hashharacter() { let predicate = NSPredicate.predicateForEmailValidation() XCTAssertFalse(predicate.evaluate(with: "simplenote.com")) } /// Verifies that `predicateForEmailValidation` evaluates false whenever the input string is a malformed address /// func testPredicateForEmailValidationEvaluatesFalseOnMalformedEmails() { let predicate = NSPredicate.predicateForEmailValidation() XCTAssertFalse(predicate.evaluate(with: "j@j..com")) XCTAssertFalse(predicate.evaluate(with: "j@j.com...ar")) XCTAssertFalse(predicate.evaluate(with: "@test")) XCTAssertFalse(predicate.evaluate(with: "@test.com")) XCTAssertFalse(predicate.evaluate(with: "test.com")) XCTAssertFalse(predicate.evaluate(with: "test.test.coffee")) } /// Verifies that `predicateForEmailValidation` evaluates true when the email is well formed /// func your_sha256_hashs() { let predicate = NSPredicate.predicateForEmailValidation() XCTAssertTrue(predicate.evaluate(with: "j@j.com")) XCTAssertTrue(predicate.evaluate(with: "something@seriouslynotrealbutvalidsimplenote.blog")) XCTAssertTrue(predicate.evaluate(with: "something@seriouslynotrealbutvalidsimplenote.blog.ar")) } /// Verifies that `predicateForEmailValidation` returns *true* when the email contains a New / Non Standard TLD /// func your_sha256_hashwTLDs() { let predicate = NSPredicate.predicateForEmailValidation() XCTAssertTrue(predicate.evaluate(with: "test@test.coffee")) XCTAssertTrue(predicate.evaluate(with: "test@test.email")) XCTAssertTrue(predicate.evaluate(with: "test@test.education")) } } ```
/content/code_sandbox/SimplenoteTests/NSPredicateEmailTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
474
```swift import XCTest @testable import Simplenote // MARK: - String Truncation Tests // class StringSimplenoteTests: XCTestCase { /// Verifies that `truncateWords(upTo:) ` returns the N first characters of the receiver, whenever there are no words in the specified range. /// func testTruncateWordsReturnsTruncatedStringWheneverThereAreNoWords() { let sample = "1234567890" let expected = "12345" XCTAssertEqual(sample.truncateWords(upTo: 5), expected) } /// Verifies that `truncateWords(upTo:) ` truncates the receiver's full words, up to a maximum length. /// func testTruncateWordsReturnsWordsInSpecifiedRangeUpToMaximumLength() { let sample = "uno dos tres catorce!" let expected = "uno dos" XCTAssertEqual(sample.truncateWords(upTo: 10), expected) } } // MARK: - String droppingPrefix Tests // extension StringSimplenoteTests { /// Tests that droppingPrefix returns string without a specified prefix /// func testDroppingPrefixReturnsStringWithoutSpecifiedPrefix() { let sample = "uno dos tres catorce!" let prefix = "uno " let expected = "dos tres catorce!" XCTAssertEqual(sample.droppingPrefix(prefix), expected) } /// Tests that droppingPrefix returns empty string if string is a prefix /// func testDroppingPrefixReturnsEmptyStringIfOriginalStringIsPrefix() { let prefix = "uno " let expected = "" XCTAssertEqual(prefix.droppingPrefix(prefix), expected) } /// Tests that droppingPrefix returns original string if string doesn't have a prefix /// func testDroppingPrefixReturnsOriginalStringIfPrefixIsNotFound() { let sample = "uno dos tres catorce!" let prefix = "dos" let expected = sample XCTAssertEqual(sample.droppingPrefix(prefix), expected) } } // MARK: - String locationOfFirstCharacter Tests // extension StringSimplenoteTests { /// Verifies that providing incorrect starting location returns nil /// func your_sha256_hashrEndIndex() { let sample = " test " XCTAssertNil(sample.locationOfFirstCharacter(from: .alphanumerics, startingFrom: (sample + sample).endIndex)) } /// Verifies correct location of first character in standard direction /// func testLocationOfFirstCharacterStandardDirection() { let sample = " test " let expected = sample.index(after: sample.startIndex) let actual = sample.locationOfFirstCharacter(from: .alphanumerics, startingFrom: sample.startIndex) XCTAssertEqual(actual, expected) } /// Verifies searching backwards from the start location of the string returns nil /// func your_sha256_hashnNil() { let sample = " test " let actual = sample.locationOfFirstCharacter(from: .alphanumerics, startingFrom: sample.startIndex, backwards: true) XCTAssertNil(actual) } /// Verifies correct location of first character in backwards direction /// func testLocationOfFirstCharacterBackwardDirection() { let sample = " test " let expected = sample.index(sample.endIndex, offsetBy: -2) let actual = sample.locationOfFirstCharacter(from: .alphanumerics, startingFrom: sample.endIndex, backwards: true) XCTAssertEqual(actual, expected) } /// Verifies searching from the end location of the string returns nil /// func your_sha256_hashil() { let sample = " test " let actual = sample.locationOfFirstCharacter(from: .alphanumerics, startingFrom: sample.endIndex) XCTAssertNil(actual) } /// Verifies the correct return from occurancesOf /// func testOccurancesOfReturnsCorrectValue() { let sampleA = "test x value, x test" let sampleB = "test x value x" let sampleC = "x test x value" let sampleD = "X test X value" let sampleE = "x test xxx valxue" let sampleF = "" let testValue = "x" XCTAssertEqual(sampleA.occurrences(of: testValue), 2) XCTAssertEqual(sampleB.occurrences(of: testValue), 2) XCTAssertEqual(sampleC.occurrences(of: testValue), 2) XCTAssertEqual(sampleD.occurrences(of: testValue), 0) XCTAssertEqual(sampleE.occurrences(of: testValue), 5) XCTAssertEqual(sampleF.occurrences(of: testValue), 0) } } ```
/content/code_sandbox/SimplenoteTests/StringSimplenoteTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
985
```swift @testable import Simplenote class MockTimerFactory: TimerFactory { var timer: MockTimer? override func scheduledTimer(with timeInterval: TimeInterval, completion: @escaping () -> Void) -> Timer { let timer = MockTimer() self.timer = timer timer.completion = completion return timer } } class MockTimer: Timer { var completion: (() -> Void)? convenience init(completion: (() -> Void)? = nil) { self.init() self.completion = completion } override func fire() { completion?() } override func invalidate() { completion = nil } } ```
/content/code_sandbox/SimplenoteTests/MockTimerFactory.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
137
```swift import XCTest @testable import Simplenote // MARK: - CGRect Tests // class CGRectSimplenoteTests: XCTestCase { /// Verifies that `splity(by:)` returns a zero height lower slice whenever the anchor has Zero location and Height /// func your_sha256_hashht() { let input = CGRect(x: .zero, y: .zero, width: 300, height: 300) let anchor = CGRect(x: .zero, y: .zero, width: 0, height: 0) let expectedBelow = CGRect(x: .zero, y: .zero, width: 300, height: 0) let (above, below) = input.split(by: anchor) XCTAssertEqual(above, input) XCTAssertEqual(below, expectedBelow) } /// Verifies that `splity(by:)` returns the expected Slices /// func testSplitByRectReturnsTheExpectedResultingSlices() { let input = CGRect(x: .zero, y: .zero, width: 300, height: 300) let anchor = CGRect(x: .zero, y: 100, width: .zero, height: 100) let expectedAbove = CGRect(x: .zero, y: 200, width: 300, height: 100) let expectedBelow = CGRect(x: .zero, y: .zero, width: 300, height: 100) let (above, below) = input.split(by: anchor) XCTAssertEqual(above, expectedAbove) XCTAssertEqual(below, expectedBelow) } } ```
/content/code_sandbox/SimplenoteTests/CGRectSimplenoteTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
341
```objective-c // // Use this file to import your target's public headers that you would like to expose to Swift. // #import "Simplenote-Bridging-Header.h" ```
/content/code_sandbox/SimplenoteTests/SimplenoteTests-Bridging-Header.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
37
```swift import XCTest import SimplenoteFoundation @testable import Simplenote // MARK: - NotesListControllerTests // class NotesListControllerTests: XCTestCase { /// InMemory Storage! /// private let storage = MockupStorageManager() /// List Controller /// private var noteListController: NotesListController! // MARK: - Overridden Methods override func setUp() { super.setUp() noteListController = NotesListController(viewContext: storage.viewContext) noteListController.performFetch() } override func tearDown() { super.tearDown() storage.reset() } // MARK: - Tests: Filters /// Verifies that the Filter property properly filters out non matching entities /// func your_sha256_hash() { let note = storage.insertSampleNote() storage.save() XCTAssertEqual(noteListController.numberOfObjects, 1) note.deleted = true storage.save() XCTAssertEqual(noteListController.numberOfObjects, 0) noteListController.filter = .deleted XCTAssertEqual(noteListController.numberOfObjects, 0) noteListController.performFetch() XCTAssertEqual(noteListController.numberOfObjects, 1) } // MARK: - Tests: Sorting /// Verifies that the SortMode property properly applies the specified order mode to the retrieved entities /// func testListControllerProperlyAppliesSortModeToRetrievedNotes() { let (notes, _, _) = insertSampleEntities(count: 100) storage.save() XCTAssertEqual(noteListController.numberOfObjects, notes.count) noteListController.sortMode = .alphabeticallyDescending noteListController.performFetch() let reversedNotes = Array(notes.reversed()) let retrievedNotes = noteListController.sections.first!.objects.compactMap { $0 as? Note } for (index, note) in retrievedNotes.enumerated() { XCTAssertEqual(note.content, reversedNotes[index].content) } } // MARK: - Tests: Sections /// Verifies that the Tag Entities aren't fetched when in Results Mode /// func testListControllerIgnoresTagsEntitiesWhenInResultsMode() { let (notes, _, _) = insertSampleEntities(count: 100) XCTAssertEqual(noteListController.numberOfObjects, 0) XCTAssertEqual(noteListController.sections.count, 1) XCTAssertEqual(noteListController.sections[0].numberOfObjects, 0) storage.save() XCTAssertEqual(noteListController.numberOfObjects, notes.count) XCTAssertEqual(noteListController.sections.count, 1) XCTAssertEqual(noteListController.sections[0].numberOfObjects, notes.count) } // MARK: - Tests: Search /// Verifies that the Tag Entities are fetched when in search mode /// func testSearchModeYieldsTwoSectionsWithMatchingEntities() { storage.insertSampleTag(name: "12345") storage.insertSampleNote(contents: "12345") storage.save() noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "34") XCTAssertEqual(noteListController.numberOfObjects, 2) XCTAssertEqual(noteListController.sections.count, 2) XCTAssertEqual(noteListController.sections[0].numberOfObjects, 1) XCTAssertEqual(noteListController.sections[1].numberOfObjects, 1) } /// Verifies that there are always *two* sections when in search mode, even when there are no objects /// func testSearchModeYieldsTwoSections() { noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "Something") XCTAssertEqual(noteListController.numberOfObjects, 0) XCTAssertEqual(noteListController.sections.count, 2) } /// Verifies that the `endSearch` switches the NotesList back to a single section /// func testEndSearchSwitchesBackToSingleSectionMode() { let (notes, _, _) = insertSampleEntities(count: 100) storage.save() XCTAssertEqual(noteListController.numberOfObjects, notes.count) noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "0") XCTAssertEqual(noteListController.numberOfObjects, notes.count + noteListController.limitForTagResults) noteListController.endSearch() XCTAssertEqual(noteListController.numberOfObjects, notes.count) } /// Verifies that the SearchMode disregards active Filters /// func testSearchModeYieldsGlobalResultsDisregardingActiveFilter() { let note = storage.insertSampleNote(contents: "Something Here") storage.save() noteListController.filter = .deleted noteListController.performFetch() XCTAssertEqual(noteListController.numberOfObjects, 0) noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "Here") let retrievedNote = noteListController.object(at: IndexPath(row: 0, section: 1)) as! Note XCTAssertEqual(retrievedNote, note) } /// Verifies that the SearchMode yields a limited number of Tags /// func testSearchModeReturnsLimitedNumberOfTags() { insertSampleEntities(count: 100) storage.save() noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "0") XCTAssert(noteListController.sections[0].numberOfObjects <= noteListController.limitForTagResults) } // MARK: - Tests: `object(at:)` /// Verifies that `object(at: IndexPath)` returns the proper Note when in results mode /// func testObjectAtIndexPathReturnsTheProperEntityWhenInResultsMode() { let (_, _, expected) = insertSampleEntities(count: 100) storage.save() for (index, payload) in expected.enumerated() { let note = noteListController.object(at: IndexPath(row: index, section: 0)) as! Note XCTAssertEqual(note.content, payload) } } /// Verifies that `object(at: IndexPath)` returns the proper Note when in Search Mode (without Keywords) /// func your_sha256_hashutKeywords() { let (_, _, expected) = insertSampleEntities(count: 100) storage.save() noteListController.beginSearch() // This is a specific keyword contained by eeeevery siiiiinnnnngle entity! noteListController.refreshSearchResults(keyword: "0") for (index, payload) in expected.enumerated() { let note = noteListController.object(at: IndexPath(row: index, section: 1)) as! Note XCTAssertEqual(note.content, payload) } // We're capping the number of Tags to 5! for (index, payload) in expected.enumerated() where index < noteListController.limitForTagResults { let tag = noteListController.object(at: IndexPath(row: index, section: 0)) as! Tag XCTAssertEqual(tag.name, payload) } } /// Verifies that `object(at: IndexPath)` returns the proper Note when in Search Mode (with Keywords) /// func your_sha256_hashomeKeyword() { insertSampleEntities(count: 100) storage.save() noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "055") XCTAssertEqual(noteListController.numberOfObjects, 2) let tag = noteListController.object(at: IndexPath(row: 0, section: 0)) as! Tag let note = noteListController.object(at: IndexPath(row: 0, section: 1)) as! Note XCTAssertEqual(tag.name, "055") XCTAssertEqual(note.content, "055") } // MARK: - Tests: `indexPath(forObject:)` /// Verifies that `indexPath(forObject:)` returns the proper Note when in Results Mode /// func testIndexPathForObjectReturnsTheProperPathWhenInResultsMode() { let (notes, _, _) = insertSampleEntities(count: 100) storage.save() for (row, note) in notes.enumerated() { let expected = IndexPath(row: row, section: 0) XCTAssertEqual(noteListController.indexPath(forObject: note), expected) } } /// Verifies that `indexPath(forObject:)` returns the proper Note/Tag when in Search Mode /// func testIndexPathForObjectReturnsTheProperPathWhenInSearchMode() { let (notes, tags, _) = insertSampleEntities(count: 100) storage.save() noteListController.beginSearch() // This is a specific keyword contained by eeeevery siiiiinnnnngle entity! noteListController.refreshSearchResults(keyword: "0") for (row, tag) in tags.enumerated() where row < noteListController.limitForTagResults { XCTAssertEqual(noteListController.indexPath(forObject: tag), IndexPath(row: row, section: 0)) } for (row, note) in notes.enumerated() { XCTAssertEqual(noteListController.indexPath(forObject: note), IndexPath(row: row, section: 1)) } } // MARK: - Tests: onBatchChanges /// Verifies that `onBatchChanges` is never called for **Tags** in the following scenarios: /// /// - Mode: Results /// - OP: Insert / Update / Delete /// func your_sha256_hashenInResultsMode() { noteListController.onBatchChanges = { (_, _) in XCTFail() } let tag = storage.insertSampleTag() storage.save() tag.name = "Updated" storage.save() storage.delete(tag) storage.save() } /// Verifies that `onBatchChanges` runs for **Notes** in the following scenarios /// /// - Mode: Results /// - OP: Insert /// func testOnBatchChangesDoesRunForNoteInsertionsWhenInResultsMode() { expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(inserted: [ IndexPath(row: 0, section: 0) ])) storage.insertSampleNote() storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Notes** in the following scenarios /// /// - Mode: Results /// - OP: Deletion /// func testOnBatchChangesDoesRunForNoteDeletionsWhenInResultsMode() { let note = storage.insertSampleNote() storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(deleted: [ IndexPath(row: 0, section: 0) ])) storage.delete(note) storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Notes** in the following scenarios /// /// - Mode: Results /// - OP: Update /// func testOnBatchChangesDoesRunForNoteUpdatesWhenInResultsMode() { let note = storage.insertSampleNote() storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(updated: [ IndexPath(row: 0, section: 0) ])) note.content = "Updated" storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Notes** in the following scenarios /// /// - Mode: Results /// - OP: Update /// func your_sha256_hashMoveOperations() { let firstNote = storage.insertSampleNote(contents: "A") storage.insertSampleNote(contents: "B") storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(moved: [ (from: IndexPath(row: 0, section: 0), to: IndexPath(row: 1, section: 0)) ])) firstNote.content = "C" storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Tag** in the following scenarios /// /// - Mode: Search /// - OP: Insert /// func testOnBatchChangesDoesRunForTagInsertionsWhenInSearchMode() { expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(inserted: [ IndexPath(row: 0, section: 0) ])) noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "Test") storage.insertSampleTag(name: "Test") storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Tag** in the following scenarios /// /// - Mode: Search /// - OP: Update /// func testOnBatchChangesDoesRunForTagUpdatesWhenInSearchMode() { let tag = storage.insertSampleTag(name: "Test") storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(updated: [ IndexPath(row: 0, section: 0) ])) noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "Test") tag.name = "Test Updated" storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Tag** in the following scenarios /// /// - Mode: Search /// - OP: Delete /// func testOnBatchChangesDoesRunForTagDeletionWhenInSearchMode() { let tag = storage.insertSampleTag(name: "Test") storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(deleted: [ IndexPath(row: 0, section: 0) ])) noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "Test") storage.delete(tag) storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Note** in the following scenarios /// /// - Mode: Search /// - OP: Insert /// func your_sha256_hashSectionIndexIsProperlyCorrected() { expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(inserted: [ IndexPath(row: 0, section: 1) ])) noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "Test") storage.insertSampleNote(contents: "Test") storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Note** in the following scenarios /// /// - Mode: Search /// - OP: Update /// func your_sha256_hashtionIndexIsProperlyCorrected() { let note = storage.insertSampleNote(contents: "Test") storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(updated: [ IndexPath(row: 0, section: 1) ])) noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "Test") note.content = "Test Updated" storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` runs for **Note** in the following scenarios /// /// - Mode: Search /// - OP: Delete /// func your_sha256_hashctionIndexIsProperlyCorrected() { let note = storage.insertSampleNote(contents: "Test") storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(deleted: [ IndexPath(row: 0, section: 1) ])) noteListController.beginSearch() noteListController.refreshSearchResults(keyword: "Test") storage.delete(note) storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` does not relay duplicated Changesets /// func testOnBatchChangesDoesNotRelayDuplicatedEvents() { storage.insertSampleNote(contents: "A") storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(inserted: [ IndexPath(row: 1, section: 0) ])) storage.insertSampleNote(contents: "B") storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } /// Verifies that `onBatchChanges` relays move events /// func testOnBatchChangesRelaysMoveEvents() { storage.insertSampleNote(contents: "A") storage.insertSampleNote(contents: "B") let note = storage.insertSampleNote(contents: "C") storage.save() expectBatchChanges(objectsChangeset: ResultsObjectsChangeset(moved: [ (from: IndexPath(row: 2, section: .zero), to: IndexPath(row: .zero, section: .zero)) ])) note.pinned = true storage.save() waitForExpectations(timeout: Constants.expectationTimeout, handler: nil) } } // MARK: - Private APIs // private extension NotesListControllerTests { /// Inserts `N` entities with ascending payloads (Name / Contents) /// @discardableResult func insertSampleEntities(count: Int) -> ([Note], [Tag], [String]) { var notes = [Note]() var tags = [Tag]() var expected = [String]() for index in 0..<100 { let payload = String(format: "%03d", index) tags.append( storage.insertSampleTag(name: payload) ) notes.append( storage.insertSampleNote(contents: payload) ) expected.append( payload ) } return (notes, tags, expected) } /// Expects the specified Object and Section changes to be relayed via `onBatchChanges` /// @discardableResult func expectBatchChanges(objectsChangeset: ResultsObjectsChangeset) -> XCTestExpectation { let expectation = self.expectation(description: "Waiting...") noteListController.onBatchChanges = { (receivedSectionChanges, receivedObjectChanges) in for (index, change) in objectsChangeset.deleted.enumerated() { XCTAssertEqual(change, objectsChangeset.deleted[index]) } for (index, change) in objectsChangeset.inserted.enumerated() { XCTAssertEqual(change, objectsChangeset.inserted[index]) } for (index, change) in objectsChangeset.moved.enumerated() { XCTAssertEqual(change.from, objectsChangeset.moved[index].from) XCTAssertEqual(change.to, objectsChangeset.moved[index].to) } for (index, change) in objectsChangeset.updated.enumerated() { XCTAssertEqual(change, objectsChangeset.updated[index]) } XCTAssertEqual(objectsChangeset.deleted.count, receivedObjectChanges.deleted.count) XCTAssertEqual(objectsChangeset.inserted.count, receivedObjectChanges.inserted.count) XCTAssertEqual(objectsChangeset.moved.count, receivedObjectChanges.moved.count) XCTAssertEqual(objectsChangeset.updated.count, receivedObjectChanges.updated.count) expectation.fulfill() } return expectation } } ```
/content/code_sandbox/SimplenoteTests/NotesListControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
4,101
```swift import XCTest @testable import Simplenote // MARK: - NoteScrollPositionCacheTests // class NoteScrollPositionCacheTests: XCTestCase { private lazy var storage = MockFileStorage<NoteScrollPositionCache.ScrollCache>(fileURL: URL(fileURLWithPath: "")) private lazy var cache = NoteScrollPositionCache(storage: storage) func testPositionsAreInitiallyLoadedFromStorage() { // Given let key = UUID().uuidString let value = CGFloat.random(in: -99999..<99999) storage.data = [key: value] // Then XCTAssertEqual(cache.position(for: key), value) } func testPositionsAreSavedToStorage() { // Given let key = UUID().uuidString let value = CGFloat.random(in: -99999..<99999) // When cache.store(position: value, for: key) // Then XCTAssertEqual(cache.position(for: key), value) XCTAssertEqual(storage.data, [key: value]) } func testOnlyProvidedKeysAreKeptDuringCleanup() { // Given let key1 = UUID().uuidString let value1 = CGFloat.random(in: -99999..<99999) let key2 = UUID().uuidString let value2 = CGFloat.random(in: -99999..<99999) cache.store(position: value1, for: key1) cache.store(position: value2, for: key2) // When cache.cleanup(keeping: [key1]) // Then XCTAssertEqual(cache.position(for: key1), value1) XCTAssertNil(cache.position(for: key2)) } } private class MockFileStorage<T: Codable>: FileStorage<T> { var data: T? = nil override func load() throws -> T? { return data } override func save(object: T) throws { data = object } } ```
/content/code_sandbox/SimplenoteTests/NoteScrollPositionCacheTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
409
```swift import Foundation import SimplenoteEndpoints @testable import Simplenote extension Remote { static func randomResult() -> Result<Data?, RemoteError> { if Bool.random() { return .success(nil) } return .failure(RemoteError(statusCode: 0, response: nil, networkError: nil)) } } ```
/content/code_sandbox/SimplenoteTests/RemoteResult+TestHelpers.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
73
```swift import XCTest @testable import Simplenote // MARK: - EmailVerificationTests // class EmailVerificationTests: XCTestCase { func testEmailVerificationCorrectlyParsesToken() { let payload = [ "token": #"{"username": "1234"}"# ] let parsed = EmailVerification(payload: payload) XCTAssertEqual(parsed.token?.username, "1234") } func testEmailVerificationCorrectlyParsesPending() { let payload = [ "sent_to": "1234" ] let parsed = EmailVerification(payload: payload) XCTAssertEqual(parsed.sentTo, "1234") } func testEmailVerificationCorrectlyParsesEmptyPayload() { let payload: [AnyHashable: Any] = [:] let parsed = EmailVerification(payload: payload) XCTAssertNil(parsed.token) XCTAssertNil(parsed.sentTo) } func testEmailVerificationIgnoresBrokenPayload() { let payload: [AnyHashable: Any] = [ "token": #"{"user": "1234"}"#, "sent_to": 1234 ] let parsed = EmailVerification(payload: payload) XCTAssertNil(parsed.token) XCTAssertNil(parsed.sentTo) } } ```
/content/code_sandbox/SimplenoteTests/EmailVerificationTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
264
```swift import Foundation import XCTest @testable import Simplenote // MARK: - Options Unit Tests // class OptionsTests: XCTestCase { private let suiteName = OptionsTests.classNameWithoutNamespaces.debugDescription private lazy var defaults = UserDefaults(suiteName: suiteName)! override func setUp() { super.setUp() defaults.reset() } func testEmptyLegacySortSettingsYieldModifiedNewest() { let options = Options(defaults: defaults) XCTAssert(options.listSortMode == .modifiedNewest) } func testLegacyAlphabeticalSortIsProperlyMigrated() { defaults.set(true, forKey: .listSortModeLegacy) let options = Options(defaults: defaults) XCTAssert(options.listSortMode == .alphabeticallyAscending) } func testLegacyUnspecifiedThemeIsProperlyMigrated() { let options = Options(defaults: defaults) XCTAssert(options.theme == .system) } func testLegacyDarkThemeIsProperlyMigrated() { defaults.set(true, forKey: .themeLegacy) let options = Options(defaults: defaults) XCTAssert(options.theme == .dark) } func testLegacyLightThemeIsProperlyMigrated() { defaults.set(false, forKey: .themeLegacy) let options = Options(defaults: defaults) XCTAssert(options.theme == .light) } } ```
/content/code_sandbox/SimplenoteTests/OptionsTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
290
```swift import Foundation /// Unit Tests Constants /// struct Constants { /// Default Expectation Timeout /// static let expectationTimeout = TimeInterval(10) } ```
/content/code_sandbox/SimplenoteTests/Constants.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
33
```swift import Foundation // MARK: - UserDefaults Extension Methods // extension UserDefaults { /// Resets all of the receiver's values /// func reset() { for (key, _) in dictionaryRepresentation() { removeObject(forKey: key) } synchronize() } } ```
/content/code_sandbox/SimplenoteTests/UserDefaults+Tests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
58
```swift import XCTest @testable import Simplenote // MARK: - NSMutableAttributedString Styling Tests // class NSMutableAttributedStringStylingTests: XCTestCase { /// Verifies that `NSRegularExpression.regexForChecklists` will not match checklists that are in the middle of a string /// func your_sha256_hashTheString() { let string = "This is a badly formed todo - [ ] Buy avocados - []" let regex = NSRegularExpression.regexForChecklists let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertTrue(matches.isEmpty) } /// Verifies that `NSRegularExpression.regexForChecklistsEmbeddedAnywhere` matches multiple checklists in the same line /// func your_sha512_hash() { let string = "The second regex should consider this as a valid checklist - [ ] Buy avocados - []" let regex = NSRegularExpression.regexForChecklistsEmbeddedAnywhere let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertEqual(matches.count, 2) } /// Verifies that `NSRegularExpression.regexForChecklists` matches multiple spacing prefixes /// func testRegexForChecklistsProperlyMatchesMultipleWhitespacePrefixes() { let string = " - [ ] Buy avocados - [ ]" let regex = NSRegularExpression.regexForChecklists let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertEqual(matches.count, 1) } /// Verifies that `NSRegularExpression.regexForChecklistsEmbeddedAnywhere` matches multiple spacing prefixes /// func your_sha256_hashePrefixes() { let string = " - [ ] Buy avocados - [ ]" let regex = NSRegularExpression.regexForChecklistsEmbeddedAnywhere let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertEqual(matches.count, 2) } /// Verifies that `NSRegularExpression.regexForChecklists` only matches corretly formed strings /// func testRegexForChecklistsMatchProperlyFormattedChecklists() { let string = "ToDo\n\n- [ ] Buy avocados\n- [ ] Ship it\n- [x ] Malformed!\n- [x] Correct." let regex = NSRegularExpression.regexForChecklists let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertEqual(matches.count, 3) } /// Verifies that `NSRegularExpression.regexForChecklists` will not match malformed strings /// func testRegexForChecklistsWillNotMatchMalformedChecklists() { let string = "- [x ] Malformed!" let regex = NSRegularExpression.regexForChecklists let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertTrue(matches.isEmpty) } /// Verifies that `NSRegularExpression.regexForChecklistsEverywhere` will not match malformed strings /// func testRegexForChecklistsEverywhereWillNotMatchMalformedChecklists() { let string = "- [x ] Malformed!" let regex = NSRegularExpression.regexForChecklistsEmbeddedAnywhere let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertTrue(matches.isEmpty) } /// Verifies that `NSRegularExpression.regexForChecklists` will match checklists with no spaces between brackets /// func testRegexForChecklistsWillMatchChecklistsWithNoInternalSpaces() { let string = "- [] Item" let regex = NSRegularExpression.regexForChecklists let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertEqual(matches.count, 1) } /// Verifies that `NSRegularExpression.regexForChecklistsEmbeddedAnywhere` will match checklists with no spaces between brackets /// func your_sha256_hashlSpaces() { let string = "- [] Item" let regex = NSRegularExpression.regexForChecklistsEmbeddedAnywhere let matches = regex.matches(in: string, options: [], range: string.fullRange) XCTAssertEqual(matches.count, 1) } /// Verifies that `NSRegularExpression.regexForChecklists` always produces the expected number of ranges /// func testRegexForChecklistsAlwaysProduceTwoRanges() { let samples = [ (text: " - [ ] Buy avocados - [ ]", expected: 1), (text: "ToDo\n\n- [ ] Buy avocados\n- [ ] Ship it\n- [x ] Malformed!\n- [x] Correct.", expected: 3), (text: "- [] Item", expected: 1) ] let regex = NSRegularExpression.regexForChecklists for (sample, expected) in samples { let matches = regex.matches(in: sample, options: [], range: sample.fullRange) XCTAssertEqual(matches.count, expected) for match in matches where match.numberOfRanges != NSRegularExpression.regexForChecklistsExpectedNumberOfRanges { XCTFail() } } } /// Verifies that `NSRegularExpression.regexForChecklistsEmbeddedAnywhere` always produces the expected number of ranges /// func testRegexForChecklistsEverywhereAlwaysProduceTwoRanges() { let samples = [ (text: " - [ ] Buy avocados - [ ]", expected: 2), (text: "ToDo\n\n- [ ] Buy avocados\n- [ ] Ship it\n- [x ] Malformed!\n- [x] Correct.", expected: 3), (text: "- [] Item", expected: 1), (text: "The second regex should consider this as a valid checklist - [ ] Buy avocados - []", expected: 2) ] let regex = NSRegularExpression.regexForChecklistsEmbeddedAnywhere for (sample, expected) in samples { let matches = regex.matches(in: sample, options: [], range: sample.fullRange) XCTAssertEqual(matches.count, expected) for match in matches where match.numberOfRanges != NSRegularExpression.regexForChecklistsExpectedNumberOfRanges { XCTFail() } } } } ```
/content/code_sandbox/SimplenoteTests/NSMutableAttributedStringStylingTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,313
```swift import Foundation import XCTest @testable import Simplenote // MARK: - NSString+Condensing Unit Tests // class NSStringCondensingTests: XCTestCase { /// Verifies that `replacingNewlinesWithSpaces` returns an empty string, whenever the receiver is an empty string /// func testReplaceNewlinesWithSpacesDoesNotBreakWithEmptyStrings() { let sample: NSString = "" XCTAssertEqual(sample.replacingNewlinesWithSpaces(), "") } /// Verifies that `replacingNewlinesWithSpaces` returns an empty string, whenever the receiver is a string containing a single Newline /// func testReplaceNewlinesWithSpacesProperlyHandlesSingleNewlineString() { let sample: NSString = "\n" XCTAssertEqual(sample.replacingNewlinesWithSpaces(), "") } /// Verifies that `replacingNewlinesWithSpaces` returns an empty string, whenever the receiver is a string containing *Multiple* Newline(s) /// func your_sha256_hashg() { let sample: NSString = "\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r" XCTAssertEqual(sample.replacingNewlinesWithSpaces(), "") } /// Verifies that `replacingNewlinesWithSpaces` replaces consecutive newlines with a single space /// func your_sha256_hashSingleSpace() { let sample: NSString = "WORD1\n\n\n\r\nWORD2\nWORD3\n\r\n\r\n\rWORD4" XCTAssertEqual(sample.replacingNewlinesWithSpaces(), "WORD1 WORD2 WORD3 WORD4") } /// Verifies that `replacingNewlinesWithSpaces` trims leading and trailing newlines /// func testReplaceNewlinesWithSpacesTrimsLeadingAndTrailingNewlines() { let sample: NSString = "\n\r\n\r\n\n\nWORD1\nWORD2\n\nWORD3\n\n\n\n" XCTAssertEqual(sample.replacingNewlinesWithSpaces(), "WORD1 WORD2 WORD3") } } ```
/content/code_sandbox/SimplenoteTests/NSStringCondensingTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
429
```swift import XCTest @testable import Simplenote class UIColorSimplenoteTests: XCTestCase { func testUIColorFromHexStringReturnsCorrectColor() { //spBlue20 in RGB is r: 132 g: 164 b: 240 let spBlue20 = UIColor(hexString: "84a4f0") //gray5 in RGB is r: 220 g: 220 b: 222 let gray5 = UIColor(hexString: "dcdcde") let spBlue20RGB = UIColor(red: rgbPercent(132), green: rgbPercent(164), blue: rgbPercent(240), alpha: 1) let gray5RGB = UIColor(red: rgbPercent(220), green: rgbPercent(220), blue: rgbPercent(222), alpha: 1) XCTAssertEqual(spBlue20, spBlue20RGB) XCTAssertEqual(gray5, gray5RGB) } func rgbPercent(_ value: Double) -> CGFloat { return CGFloat(value / 255.0) } func testUIColorFromHexStringRemovesHashtagIfPresent() { //spBlue20 in RGB is r: 132 g: 164 b: 240 let spBlue20 = UIColor(hexString: "#84a4f0") //gray5 in RGB is r: 220 g: 220 b: 222 let gray5 = UIColor(hexString: "#dcdcde") let spBlue20RGB = UIColor(red: rgbPercent(132), green: rgbPercent(164), blue: rgbPercent(240), alpha: 1) let gray5RGB = UIColor(red: rgbPercent(220), green: rgbPercent(220), blue: rgbPercent(222), alpha: 1) XCTAssertEqual(spBlue20, spBlue20RGB) XCTAssertEqual(gray5, gray5RGB) } } ```
/content/code_sandbox/SimplenoteTests/UIColorSimplenoteTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
392
```swift import Foundation import CoreData @testable import Simplenote /// MockupStorageManager: InMemory CoreData Stack. /// class MockupStorageManager { /// DataModel Name /// private let name = "Simplenote" /// Returns the Storage associated with the View Thread. /// var viewContext: NSManagedObjectContext { return persistentContainer.viewContext } /// Persistent Container: Holds the full CoreData Stack /// private(set) lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: name, managedObjectModel: managedModel) container.persistentStoreDescriptions = [storeDescription] container.loadPersistentStores { (storeDescription, error) in if let error = error as NSError? { fatalError("[MockupStorageManager] Fatal Error: \(error) [\(error.userInfo)]") } } return container }() /// Nukes the specified Object /// func delete(_ object: NSManagedObject) { viewContext.delete(object) } /// This method effectively destroys all of the stored data, and generates a blank Persistent Store from scratch. /// func reset() { let storeCoordinator = persistentContainer.persistentStoreCoordinator let storeDescriptor = self.storeDescription let viewContext = persistentContainer.viewContext viewContext.performAndWait { do { viewContext.reset() for store in storeCoordinator.persistentStores { try storeCoordinator.remove(store) } } catch { fatalError(" [MockupStorageManager] Cannot Destroy persistentStore! \(error)") } storeCoordinator.addPersistentStore(with: storeDescriptor) { (_, error) in guard let error = error else { return } fatalError(" [MockupStorageManager] Unable to regenerate Persistent Store! \(error)") } NSLog(" [MockupStorageManager] Stack Destroyed!") } } /// "Persists" the changes /// func save() { try? viewContext.save() } } // MARK: - Descriptors // extension MockupStorageManager { /// Returns the Application's ManagedObjectModel /// var managedModel: NSManagedObjectModel { guard let mom = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("[MockupStorageManager] Could not load model") } return mom } /// Returns the PersistentStore Descriptor /// var storeDescription: NSPersistentStoreDescription { let description = NSPersistentStoreDescription() description.type = NSInMemoryStoreType return description } } // MARK: - Stack URL's // extension MockupStorageManager { /// Returns the ManagedObjectModel's URL: Pick this up from the Storage bundle. OKAY? /// var modelURL: URL { let bundle = Bundle(for: Note.self) guard let url = bundle.url(forResource: name, withExtension: "momd") else { fatalError("[MockupStorageManager] Missing Model Resource") } return url } } ```
/content/code_sandbox/SimplenoteTests/MockupStorage.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
639
```swift import XCTest @testable import Simplenote // MARK: - String Truncation Tests // class NoteBodyExcerptTests: XCTestCase { /// InMemory Storage! /// private let storage = MockupStorageManager() private let noteBody = "Download the latest version of Simplenote and youll be able to insert links from one note into another note to easily organize and cross-reference\ninformation" private lazy var noteBodyWithoutNewlines = noteBody.replacingOccurrences(of: "\n", with: " ") private lazy var note = storage.insertSampleNote(contents: "Title \n \(noteBody)") private lazy var titleOnlyNote = storage.insertSampleNote(contents: "Title") override func setUp() { note.ensurePreviewStringsAreAvailable() titleOnlyNote.ensurePreviewStringsAreAvailable() } /// Verifies that nil is returned when keywords are nil /// func testProvidingNilKeywordsReturnsBodyPreview() { let expected = noteBodyWithoutNewlines let actual = note.bodyExcerpt(keywords: nil) XCTAssertEqual(actual, expected) } /// Verifies that nil is returned when keywords are empty /// func testProvidingEmptyKeywordsReturnsBodyPreview() { let expected = noteBodyWithoutNewlines let actual = note.bodyExcerpt(keywords: []) XCTAssertEqual(actual, expected) } /// Verifies that nil is returned when note has only title /// func testNoteWithOnlyTitleReturnsNil() { let actual = titleOnlyNote.bodyExcerpt(keywords: ["Title"]) XCTAssertNil(actual) } /// Verifies that when keywords are not found, body preview is returned /// func testProvidingNonExistingKeywordsReturnsBodyPreview() { let expected = noteBodyWithoutNewlines let actual = note.bodyExcerpt(keywords: ["abcdef"]) XCTAssertEqual(actual, expected) } /// Verifies that ellipsis is added if excerpt doesn't start at the beginning /// func testEllipsisIsAddedIfExcerptDoesntStartAtTheBeginning() { let expected = "organize and cross-reference information" let actual = note.bodyExcerpt(keywords: ["information"]) XCTAssertEqual(actual, expected) } /// Verifies that no ellipsis is added if excerpt starts at the beginning /// func testNoEllipsisIsAddedIfExcerptStartsAtTheBeginning() { let expected = noteBody.replacingOccurrences(of: "\n", with: " ") let actual = note.bodyExcerpt(keywords: ["version"]) XCTAssertEqual(actual, expected) } /// Verifies that certain character sequence doesn't crash the app /// func testCertainCharacterSequenceDoesntCrash() { let body = "t\n\u{30bf}\nglo\u{0300}b" note = storage.insertSampleNote(contents: "Title\n\(body)") let expected = body.replacingOccurrences(of: "\n", with: " ") let actual = note.bodyExcerpt(keywords: ["t"]) XCTAssertEqual(actual, expected) } } ```
/content/code_sandbox/SimplenoteTests/NoteBodyExcerptTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
654
```swift import XCTest @testable import Simplenote class NoticeControllerTests: XCTestCase { private lazy var presenter = MockNoticePresenter() private lazy var timerFactory = MockTimerFactory() private lazy var controller = NoticeController(presenter: presenter, timerFactory: timerFactory) func testSetupNoticeContoller() { controller.setupNoticeController() XCTAssertTrue(presenter.listeningToKeyboard == true) } func testPresentNotice() { let notice = Notice(message: "Message", action: nil) let expectedActions: [MockNoticePresenter.Action] = [ .present(notice.message) ] controller.present(notice) XCTAssertEqual(expectedActions, presenter.actionLog) XCTAssertEqual(presenter.lastNoticeView?.message, notice.message) } func testControllerDissmissesNoticeIfAlreadyPresenting() { let noticeA = Notice(message: "Message A", action: nil) let noticeB = Notice(message: "Message B", action: nil) var expectedActions: [MockNoticePresenter.Action] = [] controller.present(noticeA) expectedActions.append(.present(noticeA.message)) controller.present(noticeB) expectedActions.append(.dismiss(noticeA.message)) expectedActions.append(.present(noticeB.message)) XCTAssertEqual(expectedActions, presenter.actionLog) XCTAssertEqual(presenter.lastNoticeView?.message, noticeB.message) } func testMakeNoticeView() throws { let notice = Notice(message: "Message", action: nil) controller.present(notice) XCTAssertEqual(notice.message, presenter.lastNoticeView?.message) XCTAssertEqual(notice.action?.title, presenter.lastNoticeView?.actionTitle) XCTAssertNil(presenter.lastNoticeView?.handler) } func testMakeNoticeViewWithAction() { let action = NoticeAction(title: "Title") { print("Action") } let notice = Notice(message: "Message ", action: action) checkNoticeViewPropertiesCreatedCorrectly(notice) } func testMakeNoticeViewWithEmptyNotice() { let action = NoticeAction(title: "") { } let notice = Notice(message: "", action: action) checkNoticeViewPropertiesCreatedCorrectly(notice) } private func checkNoticeViewPropertiesCreatedCorrectly(_ notice: Notice) { controller.present(notice) XCTAssertEqual(notice.message, presenter.lastNoticeView?.message) XCTAssertEqual(notice.action?.title, presenter.lastNoticeView?.actionTitle) XCTAssertNotNil(presenter.lastNoticeView?.handler) } func testDismiss() throws { let noticeA = Notice(message: "Message A", action: nil) controller.present(noticeA) var expectedActions: [MockNoticePresenter.Action] = [ .present(noticeA.message) ] try XCTUnwrap(timerFactory.timer).fire() expectedActions.append(.dismiss(noticeA.message)) XCTAssertEqual(expectedActions, presenter.actionLog) } func testPressingOnActionDismissesNotice() { let action = NoticeAction(title: "Action", handler: {}) let noticeA = Notice(message: "Message A", action: action) controller.present(noticeA) var expectedActions: [MockNoticePresenter.Action] = [ .present(noticeA.message) ] controller.actionWasTapped() expectedActions.append(.dismiss(noticeA.message)) XCTAssertEqual(expectedActions, presenter.actionLog) } func testLongPressInvalidatesTimerAndNoticeDoesNotDismiss() { let noticeA = Notice(message: "Message A", action: nil) controller.present(noticeA) let expectedActions: [MockNoticePresenter.Action] = [ .present(noticeA.message) ] controller.noticePressBegan() XCTAssertEqual(expectedActions, presenter.actionLog) XCTAssertNil(timerFactory.timer?.completion) } func testLongPressReleasedDismissesTimer() throws { let noticeA = Notice(message: "Message A", action: nil) controller.present(noticeA) controller.noticePressBegan() controller.noticePressEnded() try XCTUnwrap(timerFactory.timer).fire() let expectedActions: [MockNoticePresenter.Action] = [ .present(noticeA.message), .dismiss(noticeA.message) ] XCTAssertEqual(expectedActions, presenter.actionLog) } } extension NoticeControllerTests { static var timeInterval = TimeInterval.zero static var timerNoActionCompletionHandler: (Timer) -> Void = { (_) in } } class MockNoticePresenter: NoticePresenter { enum Action: Equatable { case present(String?) case dismiss(String?) } var actionLog: [Action] = [] var listeningToKeyboard: Bool = false var lastNoticeView: NoticeView? override func presentNoticeView(_ noticeView: NoticeView, completion: @escaping () -> Void) { lastNoticeView = noticeView actionLog.append(.present(noticeView.message)) completion() } override func dismissNotification(withDuration duration: TimeInterval = UIKitConstants.animationLongDuration, completion: (() -> Void)? = nil) { let noticeView = try! XCTUnwrap(lastNoticeView) lastNoticeView = nil actionLog.append(.dismiss(noticeView.message)) completion?() } override func startListeningToKeyboardNotifications() { listeningToKeyboard = true } } ```
/content/code_sandbox/SimplenoteTests/NoticeControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,123
```swift import XCTest @testable import Simplenote // MARK: - PinLockRemoveControllerTests // class PinLockRemoveControllerTests: XCTestCase { private lazy var delegate = MockPinLockRemoveControllerDelegate() private lazy var pinLockManager = MockPinLockManager() private lazy var controller = PinLockRemoveController(pinLockManager: pinLockManager, delegate: delegate) private lazy var configurationObserver = PinLockControllerConfigurationObserver() func testProvidingInvalidPinShakesUI() { // Given controller.configurationObserver = configurationObserver.handler // When controller.handlePin(UUID().uuidString) // Then XCTAssertEqual(configurationObserver.animations, [nil, .shake]) } func testProvidingInvalidPinDoesntRemovePin() { // When controller.handlePin(UUID().uuidString) // Then delegate.assertNotCalled() XCTAssertEqual(pinLockManager.numberOfTimesRemovePinIsCalled, 0) } func testProvidingValidPinRemovesIt() { // When controller.handlePin(pinLockManager.actualPin) // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 1) XCTAssertEqual(delegate.numberOfTimesCancelIsCalled, 0) XCTAssertEqual(pinLockManager.numberOfTimesRemovePinIsCalled, 1) } func testCancelCallsDelegate() { // When controller.handleCancellation() // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 0) XCTAssertEqual(delegate.numberOfTimesCancelIsCalled, 1) XCTAssertEqual(pinLockManager.numberOfTimesRemovePinIsCalled, 0) } } // MARK: - MockPinLockRemoveControllerDelegate // private class MockPinLockRemoveControllerDelegate: PinLockRemoveControllerDelegate { var numberOfTimesCompleteIsCalled: Int = 0 var numberOfTimesCancelIsCalled: Int = 0 func pinLockRemoveControllerDidComplete(_ controller: PinLockRemoveController) { numberOfTimesCompleteIsCalled += 1 } func pinLockRemoveControllerDidCancel(_ controller: PinLockRemoveController) { numberOfTimesCancelIsCalled += 1 } func assertNotCalled() { XCTAssertEqual(numberOfTimesCompleteIsCalled, 0) XCTAssertEqual(numberOfTimesCancelIsCalled, 0) } } ```
/content/code_sandbox/SimplenoteTests/PinLock/PinLockRemoveControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
478
```swift import XCTest @testable import Simplenote // MARK: - String Content Slice Tests // class StringContentSliceTests: XCTestCase { private let sampleExcerpt = "Download the latest version of Simplenote and youll be able to insert links from one note into another note to easily organize and cross-reference information." private lazy var sample = """ Excited to announce that one of our most frequently-requested features, the ability to link to a note from within nThR note, is now available. \(sampleExcerpt) Internal note links begin with simplenote:// instead of the usual https:// prefix, which lets the app know that it should load up a different note within the editor. """ private lazy var sampleExcerptRange = sample.range(of: sampleExcerpt)! /// Providing empty keywords will return nil /// func testProvidingEmptyKeywordsReturnsNil() { XCTAssertNil(sample.contentSlice(matching: [])) } /// When no matches are found, return nil /// func testNoMatchesReturnsNil() { XCTAssertNil(sample.contentSlice(matching: ["abcdef"])) } /// Test that all matches of a given keyword are found /// func testAllMatchesOfAGivenKeywordAreFound() { let expected = ContentSlice(content: sample, range: sample.fullRange, matches: sample.ranges(of: "Simplenote")) let actual = sample.contentSlice(matching: ["Simplenote"]) XCTAssertEqual(actual, expected) XCTAssertEqual(actual?.matches.count, 2) } /// Test that returned ranges are for full words, even when keywords are substrings /// func testMatchedRangesAreFullWords() { let expected = ContentSlice(content: sample, range: sample.fullRange, matches: sample.ranges(of: "Simplenote")) let actual = sample.contentSlice(matching: ["mplen"]) XCTAssertEqual(actual, expected) } /// Test that by providing range matching is limited to that range /// func testProvidingRangeWillLimitMatching() { let expected = ContentSlice(content: sample, range: sampleExcerptRange, matches: [sample.range(of: "Simplenote")!]) let actual = sample.contentSlice(matching: ["Simplenote"], in: sampleExcerptRange) XCTAssertEqual(actual, expected) XCTAssertEqual(actual?.matches.count, 1) } /// Test that using leading and trailing limit doesn't cut half word /// func testLeadingAndTrailingLimitUsesFullWords() { let expectedRange = sample.range(of: "version of Simplenote and youll")! let expected = ContentSlice(content: sample, range: expectedRange, matches: [sample.range(of: "Simplenote")!]) let actual = sample.contentSlice(matching: ["Simplenote"], leadingLimit: 15, trailingLimit: 12) XCTAssertEqual(actual, expected) XCTAssertEqual(actual?.matches.count, 1) } /// Test that matching is case and diactric insensitive /// func testMatchingIsCaseAndDiactricInsensitive() { let expected = ContentSlice(content: sample, range: sample.fullRange, matches: sample.ranges(of: "another")) let actual = sample.contentSlice(matching: ["otHer"]) XCTAssertEqual(actual, expected) } /// Test that all provided keywords are used for matching /// func testMatchingMultipleKeywords() { let keywords = ["Excited", "instead", "editor"] let expectedRanges = keywords.map { sample.range(of: $0)! } let expected = ContentSlice(content: sample, range: sample.fullRange, matches: expectedRanges) let actual = sample.contentSlice(matching: keywords) XCTAssertEqual(actual, expected) } } private extension String { func ranges(of substring: String) -> [Range<Index>] { var ranges: [Range<Index>] = [] while let range = range(of: substring, options: [.caseInsensitive, .diacriticInsensitive], range: (ranges.last?.upperBound ?? startIndex)..<endIndex, locale: nil) { ranges.append(range) } return ranges } } ```
/content/code_sandbox/SimplenoteTests/StringContentSliceTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
907
```swift import XCTest @testable import Simplenote // MARK: - PinLockBaseControllerTests // class PinLockBaseControllerTests: XCTestCase { private let controller = PinLockBaseController() private let configurationObserver = PinLockControllerConfigurationObserver() func your_sha256_hashon() { // Given let configuration = PinLockControllerConfiguration.random() // When controller.configuration = configuration controller.configurationObserver = configurationObserver.handler // Then XCTAssertEqual(configurationObserver.configurations, [configuration]) XCTAssertEqual(configurationObserver.animations, [nil]) } func testSwitchToConfigurationCallsObserver() { // Given let configuration = PinLockControllerConfiguration.random() let animation = UIView.ReloadAnimation.slideLeading // When controller.configurationObserver = configurationObserver.handler controller.switchTo(configuration, with: animation) // Then XCTAssertEqual(configurationObserver.lastConfiguration, configuration) XCTAssertEqual(configurationObserver.lastAnimation, animation) } } ```
/content/code_sandbox/SimplenoteTests/PinLock/PinLockBaseControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
202
```swift import XCTest @testable import Simplenote // MARK: - PinLockSetupControllerTests // class PinLockSetupControllerTests: XCTestCase { private lazy var delegate = MockPinLockSetupControllerDelegate() private lazy var pinLockManager = MockPinLockManager() private lazy var controller = PinLockSetupController(pinLockManager: pinLockManager, delegate: delegate) private lazy var configurationObserver = PinLockControllerConfigurationObserver() func testProvidingEmptyMatchingPinsDontUpdatePin() { // Given controller.configurationObserver = configurationObserver.handler // When controller.handlePin("") controller.handlePin("") // Then delegate.assertNotCalled() XCTAssertEqual(configurationObserver.animations, [nil, .shake, .shake]) XCTAssertEqual(pinLockManager.setPinInvocations, []) } func testNonMatchingPinsDontUpdatePin() { // Given controller.configurationObserver = configurationObserver.handler // When controller.handlePin(UUID().uuidString) controller.handlePin(UUID().uuidString) // Then delegate.assertNotCalled() XCTAssertEqual(configurationObserver.animations, [nil, .slideLeading, .slideTrailing]) XCTAssertEqual(pinLockManager.setPinInvocations, []) } func testMatchingPinsUpdatePinAndCallDelegate() { // Given let pin = UUID().uuidString controller.configurationObserver = configurationObserver.handler // When controller.handlePin(pin) controller.handlePin(pin) // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 1) XCTAssertEqual(delegate.numberOfTimesCancelIsCalled, 0) XCTAssertEqual(configurationObserver.animations, [nil, .slideLeading]) XCTAssertEqual(pinLockManager.setPinInvocations, [pin]) } func testProvidingOnlyOnePinDoesntTriggerUpdate() { // Given let pin = UUID().uuidString controller.configurationObserver = configurationObserver.handler // When controller.handlePin(pin) // Then delegate.assertNotCalled() XCTAssertEqual(configurationObserver.animations, [nil, .slideLeading]) XCTAssertEqual(pinLockManager.setPinInvocations, []) } func testCancelCallsDelegate() { // When controller.handleCancellation() // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 0) XCTAssertEqual(delegate.numberOfTimesCancelIsCalled, 1) XCTAssertEqual(pinLockManager.setPinInvocations, []) } } // MARK: - MockPinLockSetupControllerDelegate // private class MockPinLockSetupControllerDelegate: PinLockSetupControllerDelegate { var numberOfTimesCompleteIsCalled: Int = 0 var numberOfTimesCancelIsCalled: Int = 0 func pinLockSetupControllerDidComplete(_ controller: PinLockSetupController) { numberOfTimesCompleteIsCalled += 1 } func pinLockSetupControllerDidCancel(_ controller: PinLockSetupController) { numberOfTimesCancelIsCalled += 1 } func assertNotCalled() { XCTAssertEqual(numberOfTimesCompleteIsCalled, 0) XCTAssertEqual(numberOfTimesCancelIsCalled, 0) } } ```
/content/code_sandbox/SimplenoteTests/PinLock/PinLockSetupControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
651
```swift import Foundation @testable import Simplenote // MARK: - PinLockControllerConfigurationObserver // class PinLockControllerConfigurationObserver { var lastConfiguration: PinLockControllerConfiguration? { configurations.last } var lastAnimation: UIView.ReloadAnimation? { animations.last ?? nil } var configurations: [PinLockControllerConfiguration] { invocations.map({ $0.0 }) } var animations: [UIView.ReloadAnimation?] { invocations.map({ $0.1 }) } var invocations: [(PinLockControllerConfiguration, UIView.ReloadAnimation?)] = [] func handler(_ configuration: PinLockControllerConfiguration, _ animation: UIView.ReloadAnimation?) { invocations.append((configuration, animation)) } } ```
/content/code_sandbox/SimplenoteTests/PinLock/Helpers/PinLockControllerConfigurationObserver.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
161
```swift import XCTest @testable import Simplenote // MARK: - PinLockVerifyControllerTests // class PinLockVerifyControllerTests: XCTestCase { private lazy var delegate = MockPinLockVerifyControllerDelegate() private lazy var pinLockManager = MockPinLockManager() private lazy var controller = PinLockVerifyController(pinLockManager: pinLockManager, application: MockApplication(), delegate: delegate) private lazy var configurationObserver = PinLockControllerConfigurationObserver() func testProvidingInvalidPinShakesUI() { // Given controller.configurationObserver = configurationObserver.handler // When controller.handlePin(UUID().uuidString) // Then XCTAssertEqual(configurationObserver.animations, [nil, .shake]) } func testProvidingInvalidPinDoesntCallDelegate() { // When controller.handlePin(UUID().uuidString) // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 0) } func testProvidingValidPinCallsDelegate() { // When controller.handlePin(pinLockManager.actualPin) // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 1) } func testCancelDoesntCallDelegate() { // When controller.handleCancellation() // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 0) } func testBiometryIsEvaluatedWhenApplicationBecomesActive() { // When controller.applicationDidBecomeActive() // Then XCTAssertEqual(pinLockManager.evaluateBiometryCompletions.count, 1) } func testBiometryIsEvaluatedWhenViewAppears() { // When controller.viewDidAppear() // Then XCTAssertEqual(pinLockManager.evaluateBiometryCompletions.count, 1) } func testEvaluationIsPresentedOnlyOnce() { // When controller.viewDidAppear() controller.viewDidAppear() // Then XCTAssertEqual(pinLockManager.evaluateBiometryCompletions.count, 1) } func testEvaluationIsNotPresentedAgainAfterItIsCancelled() throws { // When controller.viewDidAppear() try pinLockManager.evaluateBiometry(withSuccess: false) controller.viewDidAppear() // Then XCTAssertEqual(pinLockManager.evaluateBiometryCompletions.count, 0) } func testFailedBiometryEvaluationDoesntCallDelegate() throws { // When controller.viewDidAppear() try pinLockManager.evaluateBiometry(withSuccess: false) // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 0) } func testSuccessfulBiometryEvaluationCallsDelegate() throws { // When controller.viewDidAppear() try pinLockManager.evaluateBiometry(withSuccess: true) // Then XCTAssertEqual(delegate.numberOfTimesCompleteIsCalled, 1) } } // MARK: - MockPinLockVerifyControllerDelegate // private class MockPinLockVerifyControllerDelegate: PinLockVerifyControllerDelegate { var numberOfTimesCompleteIsCalled: Int = 0 func pinLockVerifyControllerDidComplete(_ controller: PinLockVerifyController) { numberOfTimesCompleteIsCalled += 1 } } ```
/content/code_sandbox/SimplenoteTests/PinLock/PinLockVerifyControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
661
```swift import Foundation @testable import Simplenote // MARK: - PinLockControllerConfiguration // extension PinLockControllerConfiguration { static func random() -> PinLockControllerConfiguration { return PinLockControllerConfiguration(title: UUID().uuidString, message: UUID().uuidString) } } ```
/content/code_sandbox/SimplenoteTests/PinLock/Helpers/PinLockControllerConfiguration+Tests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
61
```swift import XCTest @testable import Simplenote // MARK: - MockPinLockManager // class MockPinLockManager: SPPinLockManager { var actualPin: String = UUID().uuidString var setPinInvocations: [String] = [] var numberOfTimesRemovePinIsCalled: Int = 0 var evaluateBiometryCompletions: [(Bool) -> Void] = [] override func setPin(_ pin: String) { setPinInvocations.append(pin) } override func validatePin(_ pin: String) -> Bool { return pin == actualPin } override func removePin() { numberOfTimesRemovePinIsCalled += 1 } override func evaluateBiometry(completion: @escaping (Bool) -> Void) { evaluateBiometryCompletions.append(completion) } func evaluateBiometry(withSuccess success: Bool) throws { let completion = try XCTUnwrap(evaluateBiometryCompletions.popLast()) completion(success) } } ```
/content/code_sandbox/SimplenoteTests/PinLock/Helpers/MockPinLockManager.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
217
```swift import XCTest @testable import SimplenoteEndpoints @testable import Simplenote class MockAccountVerificationRemote: AccountRemote { private var pendingVerifications: [(email: String, completion: (Result<Data?, RemoteError>) -> Void)] = [] override func verify(email: String, completion: @escaping (Result<Data?, RemoteError>) -> Void) { pendingVerifications.append((email, completion)) } func processVerification(for email: String, with result: Result<Data?, RemoteError>) { guard let index = pendingVerifications.firstIndex(where: { $0.email == email }) else { XCTFail("Cannot find pending verification for email \(email)") return } let pendingVerification = pendingVerifications.remove(at: index) pendingVerification.completion(result) } } ```
/content/code_sandbox/SimplenoteTests/Verification/Helpers/MockAccountVerificationRemote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
168
```swift import XCTest import SimplenoteEndpoints @testable import Simplenote // MARK: - AccountVerificationControllerTests // class AccountVerificationControllerTests: XCTestCase { private let email = UUID().uuidString private lazy var remote = MockAccountVerificationRemote() private lazy var controller = AccountVerificationController(email: email, remote: remote) private lazy var invalidVerification: [String: Any] = [:] private lazy var unverifiedVerification: [String: Any] = ["token": #"{"username": "123"}"#] private lazy var inProgressVerification: [String: Any] = ["sent_to": "123"] private lazy var verifiedVerification: [String: Any] = ["token": "{\"username\": \"\(email)\"}"] } // MARK: - Verify // extension AccountVerificationControllerTests { func testVerifyCallsRemoteWithProvidedEmail() { // When let expectedResult = Remote.randomResult() var verificationResult: Result<Data?, RemoteError>? controller.verify { (result) in verificationResult = result } remote.processVerification(for: email, with: expectedResult) // Then XCTAssertEqual(verificationResult, expectedResult) } } // MARK: - State // extension AccountVerificationControllerTests { func testInitialStateIsUnknown() { XCTAssertEqual(controller.state, .unknown) } func testStateIsUnverifiedWhenUpdatingWithInvalidData() { controller.update(with: nil) XCTAssertEqual(controller.state, .unverified) controller.update(with: "verified") XCTAssertEqual(controller.state, .unverified) controller.update(with: invalidVerification) XCTAssertEqual(controller.state, .unverified) } func testStateIsUnverifiedIfTokenEmailDoesntMatchAccountEmail() { controller.update(with: unverifiedVerification) XCTAssertEqual(controller.state, .unverified) } func testStateIsInProgressIfStatusIsSent() { controller.update(with: inProgressVerification) XCTAssertEqual(controller.state, .verificationInProgress) } func testStateIsVerifiedIfTokenEmailMatchesAccountEmail() { controller.update(with: verifiedVerification) XCTAssertEqual(controller.state, .verified) } } // MARK: - OnStateChange // extension AccountVerificationControllerTests { func testOnStateChangeIsCalledWhenStateChanges() { // Given let expectedStateChangeHistory: [AccountVerificationController.State] = [ .unknown, .unverified, .unverified, .verified ] var stateChangeHistory: [AccountVerificationController.State] = [] controller.onStateChange = { (oldState, state) in stateChangeHistory.append(oldState) stateChangeHistory.append(state) } // When controller.update(with: unverifiedVerification) controller.update(with: verifiedVerification) // Then XCTAssertEqual(stateChangeHistory, expectedStateChangeHistory) } func testOnlyUniqueStateChangesAreReportedViaCallback() { // Given let expectedStateChangeHistory: [AccountVerificationController.State] = [ .unknown, .unverified ] var stateChangeHistory: [AccountVerificationController.State] = [] controller.onStateChange = { (oldState, state) in stateChangeHistory.append(oldState) stateChangeHistory.append(state) } // When controller.update(with: unverifiedVerification) controller.update(with: unverifiedVerification) // Then XCTAssertEqual(stateChangeHistory, expectedStateChangeHistory) } } ```
/content/code_sandbox/SimplenoteTests/Verification/AccountVerificationControllerTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
731
```swift import XCTest @testable import Simplenote // MARK: - TagTextFieldInputValidatorTests // class TagTextFieldInputValidatorTests: XCTestCase { let validator = TagTextFieldInputValidator() func testValidationSucceeds() { let text = "" let range = text.endIndex..<text.endIndex let expectedResult = TagTextFieldInputValidator.Result.valid let replacements = [ "", "t", "tag", String(repeating: "a", count: 256) ] for replacement in replacements { XCTAssertEqual(validator.validateInput(originalText: text, range: range, replacement: replacement), expectedResult) } } func testValidationFailsWhenReplacementHasWhiteSpaceOrNewline() { let text = "tag" let range = text.endIndex..<text.endIndex let expectedResult = TagTextFieldInputValidator.Result.invalid let replacements = [ " tag", "t ag", " tag ", "tag ", "\ntag", "t\nag", "\ntag\n", "\ntag ", ] for replacement in replacements { XCTAssertEqual(validator.validateInput(originalText: text, range: range, replacement: replacement), expectedResult) } } func testValidationFailsWhenReplacementHasComma() { let text = "tag" let range = text.endIndex..<text.endIndex let expectedResult = TagTextFieldInputValidator.Result.invalid let replacements = [ ",tag", "ta,g", ",tag,", "tag,," ] for replacement in replacements { XCTAssertEqual(validator.validateInput(originalText: text, range: range, replacement: replacement), expectedResult) } } func your_sha256_hashWhiteSpaceOrNewline() { let text = "tag" let midIndex = text.index(text.startIndex, offsetBy: 1) let range = midIndex..<midIndex let expectedResult = TagTextFieldInputValidator.Result.invalid let replacements = [ " tag", "t ag", " tag ", "tag ", "tag ", "tag\n", "\ntag", "t\nag", "\ntag\n", "\ntag ", ] for replacement in replacements { XCTAssertEqual(validator.validateInput(originalText: text, range: range, replacement: replacement), expectedResult) } } func testReplacingTextWithWhitespaceAtTheEnd() { let text = "tag" let range = text.endIndex..<text.endIndex let expectedResult = TagTextFieldInputValidator.Result.endingWithDisallowedCharacter("tagtag") let replacements = [ "tag ", "tag\n", ] for replacement in replacements { XCTAssertEqual(validator.validateInput(originalText: text, range: range, replacement: replacement), expectedResult) } } func testReplacingTextWithCommaAtTheEnd() { let text = "tag" let range = text.endIndex..<text.endIndex let expectedResult = TagTextFieldInputValidator.Result.endingWithDisallowedCharacter("tagtag") let replacement = "tag," XCTAssertEqual(validator.validateInput(originalText: text, range: range, replacement: replacement), expectedResult) } func testValidationFailsWhenTagExceedsLengthLimit() { let text = "t" let range = text.endIndex..<text.endIndex let replacement = String(repeating: "a", count: 256) let expectedResult = TagTextFieldInputValidator.Result.invalid XCTAssertEqual(validator.validateInput(originalText: text, range: range, replacement: replacement), expectedResult) } func your_sha256_hashFirstPart() { let cases = [ "tag": "tag", " tag ": "tag", "\nt \n ag": "t" ] for (tag, expected) in cases { XCTAssertEqual(validator.preprocessForPasting(tag: tag), expected) } } } ```
/content/code_sandbox/SimplenoteTests/Tags/TagTextFieldInputValidatorTests.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
832
```ruby #!/usr/bin/env ruby # frozen_string_literal: true # Supported languages: # ar,cy,zh-Hans,zh-Hant,nl,fa,fr,de,el,he,id,ko,pt,ru,es,sv,tr,ja,it # * Arabic # * Welsh # * Chinese (China) [zh-Hans] # * Chinese (Taiwan) [zh-Hant] # * Dutch # * French # * Greek # * German # * Hebrew # * Indonesian # * Korean # * Portuguese (Brazil) # * Russian # * Spanish # * Swedish # * Turkish # * Japanese # * Italian # * Farsi require 'json' if Dir.pwd =~ /Scripts/ puts 'Must run script from root folder' exit end ALL_LANGS = { 'ar' => 'ar', # Arabic 'cy' => 'cy', # Welsh 'de' => 'de', # German 'el' => 'el', # Greek 'es' => 'es', # Spanish 'fa' => 'fa', # Farsi 'fr' => 'fr', # French 'he' => 'he', # Hebrew 'id' => 'id', # Indonesian 'it' => 'it', # Italian 'ja' => 'ja', # Japanese 'ko' => 'ko', # Korean 'nl' => 'nl', # Dutch 'pt-br' => 'pt-BR', # Portuguese (Brazil) 'ru' => 'ru', # Russian 'sv' => 'sv', # Swedish 'tr' => 'tr', # Turkish 'zh-cn' => 'zh-Hans-CN', # Chinese (China) 'zh-tw' => 'zh-Hant-TW' # Chinese (Taiwan) }.freeze def copy_header(target_file, trans_strings) trans_strings.each_line do |line| unless line.start_with?('/*') target_file.write("\n") return end target_file.write(line) end end def copy_comment(f, trans_strings, value) prev_line = '' trans_strings.each_line do |line| if line.include?(value) f.write(prev_line) return end prev_line = line end end langs = {} if ARGV.count.positive? ARGV.each do |key| unless (local = ALL_LANGS[key]) puts "Unknown language #{key}" exit 1 end langs[key] = local end else langs = ALL_LANGS end langs.each do |code, local| lang_dir = File.join('Simplenote', "#{local}.lproj") puts "Updating #{code}" system "mkdir -p #{lang_dir}" # Backup the current file system "if [ -e #{lang_dir}/Localizable.strings ]; then cp #{lang_dir}/Localizable.strings #{lang_dir}/Localizable.strings.bak; fi" # Download translations in strings format in order to get the comments system "curl -fLso #{lang_dir}/Localizable.strings path_to_url#{code}/default/export-translations?format=strings" or begin puts "Error downloading #{code}" end system "./Scripts/fix-translation #{lang_dir}/Localizable.strings" system "plutil -lint #{lang_dir}/Localizable.strings" and system "rm #{lang_dir}/Localizable.strings.bak" system "grep -a '\\x00\\x20\\x00\\x22\\x00\\x22\\x00\\x3b$' #{lang_dir}/Localizable.strings" end ```
/content/code_sandbox/Scripts/update-translations.rb
ruby
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
834
```ruby # frozen_string_literal: true # Parses the release notes file to extract the current version information and # puts it to STDOUT. # # To update the release notes for localization: # # ruby ./this_script >| Simplenote/Resources/release_notes.txt # # To generate the App Store Connect release message: # # ruby ./this_script | pbcopy # # To generate the GitHub and App Center release message: # # ruby ./this_script -k | pbcopy GITHUB_URL = 'path_to_url RELEASE_NOTES_FILE = 'RELEASE-NOTES.txt' NOTES = File.read(RELEASE_NOTES_FILE) lines = NOTES.lines def replace_pr_number_with_markdown_link(string) string.gsub(/\#\d*$/) do |pr_number| "[#{pr_number}](#{GITHUB_URL}/pull/#{pr_number.gsub('#', '')})" end end # This is a very bare bone option parsing. It does the job for this simple use # case, but it should not be built upon. # # If you plan to add more options, please consider using a gem to manage them # properly. mode = ARGV[0] == '-k' ? :keep_pr_links : :strip_pr_links # Format: # # 1.23 # ----- # # 1.22 # ----- # - something #123 # - something #234 # # 1.21 # ----- # - something something #345 # Skip the first three lines: the next version header lines = lines[3...] # Isolate the current version by looking for the first new line release_lines = [] # Find the start of the releases by looking for the line with the '-----' # sequence. This accounts for the edge case in which more new lines make it # into the release notes file than expected. index = 0 index += 1 until lines[index].start_with? '-----' lines[(index + 1)...].each do |line| break if line.strip == '' release_lines.push line end formatted_lines = release_lines .map { |l| l.gsub('- ', '- ') } case mode when :strip_pr_links formatted_lines = formatted_lines .map { |l| l.gsub(/ \#\d*$/, '') } when :keep_pr_links formatted_lines = formatted_lines. # The PR "links" are not actually links, but PR "ids". On GitHub, they'll # be automatically parsed into links to the corresponding PR, but outside # GitHub, such as in our internal posts or on App Center, they won't. # # It's probably best to update the convention in writing the release notes # but in the meantime let's compensate with more automation. map { |l| replace_pr_number_with_markdown_link(l) } end # It would be good to either add overriding of the file where the parsed # release notes should go. I haven't done it yet because I'm using this script # also to generate the text for the release notes on GitHub, where I want to # keep the PR links. See info on the usage a the start of the file. puts formatted_lines ```
/content/code_sandbox/Scripts/extract_release_notes.rb
ruby
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
684
```shell #!/bin/bash SOURCE_PATH=$1 TARGET_PATH=$2 USAGE="error: Usage $0 source_path target_path" if [[ -z ${SOURCE_PATH:+x} || -z ${TARGET_PATH:+x} ]]; then echo $USAGE exit 1 fi git check-ignore "${TARGET_PATH}" > /dev/null GIT_IGNORE_EXIT_CODE=$? if [ $GIT_IGNORE_EXIT_CODE -ne 0 ]; then echo "error: Attempting to store secret file in path that is not ignored by Git (${TARGET_PATH})." exit 1 fi # From now on, fail the script if there's an error. # We didn't do it above because we wanted to track the `git check-ignore` exit # code. set -e if [ ! -f ${SOURCE_PATH} ]; then echo "error: Unable to copy credentials. Could not find ${SOURCE_PATH}." exit 1 fi if cmp --silent -- ${SOURCE_PATH} ${TARGET_PATH}; then echo " Credentials were not modified. Skipping..." exit 0 fi mkdir -p $(dirname $TARGET_PATH) cp ${SOURCE_PATH} ${TARGET_PATH} echo " Copied secret at ${SOURCE_PATH} to ${TARGET_PATH}" ```
/content/code_sandbox/Scripts/Build-Phases/copy-secret.sh
shell
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
267
```shell #!/bin/bash IPHONE_TIME=$(ruby -e "require 'time';puts Time.new(2007, 1, 9, 9, 42, 0).iso8601") xcrun simctl boot "${TARGET_DEVICE_IDENTIFIER}" xcrun simctl status_bar "${TARGET_DEVICE_IDENTIFIER}" override \ --time $IPHONE_TIME \ --dataNetwork wifi \ --wifiMode active \ --wifiBars 3 \ --cellularMode active \ --batteryState charged \ --batteryLevel 100 ```
/content/code_sandbox/Scripts/pre-actions/configure-status-bar.sh
shell
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
115
```objective-c // // Use this file to import your target's public headers that you would like to expose to Swift. // #import "Foundation/Foundation.h" ```
/content/code_sandbox/SimplenoteWidgets/Simplenote-Widgets-Bridging-Header.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
30
```swift import SwiftUI import WidgetKit @available(iOS 14.0, *) @main struct SimplenoteWidgets: WidgetBundle { var body: some Widget { NewNoteWidget() NoteWidget() ListWidget() } } ```
/content/code_sandbox/SimplenoteWidgets/SimplenoteWidgets.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
52
```swift // This file contains the required class structure to be able to fetch and use core data files in widgets and intents // We have collapsed the auto generated core data files into a single file as it is unlikely that the files will need to // be regenerated. Contained in this file is the generated class files Tag+CoreDataClass.swift and Tag+CoreDataProperties.swift import Foundation import CoreData @objc(Tag) public class Tag: SPManagedObject { } extension Tag { @nonobjc public class func fetchRequest() -> NSFetchRequest<Tag> { return NSFetchRequest<Tag>(entityName: "Tag") } @NSManaged public var index: NSNumber? @NSManaged public var name: String? @NSManaged public var share: String? } ```
/content/code_sandbox/SimplenoteWidgets/Models/Tag+Widget.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
160
```swift // This file contains the required class structure to be able to fetch and use core data files in widgets and intents // We have collapsed the auto generated core data files into a single file as it is unlikely that the files will need to // be regenerated. Contained in this file is the generated class files Note+CoreDataClass.swift and Note+CoreDataProperties.swift import Foundation import CoreData @objc(Note) public class Note: SPManagedObject { } extension Note { @nonobjc public class func fetchRequest() -> NSFetchRequest<Note> { return NSFetchRequest<Note>(entityName: "Note") } public override func awakeFromInsert() { super.awakeFromInsert() if simperiumKey.isEmpty { simperiumKey = UUID().uuidString.replacingOccurrences(of: "-", with: "") } } @NSManaged public var content: String? @NSManaged public var creationDate: Date? @NSManaged public override var isDeleted: Bool @NSManaged public var lastPosition: NSNumber? @NSManaged public var modificationDate: Date? @NSManaged public var noteSynced: NSNumber? @NSManaged public var owner: String? @NSManaged public var pinned: NSNumber? @NSManaged public var publishURL: String? @NSManaged public var remoteId: String? @NSManaged public var shareURL: String? @NSManaged public var systemTags: String? @NSManaged public var tags: String? } extension Note { var title: String { let noteStructure = NoteContentHelper.structure(of: content) return title(with: noteStructure.title) } private func title(with range: Range<String.Index>?) -> String { guard let range = range, let content = content else { return Constants.defaultTitle } let result = String(content[range]) return result.droppingPrefix(Constants.titleMarkdownPrefix) } var body: String { let noteStructure = NoteContentHelper.structure(of: content) return content(with: noteStructure.body) } private func content(with range: Range<String.Index>?) -> String { guard let range = range, let content = content else { // Note. Swift UI Text will crash if given String() so need to use this version of an empty string return "" } return String(content[range]) } var url: URL { return URL(string: .simplenotePath(withHost: SimplenoteConstants.simplenoteInterlinkHost) + simperiumKey)! } private func objectFromJSONString(_ json: String) -> Any? { guard let data = json.data(using: .utf8) else { return nil } return try? JSONSerialization.jsonObject(with: data) } var tagsArray: [String] { guard let tagsString = tags, let array = objectFromJSONString(tagsString) as? [String] else { return [] } return array } var systemTagsArray: [String] { guard let systemTagsString = systemTags, let array = objectFromJSONString(systemTagsString) as? [String] else { return [] } return array } func toDictionary() -> [String: Any] { return [ "tags": tagsArray, "deleted": 0, "shareURL": shareURL ?? String(), "publishURL": publishURL ?? String(), "content": content ?? "", "systemTags": systemTagsArray, "creationDate": (creationDate ?? .now).timeIntervalSince1970, "modificationDate": (modificationDate ?? .now).timeIntervalSince1970 ] } func toJsonData() -> Data? { do { return try JSONSerialization.data(withJSONObject: toDictionary(), options: .prettyPrinted) } catch { print("Error converting Note to JSON: \(error)") return nil } } } private struct Constants { static let defaultTitle = NSLocalizedString("New Note...", comment: "Default title for notes") static let previewCharacterLength = 50 static let titleMarkdownPrefix = "# " static let bodyPreviewCap = 500 } ```
/content/code_sandbox/SimplenoteWidgets/Models/Note+Widget.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
906
```swift // This file contains the required class structure to be able to fetch and use core data files in widgets and intents // We have collapsed the auto generated core data files into a single file as it is unlikely that the files will need to // be regenerated. Contained in this file is the generated class files SPManagedObject+CoreDataClass.swift and SPManagedObject+CoreDataProperties.swift import Foundation import CoreData @objc(SPManagedObject) public class SPManagedObject: NSManagedObject { } extension SPManagedObject { @nonobjc public class func fetchRequest() -> NSFetchRequest<SPManagedObject> { return NSFetchRequest<SPManagedObject>(entityName: "SPManagedObject") } @NSManaged public var ghostData: String? @NSManaged public var simperiumKey: String } ```
/content/code_sandbox/SimplenoteWidgets/Models/SPManagedObject+Widget.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
164
```swift import SwiftUI import WidgetKit struct WidgetWarningView: View { let warning: WidgetsState var body: some View { GeometryReader { geometry in ZStack(alignment: .center) { Text(warning.message) .subheadline(color: .secondaryTextColor) .multilineTextAlignment(.center) .frame(width: geometry.size.width, height: geometry.size.height, alignment: .center) } .filling() } .padding() .widgetBackground(content: { Color.widgetBackgroundColor }) .widgetURL(URL(string: .simplenotePath())) } } struct WidgetWarningView_Previews: PreviewProvider { static var previews: some View { WidgetWarningView(warning: .tagDeleted) .previewContext(WidgetPreviewContext(family: .systemSmall)) WidgetWarningView(warning: .noteMissing) .previewContext(WidgetPreviewContext(family: .systemMedium)).colorScheme(.dark) WidgetWarningView(warning: .tagDeleted) .previewContext(WidgetPreviewContext(family: .systemLarge)) } } ```
/content/code_sandbox/SimplenoteWidgets/Views/WidgetWarningView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
238
```swift import SwiftUI import WidgetKit struct NewNoteImage: View { let size: CGFloat let foregroundColor: Color let backgroundColor: Color var body: some View { ZStack { Image(Constants.newNoteImage) .resizable() .aspectRatio(contentMode: .fill) .foregroundColor(foregroundColor) .frame(side: size) } .background(backgroundColor) } } struct NewNoteButton_Previews: PreviewProvider { static var previews: some View { NewNoteImage(size: Constants.size, foregroundColor: .white, backgroundColor: .blue) .previewContext(WidgetPreviewContext(family: .systemSmall)) } } private struct Constants { static let size = CGFloat(48) static let newNoteImage = "icon_new_note" } ```
/content/code_sandbox/SimplenoteWidgets/Views/NewNoteButton.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
174
```swift import SwiftUI struct NoteListTable: View { let rows: [Row] let geometry: GeometryProxy var body: some View { let width = geometry.size.width - Constants.sidePadding let height = round((geometry.size.height - Constants.headerSize) / CGFloat(rows.count)) ForEach(.zero ..< rows.count, id: \.self) { index in let isLastRow = index == (rows.count - 1) let row = rows[index] switch row { case .note(let proxy): Link(destination: proxy.url) { NoteListRow(noteTitle: proxy.title, width: width, height: height, lastRow: isLastRow) } case .empty: NoteListRow(noteTitle: "", width: width, height: height, lastRow: isLastRow) } } } } private struct Constants { static let sidePadding = CGFloat(20) static let headerSize = CGFloat(46) } ```
/content/code_sandbox/SimplenoteWidgets/Views/NoteListTable.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
211
```swift import SwiftUI import WidgetKit struct NoteListRow: View { var noteTitle: String var width: CGFloat var height: CGFloat var lastRow: Bool var body: some View { Text(noteTitle) .font(.subheadline) .lineLimit(Constants.lineLimit) .frame(width: width, height: height, alignment: .leading) .foregroundColor(.bodyTextColor) Divider() .opacity(lastRow ? Double.zero : Constants.fullOpacity) } } private struct Constants { static let fullOpacity = 1.0 static let lineLimit = 1 } struct NoteListRow_Previews: PreviewProvider { static var previews: some View { NoteListRow(noteTitle: "Title for note", width: 300, height: 50, lastRow: false) .previewContext(WidgetPreviewContext(family: .systemLarge)) } } ```
/content/code_sandbox/SimplenoteWidgets/Views/NoteListRow.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
198
```swift import SwiftUI import WidgetKit @available(iOS 14.0, *) struct NewNoteWidgetView: View { var body: some View { ZStack { VStack(alignment: .leading) { HStack { NewNoteImage(size: Constants.side, foregroundColor: .white, backgroundColor: .widgetBlueBackgroundColor) Spacer() } Spacer() Text(Constants.newNoteText) .font(.headline) .foregroundColor(.white) } .padding(Constants.overallPadding) } .widgetBackground(content: { Color.widgetBlueBackgroundColor }) .widgetURL(URL.newNoteURL()) } } @available(iOS 14.0, *) struct NewNoteView_Previews: PreviewProvider { static var previews: some View { NewNoteWidgetView() .previewContext(WidgetPreviewContext(family: .systemSmall)) } } private struct Constants { static let side = CGFloat(48) static let overallPadding = CGFloat(16) static let newNoteText = NSLocalizedString("New Note...", comment: "Text for new note button") } ```
/content/code_sandbox/SimplenoteWidgets/Views/NewNoteWidgetView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
235
```swift import SwiftUI import WidgetKit struct NoteWidgetView: View { var entry: NoteWidgetEntry @Environment(\.widgetFamily) var widgetFamily var body: some View { GeometryReader { geometry in ZStack { VStack(alignment: .leading) { Text(entry.title) .widgetHeader(widgetFamily, color: .bodyTextColor) Text(entry.content) .subheadline(color: .bodyTextColor) } .filling() .padding([.leading, .trailing, .top], Sizes.overallPadding) .ignoresSafeArea() .widgetURL(entry.url) } .widgetBackground(content: { Color.widgetBackgroundColor }) .redacted(reason: [entry.loggedIn ? [] : .placeholder]) } } } private struct Sizes { static let overallPadding = CGFloat(20) } struct NoteWidgetView_Previews: PreviewProvider { static var previews: some View { Group { NoteWidgetView(entry: NoteWidgetEntry.placeholder()) .previewContext(WidgetPreviewContext(family: .systemSmall)) NoteWidgetView(entry: NoteWidgetEntry.placeholder()) .previewContext(WidgetPreviewContext(family: .systemMedium)).colorScheme(.dark) } } } ```
/content/code_sandbox/SimplenoteWidgets/Views/NoteWidgetView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
270
```swift import SwiftUI import WidgetKit struct ListWidgetHeaderView: View { let tag: WidgetTag @Environment(\.widgetFamily) var widgetFamily var body: some View { HStack(alignment: .center) { Link(destination: URL.internalUrl(forTag: tag.identifier)) { Text(tag.tagDescription) .font(.headline) .foregroundColor(.bodyTextColor) } Spacer() Link(destination: URL.newNoteURL(withTag: tag.identifier)) { NewNoteImage(size: Constants.side, foregroundColor: .widgetTintColor, backgroundColor: .widgetBackgroundColor) } } .padding(.zero) } } struct NotePreviewHeaderView_Previews: PreviewProvider { static var previews: some View { ListWidgetHeaderView(tag: WidgetTag(kind: .allNotes)) .previewContext(WidgetPreviewContext(family: .systemMedium)) } } private struct Constants { static let side = CGFloat(24) } ```
/content/code_sandbox/SimplenoteWidgets/Views/ListWidgetHeaderView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
205
```swift import SwiftUI import WidgetKit struct ListWidgetView: View { var entry: ListWidgetEntry @Environment(\.widgetFamily) var widgetFamily var body: some View { GeometryReader { geometry in ZStack { HStack(alignment: .top) { VStack(alignment: .leading, spacing: .zero) { ListWidgetHeaderView(tag: entry.widgetTag) .padding(.trailing, Constants.sidePadding) .padding([.bottom, .top], Constants.topAndBottomPadding) NoteListTable(rows: rows, geometry: geometry) .multilineTextAlignment(.leading) } .padding(.leading, Constants.sidePadding) } } .filling() .widgetBackground(content: { Color.widgetBackgroundColor }) .redacted(reason: entry.loggedIn ? [] : .placeholder) } } func numberOfRows(for widgetFamily: WidgetFamily) -> Int { switch widgetFamily { case .systemLarge: return Constants.largeRows default: return Constants.mediumRows } } var rows: [Row] { let data = entry.noteProxies.map({ Row.note($0) }) var rows: [Row] = [] for index in .zero..<numberOfRows(for: widgetFamily) { rows.append((data.indices.contains(index)) ? data[index] : .empty) } return rows } } enum Row { case note(ListWidgetNoteProxy) case empty } private struct Constants { static let mediumRows = 3 static let largeRows = 8 static let sidePadding = CGFloat(20) static let topAndBottomPadding = CGFloat(5) } struct ListWidgetView_Previews: PreviewProvider { static var previews: some View { Group { ListWidgetView(entry: ListWidgetEntry.placeholder()) .previewContext(WidgetPreviewContext(family: .systemMedium)) ListWidgetView(entry: ListWidgetEntry.placeholder()) .previewContext(WidgetPreviewContext(family: .systemLarge)) .colorScheme(.dark) } } } ```
/content/code_sandbox/SimplenoteWidgets/Views/ListWidgetView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
451
```swift import Foundation enum WidgetsState { case standard case noteMissing case tagDeleted case loggedOut } extension WidgetsState { var message: String { switch self { case .standard: return String() case .noteMissing: return NSLocalizedString("Note no longer available", comment: "Widget warning if note is deleted") case .tagDeleted: return NSLocalizedString("Tag no longer available", comment: "Widget warning if tag is deleted") case .loggedOut: return NSLocalizedString("Log in to see your notes", comment: "Widget warning if user is logged out") } } } ```
/content/code_sandbox/SimplenoteWidgets/Tools/WidgetsState.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
134
```swift import Foundation import SimplenoteFoundation import SimplenoteSearch import CoreData class ExtensionResultsController { /// Data Controller /// let managedObjectContext: NSManagedObjectContext /// Initialization /// init(context: NSManagedObjectContext) { self.managedObjectContext = context } // MARK: - Notes /// Fetch notes with given tag and limit /// If no tag is specified, will fetch notes that are not deleted. If there is no limit specified it will fetch all of the notes /// func notes(filteredBy filter: TagsFilter = .allNotes, limit: Int = .zero) -> [Note]? { if case let .tag(tag) = filter { if !tagExists(tagName: tag) { return nil } } let request: NSFetchRequest<Note> = fetchRequestForNotes(filteredBy: filter, limit: limit) return performFetch(from: request) } /// Returns note given a simperium key /// func note(forSimperiumKey key: String) -> Note? { return notes()?.first { note in note.simperiumKey == key } } func firstNote() -> Note? { let fetched = notes(limit: 1) return fetched?.first } func noteExists(forSimperiumKey key: String) -> Bool { note(forSimperiumKey: key) != nil } /// Creates a predicate for notes given a tag name. If not specified the predicate is for all notes that are not deleted /// private func predicateForNotes(filteredBy tagFilter: TagsFilter = .allNotes) -> NSPredicate { switch tagFilter { case .allNotes: return NSPredicate.predicateForNotes(deleted: false) case .tag(let tag): return NSCompoundPredicate(type: .and, subpredicates: [ NSPredicate.predicateForNotes(deleted: false), NSPredicate.predicateForNotes(tag: tag) ]) } } private func sortDescriptorForNotes() -> NSSortDescriptor { return NSSortDescriptor.descriptorForNotes(sortMode: WidgetDefaults.shared.sortMode) } private func fetchRequestForNotes(filteredBy filter: TagsFilter = .allNotes, limit: Int = .zero) -> NSFetchRequest<Note> { let fetchRequest = NSFetchRequest<Note>(entityName: Note.entityName) fetchRequest.fetchLimit = limit fetchRequest.sortDescriptors = [sortDescriptorForNotes()] fetchRequest.predicate = predicateForNotes(filteredBy: filter) return fetchRequest } // MARK: - Tags func tags() -> [Tag]? { performFetch(from: fetchRequestForTags()) } private func fetchRequestForTags() -> NSFetchRequest<Tag> { let fetchRequest = NSFetchRequest<Tag>(entityName: Tag.entityName) fetchRequest.sortDescriptors = [NSSortDescriptor.descriptorForTags()] return fetchRequest } private func tagExists(tagName: String) -> Bool { return tagForName(tagName: tagName) != nil } private func tagForName(tagName: String) -> Tag? { guard let tags = tags() else { return nil } let targetTagHash = tagName.byEncodingAsTagHash for tag in tags { if tag.name?.byEncodingAsTagHash == targetTagHash { return tag } } return nil } // MARK: Fetching private func performFetch<T: NSManagedObject>(from request: NSFetchRequest<T>) -> [T]? { do { let objects = try managedObjectContext.fetch(request) return objects } catch { NSLog("Couldn't fetch objects: %@", error.localizedDescription) return nil } } } enum TagsFilter { case allNotes case tag(String) } extension TagsFilter { init(from tag: String?) { guard let tag = tag else { self = .allNotes return } self = .tag(tag) } } ```
/content/code_sandbox/SimplenoteWidgets/Tools/ExtensionResultsController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
865
```swift class WidgetDefaults { static let shared = WidgetDefaults() private let defaults = UserDefaults(suiteName: SimplenoteConstants.sharedGroupDomain) private init() { } var loggedIn: Bool { get { defaults?.bool(forKey: .accountIsLoggedIn) ?? false } set { defaults?.set(newValue, forKey: .accountIsLoggedIn) } } var sortMode: SortMode { get { SortMode(rawValue: defaults?.integer(forKey: .listSortMode) ?? .zero) ?? .alphabeticallyAscending } set { let payload = newValue.rawValue defaults?.set(payload, forKey: .listSortMode) } } } ```
/content/code_sandbox/SimplenoteWidgets/Tools/WidgetDefaults.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
147
```swift import Foundation struct DemoContent { static let singleNoteTitle = "Lorem ipsum dolor sit amet" static let singleNoteContent = ", consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nulla facilisi nullam vehicula ipsum a arcu cursus. Cursus risus at ultrices mi tempus imperdiet nulla malesuada. Vitae aliquet nec ullamcorper sit amet risus nullam eget felis. Ultrices sagittis orci a scelerisque. Et ligula ullamcorper malesuada proin libero nunc. Ut diam quam nulla porttitor massa. Quam nulla porttitor massa id neque aliquam. Urna cursus eget nunc scelerisque viverra mauris in aliquam. Turpis nunc eget lorem dolor. Ac turpis egestas maecenas pharetra convallis posuere. Gravida in fermentum et sollicitudin ac. Tempor orci eu lobortis elementum nibh tellus molestie. Nec tincidunt praesent semper feugiat nibh sed pulvinar proin. Interdum velit laoreet id donec ultrices tincidunt. Aliquam vestibulum morbi blandit cursus risus at ultrices mi. Aliquet lectus proin nibh nisl condimentum id venenatis. Consequat ac felis donec et odio pellentesque. Lobortis elementum nibh tellus molestie. Sed velit dignissim sodales ut eu sem integer vitae justo." static let singleNoteContentAlt = "- [] Check item one \n- [] check item two\n- [] check item three" static let singleNoteURL = URL(string: .simplenotePath())! static let demoURL = URL(string: .simplenotePath())! static let listTag = "Cursus" static let listTitles = [ "Urna cursus eget nunc scelerisque", "Lorem Ipsum", "Interdum velit laoreet id donec ultrices", "Nec tincidunt praesent semper", "porttitor massa id neque aliquam", "Gravida in fermentum et sollicitudin ac", "Lobortis elementum nibh tellus molestie.", "Lorem Ipsum" ] static let listProxies: [ListWidgetNoteProxy] = listTitles.map { (title) in ListWidgetNoteProxy(title: title, url: demoURL) } } ```
/content/code_sandbox/SimplenoteWidgets/Tools/DemoContent.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
545
```swift import Foundation import CoreData class ExtensionCoreDataWrapper { private lazy var coreDataManager: CoreDataManager = { do { return try CoreDataManager(StorageSettings().sharedStorageURL, for: .widgets) } catch { fatalError() } }() private lazy var extensionResultsController: ExtensionResultsController = { ExtensionResultsController(context: coreDataManager.managedObjectContext) }() func resultsController() -> ExtensionResultsController? { guard FileManager.default.fileExists(atPath: StorageSettings().sharedStorageURL.path) else { return nil } return extensionResultsController } func context() -> NSManagedObjectContext { coreDataManager.managedObjectContext } } ```
/content/code_sandbox/SimplenoteWidgets/Tools/ExtensionCoreDataWrapper.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
140
```swift import Foundation struct WidgetConstants { static let rangeForSixEntries = .zero..<6 } ```
/content/code_sandbox/SimplenoteWidgets/Tools/WidgetConstants.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
22
```swift import WidgetKit struct NewNoteWidgetEntry: TimelineEntry { let date: Date } struct NewNoteTimelineProvider: TimelineProvider { typealias Entry = NewNoteWidgetEntry func placeholder(in context: Context) -> NewNoteWidgetEntry { return NewNoteWidgetEntry(date: Date()) } func getSnapshot(in context: Context, completion: @escaping (NewNoteWidgetEntry) -> Void) { let entry = NewNoteWidgetEntry(date: Date()) completion(entry) } func getTimeline(in context: Context, completion: @escaping (Timeline<NewNoteWidgetEntry>) -> Void) { let timeline = Timeline(entries: [NewNoteWidgetEntry(date: Date())], policy: .never) completion(timeline) } } ```
/content/code_sandbox/SimplenoteWidgets/Providers/NewNoteWidgetProvider.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
161
```swift import WidgetKit struct NoteWidgetEntry: TimelineEntry { let date: Date let title: String let content: String let url: URL let loggedIn: Bool let state: State enum State { case standard case noteMissing case loggedOut } } extension NoteWidgetEntry { init(date: Date, note: Note, loggedIn: Bool = WidgetDefaults.shared.loggedIn, state: State = .standard) { self.init(date: date, title: note.title, content: note.body, url: note.url, loggedIn: loggedIn, state: state) } static func placeholder(loggedIn: Bool = false, state: State = .standard) -> NoteWidgetEntry { return NoteWidgetEntry(date: Date(), title: DemoContent.singleNoteTitle, content: DemoContent.singleNoteContent, url: DemoContent.demoURL, loggedIn: loggedIn, state: state) } } struct NoteWidgetProvider: IntentTimelineProvider { typealias Intent = NoteWidgetIntent typealias Entry = NoteWidgetEntry let coreDataWrapper = ExtensionCoreDataWrapper() func placeholder(in context: Context) -> NoteWidgetEntry { return NoteWidgetEntry.placeholder() } func getSnapshot(for configuration: NoteWidgetIntent, in context: Context, completion: @escaping (NoteWidgetEntry) -> Void) { guard WidgetDefaults.shared.loggedIn, let note = coreDataWrapper.resultsController()?.firstNote() else { completion(placeholder(in: context)) return } completion(NoteWidgetEntry(date: Date(), note: note)) } func getTimeline(for configuration: NoteWidgetIntent, in context: Context, completion: @escaping (Timeline<NoteWidgetEntry>) -> Void) { // Confirm valid configuration guard WidgetDefaults.shared.loggedIn else { completion(errorTimeline(withState: .loggedOut)) return } guard let widgetNote = configuration.note, let simperiumKey = widgetNote.identifier, let note = coreDataWrapper.resultsController()?.note(forSimperiumKey: simperiumKey) else { completion(errorTimeline(withState: .noteMissing)) return } // Prepare timeline entry for every hour for the next 6 hours // Create a new set of entries at the end of the 6 entries let entries: [NoteWidgetEntry] = WidgetConstants.rangeForSixEntries.compactMap({ (index) in guard let date = Date().increased(byHours: index) else { return nil } return NoteWidgetEntry(date: date, note: note) }) let timeline = Timeline(entries: entries, policy: .atEnd) completion(timeline) } private func errorTimeline(withState state: NoteWidgetEntry.State) -> Timeline<NoteWidgetEntry> { Timeline(entries: [NoteWidgetEntry.placeholder(state: state)], policy: .never) } } ```
/content/code_sandbox/SimplenoteWidgets/Providers/NoteWidgetProvider.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
629
```swift import WidgetKit struct ListWidgetEntry: TimelineEntry { let date: Date let widgetTag: WidgetTag let noteProxies: [ListWidgetNoteProxy] let loggedIn: Bool let state: State enum State { case standard case tagDeleted case loggedOut } } extension ListWidgetEntry { init(widgetTag: WidgetTag, noteProxies: [ListWidgetNoteProxy], state: State = .standard) { self.date = Date() self.widgetTag = widgetTag self.noteProxies = noteProxies self.loggedIn = WidgetDefaults.shared.loggedIn self.state = state } static func placeholder(loggedIn: Bool = false, state: State = .standard) -> ListWidgetEntry { return ListWidgetEntry(date: Date(), widgetTag: WidgetTag(kind: .tag, name: DemoContent.listTag), noteProxies: DemoContent.listProxies, loggedIn: loggedIn, state: state) } } struct ListWidgetNoteProxy { let title: String let url: URL } struct ListWidgetProvider: IntentTimelineProvider { typealias Intent = ListWidgetIntent typealias Entry = ListWidgetEntry let coreDataWrapper = ExtensionCoreDataWrapper() func placeholder(in context: Context) -> ListWidgetEntry { return ListWidgetEntry.placeholder() } func getSnapshot(for configuration: ListWidgetIntent, in context: Context, completion: @escaping (ListWidgetEntry) -> Void) { guard WidgetDefaults.shared.loggedIn, let allNotes = coreDataWrapper.resultsController()?.notes() else { completion(placeholder(in: context)) return } let proxies: [ListWidgetNoteProxy] = allNotes.map { (note) -> ListWidgetNoteProxy in ListWidgetNoteProxy(title: note.title, url: note.url) } completion(ListWidgetEntry(widgetTag: WidgetTag(kind: .allNotes), noteProxies: proxies)) } func getTimeline(for configuration: ListWidgetIntent, in context: Context, completion: @escaping (Timeline<ListWidgetEntry>) -> Void) { // Confirm valid configuration guard WidgetDefaults.shared.loggedIn else { completion(errorTimeline(withState: .loggedOut)) return } guard let widgetTag = configuration.tag, let notes = coreDataWrapper.resultsController()?.notes(filteredBy: TagsFilter(from: widgetTag.identifier), limit: Constants.noteFetchLimit) else { completion(errorTimeline(withState: .tagDeleted)) return } let proxies: [ListWidgetNoteProxy] = notes.map { (note) -> ListWidgetNoteProxy in ListWidgetNoteProxy(title: note.title, url: note.url) } // Prepare timeline entry for every hour for the next 6 hours // Create a new set of entries at the end of the 6 entries let entries: [ListWidgetEntry] = WidgetConstants.rangeForSixEntries.compactMap { (index) in guard let date = Date().increased(byHours: index) else { return nil } return ListWidgetEntry(date: date, widgetTag: widgetTag, noteProxies: proxies, loggedIn: WidgetDefaults.shared.loggedIn, state: .standard) } completion(Timeline(entries: entries, policy: .atEnd)) } private func errorTimeline(withState state: ListWidgetEntry.State) -> Timeline<ListWidgetEntry> { Timeline(entries: [ListWidgetEntry.placeholder(state: state)], policy: .never) } } private struct Constants { static let noteFetchLimit = 8 } ```
/content/code_sandbox/SimplenoteWidgets/Providers/ListWidgetProvider.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
770
```swift import SwiftUI extension View { func filling() -> some View { self.modifier(Filling()) } func frame(side: CGFloat, alignment: Alignment = .center) -> some View { self.frame(width: side, height: side, alignment: alignment) } } extension View { func widgetBackground(@ViewBuilder content: ()-> some View) -> some View { if #available(iOSApplicationExtension 17.0, *) { return containerBackground(for: .widget) { content() } } else { return background(content()) } } } ```
/content/code_sandbox/SimplenoteWidgets/Extensions/View+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
123
```swift import SwiftUI extension Color { static var bodyTextColor: Color { Color(light: .gray100, dark: .white) } static var secondaryTextColor: Color { Color(light: .gray50, dark: .gray30) } static var widgetBackgroundColor: Color { Color(light: .white, dark: .darkGray1) } static var widgetBlueBackgroundColor: Color { Color(studioColor: .spBlue50) } static var widgetTintColor: Color { Color(light: .spBlue50, dark: .spBlue30) } } ```
/content/code_sandbox/SimplenoteWidgets/Extensions/Color+Widgets.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
127
```swift import Foundation extension ListFilterKind { var description: String { switch self { case .tag: return NSLocalizedString("Tag", comment: "Display title for a User Tag") default: return NSLocalizedString("All Notes", comment: "Display title for All Notes") } } } extension WidgetTag { convenience init(kind: ListFilterKind, name: String? = nil) { switch kind { case .tag: self.init(identifier: name, display: name ?? Constants.unnamedTag) default: self.init(identifier: nil, display: kind.description) } self.kind = kind } var tagDescription: String { switch kind { case .tag: return displayString default: return kind.description } } } private struct Constants { static let allNotesDisplay = NSLocalizedString("All Notes", comment: "Display title for All Notes") static let unnamedTag = NSLocalizedString("Unnamed Tag", comment: "Default title for an unnamed tag") } ```
/content/code_sandbox/SimplenoteWidgets/Extensions/WidgetTag+Helpers.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
216
```swift import SwiftUI import WidgetKit @available(iOS 14.0, *) extension Text { func widgetHeader(_ widgetFamily: WidgetFamily, color: Color) -> Text { self .font(widgetFamily == .systemSmall ? .subheadline : .body) .fontWeight(.bold) .foregroundColor(color) } func subheadline(color: Color) -> Text { self .font(.subheadline) .foregroundColor(color) } } ```
/content/code_sandbox/SimplenoteWidgets/Extensions/Text+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
100
```swift import SwiftUI struct Filling: ViewModifier { func body(content: Content) -> some View { content .frame( minWidth: .zero, maxWidth: .infinity, minHeight: .zero, maxHeight: .infinity, alignment: .topLeading ) } } ```
/content/code_sandbox/SimplenoteWidgets/ViewModifiers/Filling.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
65
```swift import SwiftUI import WidgetKit @available(iOS 14.0, *) struct ListWidget: Widget { var body: some WidgetConfiguration { IntentConfiguration(kind: Constants.configurationKind, intent: ListWidgetIntent.self, provider: ListWidgetProvider()) { (entry) in prepareWidgetView(fromEntry: entry) } .configurationDisplayName(Constants.displayName) .description(Constants.description) .supportedFamilies([.systemMedium, .systemLarge]) .contentMarginsDisabled() } private func prepareWidgetView(fromEntry entry: ListWidgetEntry) -> some View { switch entry.state { case .standard: return AnyView(ListWidgetView(entry: entry)) case .loggedOut: return AnyView(WidgetWarningView(warning: .loggedOut)) case .tagDeleted: return AnyView(WidgetWarningView(warning: .tagDeleted)) } } } private struct Constants { static let configurationKind = "ListNoteWidget" static let displayName = NSLocalizedString("Note List", comment: "Note List Widget Title") static let description = NSLocalizedString("Get quick access to a list of all notes or based on the selected tag.", comment: "Note List Widget Description") } ```
/content/code_sandbox/SimplenoteWidgets/Widgets/ListWidget.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
256
```swift import SwiftUI import WidgetKit @available(iOS 14.0, *) struct NoteWidget: Widget { var body: some WidgetConfiguration { IntentConfiguration(kind: Constants.configurationKind, intent: NoteWidgetIntent.self, provider: NoteWidgetProvider()) { (entry) in prepareWidgetView(fromEntry: entry) } .configurationDisplayName(Constants.displayName) .description(Constants.description) .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) .contentMarginsDisabled() } private func prepareWidgetView(fromEntry entry: NoteWidgetEntry) -> some View { switch entry.state { case .standard: return AnyView(NoteWidgetView(entry: entry)) case .loggedOut: return AnyView(WidgetWarningView(warning: .loggedOut)) case .noteMissing: return AnyView(WidgetWarningView(warning: .noteMissing)) } } } private struct Constants { static let configurationKind = "NoteWidget" static let displayName = NSLocalizedString("Note", comment: "Note Widget Title") static let description = NSLocalizedString("Get quick access to one of your notes.", comment: "Note Widget Description") } ```
/content/code_sandbox/SimplenoteWidgets/Widgets/NoteWidget.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
249
```swift import SwiftUI import WidgetKit @available(iOS 14.0, *) struct NewNoteWidget: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: Constants.configurationKind, provider: NewNoteTimelineProvider()) { entry in NewNoteWidgetView() } .configurationDisplayName(Constants.displayName) .description(Constants.description) .supportedFamilies([.systemSmall]) .contentMarginsDisabled() } } private struct Constants { static let configurationKind = "NewNoteWidget" static let displayName = NSLocalizedString("New Note", comment: "New Note Widget Title") static let description = NSLocalizedString("Create a new note instantly with one tap.", comment: "New Note Widget Description") } ```
/content/code_sandbox/SimplenoteWidgets/Widgets/NewNoteWidget.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
150
```swift import XCTest let screenName = "Settings" class Settings { enum Elements: String { case doneButton = "Done" case condensedModeSwitch = "Condensed Note List" var element: XCUIElement { switch self { case .doneButton: return app.navigationBars[screenName].buttons[self.rawValue] case .condensedModeSwitch: return app.tables.cells.containing(.staticText, identifier: self.rawValue).firstMatch } } } static func condensedModeEnable() { switchCondensedModeIfNeeded(value: "1") } static func condensedModeDisable() { switchCondensedModeIfNeeded(value: "0") } static func switchCondensedModeIfNeeded(value: String) { toggleSwitchIfNeeded(Elements.condensedModeSwitch.element, value) } static func close() { Elements.doneButton.element.tap() } static func open() { Sidebar.open() Sidebar.getButtonSettings().tap() } } ```
/content/code_sandbox/SimplenoteUITests/Settings.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
211
```swift import XCTest class SimplenoteUISmokeTestsNoteEditor: XCTestCase { let usualLinkText = "path_to_url" let complexLinkPreviewText = "Simplenote" let complexLinkRawText = "[Simplenote](path_to_url" let webViewTexts = [String]( arrayLiteral: "Simplenote", "The simplest way to keep notes", "All your notes, synced on all your devices. Get Simplenote now for iOS, Android, Mac, Windows, Linux, or in your browser.", "Sign up now") override class func setUp() { app.launch() getToAllNotes() let _ = attemptLogOut() EmailLogin.open() EmailLogin.logIn() // Extra check for certain emails if testDataEmail.contains("trial") { dismissVerifyEmailIfNeeded() } NoteList.waitForLoad() } override func setUpWithError() throws { getToAllNotes() NoteList.trashAllNotes() Trash.empty() NoteList.openAllNotes() } func testCanPreviewMarkdownBySwiping() throws { trackTest() trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.markdownEnable() NoteEditor.clearAndEnterText(enteredValue: complexLinkRawText) NoteEditorAssert.textViewWithExactValueShownOnce(value: complexLinkRawText) trackStep() NoteEditor.swipeToPreview() PreviewAssert.previewShown() PreviewAssert.staticTextWithExactValueShownOnce(value: complexLinkPreviewText) } func testCanFlipToEditMode() throws { trackTest() trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.markdownEnable() NoteEditor.clearAndEnterText(enteredValue: complexLinkRawText) NoteEditorAssert.textViewWithExactValueShownOnce(value: complexLinkRawText) trackStep() NoteEditor.swipeToPreview() PreviewAssert.previewShown() PreviewAssert.staticTextWithExactValueShownOnce(value: complexLinkPreviewText) trackStep() Preview.leavePreviewViaBackButton() NoteEditor.setFocus() NoteEditorAssert.editorShown() NoteEditorAssert.textViewWithExactValueShownOnce(value: complexLinkRawText) } func testUsingInsertChecklistInsertsChecklist() throws { trackTest() let noteTextInitial = "Inserting checkbox with a button", noteNameInitial = noteTextInitial, noteTextWithCheckbox = " " + noteTextInitial, noteNameWithCheckbox = "- [ ]" + noteTextWithCheckbox trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.clearAndEnterText(enteredValue: noteTextInitial) NoteEditor.leaveEditor() NoteListAssert.noteExists(noteName: noteNameInitial) trackStep() NoteList.openNote(noteName: noteNameInitial) NoteEditor.markdownEnable() NoteEditorAssert.textViewWithExactValueShownOnce(value: noteTextInitial) trackStep() NoteEditor.swipeToPreview() PreviewAssert.staticTextWithExactValueShownOnce(value: noteTextInitial) PreviewAssert.boxesStates(expectedCheckedBoxesNumber: 0, expectedEmptyBoxesNumber: 0) trackStep() Preview.leavePreviewViaBackButton() NoteEditor.setFocus() NoteEditor.insertChecklist() NoteEditor.leaveEditor() NoteListAssert.noteExists(noteName: noteNameWithCheckbox) NoteListAssert.noteAbsent(noteName: noteNameInitial) trackStep() NoteList.openNote(noteName: noteNameWithCheckbox) NoteEditorAssert.textViewWithExactValueShownOnce(value: noteTextWithCheckbox) trackStep() NoteEditor.swipeToPreview() PreviewAssert.staticTextWithExactLabelShownOnce(label: noteNameInitial) PreviewAssert.boxesStates(expectedCheckedBoxesNumber: 0, expectedEmptyBoxesNumber: 1) } func testUndoUndoesTheLastEdit() throws { trackTest() let editorText = "ABCD" trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.clearAndEnterText(enteredValue: editorText) NoteEditorAssert.textViewWithExactValueShownOnce(value: editorText) trackStep() NoteEditor.undo() NoteEditorAssert.textViewWithExactValueNotShown(value: editorText) // Depending on... somehting, undoing might result in last character only "removal" // or the whole entered string removal. To decrease maintenance effort, we check // for at least one of two to be present: NoteEditorAssert.oneOfTheStringsIsShownInTextView(strings: ["ABC", ""]) } func testAddedURLIsLinkified() throws { trackTest() trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.markdownEnable() NoteEditor.clearAndEnterText(enteredValue: usualLinkText) NoteEditorAssert.textViewWithExactValueShownOnce(value: usualLinkText) trackStep() NoteEditor.leaveEditor() NoteListAssert.noteExists(noteName: usualLinkText) trackStep() NoteList.openNote(noteName: usualLinkText) NoteEditorAssert.linkifiedURL(linkText: usualLinkText) } func testLongTappingOnLinkOpensLinkInNewWindow() throws { trackTest() trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.markdownEnable() NoteEditor.clearAndEnterText(enteredValue: usualLinkText) NoteEditorAssert.textViewWithExactValueShownOnce(value: usualLinkText) trackStep() NoteEditor.leaveEditor() NoteListAssert.noteExists(noteName: usualLinkText) trackStep() NoteList.openNote(noteName: usualLinkText) NoteEditorAssert.linkifiedURL(linkText: usualLinkText) trackStep() NoteEditor.pressLink(linkText: usualLinkText) WebViewAssert.textsShownOnScreen(texts: webViewTexts) } func testTappingOnLinkInPreviewOpensLinkInNewWindow() throws { trackTest() trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.markdownEnable() NoteEditor.clearAndEnterText(enteredValue: usualLinkText) NoteEditorAssert.textViewWithExactValueShownOnce(value: usualLinkText) trackStep() NoteEditor.swipeToPreview() PreviewAssert.linkShown(linkText: usualLinkText) trackStep() Preview.tapLink(linkText: usualLinkText) WebViewAssert.textsShownOnScreen(texts: webViewTexts) } func testCreateCheckedItem() throws { trackTest() let checklistText = "Checked Item" let completeText = "- [x]" + checklistText trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.markdownEnable() NoteEditor.clearAndEnterText(enteredValue: completeText) trackStep() NoteEditor.leaveEditor() NoteListAssert.noteExists(noteName: completeText) trackStep() NoteList.openNote(noteName: completeText) NoteEditorAssert.textViewWithExactValueShownOnce(value: checklistText) NoteEditorAssert.checkboxForTextShownOnce(text: checklistText) trackStep() NoteEditor.swipeToPreview() PreviewAssert.staticTextWithExactLabelShownOnce(label: checklistText) PreviewAssert.boxesStates(expectedCheckedBoxesNumber: 1, expectedEmptyBoxesNumber: 0) } func testCreateUncheckedItem() throws { trackTest() let checklistText = "Unchecked Item" let completeText = "- [ ]" + checklistText trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() trackStep() NoteEditor.markdownEnable() NoteEditor.clearAndEnterText(enteredValue: completeText) trackStep() NoteEditor.leaveEditor() NoteListAssert.noteExists(noteName: completeText) trackStep() NoteList.openNote(noteName: completeText) NoteEditorAssert.textViewWithExactValueShownOnce(value: checklistText) NoteEditorAssert.checkboxForTextShownOnce(text: checklistText) trackStep() NoteEditor.swipeToPreview() PreviewAssert.staticTextWithExactLabelShownOnce(label: checklistText) PreviewAssert.boxesStates(expectedCheckedBoxesNumber: 0, expectedEmptyBoxesNumber: 1) } func testBulletedLists() throws { trackTest() let noteTitle = "Bulleted Lists" let noteContent = "\n\nMinuses:\n\n- Minus1\nMinus2\nMinus3" + "\n\nPluses:\n\n+ Plus1\nPlus2\nPlus3" + "\n\nAsterisks:\n\n* Asterisk1\nAsterisk2\nAsterisk3" trackStep() NoteList.addNoteTap() NoteEditorAssert.editorShown() NoteEditor.markdownEnable() trackStep() NoteEditor.clearAndEnterText(enteredValue: noteTitle + noteContent) NoteEditor.leaveEditor() NoteListAssert.noteExists(noteName: noteTitle) trackStep() NoteList.openNote(noteName: noteTitle) NoteEditorAssert.textViewWithExactLabelsShownOnce(labels: ["- Minus1", "- Minus2", "- Minus3"]) NoteEditorAssert.textViewWithExactLabelsShownOnce(labels: ["+ Plus1", "+ Plus2", "+ Plus3"]) NoteEditorAssert.textViewWithExactLabelsShownOnce(labels: ["* Asterisk1", "* Asterisk2", "* Asterisk3"]) trackStep() NoteEditor.swipeToPreview() PreviewAssert.staticTextWithExactValuesShownOnce(values: [" Minus1", " Minus2", " Minus3"]) PreviewAssert.staticTextWithExactValuesShownOnce(values: [" Plus1", " Plus2", " Plus3"]) PreviewAssert.staticTextWithExactValuesShownOnce(values: [" Asterisk1", " Asterisk2", " Asterisk3"]) } func testSelectAllAndTrashNotes() throws { trackTest() let noteTitle = "Note Title" trackStep() populateNoteList(title: noteTitle, numberToCreate: 2) NoteList.longPressNote(title: noteTitle + "-1") NoteList.selectNoteFromContextMenu() NoteList.selectAll() NoteListAssert.deselectAllButtonDisplayed() trackStep() NoteList.tapTrashNotesButton() NoteListAssert.notesNumber(expectedNotesNumber: 0) trackStep() Trash.open() TrashAssert.notesNumber(expectedNotesNumber: 2) TrashAssert.noteExists(noteName: noteTitle + "-1") TrashAssert.noteExists(noteName: noteTitle + "-2") } func testUndoTrashFromSnackbar() throws { trackTest() let noteName = "Note Title" trackStep() NoteList.createNoteAndLeaveEditor(noteName: noteName) NoteList.longPressNote(title: noteName) NoteList.deleteNoteFromContextMenu() NoteListAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.tapUndoOnSnackbar() NoteListAssert.notesNumber(expectedNotesNumber: 1) NoteListAssert.noteExists(noteName: noteName) } func testCopyAndPasteInternalLink() throws { trackTest() let originalNoteTitle = "Original Note Title" let referringNoteTitle = "Referring Note Title" let referringNoteData = NoteData( name: referringNoteTitle, content: "[\(originalNoteTitle)](simplenote://note/" ) trackStep() NoteList.createNoteAndLeaveEditor(noteName: originalNoteTitle) NoteList.longPressNote(title: originalNoteTitle) NoteList.copyInternalLinkFromContextMenu() NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() NoteList.addNoteTap() NoteEditor.enterTitle(enteredValue: referringNoteTitle) NoteEditor.pasteNoteContent() NoteEditor.leaveEditor() NoteListAssert.notesNumber(expectedNotesNumber: 2) NoteListAssert.contentIsShown(for: referringNoteData) } } ```
/content/code_sandbox/SimplenoteUITests/SimplenoteUITestsNoteEditor.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,658
```swift import XCTest class SimplenoteUISmokeTestsHistory: XCTestCase { let notePrefix = "HistoryTest" override class func setUp() { app.launch() EmailLogin.handleSavePasswordPrompt() getToAllNotes() let _ = attemptLogOut() EmailLogin.open() EmailLogin.logIn() } override func setUpWithError() throws { getToAllNotes() NoteList.trashAllNotes() Trash.empty() NoteList.openAllNotes() } override func tearDownWithError() throws { History.close() } func testHistoryCanBeDismissed() throws { trackTest() let noteText = notePrefix + getRandomId() trackStep() NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: noteText) NoteEditor.openHistory() HistoryAssert.historyShown() trackStep() History.close() HistoryAssert.historyDismissed() } func testRestoreNoteButtonIsDisabledByDefault() throws { trackTest() let noteText = notePrefix + getRandomId() trackStep() NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: noteText) NoteEditorAssert.textViewWithExactValueShownOnce(value: noteText) NoteEditor.openHistory() HistoryAssert.historyShown() HistoryAssert.restoreButtonIsDisabled() } func testRestoreButtonIsEnabledWhenAPreviousVersionIsSelected() throws { trackTest() let initialNoteText = notePrefix + getRandomId() let editedNoteText = notePrefix + getRandomId() trackStep() NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: initialNoteText) NoteEditor.waitBeforeEditingText(delayInSeconds: 3, newText: editedNoteText) NoteEditor.openHistory() HistoryAssert.historyShown() trackStep() History.setSliderPosition(position: 0.0) HistoryAssert.restoreButtonIsEnabled() } func testCanRestorePreviousVersion() throws { trackTest() let initialNoteText = notePrefix + getRandomId() let editedNoteText = notePrefix + getRandomId() trackStep() NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: initialNoteText) NoteEditor.waitBeforeEditingText(delayInSeconds: 3, newText: editedNoteText) NoteEditor.openHistory() HistoryAssert.historyShown() trackStep() History.setSliderPosition(position: 0.0) History.restoreNote() NoteEditorAssert.textViewWithExactValueShownOnce(value: initialNoteText) } func testRestoredVersionIsAddedOnTopOfTheOtherChanges() throws { trackTest() let initialNoteText = notePrefix + getRandomId() let editedNoteText = notePrefix + getRandomId() trackStep() NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: initialNoteText) NoteEditor.waitBeforeEditingText(delayInSeconds: 3, newText: editedNoteText) NoteEditor.openHistory() HistoryAssert.historyShown() trackStep() History.setSliderPosition(position: 0.0) History.restoreNote() NoteEditorAssert.textViewWithExactValueShownOnce(value: initialNoteText) trackStep() NoteEditor.openHistory() HistoryAssert.historyShown() trackStep() History.setSliderPosition(position: 1.0) NoteEditorAssert.textViewWithExactValueShownOnce(value: initialNoteText) trackStep() History.setSliderPosition(position: 0.5) NoteEditorAssert.textViewWithExactValueShownOnce(value: editedNoteText) trackStep() History.setSliderPosition(position: 0.0) NoteEditorAssert.textViewWithExactValueShownOnce(value: initialNoteText) } func testPreviousNoteIsNotRestoredWhenTheHistoryPanelIsDismissed() throws { trackTest() let initialNoteText = notePrefix + getRandomId() let editedNoteText = notePrefix + getRandomId() trackStep() NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: initialNoteText) NoteEditor.waitBeforeEditingText(delayInSeconds: 3, newText: editedNoteText) NoteEditor.openHistory() HistoryAssert.historyShown() trackStep() History.setSliderPosition(position: 0.0) History.close() NoteEditorAssert.textViewWithExactValueShownOnce(value: editedNoteText) } func testHistoryIsKeptAfterRecoveringNoteFromTrash() throws { trackTest() let initialNoteText = notePrefix + getRandomId() let editedNoteText = notePrefix + getRandomId() trackStep() NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: initialNoteText) NoteEditor.waitBeforeEditingText(delayInSeconds: 3, newText: editedNoteText) NoteEditor.leaveEditor() NoteListAssert.noteExists(noteName: editedNoteText) trackStep() NoteList.trashNote(noteName: editedNoteText) Trash.open() TrashAssert.noteExists(noteName: editedNoteText) trackStep() Trash.restoreNote(noteName: editedNoteText) TrashAssert.noteAbsent(noteName: editedNoteText) trackStep() NoteList.openAllNotes() NoteList.openNote(noteName: editedNoteText) NoteEditorAssert.textViewWithExactValueShownOnce(value: editedNoteText) trackStep() NoteEditor.openHistory() HistoryAssert.historyShown() trackStep() History.setSliderPosition(position: 0.0) History.restoreNote() NoteEditorAssert.textViewWithExactValueShownOnce(value: initialNoteText) } } ```
/content/code_sandbox/SimplenoteUITests/SimplenoteUITestsHistory.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,209
```swift import XCTest class NoteList { class func openNote(noteName: String) { app.tables.cells[noteName].tap() } class func getNavBarIdentifier() -> String? { let navBar = app.navigationBars.element guard navBar.exists else { return .none } print(">>> Currently active navigation bar: " + navBar.identifier) return navBar.identifier } class func isAllNotesListOpen() -> Bool { let navBar = app.navigationBars[UID.NavBar.allNotes] guard navBar.exists else { return false} return navBar.frame.minX == 0.0 } class func isNoteListOpen(forTag tag: String) -> Bool { return app.navigationBars[tag].exists } class func getNoteCell(_ noteName: String) -> XCUIElement { return Table.getCell(label: noteName) } class func isNotePresent(_ noteName: String) -> Bool { return NoteList.getNoteCell(noteName).exists } class func getNoteCellHeight(_ noteName: String) -> CGFloat { return NoteList.getNoteCell(noteName).frame.height.rounded() } class func openAllNotes() { guard !isAllNotesListOpen() else { return } print(">>> Opening \"All Notes\"") Sidebar.open() let allNotesButton = app.tables.staticTexts[UID.Button.allNotes] guard allNotesButton.waitForExistence(timeout: averageLoadTimeout) else { return } allNotesButton.tap() } class func addNoteTap() { app.buttons[UID.Button.newNote].tap() } static func createNoteThenLeaveEditor(_ note: NoteData, usingPaste: Bool = false) { NoteList.createNoteAndLeaveEditor( noteName: note.formattedForAutomatedInput, tags: note.tags, usingPaste: usingPaste ) } class func createNoteAndLeaveEditor(noteName: String, tags: [String] = [], usingPaste: Bool = false) { print(">>> Creating a note: " + noteName) NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: noteName, usingPaste: usingPaste) for tag in tags { NoteEditor.addTag(tagName: tag) } NoteEditor.leaveEditor() } class func createNotes(names: [String], usingPaste: Bool = false) { for noteName in names { createNoteAndLeaveEditor(noteName: noteName, usingPaste: usingPaste) } } class func trashNote(noteName: String) { Table.trashCell(noteName: noteName) } class func getNotesNumber() -> Int { return Table.getVisibleLabelledCells().count } class func getTagsSuggestionsNumber() -> Int { return Table.getVisibleNonLabelledCellsNumber() } class func tagSuggestionTap(tag: String) { print(">>> Tapping '\(tag)' tag suggestion") Table.getStaticText(label: tag).tap() } class func trashAllNotes() { NoteList.openAllNotes() Table .getVisibleLabelledCellsNames() .forEach { Table.trashCell(noteName: $0) } } class func waitForLoad() { let allNotesNavBar = app.navigationBars[UID.NavBar.allNotes] let predicate = NSPredicate { _, _ in allNotesNavBar.staticTexts[UID.Text.allNotesInProgress].exists == false } let expectation = XCTNSPredicateExpectation(predicate: predicate, object: .none) XCTWaiter().wait(for: [expectation], timeout: 10) } class func searchForText(text: String) { print(">>> Searching for '\(text)'") let searchField = app.searchFields[UID.SearchField.search] guard searchField.exists else { return } searchField.tap() let clearTextButton = searchField.buttons[UID.Button.clearText] if clearTextButton.exists { clearTextButton.tap() } searchField.typeText(text) sleep(5) } class func searchCancel() { print(">>> Canceling Search") let searchCancelButton = app.buttons[UID.Button.cancel] guard searchCancelButton.exists else { return } searchCancelButton.tap() } class func longPressNote(title: String) { app.tables.cells[title].press(forDuration: 3) } class func selectNoteFromContextMenu() { let selectButton = app.buttons[UID.Button.select] guard selectButton.exists else { return } selectButton.tap() } class func deleteNoteFromContextMenu() { let deleteNoteButton = app.buttons[UID.Button.deleteNote] guard deleteNoteButton.exists else { return } deleteNoteButton.tap() } class func copyInternalLinkFromContextMenu() { let copyInternalLinkButton = app.buttons[UID.Button.copyInternalLink] guard copyInternalLinkButton.exists else { return } copyInternalLinkButton.tap() } class func selectAll() { let selectAllButton = app.buttons[UID.Button.selectAll] guard selectAllButton.exists else { return } selectAllButton.tap() } class func tapTrashNotesButton() { let trashNotesButton = app.buttons[UID.Button.trashNotes] guard trashNotesButton.exists else { return } trashNotesButton.tap() } class func tapUndoOnSnackbar() { let undoButton = app.buttons[UID.Button.undoTrashButton] guard undoButton.exists else { return } undoButton.tap() } } class NoteListAssert { class func searchHeaderShown(header: String, numberOfOccurences: Int) { switch numberOfOccurences { case 0: print(assertSearchHeaderNotShown + header) case 1: print(assertSearchHeaderShown + header) default: print("Invalid value of \"numberOfOccurences\". Valid values are 0 or 1") return } let matches = Table.getStaticTextsWithExactLabelCount(label: header) XCTAssertEqual(matches, numberOfOccurences) } class func tagsSearchHeaderShown() { NoteListAssert.searchHeaderShown(header: UID.Text.searchByTag, numberOfOccurences: 1) } class func tagsSearchHeaderNotShown() { NoteListAssert.searchHeaderShown(header: UID.Text.searchByTag, numberOfOccurences: 0) } class func notesSearchHeaderShown() { NoteListAssert.searchHeaderShown(header: UID.Text.notes, numberOfOccurences: 1) } class func notesSearchHeaderNotShown() { NoteListAssert.searchHeaderShown(header: UID.Text.notes, numberOfOccurences: 0) } class func tagSuggestionExists(tag: String) { print(">>> Asserting that '\(tag)' tag suggestion is shown once") let matches = Table.getStaticTextsWithExactLabelCount(label: tag) XCTAssertEqual(matches, 1) } class func tagSuggestionsExist(tags: [String]) { for tag in tags { NoteListAssert.tagSuggestionExists(tag: tag) } } static func noteExists(_ note: NoteData) { notesExist([note]) } static func notesExist(_ notes: [NoteData]) { notesExist(names: notes.map { $0.name }) } class func noteExists(noteName: String) { print(">>> Asserting that note is shown once: " + noteName) let matches = Table.getCellsWithExactLabelCount(label: noteName) XCTAssertEqual(matches, 1) } class func notesExist(names: [String]) { for noteName in names { NoteListAssert.noteExists(noteName: noteName) } } class func noteAbsent(noteName: String) { XCTAssertFalse(app.tables.cells[noteName].exists, noteName + noteNotAbsentInAllNotes) } class func notesNumber(expectedNotesNumber: Int) { let actualNotesNumber = NoteList.getNotesNumber() XCTAssertEqual(actualNotesNumber, expectedNotesNumber, numberOfNotesInAllNotesNotExpected) } class func note(_ note: NoteData, hasHeight height: CGFloat) { print(">>> Asserting that note height is \(height)") XCTAssertEqual(NoteList.getNoteCellHeight(note.name), height) } class func tagsSuggestionsNumber(number: Int) { let actualNumber = NoteList.getTagsSuggestionsNumber() XCTAssertEqual(actualNumber, number, numberOfTagsSuggestionsNotExpected) } class func noteListShown(forSelection selection: String ) { print(assertNavBarIdentifier + selection) XCTAssertTrue(app.navigationBars[selection].waitForExistence(timeout: maxLoadTimeout)) if let navBarID = NoteList.getNavBarIdentifier() { XCTAssertEqual(navBarID, selection, selection + navBarNotFound) } else { XCTFail(foundNoNavBar) } } class func allNotesShown() { NoteListAssert.noteListShown(forSelection: UID.NavBar.allNotes) } class func trashShown() { NoteListAssert.noteListShown(forSelection: UID.NavBar.trash) } class func contentIsShown(for note: NoteData) { noteContentIsShownInSearch(noteName: note.name, expectedContent: note.content) } class func noteContentIsShownInSearch(noteName: String, expectedContent: String) { print(">>> Asserting that note '\(noteName)' has the following content:") print(">>>> \"\(expectedContent)\"") guard NoteList.isNotePresent(noteName) else { return XCTFail(">>>> Note not found") } if let noteContent = Table.getContentOfCell(noteName: noteName) { XCTAssertTrue(noteContent.contains(expectedContent), "Content is different.") } else if expectedContent.isEmpty { // If note content is nil, but we assert for empty content, we should not fail XCTAssert(true, "Content is not empty.") } else { // Otherwise, we should fail XCTFail("Note has no content. Only title.") } } class func searchStringIsShown(searchString: String) { print(">>> Asserting that search string is '\(searchString)'") let searchField = app.searchFields[UID.SearchField.search] guard searchField.exists else { XCTFail(">>> Search field not found") return } guard let actualSearchString = searchField.value as? String else { XCTFail(">>> Search field has no value") return } print(">>> Actual search string is '\(actualSearchString)'") XCTAssertEqual(actualSearchString, searchString) } class func deselectAllButtonDisplayed() { XCTAssertTrue(app.buttons[UID.Button.deselectAll].waitForExistence(timeout: maxLoadTimeout)) } } ```
/content/code_sandbox/SimplenoteUITests/NoteList.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,327
```swift enum UID { enum Picture { static let appLogo = "simplenote-logo" } enum Cell { static let settings = "settings" } enum NavBar { static let allNotes = "All Notes" static let logIn = "Log In" static let logInWithPassword = "Log In with Password" static let enterCode = "Enter Code" static let noteEditorPreview = "Preview" static let noteEditorOptions = "Options" static let trash = "Trash" } enum Button { static let newNote = "New note" static let done = "Done" static let edit = "Edit" static let back = "Back" static let accept = "Accept" static let yes = "Yes" static let menu = "menu" static let signUp = "Sign Up" static let logIn = "Log In" static let enterPassword = "Enter password" static let mainAction = "Main Action" static let logInWithEmail = "Log in with email" static let allNotes = "All Notes" static let trash = "Trash" static let settingsLogOut = "Log Out" static let noteEditorAllNotes = "All Notes" static let noteEditorChecklist = "Inserts a new Checklist Item" static let noteEditorInformation = "Information" static let noteEditorMenu = "note-menu" static let itemTrash = "icon trash" static let trashNote = "Move to Trash" static let restoreNote = "Restore Note" static let dismissHistory = "Dismiss History" static let deleteNote = "Delete Note" // "Empty Trash" button label is generated // differently by Xcode 12.4 and 12.5 (runs iOS 14.5+) static private(set) var trashEmptyTrash: String = { "Empty trash" }() static let clearText = "Clear text" static let cancel = "Cancel" static let dismissKeyboard = "Dismiss keyboard" static let deleteTagConfirmation = "Delete Tag" static let select = "Select" static let selectAll = "Select All" static let deselectAll = "Deselect All" static let trashNotes = "Trash Notes" static let crossIcon = "icon cross" static let undoTrashButton = "Undo" static let copyInternalLink = "Copy Internal Link" } enum Text { static let noteEditorPreview = "Preview" static let noteEditorOptionsMarkdown = "Markdown" static let noteEditorOptionsHistory = "History" static let allNotesInProgress = "In progress" static let searchByTag = "Search by Tag" static let notes = "Notes" } enum TextField { static let email = "Email" static let password = "Password" static let tag = "Tag" } enum SearchField { static let search = "Search notes or tags" } enum ContextMenuItem { static let paste = "Paste" } } enum Text { static let appName = "Simplenote" static let appTagline = "The simplest way to keep notes." static let alertHeadingSorry = "Sorry!" static let alertContentLoginFailed = "Could not login with the provided email address and password." static let alertReviewAccount = "Review Your Account" static let loginEmailInvalid = "Your email address is not valid" static let loginPasswordShort = "Password must contain at least 4 characters" } let testDataEmail = "simplenoteuitest@mailinator.com" let testDataPassword = "yang8EEF3pall" ```
/content/code_sandbox/SimplenoteUITests/UIDs.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
791
```swift import XCTest class History { class func close() { guard app.staticTexts[UID.Button.restoreNote].waitForExistence(timeout: minLoadTimeout) else { return } app.buttons[UID.Button.dismissHistory].tap() } class func setSliderPosition(position: CGFloat) { app.sliders.element.adjust(toNormalizedSliderPosition: position) } class func restoreNote() { app.buttons[UID.Button.restoreNote].tap() } } class HistoryAssert { class func historyShown() { HistoryAssert.historyExistence(shouldExist: true, errorMessage: buttonNotFound) } class func historyDismissed() { HistoryAssert.historyExistence(shouldExist: false, errorMessage: buttonNotAbsent) } class func historyExistence(shouldExist: Bool, errorMessage: String) { let dismissHistoryButton = app.buttons[UID.Button.dismissHistory] let restoreNoteButton = app.buttons[UID.Button.restoreNote] XCTAssertEqual(dismissHistoryButton.waitForExistence(timeout: minLoadTimeout), shouldExist, UID.Button.dismissHistory + errorMessage) XCTAssertEqual(restoreNoteButton.waitForExistence(timeout: minLoadTimeout), shouldExist, UID.Button.restoreNote + errorMessage) } class func restoreButtonIsDisabled() { let restoreNoteButton = app.buttons[UID.Button.restoreNote] XCTAssertFalse(restoreNoteButton.isEnabled) } class func restoreButtonIsEnabled() { let restoreNoteButton = app.buttons[UID.Button.restoreNote] XCTAssertTrue(restoreNoteButton.isEnabled) } } ```
/content/code_sandbox/SimplenoteUITests/History.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
325
```swift import UITestsFoundation import XCTest class SimplenoteUISmokeTestsLogin: XCTestCase { let testDataInvalidEmail = "user@gmail." let testDataNotExistingEmail = "nevergonnagiveyouup@gmail.com" let testDataInvalidPassword = "ABC" let testDataNotExistingPassword = "ABCD" override class func setUp() { app.launch() } override func setUpWithError() throws { Alert.closeAny() EmailLogin.close() let _ = attemptLogOut() } func testLogInWithNoEmail() throws { trackTest() trackStep() EmailLogin.open() EmailLogin.enterEmailAndAttemptLogin(email: "") Assert.labelExists(labelText: Text.loginEmailInvalid) } func testLogInWithInvalidEmail() throws { trackTest() trackStep() EmailLogin.open() EmailLogin.enterEmailAndAttemptLogin(email: testDataInvalidEmail) Assert.labelExists(labelText: Text.loginEmailInvalid) Assert.labelAbsent(labelText: Text.loginPasswordShort) } func testLogInWithNoPassword() throws { trackTest() trackStep() EmailLogin.open() EmailLogin.logIn(email: testDataEmail, password: "") Assert.labelAbsent(labelText: Text.loginEmailInvalid) Assert.labelExists(labelText: Text.loginPasswordShort) } func testLogInWithTooShortPassword() throws { trackTest() trackStep() EmailLogin.open() EmailLogin.logIn(email: testDataEmail, password: testDataInvalidPassword) Assert.labelAbsent(labelText: Text.loginEmailInvalid) Assert.labelExists(labelText: Text.loginPasswordShort) } func testLogInWithExistingEmailIncorrectPassword() throws { trackTest() trackStep() EmailLogin.open() EmailLogin.logIn(email: testDataEmail, password: testDataNotExistingPassword) Assert.alertExistsAndClose(headingText: Text.alertHeadingSorry, content: Text.alertContentLoginFailed, buttonText: UID.Button.accept) } func testLogInWithCorrectCredentials() throws { trackTest() trackStep() EmailLogin.open() EmailLogin.logIn(email: testDataEmail, password: testDataPassword) NoteListAssert.allNotesShown() } func testLogOut() throws { trackTest() trackStep() EmailLogin.open() EmailLogin.logIn(email: testDataEmail, password: testDataPassword) NoteListAssert.allNotesShown() trackStep() _ = logOut() Assert.signUpLogInScreenShown() } } ```
/content/code_sandbox/SimplenoteUITests/SimplenoteUITestsLogin.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
542
```swift import XCTest class NoteEditor { class func dismissKeyboard() { let dismissKeyboardButton = app.buttons[UID.Button.dismissKeyboard] guard dismissKeyboardButton.exists else { return } dismissKeyboardButton.tap() } class func addTag(tagName: String) { NoteEditor.dismissKeyboard() let tagInput = app.textFields[UID.TextField.tag] guard tagInput.exists else { return } print(">>> Adding tag: " + tagName) tagInput.tap() tagInput.typeText(tagName + "\n") } class func clearText() { app.textViews.element.clearAndEnterText(text: "") } class func clearAndEnterText(enteredValue: String, usingPaste: Bool = false) { let noteContentTextView = app.textViews.element if usingPaste { // Clear clipboard before usage to adress flakiness // that appears when it's not done UIPasteboard.general.strings = [] noteContentTextView.clearText() noteContentTextView.paste(text: enteredValue) // Once the text is pasted, there might be an info bubble shown at the note top, // saying "Simplenote pasted from Simplenote-UITestsRunner". Since it covers all // NavBar buttons, we have to wait for it to disappear: let isHittablePredicate = NSPredicate { _, _ in app.buttons[UID.Button.dismissKeyboard].isHittable == true } let expectation = XCTNSPredicateExpectation(predicate: isHittablePredicate, object: .none) XCTWaiter().wait(for: [expectation], timeout: averageLoadTimeout) // Swipe up fast to show tags input, which disappears if pasted text is large // enough to push tags input off screen noteContentTextView.swipeUp(velocity: .fast) } else { noteContentTextView.clearAndEnterText(text: enteredValue) } } class func enterTitle(enteredValue: String) { let noteContentTextView = app.textViews.element noteContentTextView.clearAndEnterText(text: enteredValue + "\n") } class func waitBeforeEditingText(delayInSeconds: UInt32, newText: String) { let noteContentTextView = app.textViews.element sleep(delayInSeconds) noteContentTextView.clearAndEnterText(text: newText) } class func pasteNoteContent() { app.press(forDuration: 1.2) app.menuItems[UID.ContextMenuItem.paste].tap() } class func getEditorText() -> String { return app.textViews.element.value as! String } class func setFocus() { // Waiting for the TextView to become hittable before using it let isHittablePredicate = NSPredicate { _, _ in app.textViews.firstMatch.isHittable == true } let expectation = XCTNSPredicateExpectation(predicate: isHittablePredicate, object: .none) XCTWaiter().wait(for: [expectation], timeout: averageLoadTimeout) app.textViews.firstMatch.tap() } class func undo() { app.textViews.element.tap(withNumberOfTaps: 2, numberOfTouches: 3) } class func swipeToPreview() { app.textViews.firstMatch.swipeLeft() sleep(5) } class func leaveEditor() { let backButton = app.navigationBars[UID.NavBar.allNotes].buttons[UID.Button.noteEditorAllNotes] guard backButton.exists else { return } backButton.tap() } class func toggleMarkdownState() { app.navigationBars[UID.NavBar.allNotes].buttons[UID.Button.noteEditorMenu].tap() app.tables.staticTexts[UID.Text.noteEditorOptionsMarkdown].tap() app.navigationBars[UID.NavBar.noteEditorOptions].buttons[UID.Button.done].tap() } class func insertChecklist() { app.navigationBars[UID.NavBar.allNotes].buttons[UID.Button.noteEditorChecklist].tap() } class func markdownEnable() { swipeToPreview() if app.navigationBars[UID.NavBar.noteEditorPreview].exists { Preview.leavePreviewViaBackButton() } else { toggleMarkdownState() } } class func markdownDisable() { swipeToPreview() guard app.navigationBars[UID.NavBar.noteEditorPreview].exists else { return } Preview.leavePreviewViaBackButton() toggleMarkdownState() } class func getLink(byText linkText: String) -> XCUIElement { // As of iOS 16.0, a link in Note Editor is presented by two elements: // First is of `link` type and has zero dimensions, the other is its child // and has proper dimensions. Only the latter is usable for interactions: return app.links.matching(identifier: linkText).allElementsBoundByIndex.last! } class func pressLink(linkText: String) { let link = getLink(byText: linkText) guard link.exists else { return } // Should be replaced with proper way to determine if page is loaded link.press(forDuration: 1.3) sleep(5) } class func getAllTextViews() -> XCUIElementQuery { // If we are in Note Editor, and there's zero TextViews, we should try setting focus first if app.descendants(matching: .textView).count < 1 { NoteEditor.setFocus() } return app.descendants(matching: .textView) } class func getCheckboxesForTextCount(text: String) -> Int { let matches = NoteEditor.getTextViewsWithExactLabelCount(label: text) print(">>> ^ Found \(matches) Checkbox(es) for '\(text)'") return matches } class func getTextViewsWithExactValueCount(value: String) -> Int { // We wait for at least one element with exact value to appear before counting // all occurences. The downside is having one extra call before the actual count. let equalValuePredicate = NSPredicate(format: "value == '" + value + "'") _ = app .descendants(matching: .textView) .element(matching: equalValuePredicate) .waitForExistence(timeout: averageLoadTimeout) let matchingTextViews = getAllTextViews() .compactMap { ($0.value as? String)?.strippingUnicodeObjectReplacementCharacter() } .filter { $0 == value } let matches = matchingTextViews.count print(">>> Found \(matches) TextView(s) with '\(value)' value") return matches } class func getTextViewsWithExactLabelCount(label: String) -> Int { let _ = getAllTextViews()// To initialize the editor let equalLabelPredicate = NSPredicate(format: "label == '" + label + "'") // We wait for at least one element with exact label to appear before counting // all occurences. The downside is having one extra call before the actual count. _ = app.textViews[label].waitForExistence(timeout: averageLoadTimeout) let matchingTextViews = app.textViews.matching(equalLabelPredicate) let matches = matchingTextViews.count print(">>> Found \(matches) TextView(s) with '\(label)' label") return matches } class func openHistory() { app.buttons[UID.Button.noteEditorMenu].tap() let historyButton = app.tables.staticTexts[UID.Text.noteEditorOptionsHistory] guard historyButton.waitForExistence(timeout: minLoadTimeout) else { return } historyButton.tap() } } class NoteEditorAssert { class func linkifiedURL(linkText: String) { let linkElement = NoteEditor.getLink(byText: linkText) XCTAssertTrue(linkElement.exists, "\"" + linkText + linkNotFoundInEditor) } class func editorShown() { let allNotesNavBar = app.navigationBars[UID.NavBar.allNotes] XCTAssertTrue(allNotesNavBar.waitForExistence(timeout: minLoadTimeout), UID.NavBar.allNotes + navBarNotFound) XCTAssertTrue(allNotesNavBar.buttons[UID.Button.noteEditorAllNotes].waitForExistence(timeout: minLoadTimeout), UID.Button.noteEditorAllNotes + buttonNotFound) XCTAssertTrue(allNotesNavBar.buttons[UID.Button.noteEditorChecklist].waitForExistence(timeout: minLoadTimeout), UID.Button.noteEditorChecklist + buttonNotFound) XCTAssertTrue(allNotesNavBar.buttons[UID.Button.noteEditorInformation].waitForExistence(timeout: minLoadTimeout), UID.Button.noteEditorInformation + buttonNotFound) XCTAssertTrue(allNotesNavBar.buttons[UID.Button.noteEditorMenu].waitForExistence(timeout: minLoadTimeout), UID.Button.noteEditorMenu + buttonNotFound) } class func textViewWithExactValueShownOnce(value: String) { let matches = NoteEditor.getTextViewsWithExactValueCount(value: value) XCTAssertEqual(matches, 1) } class func textViewWithExactValueNotShown(value: String) { let matches = NoteEditor.getTextViewsWithExactValueCount(value: value) XCTAssertEqual(matches, 0) } class func oneOfTheStringsIsShownInTextView(strings: [String]) { var matchFound = false for string in strings { if NoteEditor.getTextViewsWithExactValueCount(value: string) > 0 { matchFound = true break } } XCTAssertTrue(matchFound) } class func textViewWithExactLabelShownOnce(label: String) { let matches = NoteEditor.getTextViewsWithExactLabelCount(label: label) XCTAssertEqual(matches, 1) } class func textViewWithExactLabelsShownOnce(labels: [String]) { for label in labels { NoteEditorAssert.textViewWithExactLabelShownOnce(label: label) } } class func checkboxForTextShownOnce(text: String) { let matches = NoteEditor.getCheckboxesForTextCount(text: text) XCTAssertEqual(matches, 1) } class func checkboxForTextNotShown(text: String) { let matches = NoteEditor.getCheckboxesForTextCount(text: text) XCTAssertEqual(matches, 0) } } ```
/content/code_sandbox/SimplenoteUITests/NoteEditor.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,157
```swift import XCTest class SimplenoteUISmokeTestsSettings: XCTestCase { override class func setUp() { app.launch() getToAllNotes() _ = attemptLogOut() EmailLogin.open() EmailLogin.logIn() NoteList.waitForLoad() } override func setUpWithError() throws { getToAllNotes() NoteList.trashAllNotes() Trash.empty() NoteList.openAllNotes() } override class func tearDown() { Settings.open() Settings.condensedModeDisable() Settings.close() } func testUsingCondensedNoteList() throws { trackTest() let cellHeightCondensed: CGFloat = 44.0 let cellHeightUsual: CGFloat = 81.0 let note = NoteData( name: "Condensed Mode Test", content: "Condensed Mode Content" ) trackStep() NoteList.openAllNotes() NoteList.createNoteThenLeaveEditor(note) NoteListAssert.noteExists(note) trackStep() Settings.open() Settings.condensedModeEnable() Settings.close() NoteList.openAllNotes() NoteListAssert.noteContentIsShownInSearch(noteName: note.name, expectedContent: "") NoteListAssert.note(note, hasHeight: cellHeightCondensed) trackStep() Settings.open() Settings.condensedModeDisable() Settings.close() NoteList.openAllNotes() NoteListAssert.contentIsShown(for: note) NoteListAssert.note(note, hasHeight: cellHeightUsual) } } ```
/content/code_sandbox/SimplenoteUITests/SimplenoteUISmokeTestsSettings.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
333
```swift import XCTest import XCUITestHelpers class Preview { class func getText() -> String { // swiftlint:disable:next force_cast return app.webViews.descendants(matching: .staticText).element.value as! String } class func getAllStaticTexts() -> XCUIElementQuery { return app.webViews.descendants(matching: .staticText) } class func leavePreviewViaBackButton() { let backButton = app.navigationBars[UID.NavBar.noteEditorPreview].buttons[UID.Button.back] guard backButton.exists else { return } backButton.tap() } class func tapLink(linkText: String) { // Should be replaced with proper way to determine if page is loaded let link = app.descendants(matching: .link).element(matching: .link, identifier: linkText) link.tap() sleep(5) } class func getStaticTextsWithExactValueCount(value: String) -> Int { let predicate = NSPredicate(format: "value == '" + value + "'") // We wait for at least one element with exact value to appear before counting // all occurences. The downside is having one extra call before the actual count. _ = app .webViews .descendants(matching: .staticText) .element(matching: predicate) .waitForExistence(timeout: averageLoadTimeout) let matchingStaticTexts = app.webViews.descendants(matching: .staticText).matching(predicate) let matches = matchingStaticTexts.count print(">>> Found \(matches) StaticTexts(s) with '\(value)' value") return matches } class func getStaticTextsWithExactLabelCount(label: String) -> Int { let predicate = NSPredicate(format: "label == '" + label + "'") let matchingStaticTexts = app.webViews.descendants(matching: .staticText).matching(predicate) let matches = matchingStaticTexts.count print(">>> Found \(matches) StaticTexts(s) with '\(label)' label") return matches } } class PreviewAssert { class func linkShown(linkText: String) { let linkPredicate = NSPredicate(format: "label == '" + linkText + "'") let link = app.links.element(matching: linkPredicate) XCTAssertTrue(link.exists, "\"" + linkText + linkNotFoundInPreview) } class func previewShown() { let previewNavBar = app.navigationBars[UID.NavBar.noteEditorPreview] XCTAssertTrue( previewNavBar.waitForExistence(timeout: minLoadTimeout), UID.NavBar.noteEditorPreview + navBarNotFound ) XCTAssertTrue( previewNavBar.buttons[UID.Button.back].waitForExistence(timeout: minLoadTimeout), UID.Button.back + buttonNotFound ) XCTAssertTrue( previewNavBar.staticTexts[UID.Text.noteEditorPreview].waitForExistence(timeout: minLoadTimeout), UID.Text.noteEditorPreview + labelNotFound ) } class func wholeTextShown(text: String) { XCTAssertEqual(text, Preview.getText(), "Preview text" + notExpectedEnding) } class func staticTextWithExactLabelShownOnce(label: String) { let matches = Preview.getStaticTextsWithExactLabelCount(label: label) XCTAssertEqual(matches, 1) } class func staticTextWithExactValueShownOnce(value: String) { let matches = Preview.getStaticTextsWithExactValueCount(value: value) XCTAssertEqual(matches, 1) } class func staticTextWithExactValuesShownOnce(values: [String]) { for value in values { PreviewAssert.staticTextWithExactValueShownOnce(value: value) } } class func boxesTotalNumber(expectedSwitchesNumber: Int) { XCTAssertEqual(expectedSwitchesNumber, app.switches.count, numberOfBoxesInPreviewNotExpected) } class func boxesStates(expectedCheckedBoxesNumber: Int, expectedEmptyBoxesNumber: Int) { let expectedBoxesCount = expectedCheckedBoxesNumber + expectedEmptyBoxesNumber let boxes = app.switches let actualBoxesCount = boxes.count print(">>> Number of boxes found: \(actualBoxesCount)") XCTAssertEqual(actualBoxesCount, expectedBoxesCount, numberOfBoxesInPreviewNotExpected) guard actualBoxesCount > 0 else { return } let actualCheckedBoxesCount = boxes.filter { $0.value.debugDescription == "Optional(1)" }.count let actualEmptyBoxesCount = boxes.filter { $0.value.debugDescription == "Optional(0)" }.count XCTAssertEqual(actualCheckedBoxesCount, expectedCheckedBoxesNumber, numberOfCheckedBoxesInPreviewNotExpected) XCTAssertEqual(actualEmptyBoxesCount, expectedEmptyBoxesNumber, numberOfEmptyBoxesInPreviewNotExpected) } } ```
/content/code_sandbox/SimplenoteUITests/Preview.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,009
```swift /// Value-type to describe the elements that represent a not as seen from the UI. struct NoteData { let name: String let content: String private(set) var tags: [String] = [] var formattedForAutomatedInput: String { "\(name)\n\n\(content)" } } ```
/content/code_sandbox/SimplenoteUITests/NoteData.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
66
```swift import XCTest class SimplenoteUISmokeTestsTrash: XCTestCase { override class func setUp() { app.launch() let _ = attemptLogOut() EmailLogin.open() EmailLogin.logIn() NoteList.waitForLoad() } override func setUpWithError() throws { NoteList.trashAllNotes() Trash.empty() NoteList.openAllNotes() } func testCanViewTrashedNotes() throws { trackTest() let noteOneName = "CanView" let noteTwoName = "Trashed" let noteThreeName = "Notes" let noteNamesArray = [noteOneName, noteTwoName, noteThreeName] trackStep() Trash.open() TrashAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.openAllNotes() NoteList.createNotes(names: noteNamesArray) NoteListAssert.notesExist(names: noteNamesArray) NoteListAssert.notesNumber(expectedNotesNumber: 3) trackStep() NoteList.trashNote(noteName: noteOneName) NoteListAssert.noteAbsent(noteName: noteOneName) NoteListAssert.noteExists(noteName: noteTwoName) NoteListAssert.noteExists(noteName: noteThreeName) NoteListAssert.notesNumber(expectedNotesNumber: 2) trackStep() Trash.open() TrashAssert.noteExists(noteName: noteOneName) TrashAssert.notesNumber(expectedNotesNumber: 1) } func testCanDeleteNoteForeverIndividually() throws { trackTest() let noteOneName = "CanDelete" let noteTwoName = "Note" let noteThreeName = "Forever" let noteNamesArray = [noteOneName, noteTwoName, noteThreeName] trackStep() Trash.open() TrashAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.openAllNotes() NoteList.createNotes(names: noteNamesArray) NoteListAssert.notesExist(names: noteNamesArray) NoteListAssert.notesNumber(expectedNotesNumber: 3) trackStep() NoteList.trashNote(noteName: noteOneName) NoteList.trashNote(noteName: noteTwoName) NoteListAssert.noteAbsent(noteName: noteOneName) NoteListAssert.noteAbsent(noteName: noteTwoName) NoteListAssert.noteExists(noteName: noteThreeName) NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() Trash.open() TrashAssert.noteExists(noteName: noteOneName) TrashAssert.noteExists(noteName: noteTwoName) TrashAssert.notesNumber(expectedNotesNumber: 2) trackStep() Trash.deleteNote(noteName: noteOneName) TrashAssert.noteAbsent(noteName: noteOneName) TrashAssert.noteExists(noteName: noteTwoName) TrashAssert.notesNumber(expectedNotesNumber: 1) trackStep() NoteList.openAllNotes() NoteListAssert.noteAbsent(noteName: noteOneName) NoteListAssert.noteAbsent(noteName: noteTwoName) NoteListAssert.noteExists(noteName: noteThreeName) NoteListAssert.notesNumber(expectedNotesNumber: 1) } func testCanDeleteNotesForeverViaEmpty() throws { trackTest() let noteOneName = "CanDelete" let noteTwoName = "Note" let noteThreeName = "Forever" let noteNamesArray = [noteOneName, noteTwoName, noteThreeName] trackStep() Trash.open() TrashAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.openAllNotes() NoteList.createNotes(names: noteNamesArray) NoteListAssert.notesExist(names: noteNamesArray) NoteListAssert.notesNumber(expectedNotesNumber: 3) trackStep() NoteList.trashNote(noteName: noteOneName) NoteList.trashNote(noteName: noteTwoName) NoteListAssert.noteAbsent(noteName: noteOneName) NoteListAssert.noteAbsent(noteName: noteTwoName) NoteListAssert.noteExists(noteName: noteThreeName) NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() Trash.open() TrashAssert.noteExists(noteName: noteOneName) TrashAssert.noteExists(noteName: noteTwoName) TrashAssert.notesNumber(expectedNotesNumber: 2) trackStep() Trash.empty() TrashAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.openAllNotes() NoteListAssert.noteAbsent(noteName: noteOneName) NoteListAssert.noteAbsent(noteName: noteTwoName) NoteListAssert.noteExists(noteName: noteThreeName) NoteListAssert.notesNumber(expectedNotesNumber: 1) } func testCanRestoreNote() throws { trackTest() let noteOneName = "CanRestore" let noteTwoName = "Trashed" let noteThreeName = "Notes" let noteNamesArray = [noteOneName, noteTwoName, noteThreeName] trackStep() Trash.open() TrashAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.openAllNotes() NoteList.createNotes(names: noteNamesArray) NoteListAssert.notesExist(names: noteNamesArray) NoteListAssert.notesNumber(expectedNotesNumber: 3) trackStep() NoteList.trashNote(noteName: noteOneName) NoteListAssert.noteAbsent(noteName: noteOneName) NoteListAssert.noteExists(noteName: noteTwoName) NoteListAssert.noteExists(noteName: noteThreeName) NoteListAssert.notesNumber(expectedNotesNumber: 2) trackStep() Trash.open() TrashAssert.noteExists(noteName: noteOneName) TrashAssert.notesNumber(expectedNotesNumber: 1) trackStep() Trash.restoreNote(noteName: noteOneName) TrashAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.openAllNotes() NoteListAssert.notesExist(names: noteNamesArray) NoteListAssert.notesNumber(expectedNotesNumber: 3) } func testCanTrashNote() throws { trackTest() let noteName = "can trash note" trackStep() Trash.open() TrashAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.openAllNotes() NoteList.createNoteAndLeaveEditor(noteName: noteName) NoteListAssert.noteExists(noteName: noteName) NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() NoteList.trashNote(noteName: noteName) NoteListAssert.noteAbsent(noteName: noteName) NoteListAssert.notesNumber(expectedNotesNumber: 0) trackStep() Trash.open() TrashAssert.noteExists(noteName: noteName) TrashAssert.notesNumber(expectedNotesNumber: 1) } } ```
/content/code_sandbox/SimplenoteUITests/SimplenoteUITestsTrash.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,492
```swift import XCTest extension String { func strippingUnicodeObjectReplacementCharacter() -> String { replacingOccurrences(of: "\u{fffc}", with: "") } } ```
/content/code_sandbox/SimplenoteUITests/Extensions.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
35
```swift import XCTest class Sidebar { class func getButtonSettings() -> XCUIElement { let predicate = NSPredicate(format: "identifier == '\(UID.Cell.settings)'") return app.tables.cells.element(matching: predicate) } class func getButtonTagsEdit() -> XCUIElement { // Returning first match, because there are two 'Done' buttons // for some reason, having same coordinates... return app.tables.buttons[UID.Button.edit].firstMatch } class func getButtonTagsDone() -> XCUIElement { // Returning first match, because there are two 'Edit' buttons // for some reason, having same coordinates... return app.tables.buttons[UID.Button.done].firstMatch } class func isOpen() -> Bool { // Checking for 'isHittable' of Settings button, because Settings button // is actually shown even when Sidebar is closed, but has the negative coordinates. // This is the property used to determine if Sidebar is open return Sidebar.getButtonSettings().isHittable } class func open() { guard !Sidebar.isOpen() else { return } let menuButton = app.navigationBars.element.buttons[UID.Button.menu] guard menuButton.exists else { return } menuButton.tap() } class func tagSelect(tagName: String) { Sidebar.open() let tagCell = app.tables.cells[tagName] guard tagCell.isHittable else { return } print(">>> Selecting tag: \(tagName)") tagCell.tap() } class func tagsEditStart() { let editButton = Sidebar.getButtonTagsEdit() guard editButton.exists else { return } editButton.tap() } class func tagsEditStop() { let doneButton = Sidebar.getButtonTagsDone() guard doneButton.exists else { return } doneButton.tap() } class func tagsDeleteAll() { Sidebar.tagsEditStart() while app.tables.buttons[UID.Button.itemTrash].firstMatch.isHittable { app.tables.buttons[UID.Button.itemTrash].firstMatch.tap() sleep(1) app.buttons[UID.Button.deleteTagConfirmation].tap() sleep(1) } Sidebar.tagsEditStop() } } ```
/content/code_sandbox/SimplenoteUITests/Sidebar.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
479
```swift import XCTest class Trash { class func open() { print(">>> Opening \"Trash\"") Sidebar.open() app.tables.staticTexts[UID.Button.trash].tap() } class func restoreNote(noteName: String) { app.tables.cells[noteName].swipeLeft() app.tables.cells[noteName].buttons[UID.Button.restoreNote].tap() } class func deleteNote(noteName: String) { Table.trashCell(noteName: noteName) } class func empty() { Trash.open() let emptyTrashButton = app.buttons[UID.Button.trashEmptyTrash] guard emptyTrashButton.isEnabled else { return } emptyTrashButton.tap() app.alerts.scrollViews.otherElements.buttons[UID.Button.yes].tap() } class func getNotesNumber() -> Int { return Table.getVisibleLabelledCells().count } } class TrashAssert { class func noteExists(noteName: String) { XCTAssertTrue(app.tables.cells[noteName].exists, noteName + noteNotFoundInTrash) } class func noteAbsent(noteName: String) { XCTAssertFalse(app.tables.cells[noteName].exists, noteName + noteNotAbsentInTrash) } class func notesNumber(expectedNotesNumber: Int) { let actualNotesNumber = Trash.getNotesNumber() XCTAssertEqual(actualNotesNumber, expectedNotesNumber, numberOfNotesInTrashNotExpected) } } ```
/content/code_sandbox/SimplenoteUITests/Trash.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
306
```swift import XCTest let app = XCUIApplication() private var stepIndex = 0 func attemptLogOut() -> Bool { let allNotesNavBar = app.navigationBars[UID.NavBar.allNotes] var loggedOut: Bool = false if allNotesNavBar.exists { loggedOut = logOut() } else { loggedOut = true } return loggedOut } func logOut() -> Bool { Sidebar.open() Sidebar.getButtonSettings().tap() app.tables.staticTexts[UID.Button.settingsLogOut].tap() return app.buttons[UID.Button.logIn].waitForExistence(timeout: maxLoadTimeout) } func trackTest(_ function: String = #function) { print("> Test: \(function)") stepIndex = 1 } func trackStep() { print(">> Step \(stepIndex)") stepIndex += 1 } func getToAllNotes() { WebView.tapDone() Preview.leavePreviewViaBackButton() NoteEditor.leaveEditor() } func toggleSwitchIfNeeded(_ switchElement: XCUIElement, _ value: String) { let switchValue = switchElement.value as? String guard switchValue != value else { return } switchElement.tap() } func dismissVerifyEmailIfNeeded() { guard app.staticTexts[Text.alertReviewAccount].waitForExistence(timeout: 15) else { return } app.buttons[UID.Button.crossIcon].tap() } func populateNoteList(title: String, numberToCreate: Int) { for i in 1...numberToCreate { let noteTitle = title + "-" + String(i) let noteContent = "\n\nSome content here for note " + String(i) NoteList.addNoteTap() NoteEditor.clearAndEnterText(enteredValue: noteTitle + noteContent) NoteEditor.leaveEditor() } } func getRandomId() -> String { let id = NSDate().timeIntervalSince1970.description.suffix(6) return String(id) } class Table { class func getAllCells() -> XCUIElementQuery { return app.tables.element.children(matching: .cell) } class func getVisibleLabelledCells() -> [XCUIElement] { // We need only the table cells that have X = 0 and a non-empty label // Currently (besides using object dimensions) this is the way to // locate note cells return Table.getAllCells() .filter { $0.frame.minX == 0.0 && $0.label.isEmpty == false } } class func getVisibleLabelledCellsNames() -> [String] { return Table.getVisibleLabelledCells().compactMap { $0.label } } class func getVisibleNonLabelledCellsNumber() -> Int { // We need only the table cells that have X = 0 and an empty label // Currently (besides using object dimensions) this is the way to // locate tags search suggestions return Table.getAllCells() .filter { $0.frame.minX == 0.0 && $0.label.isEmpty == true } .count } class func trashCell(noteName: String) { // `Trash Note` and `Delete note forever` buttons have different labels // since 07fcccf1039495768ecdf9909d3dbd1b255936cd // (path_to_url // To use the correct label, we need to know where we are. let deleteButtonLabel = app.navigationBars[UID.NavBar.trash].exists ? UID.Button.deleteNote : UID.Button.trashNote let noteCell = Table.getCell(label: noteName) noteCell.swipeLeft() noteCell.buttons[deleteButtonLabel].tap() } class func getCell(label: String) -> XCUIElement { let predicate = NSPredicate(format: "label LIKE '\(label)'") let cell = app.tables.cells.element(matching: predicate).firstMatch return cell } class func getStaticText(label: String) -> XCUIElement { let staticText = app.tables.staticTexts[label] return staticText } class func getCellsWithExactLabelCount(label: String) -> Int { let predicate = NSPredicate(format: "label == '" + label + "'") let matchingCells = app.cells.matching(predicate) let matches = matchingCells.count print(">>> Found \(matches) Cell(s) with '\(label)' label") return matches } class func getStaticTextsWithExactLabelCount(label: String) -> Int { let predicate = NSPredicate(format: "label == '" + label + "'") let matchingCells = app.tables.staticTexts.matching(predicate) let matches = matchingCells.count print(">>> Found \(matches) StaticText(s) with '\(label)' label") return matches } class func getContentOfCell(noteName: String) -> String? { let cell = Table.getCell(label: noteName) guard cell.exists else { return "" } // We need to find a child element of the cell from above, // a static text that has a content different from note name - // this is the one we need. let predicate = NSPredicate(format: "label != '" + noteName + "'") let staticTextWithContent = cell.staticTexts.element(matching: predicate) guard staticTextWithContent.exists else { return .none } return staticTextWithContent.label } } class WebView { class func tapDone() { let doneButton = app.buttons[UID.Button.done] guard doneButton.exists else { return } doneButton.tapCenterCoordinates(in: app) } } class WebViewAssert { class func textShownOnScreen(text: String) { let textPredicate = NSPredicate(format: "label MATCHES '" + text + "'") let staticTextExists = app .staticTexts .element(matching: textPredicate) .waitForExistence(timeout: averageLoadTimeout) XCTAssertTrue(staticTextExists, "\"" + text + textNotFoundInWebView) } class func textsShownOnScreen(texts: [String]) { for text in texts { WebViewAssert.textShownOnScreen(text: text) } } } class Alert { class func closeAny() { let alert = app.alerts.element guard alert.exists else { return } let confirmPredicate = NSPredicate(format: "label == '" + UID.Button.accept + "' || label == 'AnythingElse'") let confirmationButton = alert.buttons.element(matching: confirmPredicate) guard confirmationButton.exists else { return } confirmationButton.tap() } } extension XCUIElement { func tapCenterCoordinates(in app: XCUIApplication) { let coordinates = app.coordinate(withNormalizedOffset: .zero) .withOffset(CGVector(dx: frame.midX, dy: frame.midY)) coordinates.tap() } } ```
/content/code_sandbox/SimplenoteUITests/Generic.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,482
```swift import XCTest class EmailLogin { class func open() { app.buttons[UID.Button.logIn].waitForIsHittable() app.buttons[UID.Button.logIn].tap() } class func close() { /// Exit: We're already in the Onboarding UI /// if app.buttons[UID.Button.logIn].exists, app.buttons[UID.Button.signUp].exists { return } /// Back from Password > Code UI /// let backFromPasswordUI = app.navigationBars[UID.NavBar.logInWithPassword].buttons.element(boundBy: 0) if backFromPasswordUI.exists { backFromPasswordUI.tap() _ = app.navigationBars[UID.NavBar.enterCode].waitForExistence(timeout: minLoadTimeout) } /// Back from Code UI > Email UI /// Important: When rate-limited, the Code UI is skipped /// let codeNavigationBar = app.navigationBars[UID.NavBar.enterCode] if codeNavigationBar.exists { codeNavigationBar.buttons.element(boundBy: 0).tap() _ = app.navigationBars[UID.NavBar.logIn].waitForExistence(timeout: minLoadTimeout) } /// Back from Email UI > Onboarding /// let emailNavigationBar = app.navigationBars[UID.NavBar.logIn] if emailNavigationBar.exists { emailNavigationBar.buttons.element(boundBy: 0).tap() } handleSavePasswordPrompt() } class func logIn() { let testAccountKey = "UI_TEST_ACCOUNT" let testAccount: String switch ProcessInfo.processInfo.environment[testAccountKey] { case .none: fatalError("Expected \(testAccountKey) environment variable to be defined in the scheme") case .some(let value): // Use 'default' account if test account was not passed via environment variable testAccount = value.isEmpty ? testDataEmail : value } EmailLogin.logIn(email: testAccount, password: testDataPassword) } class func logIn(email: String, password: String) { enterEmail(enteredValue: email) app.buttons[UID.Button.logInWithEmail].tap() /// Code UI > Password UI /// Important: When rate-limited, the Code UI is skipped /// let codeNavigationBar = app.navigationBars[UID.NavBar.enterCode] _ = codeNavigationBar.waitForExistence(timeout: minLoadTimeout) if codeNavigationBar.exists { app.buttons[UID.Button.enterPassword].tap() } /// Password UI /// _ = app.buttons[UID.Button.logIn].waitForExistence(timeout: minLoadTimeout) enterPassword(enteredValue: password) app.buttons[UID.Button.mainAction].tap() handleSavePasswordPrompt() waitForSpinnerToDisappear() } class func enterEmailAndAttemptLogin(email: String) { enterEmail(enteredValue: email) app.buttons[UID.Button.logInWithEmail].tap() } class func enterEmail(enteredValue: String) { let field = app.textFields[UID.TextField.email] field.tap() field.typeText(enteredValue) } class func enterPassword(enteredValue: String) { let field = app.secureTextFields[UID.TextField.password] field.tap() field.typeText(enteredValue) } class func handleSavePasswordPrompt() { // As of Xcode 14.3, the Simulator might ask to save the password which, of course, we don't want to do. if app.buttons["Save Password"].waitForExistence(timeout: 5) { // There should be no need to wait for this button to exist since it's part of the same // alert where "Save Password" is. app.buttons["Not Now"].tap() } } class func waitForSpinnerToDisappear() { let predicate = NSPredicate(format: "exists == false && isHittable == false") let expectation = XCTNSPredicateExpectation(predicate: predicate, object: app.staticTexts["In progress"]) XCTWaiter().wait(for: [ expectation ], timeout: 10) } } ```
/content/code_sandbox/SimplenoteUITests/EmailLogin.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
889
```swift import XCTest // swiftlint:disable line_length let godzilla = NoteData( name: "Godzilla", content: "Godzilla (Japanese: , Hepburn: Gojira, /dzl/; [odia] (About this soundlisten)) is a fictional monster, or kaiju, originating from a series of Japanese films. The character first appeared in the 1954 film Godzilla and became a worldwide pop culture icon, appearing in various media, including 32 films produced by Toho, four Hollywood films and numerous video games, novels, comic books and television shows. Godzilla has been dubbed the'King of the Monsters', a phrase first used in Godzilla, King of the Monsters! (1956), the Americanized version of the original film.", tags: ["sea-monster", "reptile", "prehistoric"] ) let kingGong = NoteData( name: "King Kong", content: "King Kong is a film monster, resembling an enormous gorilla, that has appeared in various media since 1933. He has been dubbed The Eighth Wonder of the World, a phrase commonly used within the films. The character first appeared in the novelization of the 1933 film King Kong from RKO Pictures, with the film premiering a little over two months later. The film received universal acclaim upon its initial release and re-releases. A sequel quickly followed that same year with The Son of Kong, featuring Little Kong. In the 1960s, Toho produced King Kong vs. Godzilla (1962), pitting a larger Kong against Toho's own Godzilla, and King Kong Escapes (1967), based on The King Kong Show (19661969) from Rankin/Bass Productions. In 1976, Dino De Laurentiis produced a modern remake of the original film directed by John Guillermin.", tags: ["ape", "prehistoric"] ) let mechagodzilla = NoteData( name: "Mechagodzilla", content: "Mechagodzilla (, Mekagojira) is a fictional mecha character that first appeared in the 1974 film Godzilla vs. Mechagodzilla. In its debut appearance, Mechagodzilla is depicted as an extraterrestrial villain that confronts Godzilla. In subsequent iterations, Mechagodzilla is usually depicted as a man-made weapon designed to defend Japan from Godzilla. In all incarnations, the character is portrayed as a robotic doppelgnger with a vast array of weaponry, and along with King Ghidorah, is commonly considered to be an archenemy of Godzilla.", tags: ["man-made", "robot"] ) let diacritic = NoteData( name: "Diacritic", content: "A diacritic (also diacritical mark, diacritical point, diacritical sign, or accent) is a glyph added to a letter or basic glyph. The term derives from the Ancient Greek (diakritiks, \"distinguishing\"), from (diakrn, \"to distinguish\"). Some diacritical marks, such as the acute () and grave (`), are often called accents. Examples are the diaereses in the borrowed French words nave and Nol, which show that the vowel with the diaeresis mark is pronounced separately from the preceding vowel; the acute and grave accents, which can indicate that a final vowel is to be pronounced, as in sak and poetic breathd; and the cedilla under the \"c\" in the borrowed French word faade, which shows it is pronounced /s/ rather than /k/. In other Latin-script alphabets, they may distinguish between homonyms, such as the French l (\"there\") versus la (\"the\") that are both pronounced /la/. In Gaelic type, a dot over a consonant indicates lenition of the consonant in question.", tags: ["language", "diacritic"] ) // swiftlint:enable line_length let allNotes: [NoteData] = [ godzilla, kingGong, mechagodzilla, diacritic ] class SimplenoteUISmokeTestsSearch: XCTestCase { override class func setUp() { app.launch() _ = attemptLogOut() EmailLogin.open() EmailLogin.logIn() NoteList.waitForLoad() NoteList.trashAllNotes() Trash.empty() Sidebar.open() Sidebar.tagsDeleteAll() NoteList.openAllNotes() allNotes.forEach { NoteList.createNoteThenLeaveEditor($0, usingPaste: true) } } override func setUpWithError() throws { NoteList.searchForText(text: "") NoteList.searchCancel() } func testClearingSearchFieldUpdatesFilteredNotes() throws { trackTest() trackStep() NoteList.openAllNotes() NoteListAssert.notesExist(allNotes) NoteListAssert.notesNumber(expectedNotesNumber: 4) trackStep() NoteList.searchForText(text: "Japan") NoteListAssert.notesExist([godzilla, mechagodzilla]) trackStep() NoteList.searchCancel() NoteListAssert.notesExist(allNotes) NoteListAssert.notesNumber(expectedNotesNumber: 4) trackStep() NoteList.searchForText(text: "weapon") NoteListAssert.noteExists(mechagodzilla) NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() NoteList.searchForText(text: "") NoteListAssert.notesExist(allNotes) NoteListAssert.notesNumber(expectedNotesNumber: 4) } func testCanFilterByTagWhenClickingOnTagInTagDrawer() throws { trackTest() trackStep() var testedTag = "prehistoric" Sidebar.tagSelect(tagName: testedTag) NoteListAssert.noteListShown(forSelection: testedTag) NoteListAssert.notesExist([godzilla, kingGong]) NoteListAssert.notesNumber(expectedNotesNumber: 2) trackStep() testedTag = "reptile" Sidebar.tagSelect(tagName: testedTag) NoteListAssert.noteListShown(forSelection: testedTag) NoteListAssert.noteExists(godzilla) NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() testedTag = "robot" Sidebar.tagSelect(tagName: testedTag) NoteListAssert.noteListShown(forSelection: testedTag) NoteListAssert.noteExists(mechagodzilla) NoteListAssert.notesNumber(expectedNotesNumber: 1) } func your_sha256_hashlteredNotes() throws { trackTest() trackStep() var testedTag = "prehistoric" Sidebar.tagSelect(tagName: testedTag) NoteListAssert.noteListShown(forSelection: testedTag) NoteListAssert.notesExist([godzilla, kingGong]) NoteListAssert.notesNumber(expectedNotesNumber: 2) trackStep() NoteList.openAllNotes() NoteListAssert.allNotesShown() NoteListAssert.notesExist(allNotes) NoteListAssert.notesNumber(expectedNotesNumber: 4) trackStep() Trash.open() NoteListAssert.trashShown() TrashAssert.notesNumber(expectedNotesNumber: 0) trackStep() testedTag = "language" Sidebar.tagSelect(tagName: testedTag) NoteListAssert.noteListShown(forSelection: testedTag) NoteListAssert.noteExists(diacritic) NoteListAssert.notesNumber(expectedNotesNumber: 1) } func testCanSearchByKeyword() throws { trackTest() trackStep() NoteList.openAllNotes() NoteListAssert.notesExist(allNotes) NoteListAssert.notesNumber(expectedNotesNumber: 4) trackStep() NoteList.searchForText(text: "Godzilla") NoteListAssert.notesExist([godzilla, kingGong, mechagodzilla]) NoteListAssert.notesNumber(expectedNotesNumber: 3) trackStep() NoteList.searchForText(text: "Gorilla") NoteListAssert.notesExist([kingGong]) NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() NoteList.searchForText(text: "Gaelic") NoteListAssert.notesExist([diacritic]) NoteListAssert.notesNumber(expectedNotesNumber: 1) } func testTagSuggestionsSuggestTagsRegardlessOfCase() throws { trackTest() trackStep() NoteList.searchForText(text: "robot") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionExists(tag: "tag:robot") NoteListAssert.tagsSuggestionsNumber(number: 1) NoteListAssert.notesSearchHeaderShown() NoteListAssert.noteExists(mechagodzilla) NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() NoteList.searchForText(text: "ROBOT") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionExists(tag: "tag:robot") NoteListAssert.tagsSuggestionsNumber(number: 1) NoteListAssert.notesSearchHeaderShown() NoteListAssert.noteExists(mechagodzilla) NoteListAssert.notesNumber(expectedNotesNumber: 1) trackStep() NoteList.searchForText(text: "PrEhIsToRiC") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionExists(tag: "tag:prehistoric") NoteListAssert.tagsSuggestionsNumber(number: 1) NoteListAssert.notesSearchHeaderNotShown() NoteListAssert.notesNumber(expectedNotesNumber: 0) } func testTagAutoCompletesAppearWhenTypingInSearchField() throws { trackTest() trackStep() NoteList.searchForText(text: "t") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionsExist( tags: ["tag:diacritic", "tag:prehistoric", "tag:reptile", "tag:robot", "tag:sea-monster"] ) NoteListAssert.tagsSuggestionsNumber(number: 5) NoteListAssert.notesSearchHeaderShown() trackStep() NoteList.searchForText(text: "a") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionsExist( tags: ["tag:ape", "tag:diacritic", "tag:language", "tag:man-made", "tag:sea-monster"] ) NoteListAssert.tagsSuggestionsNumber(number: 5) NoteListAssert.notesSearchHeaderShown() trackStep() NoteList.searchForText(text: "ic") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionsExist(tags: ["tag:diacritic", "tag:prehistoric"]) NoteListAssert.tagsSuggestionsNumber(number: 2) NoteListAssert.notesSearchHeaderShown() trackStep() NoteList.searchForText(text: "abc") NoteListAssert.tagsSearchHeaderNotShown() NoteListAssert.notesSearchHeaderNotShown() NoteListAssert.notesNumber(expectedNotesNumber: 0) } func your_sha512_hash() throws { trackTest() trackStep() NoteList.searchForText(text: "tag:re") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionsExist(tags: ["tag:prehistoric", "tag:reptile"]) NoteListAssert.tagsSuggestionsNumber(number: 2) NoteListAssert.notesSearchHeaderNotShown() NoteListAssert.notesNumber(expectedNotesNumber: 0) trackStep() NoteList.searchForText(text: "tag:-") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionsExist(tags: ["tag:man-made", "tag:sea-monster"]) NoteListAssert.tagsSuggestionsNumber(number: 2) NoteListAssert.notesSearchHeaderNotShown() NoteListAssert.notesNumber(expectedNotesNumber: 0) } func testSearchFieldUpdatesWithResultsOfTagFormatSearchString() throws { trackTest() let testedTag = "tag:prehistoric" trackStep() NoteList.searchForText(text: "pre") NoteListAssert.tagsSearchHeaderShown() NoteListAssert.tagSuggestionExists(tag: testedTag) trackStep() NoteList.tagSuggestionTap(tag: testedTag) NoteListAssert.searchStringIsShown(searchString: testedTag + " ") NoteListAssert.notesSearchHeaderShown() NoteListAssert.notesExist([godzilla, kingGong]) NoteListAssert.notesNumber(expectedNotesNumber: 2) } func testCanSeeExcerpts() throws { trackTest() trackStep() NoteList.openAllNotes() NoteListAssert.notesExist(allNotes) NoteListAssert.notesNumber(expectedNotesNumber: 4) trackStep() NoteList.searchForText(text: "Hepburn") // swiftlint:disable:next line_length NoteListAssert.noteContentIsShownInSearch(noteName: godzilla.name, expectedContent: "Godzilla (Japanese: , Hepburn: Gojira, /dzl/; [odia] (About this soundlisten)) is a fictional monster, or kaiju, originating from a series of Japanese films. The character first appeared in the 1954 film Godzilla and became a worldwide pop culture icon, appearing in various media, including 32 films produced by Toho") trackStep() NoteList.searchForText(text: "1962") // swiftlint:disable:next line_length NoteListAssert.noteContentIsShownInSearch(noteName: kingGong.name, expectedContent: "King Kong vs. Godzilla (1962), pitting a larger Kong against Toho's own Godzilla, and King Kong Escapes (1967), based on The King Kong Show (19661969) from Rankin/Bass Productions. In 1976, Dino De Laurentiis produced a modern remake of the original film directed by John Guillermin") trackStep() NoteList.searchForText(text: "archenemy") // swiftlint:disable:next line_length NoteListAssert.noteContentIsShownInSearch(noteName: mechagodzilla.name, expectedContent: "commonly considered to be an archenemy of Godzilla") } } ```
/content/code_sandbox/SimplenoteUITests/SimplenoteUITestsSearch.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
3,038
```swift import XCTest let notExpectedEnding = " is NOT as expected", notFoundEnding = " NOT found", notAbsentEnding = " NOT absent" let inAllNotesEnding = #" in "All Notes""#, inNoteListEnding = #" in "Note List""#, inTrashEnding = " in \"Trash\"", inEditorEnding = " in Note Editor", inNotePreviewEnding = " in Note Preview", inWebViewEnding = " in WebView" let checkboxNotFound = " checkbox" + notFoundEnding, checkboxNotAbsent = " checkbox" + notAbsentEnding, textViewNotFound = " TextView" + notFoundEnding, buttonNotFound = " button" + notFoundEnding, buttonNotAbsent = " button" + notAbsentEnding, labelNotFound = " label" + notFoundEnding, labelNotAbsent = " label" + notAbsentEnding let alertHeadingNotFound = " alert heading" + notFoundEnding, alertContentNotFound = " alert content" + notFoundEnding, alertButtonNotFound = " alert button" + notFoundEnding let navBarNotFound = " navigation bar" + notFoundEnding, imageNotFound = " image" + notFoundEnding let noteNotFoundInAllNotes = "\" Note" + notFoundEnding + inAllNotesEnding, noteNotAbsentInAllNotes = " Note" + notAbsentEnding + inAllNotesEnding, noteNotFoundInTrash = " Note" + notFoundEnding + inTrashEnding, noteNotAbsentInTrash = " Note" + notAbsentEnding + inTrashEnding let numberOfNotesInAllNotesNotExpected = "Notes Number" + inAllNotesEnding + notExpectedEnding, numberOfNotesInTrashNotExpected = "Notes Number" + inTrashEnding + notExpectedEnding, numberOfTagsSuggestionsNotExpected = "Tags search suggestions " + inNoteListEnding + notExpectedEnding let linkNotFoundInEditor = "\" link" + notFoundEnding + inEditorEnding, linkNotFoundInPreview = "\" link" + notFoundEnding + inNotePreviewEnding let textNotFoundInEditor = "\" text" + notFoundEnding + inEditorEnding, textNotFoundInPreview = "\" text" + notFoundEnding + inNotePreviewEnding, textNotFoundInWebView = "\" text" + notFoundEnding + inWebViewEnding let numberOfBoxesInPreviewNotExpected = "Boxes number" + inNotePreviewEnding + notExpectedEnding, numberOfCheckedBoxesInPreviewNotExpected = "Checked boxes number" + inNotePreviewEnding + notExpectedEnding, numberOfEmptyBoxesInPreviewNotExpected = "Empty boxes number" + inNotePreviewEnding + notExpectedEnding let checkboxFoundMoreThanOnce = "Checkbox found more than once" let assertNavBarIdentifier = ">>> Asserting that currenly active navigation bar is: " let assertSearchHeaderShown = ">>> Asserting that search results header is shown: " let assertSearchHeaderNotShown = ">>> Asserting that search results header is NOT shown: " let foundNoNavBar = "Could not find any navigation bar" let maxLoadTimeout = 20.0, averageLoadTimeout = 10.0, minLoadTimeout = 5.0 class Assert { class func labelExists(labelText: String) { XCTAssertTrue(app.staticTexts[labelText].waitForExistence(timeout: minLoadTimeout), labelText + labelNotFound) } class func labelAbsent(labelText: String) { XCTAssertFalse(app.staticTexts[labelText].waitForExistence(timeout: minLoadTimeout), labelText + labelNotAbsent) } class func alertExistsAndClose(headingText: String, content: String, buttonText: String) { let alert = app.alerts[headingText] let alertHeadingExists = alert.waitForExistence(timeout: maxLoadTimeout) XCTAssertTrue(alertHeadingExists, headingText + alertHeadingNotFound) if alertHeadingExists { XCTAssertTrue(alert.staticTexts[content].waitForExistence(timeout: minLoadTimeout), content + alertContentNotFound) XCTAssertTrue(alert.buttons[buttonText].waitForExistence(timeout: minLoadTimeout), buttonText + alertButtonNotFound) } alert.buttons[buttonText].tap() } class func signUpLogInScreenShown() { XCTAssertTrue(app.images[UID.Picture.appLogo].waitForExistence(timeout: minLoadTimeout), UID.Picture.appLogo + imageNotFound) XCTAssertTrue(app.staticTexts[Text.appName].waitForExistence(timeout: minLoadTimeout), Text.appName + labelNotFound) XCTAssertTrue(app.staticTexts[Text.appTagline].waitForExistence(timeout: minLoadTimeout), Text.appTagline + labelNotFound) XCTAssertTrue(app.buttons[UID.Button.signUp].waitForExistence(timeout: minLoadTimeout), UID.Button.signUp + buttonNotFound) XCTAssertTrue(app.buttons[UID.Button.logIn].waitForExistence(timeout: minLoadTimeout), UID.Button.logIn + buttonNotFound) } } ```
/content/code_sandbox/SimplenoteUITests/AssertGeneric.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,034
```objective-c // // Use this file to import your target's public headers that you would like to expose to Swift. // #import "SPConstants.h" #import "TextBundleWrapper.h" ```
/content/code_sandbox/SimplenoteShare/Simplenote-Share-Bridging-Header.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
37
```swift import Foundation /// The purpose of this class is to encapsulate NSURLSession's interaction code, required to upload /// a note to Simperium's REST endpoint. /// class Uploader: NSObject { /// Simperium's Token /// private let token: String /// Designated Initializer /// init(simperiumToken: String) { token = simperiumToken } // MARK: - Public Methods func send(_ note: Note) { let request = requestToSend(note) // Task! let sc = URLSessionConfiguration.backgroundSessionConfigurationWithRandomizedIdentifier() let session = Foundation.URLSession(configuration: sc, delegate: self, delegateQueue: .main) let task = session.downloadTask(with: request) task.resume() } func send(_ note: Note) async throws -> (URL, URLResponse) { let request = requestToSend(note) let session = Foundation.URLSession(configuration: .default) return try await session.download(for: request) } private func requestToSend(_ note: Note) -> URLRequest { // Build the targetURL let endpoint = String(format: "%@/%@/%@/i/%@", kSimperiumBaseURL, SPCredentials.simperiumAppID, Settings.bucketName, note.simperiumKey) let targetURL = URL(string: endpoint.lowercased())! // Request var request = URLRequest(url: targetURL) request.httpMethod = Settings.httpMethodPost request.httpBody = note.toJsonData() request.setValue(token, forHTTPHeaderField: Settings.authHeader) return request } } // MARK: - URLSessionDelegate // extension Uploader: URLSessionDelegate { @objc func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { print("<> Uploader.didBecomeInvalidWithError: \(String(describing: error))") } @objc func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { print("<> Uploader.URLSessionDidFinishEventsForBackgroundURLSession") } } // MARK: - URLSessionTaskDelegate // extension Uploader: URLSessionTaskDelegate { @objc func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { print("<> Uploader.didCompleteWithError: \(String(describing: error))") } } // MARK: - Settings // private struct Settings { static let authHeader = "X-Simperium-Token" static let bucketName = "note" static let httpMethodPost = "POST" } ```
/content/code_sandbox/SimplenoteShare/Simperium/Uploader.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
555
```swift import Foundation /// This class encapsulates the Note entity. It's the main project (non core data) counterpart. /// class Note { /// Note's Simperium Unique Key /// let simperiumKey: String = { return UUID().uuidString.replacingOccurrences(of: "-", with: "") }() /// Payload /// let content: String /// Indicates if the Note is a Markdown document /// let markdown: Bool /// Creation Date: Now, by default! /// let creationDate = Date() /// Last Modification Date: Now, by default! /// let modificationDate = Date() /// Designated Initializer /// init(content: String, markdown: Bool = false) { self.content = content self.markdown = markdown } func toDictionary() -> [String: Any] { var systemTags = [String]() if markdown { systemTags.append("markdown") } return [ "tags": [], "deleted": 0, "shareURL": String(), "publishURL": String(), "content": content, "systemTags": systemTags, "creationDate": creationDate.timeIntervalSince1970, "modificationDate": modificationDate.timeIntervalSince1970 ] } func toJsonData() -> Data? { do { return try JSONSerialization.data(withJSONObject: toDictionary(), options: .prettyPrinted) } catch { print("Error converting Note to JSON: \(error)") return nil } } } ```
/content/code_sandbox/SimplenoteShare/Simperium/Note.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
336
```swift // // Downloader.swift // SimplenoteShare // // Created by Charlie Scheer on 5/13/24. // import Foundation enum DownloaderError: Error { case couldNotFetchNoteContent var title: String { switch self { case .couldNotFetchNoteContent: return NSLocalizedString("Could not fetch note content", comment: "note content fetch error title") } } var message: String { switch self { case .couldNotFetchNoteContent: return NSLocalizedString("Attempt to fetch current note content failed. Please try again later.", comment: "Data Fetch error message") } } } class Downloader: NSObject { /// Simperium's Token /// private let token: String /// Designated Initializer /// init(simperiumToken: String) { token = simperiumToken } func getNoteContent(for simperiumKey: String) async throws -> String? { let endpoint = String(format: "%@/%@/%@/i/%@", kSimperiumBaseURL, SPCredentials.simperiumAppID, Settings.bucketName, simperiumKey) let targetURL = URL(string: endpoint.lowercased())! // Request var request = URLRequest(url: targetURL) request.httpMethod = Settings.httpMethodGet request.setValue(token, forHTTPHeaderField: Settings.authHeader) let sc = URLSessionConfiguration.default let session = Foundation.URLSession(configuration: sc, delegate: nil, delegateQueue: .main) let downloadedData = try await session.data(for: request) return try extractNoteContent(from: downloadedData.0) } func extractNoteContent(from data: Data) throws -> String? { let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] guard let content = jsonObject?["content"] as? String else { throw DownloaderError.couldNotFetchNoteContent } return content } } // MARK: - Settings // private struct Settings { static let authHeader = "X-Simperium-Token" static let bucketName = "note" static let httpMethodGet = "GET" } ```
/content/code_sandbox/SimplenoteShare/Simperium/Downloader.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
482