-
Notifications
You must be signed in to change notification settings - Fork 5.2k
[FileStream] add tests for device and UNC paths #54545
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
0b5978a
add a test for unseekable device by using a path to named pipe
adamsitnik 518871d
add a test for seekable device by using DeviceID instead of drive letter
adamsitnik 0efd744
add a test for a UNC file path (local file share)
adamsitnik 20ba569
don't forget to remove the share
adamsitnik d1229ff
Merge remote-tracking branch 'upstream/main' into devicePathTests
adamsitnik a8c89fa
test both type of slashes in the UNC paths
adamsitnik 47d2457
fix the compilation errors
adamsitnik 37675fc
check if Server Service is running for tests that use file sharing
adamsitnik 051d4d7
address code review feedback
adamsitnik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
179 changes: 179 additions & 0 deletions
179
src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.Windows.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,179 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.Win32.SafeHandles; | ||
using System.ComponentModel; | ||
using System.IO.Pipes; | ||
using System.Linq; | ||
using System.Runtime.CompilerServices; | ||
using System.Runtime.InteropServices; | ||
using System.Text; | ||
using System.ServiceProcess; | ||
using System.Threading.Tasks; | ||
using Xunit; | ||
|
||
namespace System.IO.Tests | ||
{ | ||
[PlatformSpecific(TestPlatforms.Windows)] // DOS device paths (\\.\ and \\?\) are a Windows concept | ||
public class UnseekableDeviceFileStreamConnectedConformanceTests : ConnectedStreamConformanceTests | ||
{ | ||
protected override async Task<StreamPair> CreateConnectedStreamsAsync() | ||
{ | ||
string pipeName = FileSystemTest.GetNamedPipeServerStreamName(); | ||
string pipePath = Path.GetFullPath($@"\\.\pipe\{pipeName}"); | ||
|
||
var server = new NamedPipeServerStream(pipeName, PipeDirection.In); | ||
var clienStream = new FileStream(File.OpenHandle(pipePath, FileMode.Open, FileAccess.Write, FileShare.None), FileAccess.Write); | ||
|
||
await server.WaitForConnectionAsync(); | ||
|
||
var serverStrean = new FileStream(new SafeFileHandle(server.SafePipeHandle.DangerousGetHandle(), true), FileAccess.Read); | ||
|
||
server.SafePipeHandle.SetHandleAsInvalid(); | ||
|
||
return (serverStrean, clienStream); | ||
} | ||
|
||
protected override Type UnsupportedConcurrentExceptionType => null; | ||
protected override bool UsableAfterCanceledReads => false; | ||
protected override bool FullyCancelableOperations => false; | ||
protected override bool BlocksOnZeroByteReads => OperatingSystem.IsWindows(); | ||
protected override bool SupportsConcurrentBidirectionalUse => false; | ||
} | ||
|
||
[PlatformSpecific(TestPlatforms.Windows)] // DOS device paths (\\.\ and \\?\) are a Windows concept | ||
public class SeekableDeviceFileStreamStandaloneConformanceTests : UnbufferedAsyncFileStreamStandaloneConformanceTests | ||
{ | ||
protected override string GetTestFilePath(int? index = null, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) | ||
{ | ||
string filePath = Path.GetFullPath(base.GetTestFilePath(index, memberName, lineNumber)); | ||
string drive = Path.GetPathRoot(filePath); | ||
StringBuilder volumeNameBuffer = new StringBuilder(filePath.Length + 1024); | ||
|
||
// the following method maps drive letter like "C:\" to a DeviceID (a DOS device path) | ||
// example: "\\?\Volume{724edb31-eaa5-4728-a4e3-f2474fd34ae2}\" | ||
if (!GetVolumeNameForVolumeMountPoint(drive, volumeNameBuffer, volumeNameBuffer.Capacity)) | ||
{ | ||
throw new Win32Exception(Marshal.GetLastPInvokeError(), "GetVolumeNameForVolumeMountPoint failed"); | ||
} | ||
|
||
// instead of: | ||
// 'C:\Users\x\AppData\Local\Temp\y\z | ||
// we want something like: | ||
// '\\.\Volume{724edb31-eaa5-4728-a4e3-f2474fd34ae2}\Users\x\AppData\Local\Temp\y\z | ||
string devicePath = filePath.Replace(drive, volumeNameBuffer.ToString()); | ||
Assert.StartsWith(@"\\?\", devicePath); | ||
#if DEBUG | ||
// we do want to test \\.\ prefix as well | ||
devicePath = devicePath.Replace(@"\\?\", @"\\.\"); | ||
#endif | ||
|
||
return devicePath; | ||
} | ||
|
||
[DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetVolumeNameForVolumeMountPointW", CharSet = CharSet.Unicode, BestFitMapping = false, SetLastError = true)] | ||
private static extern bool GetVolumeNameForVolumeMountPoint(string volumeName, StringBuilder uniqueVolumeName, int uniqueNameBufferCapacity); | ||
} | ||
|
||
[PlatformSpecific(TestPlatforms.Windows)] // the test setup is Windows-specifc | ||
[Collection("NoParallelTests")] // don't run in parallel, as file sharing logic is not thread-safe | ||
[OuterLoop("Requires admin privileges to create a file share")] | ||
[ConditionalClass(typeof(UncFilePathFileStreamStandaloneConformanceTests), nameof(CanShareFiles))] | ||
public class UncFilePathFileStreamStandaloneConformanceTests : UnbufferedAsyncFileStreamStandaloneConformanceTests | ||
{ | ||
public static bool CanShareFiles => _canShareFiles.Value; | ||
|
||
private static Lazy<bool> _canShareFiles = new Lazy<bool>(() => | ||
{ | ||
if (!PlatformDetection.IsWindowsAndElevated || PlatformDetection.IsWindowsNanoServer) | ||
{ | ||
return false; | ||
} | ||
|
||
// the "Server Service" allows for file sharing. It can be disabled on some of our CI machines. | ||
using (ServiceController sharingService = new ServiceController("Server")) | ||
{ | ||
return sharingService.Status == ServiceControllerStatus.Running; | ||
} | ||
}); | ||
|
||
protected override string GetTestFilePath(int? index = null, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) | ||
{ | ||
string testDirectoryPath = Path.GetFullPath(TestDirectory); | ||
string shareName = new DirectoryInfo(testDirectoryPath).Name; | ||
string fileName = GetTestFileName(index, memberName, lineNumber); | ||
|
||
SHARE_INFO_502 shareInfo = default; | ||
shareInfo.shi502_netname = shareName; | ||
shareInfo.shi502_path = testDirectoryPath; | ||
shareInfo.shi502_remark = "folder created to test UNC file paths"; | ||
shareInfo.shi502_max_uses = -1; | ||
|
||
int infoSize = Marshal.SizeOf(shareInfo); | ||
IntPtr infoBuffer = Marshal.AllocCoTaskMem(infoSize); | ||
|
||
try | ||
{ | ||
Marshal.StructureToPtr(shareInfo, infoBuffer, false); | ||
|
||
int shareResult = NetShareAdd(string.Empty, 502, infoBuffer, IntPtr.Zero); | ||
|
||
if (shareResult != 0 && shareResult != 2118) // is a failure that is not a NERR_DuplicateShare | ||
{ | ||
throw new Exception($"Failed to create a file share, NetShareAdd returned {shareResult}"); | ||
} | ||
} | ||
finally | ||
{ | ||
Marshal.FreeCoTaskMem(infoBuffer); | ||
} | ||
|
||
// now once the folder has been shared we can use "localhost" to access it: | ||
// both type of slashes are valid, so let's test one for Debug and another for other configs | ||
#if DEBUG | ||
return @$"//localhost/{shareName}/{fileName}"; | ||
#else | ||
return @$"\\localhost\{shareName}\{fileName}"; | ||
#endif | ||
} | ||
|
||
protected override void Dispose(bool disposing) | ||
{ | ||
string testDirectoryPath = Path.GetFullPath(TestDirectory); | ||
string shareName = new DirectoryInfo(testDirectoryPath).Name; | ||
|
||
try | ||
{ | ||
NetShareDel(string.Empty, shareName, 0); | ||
} | ||
finally | ||
{ | ||
base.Dispose(disposing); | ||
} | ||
} | ||
|
||
[StructLayout(LayoutKind.Sequential)] | ||
public struct SHARE_INFO_502 | ||
{ | ||
[MarshalAs(UnmanagedType.LPWStr)] | ||
public string shi502_netname; | ||
public uint shi502_type; | ||
[MarshalAs(UnmanagedType.LPWStr)] | ||
public string shi502_remark; | ||
public int shi502_permissions; | ||
public int shi502_max_uses; | ||
public int shi502_current_uses; | ||
[MarshalAs(UnmanagedType.LPWStr)] | ||
public string shi502_path; | ||
public IntPtr shi502_passwd; | ||
public int shi502_reserved; | ||
public IntPtr shi502_security_descriptor; | ||
} | ||
|
||
[DllImport(Interop.Libraries.Netapi32)] | ||
public static extern int NetShareAdd([MarshalAs(UnmanagedType.LPWStr)]string servername, int level, IntPtr buf, IntPtr parm_err); | ||
|
||
[DllImport(Interop.Libraries.Netapi32)] | ||
public static extern int NetShareDel([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string netname, int reserved); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.