diff --git a/Sources/NIOCore/ChannelOption.swift b/Sources/NIOCore/ChannelOption.swift index 2aa2605f9..255803a5e 100644 --- a/Sources/NIOCore/ChannelOption.swift +++ b/Sources/NIOCore/ChannelOption.swift @@ -93,6 +93,14 @@ extension ChannelOptions { } #if !os(Windows) + // Unavailable on Windows: there, WinSDK imports the socket option + // level/name constants (`IPPROTO_IP`, `IP_TTL`, `SO_REUSEADDR`, …) + // as enumeration cases rather than plain integers, so they don't fit + // the integer `SocketOptionLevel`/`SocketOptionName` typealiases. + // Use `init(level:name:)` taking `NIOBSDSocket.OptionLevel`/`Option` + // instead (their `.ip`/`.tcp`/etc. accessors read the enum's raw + // value). + /// Create a new `SocketOption`. /// /// - Parameters: @@ -312,6 +320,8 @@ extension ChannelOptions { /// Provides `ChannelOption`s to be used with a `Channel`, `Bootstrap` or `ServerBootstrap`. public struct ChannelOptions: Sendable { + // Unavailable on Windows; see `SocketOption.init(level:name:)`. Use the + // typed `socketOption(_:)`/`ipOption(_:)`/`tcpOption(_:)` accessors instead. #if !os(Windows) public static let socket: @Sendable (SocketOptionLevel, SocketOptionName) -> ChannelOptions.Types.SocketOption = { (level: SocketOptionLevel, name: SocketOptionName) -> Types.SocketOption in @@ -388,6 +398,8 @@ public struct ChannelOptions: Sendable { /// - seealso: `SocketOption`. extension ChannelOption where Self == ChannelOptions.Types.SocketOption { + // Unavailable on Windows; see `SocketOption.init(level:name:)`. Use the + // typed `socketOption(_:)`/`ipOption(_:)`/`tcpOption(_:)` accessors instead. #if !(os(Windows)) public static func socket(_ level: SocketOptionLevel, _ name: SocketOptionName) -> Self { .init(level: NIOBSDSocket.OptionLevel(rawValue: CInt(level)), name: NIOBSDSocket.Option(rawValue: CInt(name))) diff --git a/Sources/NIOFS/Internal/System Calls/SystemPackage+Windows.swift b/Sources/NIOFS/Internal/System Calls/SystemPackage+Windows.swift index 79375386d..77923e13f 100644 --- a/Sources/NIOFS/Internal/System Calls/SystemPackage+Windows.swift +++ b/Sources/NIOFS/Internal/System Calls/SystemPackage+Windows.swift @@ -103,25 +103,28 @@ extension CInterop { extension FileDescriptor.OpenOptions { // Distinct high bits we own. These are placeholders for a real Win32 - // mapping in the future implementation. - static var noFollow: FileDescriptor.OpenOptions { + // mapping in the future implementation. They are `@_spi(Testing) public` to + // match the accessibility of the swift-system equivalents on other + // platforms (which NIOFS's tests reach via an SPI import). + @_spi(Testing) public static var noFollow: FileDescriptor.OpenOptions { FileDescriptor.OpenOptions(rawValue: 0x4000_0000) } - static var closeOnExec: FileDescriptor.OpenOptions { + @_spi(Testing) public static var closeOnExec: FileDescriptor.OpenOptions { FileDescriptor.OpenOptions(rawValue: 0x2000_0000) } - static var nonBlocking: FileDescriptor.OpenOptions { + @_spi(Testing) public static var nonBlocking: FileDescriptor.OpenOptions { FileDescriptor.OpenOptions(rawValue: 0x1000_0000) } - static var directory: FileDescriptor.OpenOptions { + @_spi(Testing) public static var directory: FileDescriptor.OpenOptions { FileDescriptor.OpenOptions(rawValue: 0x0800_0000) } } extension Errno { /// No direct equivalent on Windows; alias to `EINVAL` so switches stay - /// exhaustive. - static var noData: Errno { Errno.invalidArgument } + /// exhaustive. `@_spi(Testing) public` to match the swift-system equivalent + /// on other platforms (which NIOFS's tests reach via an SPI import). + @_spi(Testing) public static var noData: Errno { Errno.invalidArgument } } // MARK: - `stat` mode constants (typed to `CInterop.Mode`) diff --git a/Sources/NIOPosix/System.swift b/Sources/NIOPosix/System.swift index d661eb533..cf1098aa7 100644 --- a/Sources/NIOPosix/System.swift +++ b/Sources/NIOPosix/System.swift @@ -101,6 +101,7 @@ private let sysWrite = _write private let sysRead = _read private let sysLseek = _lseek private let sysFtruncate = _chsize_s +private let sysClose = _close #endif #if os(Android) @@ -580,6 +581,7 @@ internal enum Posix: Sendable { sysShutdown(descriptor, how.cValue) } } + #endif @inline(never) public static func close(descriptor: CInt) throws { @@ -605,6 +607,7 @@ internal enum Posix: Sendable { } } + #if !os(Windows) @inline(never) public static func bind(descriptor: CInt, ptr: UnsafePointer, bytes: Int) throws { _ = try syscall(blocking: false) { diff --git a/Sources/_NIOFileSystem/Internal/System Calls/SystemPackage+Windows.swift b/Sources/_NIOFileSystem/Internal/System Calls/SystemPackage+Windows.swift index 79375386d..77923e13f 100644 --- a/Sources/_NIOFileSystem/Internal/System Calls/SystemPackage+Windows.swift +++ b/Sources/_NIOFileSystem/Internal/System Calls/SystemPackage+Windows.swift @@ -103,25 +103,28 @@ extension CInterop { extension FileDescriptor.OpenOptions { // Distinct high bits we own. These are placeholders for a real Win32 - // mapping in the future implementation. - static var noFollow: FileDescriptor.OpenOptions { + // mapping in the future implementation. They are `@_spi(Testing) public` to + // match the accessibility of the swift-system equivalents on other + // platforms (which NIOFS's tests reach via an SPI import). + @_spi(Testing) public static var noFollow: FileDescriptor.OpenOptions { FileDescriptor.OpenOptions(rawValue: 0x4000_0000) } - static var closeOnExec: FileDescriptor.OpenOptions { + @_spi(Testing) public static var closeOnExec: FileDescriptor.OpenOptions { FileDescriptor.OpenOptions(rawValue: 0x2000_0000) } - static var nonBlocking: FileDescriptor.OpenOptions { + @_spi(Testing) public static var nonBlocking: FileDescriptor.OpenOptions { FileDescriptor.OpenOptions(rawValue: 0x1000_0000) } - static var directory: FileDescriptor.OpenOptions { + @_spi(Testing) public static var directory: FileDescriptor.OpenOptions { FileDescriptor.OpenOptions(rawValue: 0x0800_0000) } } extension Errno { /// No direct equivalent on Windows; alias to `EINVAL` so switches stay - /// exhaustive. - static var noData: Errno { Errno.invalidArgument } + /// exhaustive. `@_spi(Testing) public` to match the swift-system equivalent + /// on other platforms (which NIOFS's tests reach via an SPI import). + @_spi(Testing) public static var noData: Errno { Errno.invalidArgument } } // MARK: - `stat` mode constants (typed to `CInterop.Mode`) diff --git a/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift b/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift index 5837244a4..fa0579b79 100644 --- a/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift +++ b/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift @@ -24,6 +24,16 @@ import Darwin import Glibc #elseif canImport(Android) import Android +#elseif os(Windows) +import WinSDK + +// Windows has no `usleep`; approximate it with `Sleep`, which takes whole +// milliseconds. The coarse precision is fine for these test poll loops. +@discardableResult +func usleep(_ microseconds: UInt32) -> CInt { + Sleep(microseconds / 1000) + return 0 +} #else #error("The Concurrency helpers test module was unable to identify your C library.") #endif diff --git a/Tests/NIOCoreTests/UtilitiesTest.swift b/Tests/NIOCoreTests/UtilitiesTest.swift index b2a981416..17fbdee28 100644 --- a/Tests/NIOCoreTests/UtilitiesTest.swift +++ b/Tests/NIOCoreTests/UtilitiesTest.swift @@ -22,6 +22,9 @@ class UtilitiesTest: XCTestCase { @available(*, deprecated) func testEnumeratingInterfaces() throws { + // `System.enumerateInterfaces` is not available on Windows; the + // equivalent coverage is provided by `testEnumeratingDevices`. + #if !os(Windows) // This is a tricky test, because we can't really assert much and expect this // to pass on all systems. The best we can do is assume there is a loopback: // maybe an IPv4 one, maybe an IPv6 one, but there will be one. We look for @@ -50,6 +53,7 @@ class UtilitiesTest: XCTestCase { } XCTAssertTrue(ipv4LoopbackPresent || ipv6LoopbackPresent) + #endif } func testEnumeratingDevices() throws { diff --git a/Tests/NIOCoreTests/XCTest+Extensions.swift b/Tests/NIOCoreTests/XCTest+Extensions.swift index 2970c6551..1fca3d913 100644 --- a/Tests/NIOCoreTests/XCTest+Extensions.swift +++ b/Tests/NIOCoreTests/XCTest+Extensions.swift @@ -17,6 +17,16 @@ import XCTest #if canImport(Android) import Android +#elseif os(Windows) +import WinSDK + +// Windows has no `usleep`; approximate it with `Sleep`, which takes whole +// milliseconds. The coarse precision is fine for these test poll loops. +@discardableResult +func usleep(_ microseconds: UInt32) -> CInt { + Sleep(microseconds / 1000) + return 0 +} #endif func assert( diff --git a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift index f8c69c421..19fa82a2d 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift @@ -751,6 +751,9 @@ class AsyncTestingChannelTests: XCTestCase { } func testGetSetOption() async throws { + // `ChannelOptions.socket(_:_:)` and the `IPPROTO_IP`/`IP_TTL` constants + // are not available on Windows. + #if !os(Windows) let channel = NIOAsyncTestingChannel() let option = ChannelOptions.socket(IPPROTO_IP, IP_TTL) let _ = try await channel.setOption(option, value: 1).get() @@ -761,6 +764,7 @@ class AsyncTestingChannelTests: XCTestCase { let _ = try await channel.setOption(option, value: 2).get() let optionValue2 = try await channel.getOption(option).get() XCTAssertEqual(2, optionValue2) + #endif } func testSocketAddressesOnContext() async throws { diff --git a/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift b/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift index c3ea10c11..8f76d7ca3 100644 --- a/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift +++ b/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift @@ -825,6 +825,9 @@ class EmbeddedChannelTest: XCTestCase { } func testGetSetOption() throws { + // `ChannelOptions.socket(_:_:)` and the `IPPROTO_IP`/`IP_TTL` constants + // are not available on Windows. + #if !os(Windows) let channel = EmbeddedChannel() let option = ChannelOptions.socket(IPPROTO_IP, IP_TTL) let _ = channel.setOption(option, value: 1) @@ -835,6 +838,7 @@ class EmbeddedChannelTest: XCTestCase { let _ = channel.setOption(option, value: 2) let optionValue2 = try channel.getOption(option).wait() XCTAssertEqual(2, optionValue2) + #endif } func testGetSetOptionOptInThrowing() { diff --git a/Tests/NIOEmbeddedTests/TestUtils.swift b/Tests/NIOEmbeddedTests/TestUtils.swift index 3cefa8106..742e017d5 100644 --- a/Tests/NIOEmbeddedTests/TestUtils.swift +++ b/Tests/NIOEmbeddedTests/TestUtils.swift @@ -19,6 +19,16 @@ import XCTest #if canImport(Android) import Android +#elseif os(Windows) +import WinSDK + +// Windows has no `usleep`; approximate it with `Sleep`, which takes whole +// milliseconds. The coarse precision is fine for these test poll loops. +@discardableResult +func usleep(_ microseconds: UInt32) -> CInt { + Sleep(microseconds / 1000) + return 0 +} #endif // FIXME: Duplicated with NIO diff --git a/Tests/NIOFSFoundationCompatTests/FileSystemFoundationCompatTests.swift b/Tests/NIOFSFoundationCompatTests/FileSystemFoundationCompatTests.swift index 9566c32fa..c43bf6289 100644 --- a/Tests/NIOFSFoundationCompatTests/FileSystemFoundationCompatTests.swift +++ b/Tests/NIOFSFoundationCompatTests/FileSystemFoundationCompatTests.swift @@ -64,6 +64,9 @@ final class FileSystemBytesConformanceTests: XCTestCase { ) } + // `Data(contentsOf:maximumSizeAllowed:)` is only provided on these + // platforms (see `NIOFSFoundationCompat/Data+FileSystem.swift`). + #if canImport(Darwin) || os(Linux) || os(Android) func testReadFileIntoData() async throws { let fs = FileSystem.shared let path = try await fs.temporaryFilePath() @@ -76,4 +79,5 @@ final class FileSystemBytesConformanceTests: XCTestCase { XCTAssertEqual(contents, Data([0, 1, 2])) } + #endif } diff --git a/Tests/NIOFSIntegrationTests/FileHandleTests.swift b/Tests/NIOFSIntegrationTests/FileHandleTests.swift index 50fa949e8..162122b25 100644 --- a/Tests/NIOFSIntegrationTests/FileHandleTests.swift +++ b/Tests/NIOFSIntegrationTests/FileHandleTests.swift @@ -302,6 +302,8 @@ final class FileHandleTests: XCTestCase { } } + // These tests create FIFOs via `mkfifo`, which is unavailable on Windows. + #if !os(Windows) func testWriteAndReadUnseekableFile() async throws { let privateTempDirPath = try await FileSystem.shared.createTemporaryDirectory(template: "test-XXX") self.addTeardownBlock { @@ -384,6 +386,7 @@ final class FileHandleTests: XCTestCase { } } } + #endif // !os(Windows) func testReadWholeFileWithOffsets() async throws { try await self.withHandle(forFileAtPath: Self.thisFile) { handle in diff --git a/Tests/NIOFSTests/FileInfoTests.swift b/Tests/NIOFSTests/FileInfoTests.swift index 5aa745473..e2ec33674 100644 --- a/Tests/NIOFSTests/FileInfoTests.swift +++ b/Tests/NIOFSTests/FileInfoTests.swift @@ -32,6 +32,10 @@ private let S_IFREG = Glibc.S_IFREG private let S_IFREG = Musl.S_IFREG #endif +// `CInterop.Stat` is `BY_HANDLE_FILE_INFORMATION` on Windows, so these tests +// (which build a POSIX `struct stat`) don't apply as written. Windows coverage +// that constructs a `BY_HANDLE_FILE_INFORMATION` is a follow-up. +#if !os(Windows) final class FileInfoTests: XCTestCase { private var status: CInterop.Stat { var status = CInterop.Stat() @@ -167,3 +171,4 @@ final class FileInfoTests: XCTestCase { #endif } } +#endif // !os(Windows) diff --git a/Tests/NIOFSTests/FileTypeTests.swift b/Tests/NIOFSTests/FileTypeTests.swift index 602c00aec..28350813b 100644 --- a/Tests/NIOFSTests/FileTypeTests.swift +++ b/Tests/NIOFSTests/FileTypeTests.swift @@ -56,6 +56,8 @@ final class FileTypeTests: XCTestCase { } func testConversionFromModeT() { + // `S_IFSOCK`/`S_IFLNK`/`S_IFBLK` don't exist on Windows. + #if !os(Windows) XCTAssertEqual(FileType(platformSpecificMode: S_IFIFO), .fifo) XCTAssertEqual(FileType(platformSpecificMode: S_IFCHR), .character) XCTAssertEqual(FileType(platformSpecificMode: S_IFDIR), .directory) @@ -66,9 +68,12 @@ final class FileTypeTests: XCTestCase { #if canImport(Darwin) XCTAssertEqual(FileType(platformSpecificMode: S_IFWHT), .whiteout) #endif + #endif } func testConversionFromDirentType() { + // The `DT_*` constants aren't available on Windows. + #if !os(Windows) XCTAssertEqual(FileType(direntType: numericCast(DT_FIFO)), .fifo) XCTAssertEqual(FileType(direntType: numericCast(DT_CHR)), .character) XCTAssertEqual(FileType(direntType: numericCast(DT_DIR)), .directory) @@ -79,5 +84,6 @@ final class FileTypeTests: XCTestCase { #if canImport(Darwin) XCTAssertEqual(FileType(direntType: numericCast(DT_WHT)), .whiteout) #endif + #endif } } diff --git a/Tests/NIOFSTests/Internal/SyscallTests.swift b/Tests/NIOFSTests/Internal/SyscallTests.swift index 9ab0808eb..7d0a692dd 100644 --- a/Tests/NIOFSTests/Internal/SyscallTests.swift +++ b/Tests/NIOFSTests/Internal/SyscallTests.swift @@ -20,6 +20,9 @@ import XCTest #if ENABLE_MOCKING final class SyscallTests: XCTestCase { func test_openat() throws { + // Asserts POSIX `oflag` bit values; the Windows `OpenOptions` bits are + // placeholders, so this doesn't apply as written. + #if !os(Windows) let fd = FileDescriptor(rawValue: 42) let testCases = [ MockTestCase( @@ -60,6 +63,7 @@ final class SyscallTests: XCTestCase { ] testCases.run() + #endif } func test_stat() throws { @@ -239,7 +243,9 @@ final class SyscallTests: XCTestCase { func test_flistxattr() throws { let fd = FileDescriptor(rawValue: 42) - let buffer = UnsafeMutableBufferPointer.allocate(capacity: 1024) + // `flistxattr` takes a `CChar` buffer (equivalent to `PlatformChar` off + // Windows, where `PlatformChar` is `UInt16`). + let buffer = UnsafeMutableBufferPointer.allocate(capacity: 1024) defer { buffer.deallocate() } let testCases: [MockTestCase] = [ diff --git a/Tests/NIOHTTP1Tests/TestUtils.swift b/Tests/NIOHTTP1Tests/TestUtils.swift index 281652252..da08e9126 100644 --- a/Tests/NIOHTTP1Tests/TestUtils.swift +++ b/Tests/NIOHTTP1Tests/TestUtils.swift @@ -23,6 +23,19 @@ import XCTest @testable import NIOCore @testable import NIOPosix +#if os(Windows) +import WinSDK +import ucrt + +// Windows has no `usleep`; approximate it with `Sleep`, which takes whole +// milliseconds. The coarse precision is fine for these test poll loops. +@discardableResult +func usleep(_ microseconds: UInt32) -> CInt { + Sleep(microseconds / 1000) + return 0 +} +#endif + extension System { static var supportsIPv6: Bool { do { @@ -48,7 +61,12 @@ extension System { func withPipe(_ body: (NIOCore.NIOFileHandle, NIOCore.NIOFileHandle) throws -> [NIOCore.NIOFileHandle]) throws { var fds: [Int32] = [-1, -1] fds.withUnsafeMutableBufferPointer { ptr in + #if os(Windows) + // Windows has no `pipe`; `_pipe` is the CRT equivalent. + XCTAssertEqual(0, _pipe(ptr.baseAddress!, 4096, _O_BINARY)) + #else XCTAssertEqual(0, pipe(ptr.baseAddress!)) + #endif } let readFH = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fds[0]) let writeFH = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fds[1]) @@ -73,7 +91,12 @@ func withPipe( ) async throws { var fds: [Int32] = [-1, -1] fds.withUnsafeMutableBufferPointer { ptr in + #if os(Windows) + // Windows has no `pipe`; `_pipe` is the CRT equivalent. + XCTAssertEqual(0, _pipe(ptr.baseAddress!, 4096, _O_BINARY)) + #else XCTAssertEqual(0, pipe(ptr.baseAddress!)) + #endif } let readFH = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fds[0]) let writeFH = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fds[1]) @@ -235,6 +258,16 @@ var temporaryDirectory: String { } func createTemporaryDirectory() -> String { + #if os(Windows) + // Windows has no `mkdtemp`. Build a uniquely-named directory (using a GUID) + // under the temporary directory and create it with `CreateDirectoryW`. + let path = "\(temporaryDirectory)/.NIOTests-temp-dir_\(UUID().uuidString)" + let created = path.withCString(encodedAs: UTF16.self) { + CreateDirectoryW($0, nil) + } + XCTAssertTrue(created) + return path + #else let template = "\(temporaryDirectory)/.NIOTests-temp-dir_XXXXXX" var templateBytes = template.utf8 + [0] @@ -248,9 +281,34 @@ func createTemporaryDirectory() -> String { } templateBytes.removeLast() return String(decoding: templateBytes, as: Unicode.UTF8.self) + #endif } func openTemporaryFile() -> (CInt, String) { + #if os(Windows) + // Windows has no `mkstemp`. Generate a unique name with `_mktemp_s`, then + // create and open it with `_sopen_s`. + var templateBytes = "\(temporaryDirectory)/nio_XXXXXX".utf8 + [0] + let templateBytesCount = templateBytes.count + let fd = templateBytes.withUnsafeMutableBufferPointer { ptr in + ptr.baseAddress!.withMemoryRebound(to: CChar.self, capacity: templateBytesCount) { + (ptr: UnsafeMutablePointer) -> CInt in + XCTAssertEqual(_mktemp_s(ptr, templateBytesCount), 0) + var fd: CInt = -1 + let err = _sopen_s( + &fd, + ptr, + _O_CREAT | _O_EXCL | _O_RDWR | _O_BINARY, + _SH_DENYNO, + _S_IREAD | _S_IWRITE + ) + XCTAssertEqual(err, 0) + return fd + } + } + templateBytes.removeLast() + return (fd, String(decoding: templateBytes, as: Unicode.UTF8.self)) + #else let template = "\(temporaryDirectory)/nio_XXXXXX" var templateBytes = template.utf8 + [0] let templateBytesCount = templateBytes.count @@ -262,6 +320,7 @@ func openTemporaryFile() -> (CInt, String) { } templateBytes.removeLast() return (fd, String(decoding: templateBytes, as: Unicode.UTF8.self)) + #endif } extension Channel { diff --git a/Tests/NIOPosixTests/TestUtils.swift b/Tests/NIOPosixTests/TestUtils.swift index a70dcfb65..8199ff5df 100644 --- a/Tests/NIOPosixTests/TestUtils.swift +++ b/Tests/NIOPosixTests/TestUtils.swift @@ -20,6 +20,19 @@ import XCTest @testable import NIOCore @testable import NIOPosix +#if os(Windows) +import WinSDK +import ucrt + +// Windows has no `usleep`; approximate it with `Sleep`, which takes whole +// milliseconds. The coarse precision is fine for these test poll loops. +@discardableResult +func usleep(_ microseconds: UInt32) -> CInt { + Sleep(microseconds / 1000) + return 0 +} +#endif + extension System { static var supportsIPv6: Bool { do { @@ -45,7 +58,12 @@ extension System { func withPipe(_ body: (NIOCore.NIOFileHandle, NIOCore.NIOFileHandle) throws -> [NIOCore.NIOFileHandle]) throws { var fds: [Int32] = [-1, -1] fds.withUnsafeMutableBufferPointer { ptr in + #if os(Windows) + // Windows has no `pipe`; `_pipe` is the CRT equivalent. + XCTAssertEqual(0, _pipe(ptr.baseAddress!, 4096, _O_BINARY)) + #else XCTAssertEqual(0, pipe(ptr.baseAddress!)) + #endif } let readFH = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fds[0]) let writeFH = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fds[1]) @@ -70,7 +88,12 @@ func withPipe( ) async throws { var fds: [Int32] = [-1, -1] fds.withUnsafeMutableBufferPointer { ptr in + #if os(Windows) + // Windows has no `pipe`; `_pipe` is the CRT equivalent. + XCTAssertEqual(0, _pipe(ptr.baseAddress!, 4096, _O_BINARY)) + #else XCTAssertEqual(0, pipe(ptr.baseAddress!)) + #endif } let readFH = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fds[0]) let writeFH = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fds[1]) @@ -232,6 +255,16 @@ var temporaryDirectory: String { } func createTemporaryDirectory() -> String { + #if os(Windows) + // Windows has no `mkdtemp`. Build a uniquely-named directory (using a GUID) + // under the temporary directory and create it with `CreateDirectoryW`. + let path = "\(temporaryDirectory)/.NIOTests-temp-dir_\(UUID().uuidString)" + let created = path.withCString(encodedAs: UTF16.self) { + CreateDirectoryW($0, nil) + } + XCTAssertTrue(created) + return path + #else let template = "\(temporaryDirectory)/.NIOTests-temp-dir_XXXXXX" var templateBytes = template.utf8 + [0] @@ -245,9 +278,34 @@ func createTemporaryDirectory() -> String { } templateBytes.removeLast() return String(decoding: templateBytes, as: Unicode.UTF8.self) + #endif } func openTemporaryFile() -> (CInt, String) { + #if os(Windows) + // Windows has no `mkstemp`. Generate a unique name with `_mktemp_s`, then + // create and open it with `_sopen_s`. + var templateBytes = "\(temporaryDirectory)/nio_XXXXXX".utf8 + [0] + let templateBytesCount = templateBytes.count + let fd = templateBytes.withUnsafeMutableBufferPointer { ptr in + ptr.baseAddress!.withMemoryRebound(to: CChar.self, capacity: templateBytesCount) { + (ptr: UnsafeMutablePointer) -> CInt in + XCTAssertEqual(_mktemp_s(ptr, templateBytesCount), 0) + var fd: CInt = -1 + let err = _sopen_s( + &fd, + ptr, + _O_CREAT | _O_EXCL | _O_RDWR | _O_BINARY, + _SH_DENYNO, + _S_IREAD | _S_IWRITE + ) + XCTAssertEqual(err, 0) + return fd + } + } + templateBytes.removeLast() + return (fd, String(decoding: templateBytes, as: Unicode.UTF8.self)) + #else let template = "\(temporaryDirectory)/nio_XXXXXX" var templateBytes = template.utf8 + [0] let templateBytesCount = templateBytes.count @@ -259,6 +317,7 @@ func openTemporaryFile() -> (CInt, String) { } templateBytes.removeLast() return (fd, String(decoding: templateBytes, as: Unicode.UTF8.self)) + #endif } extension Channel { diff --git a/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift b/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift index 630aad2e9..ce397711b 100644 --- a/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift +++ b/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift @@ -18,6 +18,18 @@ import NIOPosix import NIOTestUtils import XCTest +#if os(Windows) +import WinSDK + +// Windows has no `usleep`; approximate it with `Sleep`, which takes whole +// milliseconds. The coarse precision is fine for these test poll loops. +@discardableResult +func usleep(_ microseconds: UInt32) -> CInt { + Sleep(microseconds / 1000) + return 0 +} +#endif + typealias SendableRequestPart = HTTPPart extension HTTPClientRequestPart {