Skip to content

Commit c7ad5a3

Browse files
authored
Merge pull request #2242 from compnerd/illiteracy
TestFoundation: construct `FileHandle` properly on Windows
2 parents f722776 + a82faa7 commit c7ad5a3

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

TestFoundation/TestFileHandle.swift

+22
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818
#endif
1919

2020
import Dispatch
21+
#if os(Windows)
22+
import WinSDK
23+
#endif
2124

2225
class TestFileHandle : XCTestCase {
2326
var allHandles: [FileHandle] = []
@@ -116,9 +119,28 @@ class TestFileHandle : XCTestCase {
116119
func createFileHandleForReadErrors() -> FileHandle {
117120
// Create a file handle where calling read returns -1.
118121
// Accomplish this by creating one for a directory.
122+
#if os(Windows)
123+
let hDirectory: HANDLE = ".".withCString(encodedAs: UTF16.self) {
124+
// NOTE(compnerd) we need the FILE_FLAG_BACKUP_SEMANTICS so that we
125+
// can create the handle to the directory.
126+
CreateFileW($0, GENERIC_READ,
127+
DWORD(FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE),
128+
nil, DWORD(OPEN_EXISTING),
129+
DWORD(FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS), nil)
130+
}
131+
if hDirectory == INVALID_HANDLE_VALUE {
132+
fatalError("unable to create handle to current directory")
133+
}
134+
let fd = _open_osfhandle(intptr_t(bitPattern: hDirectory), 0)
135+
if fd == -1 {
136+
fatalError("unable to associate file descriptor with handle")
137+
}
138+
let fh = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
139+
#else
119140
let fd = open(".", O_RDONLY)
120141
expectTrue(fd > 0, "We must be able to open a fd to the current directory (.)")
121142
let fh = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
143+
#endif
122144
allHandles.append(fh)
123145
return fh
124146
}

0 commit comments

Comments
 (0)