|
| 1 | +// |
| 2 | +// File.swift |
| 3 | +// |
| 4 | +// |
| 5 | +// Created by Tibor Bodecs on 2022. 01. 09.. |
| 6 | +// |
| 7 | + |
| 8 | +@testable import AppApi |
| 9 | +import XCTest |
| 10 | + |
| 11 | +final class AppApiTests: XCTestCase { |
| 12 | + |
| 13 | + enum HTTPError: Error { |
| 14 | + case invalidResponse |
| 15 | + case invalidStatusCode(Int) |
| 16 | + } |
| 17 | + |
| 18 | + let baseUrl = URL(string: "http://localhost:8080/api/")! |
| 19 | + |
| 20 | + private func authenticate(_ login: User.Account.Login) async throws -> User.Token.Detail { |
| 21 | + var req = URLRequest(url: baseUrl.appendingPathComponent("sign-in/")) |
| 22 | + req.httpMethod = "POST" |
| 23 | + req.addValue("application/json", forHTTPHeaderField: "Content-Type") |
| 24 | + req.httpBody = try JSONEncoder().encode(login) |
| 25 | + |
| 26 | + let (data, response) = try await URLSession.shared.data(for: req) |
| 27 | + guard let response = response as? HTTPURLResponse else { |
| 28 | + throw HTTPError.invalidResponse |
| 29 | + } |
| 30 | + guard 200...299 ~= response.statusCode else { |
| 31 | + throw HTTPError.invalidStatusCode(response.statusCode) |
| 32 | + } |
| 33 | + return try JSONDecoder().decode(User.Token.Detail.self, from: data) |
| 34 | + } |
| 35 | + |
| 36 | + private func authenticateRoot() async throws -> User.Token.Detail { |
| 37 | + try await authenticate(.init(email: "root@localhost.com", password: "ChangeMe1")) |
| 38 | + } |
| 39 | + |
| 40 | + func testAuthorization() async throws { |
| 41 | + let login = User.Account.Login(email: "root@localhost.com", password: "ChangeMe1") |
| 42 | + let token = try await authenticate(login) |
| 43 | + XCTAssertEqual(token.value.count, 64) |
| 44 | + XCTAssertEqual(token.user.email, login.email) |
| 45 | + } |
| 46 | + |
| 47 | + func testBlogCategories() async throws { |
| 48 | + let token = try await authenticateRoot() |
| 49 | + |
| 50 | + var req = URLRequest(url: baseUrl.appendingPathComponent("\(Blog.pathKey)/\(Blog.Category.pathKey)/")) |
| 51 | + req.addValue("Bearer \(token.value)", forHTTPHeaderField: "Authorization") |
| 52 | + |
| 53 | + let (data, response) = try await URLSession.shared.data(for: req) |
| 54 | + guard let response = response as? HTTPURLResponse else { |
| 55 | + throw HTTPError.invalidResponse |
| 56 | + } |
| 57 | + print(response.statusCode) |
| 58 | + guard 200...299 ~= response.statusCode else { |
| 59 | + throw HTTPError.invalidStatusCode(response.statusCode) |
| 60 | + } |
| 61 | + |
| 62 | + let categories = try JSONDecoder().decode([Blog.Category.List].self, from: data) |
| 63 | + XCTAssertFalse(categories.isEmpty) |
| 64 | + } |
| 65 | +} |
| 66 | + |
0 commit comments