convert to NUnit tests + clean up API a bit

pull/2/head
Evan Hemsley 2020-01-17 18:58:39 -08:00
parent ae0744e1f6
commit c3371361ab
7 changed files with 176 additions and 200 deletions

View File

@ -6,16 +6,22 @@ namespace SharpPhysFS
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate int InitDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate void DeinitDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate IntPtr MallocDelegate(ulong size);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate IntPtr ReallocDelegate(IntPtr ptr, ulong size);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate void FreeDelegate(IntPtr ptr);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate void StringCallback(IntPtr data, string str);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate void EnumFilesCallback(IntPtr data, string origdir, string fname);
@ -62,7 +68,7 @@ namespace SharpPhysFS
public FreeDelegate Free;
}
static class Interop
internal static class Interop
{
private const string s_nativeLibName = "physfs";
@ -106,10 +112,7 @@ namespace SharpPhysFS
public static extern int PHYSFS_setWriteDir(string s);
[DllImport(s_nativeLibName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int PHYSFS_addToSearchPath(string s, int i);
[DllImport(s_nativeLibName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int PHYSFS_removeFromSearchPath(string s);
public static extern int PHYSFS_unmount(string s);
[DllImport(s_nativeLibName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr PHYSFS_getSearchPath();

View File

@ -10,7 +10,7 @@ namespace SharpPhysFS
public static IntPtr OpenWrite(string filename, PhysFS physFS)
{
var val = Interop.PHYSFS_openWrite(filename);
if (val == null)
if (val == IntPtr.Zero)
throw new PhysFSException(physFS);
return val;
}
@ -18,7 +18,7 @@ namespace SharpPhysFS
public static IntPtr OpenAppend(string filename, PhysFS physFS)
{
var val = Interop.PHYSFS_openAppend(filename);
if (val == null)
if (val == IntPtr.Zero)
throw new PhysFSException(physFS);
return val;
}
@ -26,7 +26,7 @@ namespace SharpPhysFS
public static IntPtr OpenRead(string filename, PhysFS physFS)
{
var val = Interop.PHYSFS_openRead(filename);
if (val == null)
if (val == IntPtr.Zero)
throw new PhysFSException(physFS);
return val;
}

View File

@ -29,12 +29,12 @@ namespace SharpPhysFS
Init(argv0);
}
static T FromPtr<T>(IntPtr ptr)
private static T FromPtr<T>(IntPtr ptr)
{
return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
void ThrowException(int err)
private void ThrowException(int err)
{
if (err == 0)
{
@ -85,7 +85,7 @@ namespace SharpPhysFS
/// All default API states are restored at this point, with the exception of any custom allocator you might have specified, which survives between initializations.
/// NOTE: This is called automatically on disposal.
/// </remarks>
public void Deinit()
public void DeInit()
{
int err = Interop.PHYSFS_deinit();
ThrowException(err);
@ -179,7 +179,7 @@ namespace SharpPhysFS
{
var strPtr = (IntPtr)Marshal.PtrToStructure(ptr, typeof(IntPtr));
var str = Marshal.PtrToStringAnsi(strPtr);
if (!IsDirectory(str)) { yield return str; } // the lib seems to be returning directories. boo!
if (!IsDirectory(str)) { yield return str; } // the dll seems to be returning directories. boo!
}
Interop.PHYSFS_freeList(files);
}
@ -199,12 +199,11 @@ namespace SharpPhysFS
public IEnumerable<ArchiveInfo> SupportedArchiveTypes()
{
IntPtr archives = Interop.PHYSFS_supportedArchiveTypes();
IntPtr i = archives;
IntPtr i;
for (i = archives; Marshal.ReadIntPtr(i) != IntPtr.Zero; i = IntPtr.Add(i, IntPtr.Size))
{
IntPtr ptr = Marshal.ReadIntPtr(i);
var info = FromPtr<ArchiveInfo>(ptr);
yield return info;
yield return FromPtr<ArchiveInfo>(ptr);
}
}
@ -322,18 +321,6 @@ namespace SharpPhysFS
ThrowException(err);
}
/// <summary>
/// Add an archive or directory to the search path.
/// </summary>
/// <param name="newDir">Directory or archive to add to the path, in platform-dependent notation</param>
/// <param name="appendToPath">true to append to search path, false to prepend</param>
[Obsolete("AddToSearchPath is deprecated, please use Mount instead")]
public void AddToSearchPath(string newDir, bool appendToPath)
{
int err = Interop.PHYSFS_addToSearchPath(newDir, appendToPath ? 1 : 0);
ThrowException(err);
}
/// <summary>
/// Remove a directory or archive from the search path.
/// </summary>
@ -344,9 +331,9 @@ namespace SharpPhysFS
/// This call will fail (and fail to remove from the path) if the element still has files open in it.
/// </para>
/// <param name="oldDir"> dir/archive to remove.</param>
public void RemoveFromSearchPath(string oldDir)
public void UnMount(string oldDir)
{
int err = Interop.PHYSFS_removeFromSearchPath(oldDir);
int err = Interop.PHYSFS_unmount(oldDir);
ThrowException(err);
}
@ -434,7 +421,7 @@ namespace SharpPhysFS
/// then the function leaves the created directory behind and reports failure.
/// </para>
/// <param name="dirName">New dir to create.</param>
public void Mkdir(string dirName)
public void CreateDirectory(string dirName)
{
int err = Interop.PHYSFS_mkdir(dirName);
ThrowException(err);
@ -598,7 +585,7 @@ namespace SharpPhysFS
return s;
}
StringCallback WrapStringCallback<T>(Action<T, string> c)
private StringCallback WrapStringCallback<T>(Action<T, string> c)
{
return (d, s) =>
{
@ -607,7 +594,7 @@ namespace SharpPhysFS
};
}
void GetCdRomDirsCallback(StringCallback c, object data)
private void GetCdRomDirsCallback(StringCallback c, object data)
{
GCHandle objHandle = GCHandle.Alloc(data);
Interop.PHYSFS_getCdRomDirsCallback(c, GCHandle.ToIntPtr(objHandle));
@ -635,10 +622,10 @@ namespace SharpPhysFS
/// <param name="c">Callback function to notify about detected drives.</param>
public void GetCdRomDirsCallback(Action<string> c)
{
Interop.PHYSFS_getCdRomDirsCallback((p, s) => c(s), IntPtr.Zero);
Interop.PHYSFS_getCdRomDirsCallback((_, s) => c(s), IntPtr.Zero);
}
void GetSearchPathCallback(StringCallback c, object data)
private void GetSearchPathCallback(StringCallback c, object data)
{
GCHandle objHandle = GCHandle.Alloc(data);
Interop.PHYSFS_getSearchPathCallback(c, GCHandle.ToIntPtr(objHandle));
@ -666,10 +653,10 @@ namespace SharpPhysFS
/// <param name="c">Callback function to notify about search path elements.</param>
public void GetSearchPathCallback(Action<string> c)
{
Interop.PHYSFS_getSearchPathCallback((p, s) => c(s), IntPtr.Zero);
Interop.PHYSFS_getSearchPathCallback((_, s) => c(s), IntPtr.Zero);
}
void EnumerateFilesCallback(string dir, EnumFilesCallback c, object data)
private void EnumerateFilesCallback(string dir, EnumFilesCallback c, object data)
{
GCHandle objHandle = GCHandle.Alloc(data);
Interop.PHYSFS_enumerateFilesCallback(dir, c, GCHandle.ToIntPtr(objHandle));
@ -703,7 +690,7 @@ namespace SharpPhysFS
/// <param name="c">Callback function to notify about search path elements.</param>
public void EnumerateFilesCallback(string dir, Action<string, string> c)
{
Interop.PHYSFS_enumerateFilesCallback(dir, (data, origdir, fname) => c(origdir, fname), IntPtr.Zero);
Interop.PHYSFS_enumerateFilesCallback(dir, (_, origdir, fname) => c(origdir, fname), IntPtr.Zero);
}
public PhysFSStream OpenAppend(string file)
@ -730,13 +717,13 @@ namespace SharpPhysFS
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
void Dispose(bool disposing)
private void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
Deinit();
DeInit();
}
disposedValue = true;
}

View File

@ -5,9 +5,9 @@ namespace SharpPhysFS
{
public class PhysFSStream : Stream
{
IntPtr handle;
bool readOnly = false;
PhysFS physFS;
private IntPtr handle;
private readonly bool readOnly;
private readonly PhysFS physFS;
internal PhysFSStream(PhysFS pfs, IntPtr ptr, bool readOnly)
{
@ -77,7 +77,7 @@ namespace SharpPhysFS
public override long Seek(long offset, SeekOrigin origin)
{
long pos = 0;
long pos;
if (origin == SeekOrigin.Begin)
pos = 0;
else if (origin == SeekOrigin.Current)

View File

@ -8,11 +8,11 @@ using SharpPhysFS;
namespace Test
{
class Program
internal class Program
{
static PhysFS physFS;
private static PhysFS physFS;
static void PrintSupportedArchives()
private static void PrintSupportedArchives()
{
Console.Write("Supported archive types: ");
bool any = false;
@ -33,7 +33,7 @@ namespace Test
}
}
static IEnumerable<string> ParseInput(string input)
private static IEnumerable<string> ParseInput(string input)
{
var sb = new StringBuilder();
bool openString = false;
@ -79,10 +79,10 @@ namespace Test
}
}
static Dictionary<string, Func<string[], bool>> commands = new Dictionary<string, Func<string[], bool>>();
private static Dictionary<string, Func<string[], bool>> commands = new Dictionary<string, Func<string[], bool>>();
#region Commands
static bool Help(string[] args)
private static bool Help(string[] args)
{
Console.WriteLine("Commands:");
foreach (var kvp in commands)
@ -92,15 +92,14 @@ namespace Test
return true;
}
static bool Mount(string[] args)
private static bool Mount(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Usage: mount <archive> <mntpoint> <append>");
return false;
}
bool append;
if (!bool.TryParse(args[2], out append))
if (!bool.TryParse(args[2], out bool append))
{
Console.WriteLine("append can only be true or false");
}
@ -109,7 +108,7 @@ namespace Test
return true;
}
static bool Enumerate(string[] args)
private static bool Enumerate(string[] args)
{
if (args.Length < 1)
{
@ -124,19 +123,19 @@ namespace Test
return true;
}
static bool GetLastError(string[] args)
private static bool GetLastError(string[] args)
{
Console.WriteLine(physFS.GetLastError());
return true;
}
static bool GetDirSeparator(string[] args)
private static bool GetDirSeparator(string[] args)
{
Console.WriteLine(physFS.GetDirSeparator());
return true;
}
static bool GetCdRomDirectories(string[] args)
private static bool GetCdRomDirectories(string[] args)
{
foreach(var d in physFS.GetCdRomDirs())
{
@ -145,7 +144,7 @@ namespace Test
return true;
}
static bool GetSearchPath(string[] args)
private static bool GetSearchPath(string[] args)
{
foreach (var d in physFS.GetSearchPath())
{
@ -154,25 +153,25 @@ namespace Test
return true;
}
static bool GetBaseDirectory(string[] args)
private static bool GetBaseDirectory(string[] args)
{
Console.WriteLine(physFS.GetBaseDir());
return true;
}
static bool GetUserDirectory(string[] args)
private static bool GetUserDirectory(string[] args)
{
Console.WriteLine(physFS.GetUserDir());
return true;
}
static bool GetWriteDirectory(string[] args)
private static bool GetWriteDirectory(string[] args)
{
Console.WriteLine(physFS.GetWriteDir());
return true;
}
static bool SetWriteDirectory(string[] args)
private static bool SetWriteDirectory(string[] args)
{
if (args.Length < 1)
{
@ -183,15 +182,14 @@ namespace Test
return true;
}
static bool PermitSymlinks(string[] args)
private static bool PermitSymlinks(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: permitsymlinks <true/false>");
return false;
}
bool permit;
if (!bool.TryParse(args[0], out permit))
if (!bool.TryParse(args[0], out bool permit))
{
Console.WriteLine("Usage: permitsymlinks <true/false>");
}
@ -199,15 +197,14 @@ namespace Test
return true;
}
static bool SetSaneConfig(string[] args)
private static bool SetSaneConfig(string[] args)
{
if(args.Length < 5)
{
Console.WriteLine("Usage: setsaneconfig <org> <appName> <arcExt> <includeCdRoms> <archivesFirst>");
return false;
}
bool includeCdRoms, archivesFirst;
if(bool.TryParse(args[3], out includeCdRoms) && bool.TryParse(args[4], out archivesFirst))
if (bool.TryParse(args[3], out bool includeCdRoms) && bool.TryParse(args[4], out bool archivesFirst))
{
physFS.SetSaneConfig(args[0], args[1], args[2], includeCdRoms, archivesFirst);
}
@ -218,18 +215,18 @@ namespace Test
return true;
}
static bool MkDir(string[] args)
private static bool MkDir(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: mkdir <dir>");
return false;
}
physFS.Mkdir(args[0]);
physFS.CreateDirectory(args[0]);
return true;
}
static bool Delete(string[] args)
private static bool Delete(string[] args)
{
if (args.Length < 1)
{
@ -240,7 +237,7 @@ namespace Test
return true;
}
static bool GetRealDir(string[] args)
private static bool GetRealDir(string[] args)
{
if (args.Length < 1)
{
@ -251,7 +248,7 @@ namespace Test
return true;
}
static bool Exists(string[] args)
private static bool Exists(string[] args)
{
if (args.Length < 1)
{
@ -262,7 +259,7 @@ namespace Test
return true;
}
static bool IsDir(string[] args)
private static bool IsDir(string[] args)
{
if (args.Length < 1)
{
@ -273,7 +270,7 @@ namespace Test
return true;
}
static bool IsSymlink(string[] args)
private static bool IsSymlink(string[] args)
{
if (args.Length < 1)
{
@ -284,7 +281,7 @@ namespace Test
return true;
}
static bool Cat(string[] args)
private static bool Cat(string[] args)
{
if (args.Length < 1)
{
@ -300,7 +297,7 @@ namespace Test
return true;
}
static bool FileLength(string[] args)
private static bool FileLength(string[] args)
{
if (args.Length < 1)
{
@ -314,7 +311,7 @@ namespace Test
return true;
}
static bool GetMountPoint(string[] args)
private static bool GetMountPoint(string[] args)
{
if (args.Length < 1)
{
@ -327,7 +324,7 @@ namespace Test
#endregion
static void Main(string[] args)
private static void Main(string[] args)
{
try
{
@ -387,8 +384,7 @@ namespace Test
}
else
{
Func<string[], bool> cmd;
if (commands.TryGetValue(split.First(), out cmd))
if (commands.TryGetValue(split.First(), out Func<string[], bool> cmd))
{
try
{

View File

@ -1,99 +1,91 @@
using System;
using System.IO;
using System.Linq;
using Xunit;
using FluentAssertions;
using NUnit.Framework;
using SharpPhysFS;
namespace UnitTests
{
public class Tests
{
[Fact]
void IsInit()
[Test]
public void IsInit()
{
using (var pfs = new PhysFS(""))
using var pfs = new PhysFS("");
Assert.True(pfs.IsInit(), "PhysFS was not initialized");
}
[Theory]
[InlineData(3, 0, 2)]
void VersionCheck(byte major, byte minor, byte patch)
[TestCase(3, 0, 2)]
public void VersionCheck(byte major, byte minor, byte patch)
{
using (var pfs = new PhysFS(""))
Assert.Equal(new SharpPhysFS.Version() { major = major, minor = minor, patch = patch }, pfs.GetLinkedVersion());
using var pfs = new PhysFS("");
new SharpPhysFS.Version() { major = major, minor = minor, patch = patch }.Should().BeEquivalentTo(pfs.GetLinkedVersion());
}
[Fact]
void DirSeparator()
[Test]
public void DirSeparator()
{
using (var pfs = new PhysFS(""))
{
Assert.NotNull(pfs.GetDirSeparator());
Assert.NotEqual("", pfs.GetDirSeparator());
}
using var pfs = new PhysFS("");
pfs.GetDirSeparator().Should().NotBeNullOrEmpty();
}
[Fact]
void PermitSymbolicLinks()
[Test]
public void PermitSymbolicLinks()
{
using (var pfs = new PhysFS(""))
{
Assert.False(pfs.SymbolicLinksPermitted());
using var pfs = new PhysFS("");
pfs.SymbolicLinksPermitted().Should().BeFalse();
pfs.PermitSymbolicLinks(true);
Assert.True(pfs.SymbolicLinksPermitted());
pfs.SymbolicLinksPermitted().Should().BeTrue();
pfs.PermitSymbolicLinks(false);
Assert.False(pfs.SymbolicLinksPermitted());
}
pfs.SymbolicLinksPermitted().Should().BeFalse();
}
[Fact]
void Mounting()
[Test]
public void Mounting()
{
using (var pfs = new PhysFS(""))
{
Assert.Empty(pfs.GetSearchPath());
using var pfs = new PhysFS("");
pfs.GetSearchPath().Should().BeEmpty();
pfs.Mount("./", "/", false);
Assert.Equal(new string[] { "./" }, pfs.GetSearchPath());
Assert.Equal("/", pfs.GetMountPoint("./"));
Assert.True(pfs.IsDirectory("/"));
pfs.GetSearchPath().Should().BeEquivalentTo(new string[] { "./" });
pfs.GetMountPoint("./").Should().Be("/");
pfs.IsDirectory("/").Should().BeTrue();
pfs.Mount("../", "foo", true);
Assert.Equal(new string[] { "./", "../", }, pfs.GetSearchPath());
Assert.Equal("foo/", pfs.GetMountPoint("../"));
Assert.True(pfs.IsDirectory("/foo"));
pfs.GetSearchPath().Should().BeEquivalentTo(new string[] { "./", "../" });
pfs.GetMountPoint("../").Should().Be("foo/");
pfs.IsDirectory("/foo").Should().BeTrue();
pfs.Mount("../../", "bar", false);
Assert.Equal(new string[] { "../../", "./", "../", }, pfs.GetSearchPath());
Assert.Equal("bar/", pfs.GetMountPoint("../../"));
Assert.True(pfs.IsDirectory("/bar"));
pfs.GetSearchPath().Should().BeEquivalentTo(new string[] { "../../", "./", "../" });
pfs.GetMountPoint("../../").Should().Be("bar/");
pfs.IsDirectory("/bar").Should().BeTrue();
pfs.RemoveFromSearchPath("../");
Assert.Equal(new string[] { "../../", "./", }, pfs.GetSearchPath());
}
pfs.UnMount("../");
pfs.GetSearchPath().Should().BeEquivalentTo(new string[] { "../../", "./" });
}
[Fact]
void FileEnumeration()
{
using (var pfs = new PhysFS(""))
[Test]
public void FileEnumeration()
{
using var pfs = new PhysFS("");
pfs.Mount("./", "/", false);
System.Console.WriteLine(Path.GetFullPath("./"));
var effectiveFiles = Directory.GetFiles("./").Select(x => Path.GetFileName(x)).ToArray();
var effectiveFiles = Directory.GetFiles("./").Select(Path.GetFileName).ToArray();
Array.Sort(effectiveFiles);
var enumeratedFiles = pfs.EnumerateFiles("/").ToArray();
Array.Sort(enumeratedFiles);
Assert.Equal(effectiveFiles, enumeratedFiles);
}
enumeratedFiles.Should().BeEquivalentTo(effectiveFiles);
}
[Fact]
void DriveEnumeration()
{
using (var pfs = new PhysFS(""))
[Test]
public void DriveEnumeration()
{
using var pfs = new PhysFS("");
var effectiveCdDrives = DriveInfo.GetDrives()
.Where(x => x.DriveType == DriveType.CDRom)
.Select(x => x.RootDirectory.FullName)
@ -104,42 +96,36 @@ namespace UnitTests
Array.Sort(effectiveCdDrives);
Array.Sort(enumeratedCdDrives);
Assert.Equal(effectiveCdDrives, enumeratedCdDrives);
}
enumeratedCdDrives.Should().BeEquivalentTo(effectiveCdDrives);
}
[Fact]
void UserDirectory()
{
using (var pfs = new PhysFS(""))
[Test]
public void UserDirectory()
{
using var pfs = new PhysFS("");
var userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var pfsUserDirectory = pfs.GetUserDir();
Assert.Equal(Path.GetPathRoot(userDirectory), Path.GetPathRoot(pfsUserDirectory));
}
Path.GetPathRoot(pfsUserDirectory).Should().Be(Path.GetPathRoot(userDirectory));
}
[Fact]
void DirectoryManipulation()
{
using (var pfs = new PhysFS(""))
[Test]
public void DirectoryManipulation()
{
using var pfs = new PhysFS("");
pfs.SetWriteDir("./");
Assert.Equal("./", pfs.GetWriteDir());
pfs.GetWriteDir().Should().Be("./");
pfs.Mkdir("hello");
Assert.True(Directory.Exists("./hello"));
pfs.CreateDirectory("hello");
Directory.Exists("./hello").Should().BeTrue();
pfs.Delete("hello");
Assert.False(Directory.Exists("./hello"));
}
Directory.Exists("./hello").Should().BeFalse();
}
[Fact]
void FileManipulation()
{
using (var pfs = new PhysFS(""))
[Test]
public void FileManipulation()
{
using var pfs = new PhysFS("");
pfs.SetWriteDir("./");
pfs.Mount("./", "/", true);
@ -153,18 +139,17 @@ namespace UnitTests
var fileContent = File.ReadAllText("./foo");
using (var sr = new StreamReader(pfs.OpenRead("foo")))
{
Assert.Equal(fileContent, sr.ReadToEnd());
sr.ReadToEnd().Should().BeEquivalentTo(fileContent);
}
using (var sw = new StreamWriter(pfs.OpenAppend("foo")))
{
sw.Write("foo");
}
Assert.Equal(fileContent + "foo", File.ReadAllText("./foo"));
File.ReadAllText("./foo").Should().BeEquivalentTo(fileContent + "foo");
pfs.Delete("foo");
Assert.False(File.Exists("./foo"));
}
}
}
}

View File

@ -8,7 +8,12 @@
<ProjectReference Include="..\SharpPhysFS\SharpPhysFS.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="xunit" Version="2.4.1"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Include="FluentAssertions" Version="5.10.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>