File: PreviewServerTests.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (210 lines) | stat: -rw-r--r-- 9,564 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2021 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See https://swift.org/LICENSE.txt for license information
 See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

#if canImport(NIOHTTP1)
import XCTest
import Foundation

@testable import SwiftDocCUtilities
@testable import SwiftDocC
import SwiftDocCTestUtilities

@testable import NIO
@testable import NIOHTTP1

// rdar85046362
// Disabling this test due to accessing the temp directory and
// making network calls. The temp directories are accessible by all jobs on a
// bot, so they are subject to noise. Network calls are slow and can also be
// very noisy.
// class PreviewServerTests: XCTestCase {
class PreviewServerTests {

     func createTemporaryDirectory(
         fileManager: FileManager = .default
     ) throws -> URL {
         fatalError("This test is disabled by not conforming to XCTestCase. This helper is added here to make the code compile. This should never be called.")
     }
    
    public func createTempFolder(content: [File]) throws -> URL {
        fatalError("This test is disabled by not conforming to XCTestCase. This helper is added here to make the code compile. This should never be called.")
    }
    
    func testPreviewServerBeforeStarted() throws {
        // Create test content
        let tempFolderURL = try createTempFolder(content: [
            TextFile(name: "index.html", utf8Content: "index"),
        ])

        let socketURL = try createTemporaryDirectory().appendingPathComponent("sock")
        
        // Run test server
        var log = LogHandle.none
        let server = try PreviewServer(contentURL: tempFolderURL, bindTo: .socket(path: socketURL.path), logHandle: &log)

        // Assert server starts
        let expectationStarted = AsynchronousExpectation(description: "Server before start")
        DispatchQueue.global().async {
            do {
                try server.start() {
                    expectationStarted.fulfill()
                }
            } catch {
                XCTFail(error.localizedDescription)
            }
        }
        
        XCTAssertNotEqual(expectationStarted.wait(timeout: 5.0), .timedOut)
        
        do {
            try server.stop()
        } catch {
            XCTFail(error.localizedDescription)
        }
    }

    private func assertServer(socketPath: String, path: String, matchesContent expectedContent: String, file: StaticString = #file, line: UInt = #line) {
        let client = HTTPClient(to: .unixDomainSocket(path: socketPath), path: path)
        XCTAssertNoThrow(try client.connect(), file: (file), line: line)
        XCTAssertEqual(client.handler.statusCode, 200, file: (file), line: line)
        XCTAssertEqual(client.handler.response, expectedContent, file: (file), line: line)
    }

    private func assertServerError(socketPath: String, path: String, errorStatusCode: UInt, file: StaticString = #file, line: UInt = #line) {
        let client = HTTPClient(to: .unixDomainSocket(path: socketPath), path: path)
        XCTAssertNoThrow(try client.connect(), file: (file), line: line)
        XCTAssertNil(client.handler.response, file: (file), line: line)
        XCTAssertEqual(client.handler.statusCode, errorStatusCode, file: (file), line: line)
    }

    private func makeTempFolder() throws -> URL {
        // Create test content
        try createTempFolder(content: [
            TextFile(name: "index.html", utf8Content: "index"),
            TextFile(name: "theme-settings.js", utf8Content: "java script content"),
            TextFile(name: "theme-settings.json", utf8Content: "JSON content"),
            TextFile(name: "favicon.ico", utf8Content: "icon content"),
            TextFile(name: "apple-logo.svg", utf8Content: "svg content"),
            Folder(name: "data", content: [
                TextFile(name: "test.js", utf8Content: "data content"),
            ]),
            Folder(name: "css", content: [
                TextFile(name: "test.css", utf8Content: "css content"),
            ]),
            Folder(name: "js", content: [
                TextFile(name: "test.js", utf8Content: "js content"),
            ]),
            Folder(name: "fonts", content: [
                TextFile(name: "test.tff", utf8Content: "fonts content"),
            ]),
            Folder(name: "images", content: [
                TextFile(name: "test.png", utf8Content: "images content"),
            ]),
            Folder(name: "img", content: [
                TextFile(name: "test.gif", utf8Content: "img content"),
            ]),
            Folder(name: "videos", content: [
                TextFile(name: "test.mov", utf8Content: "videos content"),
            ]),
            Folder(name: "downloads", content: [
                TextFile(name: "test.zip", utf8Content: "downloads content"),
            ])
        ])
    }
    
    func testPreviewServerPaths() throws {
        let tempFolderURL = try makeTempFolder()
        
        // Socket URL
        let socketURL = try createTemporaryDirectory().appendingPathComponent("sock")
        
        // Create the server
        var log = LogHandle.none
        let server = try PreviewServer(contentURL: tempFolderURL, bindTo: .socket(path: socketURL.path), logHandle: &log)

        // Start the server
        let expectationStarted = AsynchronousExpectation(description: "Server before start")
        DispatchQueue.global().async {
            do {
                try server.start() {
                    expectationStarted.fulfill()
                }
            } catch {
                XCTFail(error.localizedDescription)
            }
        }
        XCTAssertNotEqual(expectationStarted.wait(timeout: 5.0), .timedOut)

        // Test server paths
        assertServer(socketPath: socketURL.path, path: "/", matchesContent: "index")
        assertServer(socketPath: socketURL.path, path: "/theme-settings.js", matchesContent: "java script content")
        assertServer(socketPath: socketURL.path, path: "/theme-settings.json", matchesContent: "JSON content")
        assertServer(socketPath: socketURL.path, path: "/favicon.ico", matchesContent: "icon content")
        assertServer(socketPath: socketURL.path, path: "/apple-logo.svg", matchesContent: "svg content")
        assertServer(socketPath: socketURL.path, path: "/data/test.js", matchesContent: "data content")
        assertServer(socketPath: socketURL.path, path: "/css/test.css", matchesContent: "css content")
        assertServer(socketPath: socketURL.path, path: "/js/test.js", matchesContent: "js content")
        assertServer(socketPath: socketURL.path, path: "/fonts/test.tff", matchesContent: "fonts content")
        assertServer(socketPath: socketURL.path, path: "/images/test.png", matchesContent: "images content")
        assertServer(socketPath: socketURL.path, path: "/img/test.gif", matchesContent: "img content")
        assertServer(socketPath: socketURL.path, path: "/videos/test.mov", matchesContent: "videos content")
        assertServer(socketPath: socketURL.path, path: "/downloads/test.zip", matchesContent: "downloads content")

        assertServerError(socketPath: socketURL.path, path: "/downloads/NOTFOUND.zip", errorStatusCode: 404)
        
        // Verify that the server stops serving content.
        XCTAssertNoThrow(try server.stop())

        let client = HTTPClient(to: .unixDomainSocket(path: socketURL.path), path: "/")
        XCTAssertThrowsError(try client.connect())
    }
    
    func testConcurrentRequests() throws {
        let tempFolderURL = try makeTempFolder()
        
        // Socket URL
        let socketURL = try createTemporaryDirectory().appendingPathComponent("sock")
        
        // Create the server
        var log = LogHandle.none
        let server = try PreviewServer(contentURL: tempFolderURL, bindTo: .socket(path: socketURL.path), logHandle: &log)

        // Start the server
        let expectationStarted = AsynchronousExpectation(description: "Server before start")
        DispatchQueue.global().async {
            do {
                try server.start() {
                    expectationStarted.fulfill()
                }
            } catch {
                XCTFail(error.localizedDescription)
            }
        }
        XCTAssertNotEqual(expectationStarted.wait(timeout: 5.0), .timedOut)
        
        // Make 5000 HTTP requests; 1000 concurrent batches x 5 requests
        DispatchQueue.concurrentPerform(iterations: 1000) { _ in
            assertServer(socketPath: socketURL.path, path: "/data/test.js", matchesContent: "data content")
            assertServer(socketPath: socketURL.path, path: "/css/test.css", matchesContent: "css content")
            assertServer(socketPath: socketURL.path, path: "/js/test.js", matchesContent: "js content")
            assertServer(socketPath: socketURL.path, path: "/fonts/test.tff", matchesContent: "fonts content")
            assertServerError(socketPath: socketURL.path, path: "/js/NotFound.js", errorStatusCode: 404)
        }
        XCTAssertNoThrow(try server.stop())
    }
    
    func testPreviewServerBindDescription() {
        let localhostBind = PreviewServer.Bind.localhost(port: 1234)
        XCTAssertEqual("\(localhostBind)", "localhost:1234")
        let socketBind = PreviewServer.Bind.socket(path: "/tmp/file.sock")
        XCTAssertEqual("\(socketBind)", "/tmp/file.sock")
    }
}
#endif