my-files-sample/Libraries/Tests/APIServiceTests/Cases/Actors/APIService+GetUserTests.swift

121 lines
3.4 KiB
Swift

//
// APIService+GetUserTests.swift
// APIServiceTests
//
// Created by Javier Cicchelli on 04/12/2022.
// Copyright © 2022 Röck+Cöde. All rights reserved.
//
import Foundation
import XCTest
@testable import APIService
final class APIServiceGetUserTests: XCTestCase {
// MARK: Properties
private let dateFormatter = DateFormatter.iso8601
private let sessionConfiguration = {
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [MockURLProtocol.self]
return configuration
}()
private let url = URL(string: "http://163.172.147.216:8080/me")!
private var service: APIService!
private var data: Data!
private var result: Me!
// MARK: Setup
override func setUp() async throws {
service = .init(configuration: sessionConfiguration)
}
override func tearDown() async throws {
service = nil
}
// MARK: Test cases
func test_withRightCredentials() async throws {
// GIVEN
data = "{\"firstName\":\"Noel\",\"lastName\":\"Flantier\",\"rootItem\":{\"id\":\"4b8e41fd4a6a89712f15bbf102421b9338cfab11\",\"parentId\":\"\",\"name\":\"dossierTest\",\"isDir\":true,\"modificationDate\":\"2021-11-29T10:57:13Z\"}}\n".data(using: .utf8)
MockURLProtocol.mockData[url] = MockURLResponse(
status: .ok,
headers: [.Header.Keys.contentType: .Header.Values.contentTypeJSON],
data: data
)
// WHEN
result = try await service.getUser(credentials: .init(
username: "username",
password: "password"
))
// THEN
XCTAssertEqual(result, Me(
firstName: "Noel",
lastName: "Flantier",
rootItem: .init(
idParent: "",
id: "4b8e41fd4a6a89712f15bbf102421b9338cfab11",
name: "dossierTest",
isDirectory: true,
lastModifiedAt: dateFormatter.date(from: "2021-11-29T10:57:13Z")!,
size: nil,
contentType: nil
)
))
}
func test_withWrongCredentials() async throws {
MockURLProtocol.mockData[url] = MockURLResponse(
status: .unauthorized,
headers: [:],
data: nil
)
// WHEN & THEN
do {
_ = try await service.getUser(credentials: .init(
username: "usrname",
password: "passwrd"
))
} catch APIClientError.authenticationFailed {
XCTAssertTrue(true)
} catch {
XCTAssertTrue(false)
}
}
func test_withMalformedResponseData() async throws {
// GIVEN
data = "{\"firstName\":\"Noel\",\"rootItem\":{\"id\":\"4b8e41fd4a6a89712f15bbf102421b9338cfab11\"\"name\":\"dossierTest\",\"isDir\":true}}\n".data(using: .utf8)
MockURLProtocol.mockData[url] = MockURLResponse(
status: .ok,
headers: [.Header.Keys.contentType: .Header.Values.contentTypeJSON],
data: data
)
// WHEN & THEN
do {
_ = try await service.getUser(credentials: .init(
username: "usrname",
password: "passwrd"
))
} catch is DecodingError {
XCTAssertTrue(true)
} catch {
XCTAssertTrue(false)
}
}
}