-3

JSON file : "credentials"

[
    
{
        
"name" : Tom Harry
        
"email" : tomharry@abc.com
        
"password" : tomharry123
    
},
    
    {
        "name" : Sam Billings
        "email" : sambillings@abc.com
        "password" : sambillings789
    }
]

Utility file :

import Foundation
import XCTest

class Utils {
    
    static func loadData(filename : String) -> [Any] {
        let filePath = Bundle(for: self).path(forResource: filename, ofType: "json") ?? "default"
        let url = URL(fileURLWithPath: filePath)
        do {
            let data = try Data(contentsOf: url)
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            let array =  json as! [Any]
            if array.isEmpty {
                XCTFail("Source file \(filename) is empty.")
            }
            return array
            }
            catch {
                    XCTFail("File \(filename) not found.")
                    return []
                }
    }
}

TestFile:

import XCTest

class UITests: XCTestCase {
    var app : XCUIApplication!

    override func setUpWithError() throws {
        launchApp()
        continueAfterFailure = false
    }

    func launchApp() {
        app = XCUIApplication()
        app.launch()
        print("APPLICATION IS LAUNCHED")
    }
    
    func signUp(fullName : String, email : String, password : String) {
        let fullNameTextField = app.textFields.matching(identifier: "full name").element
        let emailTextField = app.textFields.matching(identifier: "email").element
        let passwordTextField = app.textFields.matching(identifier: "password").element
        if fullNameTextField.exists {
            fullNameTextField.tap()
            fullNameTextField.typeText(fullName)
        }
        if emailTextField.exists {
            emailTextField.tap()
            emailTextField.typeText(email)
        }
        
        if passwordTextField.exists {
            passwordTextField.tap()
            passwordTextField.typeText(password)
        }
        
        
        
    }
  
    func register() {
        let registerButton = app.buttons.matching(identifier: "register").element
        XCTAssert(registerButton.waitForExistence(timeout: 5), "REGISTER BUTTON IS NOT PRESENT")
        if registerButton.exists {
            print("REGISTER BUTTON IS PRESENT")
            registerButton.tap()
            print("REGISTER BUTTON IS TAPPED")
        }
    }
    
    func testSignUp(){
        let dataSource = Utils.loadData(filename: "credentials")
        for iteration in dataSource {
            guard let user = iteration as? [String : Any] else {return}
            let fullname = user["name"] as! String
            let email = user["email"] as! String
            let password = user["password"] as! String
            signUp(fullName: fullname, email: email, password: password)
        }
    
    }
    
    func testflowtest() {
        register()
        testSignUp()
    }
        
}

After running the testFlowTest function in Test file, "credentials file is not found" error is showing.

I want to fill the Sign up text fields with name, email, password from the JSON file.

This is the image showing the error after using XCTFail("Error: \(error)")

enter image description here

jnpdx
  • 45,847
  • 6
  • 64
  • 94
Sumit
  • 1
  • 3
  • 2
    That isn't valid JSON. Also, you should consider using the actual `error` -- your "File not found" error doesn't accurately reflect the scenarios that could trigger a failure. – jnpdx Mar 04 '22 at 07:16
  • 1
    Regarding ASAP and shouting in comments, see https://meta.stackoverflow.com/questions/326569/under-what-circumstances-may-i-add-urgent-or-other-similar-phrases-to-my-quest – Joakim Danielson Mar 04 '22 at 07:16
  • @jnpdx The error is same : Failed: File credentials not found. Check the UTILS file Catch part. – Sumit Mar 04 '22 at 07:33
  • @JoakimDanielson Thank you for your reference. I need the solution urgently that's why I was shouting in comments. Will refer to these statements later on my next query. – Sumit Mar 04 '22 at 07:34
  • @Sumit that means the file isn't added to your target (if that's the true error). "Check the UTILS file Catch part" -- that's what I was looking at. You don't print the actual error. – jnpdx Mar 04 '22 at 07:35
  • @jnpdx I had check the target of json file to UITests from target membership. – Sumit Mar 04 '22 at 07:36
  • 1
    You should print the actual error also, not only a hardcoded one. Add `print(error)` to the catch – Joakim Danielson Mar 04 '22 at 07:37
  • @JoakimDanielson Its showing this in the console: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 3, column 17." UserInfo={NSDebugDescription=Invalid value around line 3, column 17., NSJSONSerializationErrorIndex=27} /Users/sumitverma/Documents/explain-life-ios-app/UITests/TestData/Utilities/utils.swift:27: error: -[UITests.UITests testflowtest] : failed - File credentials not found. – Sumit Mar 04 '22 at 07:39
  • @Sumit that message is just one that *you* generated and as I mentioned in my first comment, it doesn't reflect what's actually happening (necessarily). You're still not printing the actual `error`. What happens if you do `XCTFail("Error: \(error)")`? – jnpdx Mar 04 '22 at 07:41
  • @JoakimDanielson you mean like I mentioned in my comment (the first one in this thread)? – jnpdx Mar 04 '22 at 07:43
  • @jnpdx After using XCTFail("Error: \(error)") --- Same error is showing in console – Sumit Mar 04 '22 at 07:44
  • @Sumit that's not what I suggested -- note the \ before `\(error)`. By definition, if you've changed it, it *cannot* be the *same* error showing in the console. – jnpdx Mar 04 '22 at 07:45
  • @jnpdx exactly and now OP should know as well. – Joakim Danielson Mar 04 '22 at 07:45
  • @jnpdx I did the same , kindly please check the image I had attached with the issue. – Sumit Mar 04 '22 at 07:52
  • @Sumit the screenshot shows exactly what has been mentioned since the very first comment in the thread -- the "JSON" is not valid JSON. You need to format your JSON file correctly (keys and values need to have quotes surrounding them). – jnpdx Mar 04 '22 at 07:53
  • @jnpdx Okay let me correct the JSON file then I will get back to you. – Sumit Mar 04 '22 at 07:55

1 Answers1

0

Your JSON isn't properly formatted. Keys and values need to have quotes, and key/value pairs need to be separated by commas:

[
    {
        "name" : "Tom Harry",
        "email" : "tomharry@abc.com",        
        "password" : "tomharry123"    
    },
    
    {
        "name" : "Sam Billings",
        "email" : "sambillings@abc.com",
        "password" : "sambillings789"
    }
]

Here's code that is paste-able into a Playground that shows that this is parsable (and will fail with your same error if you replace it with your original JSON):

let data = """
[
    {
        "name" : "Tom Harry",
        "email" : "tomharry@abc.com",
        "password" : "tomharry123"
    },
    
    {
        "name" : "Sam Billings",
        "email" : "sambillings@abc.com",
        "password" : "sambillings789"
    }
]
""".data(using: .utf8)!

do {
    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    print(json)
} catch {
    print(error)
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • I did the same now this error is showing: failed - Error: Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed object around line 4, column 8." UserInfo={NSDebugDescription=Badly formed object around line 4, column 8., NSJSONSerializationErrorIndex=48} – Sumit Mar 04 '22 at 08:00
  • Then you've done something different than I have (I'm guessing you didn't truly copy and paste from my answer and rather typed it yourself, but did something *slightly* different). As shown in my update, you can copy and paste this directly into a Playground and it will work fine. – jnpdx Mar 04 '22 at 08:02
  • Finally first text field is filled with the name data from json file !!!! – Sumit Mar 04 '22 at 08:06
  • But getting error with second textfield. Let me check out the error, if i will not able to solve it will get back to you. Thanks for the help till now. – Sumit Mar 04 '22 at 08:07
  • That seems beyond the scope of this question. We don't have any information about how you created the textfields. Most likely you have a name/tag mismatch somewhere. If this answered your original question, please mark it as correct/accepted using the green checkmark. – jnpdx Mar 04 '22 at 08:10