Skip to content

Commit 2fcccbb

Browse files
authored
feat: implement Path.GetRelativePath in MockFileSystem (#1012)
Override the `Path.GetRelativePath` implementation on mocked file systems and use the current directory to change the parameters to a full path relative to the current directory in the mocked file system. Fixes: - #773
1 parent d8a32b3 commit 2fcccbb

File tree

2 files changed

+49
-0
lines changed
  • src/TestableIO.System.IO.Abstractions.TestingHelpers
  • tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests

2 files changed

+49
-0
lines changed

src/TestableIO.System.IO.Abstractions.TestingHelpers/MockPath.cs

+31
Original file line numberDiff line numberDiff line change
@@ -155,5 +155,36 @@ public override string GetTempFileName()
155155

156156
/// <inheritdoc />
157157
public override string GetTempPath() => defaultTempDirectory;
158+
159+
#if FEATURE_ADVANCED_PATH_OPERATIONS
160+
/// <inheritdoc />
161+
public override string GetRelativePath(string relativeTo, string path)
162+
{
163+
if (relativeTo == null)
164+
{
165+
throw new ArgumentNullException(nameof(relativeTo), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL"));
166+
}
167+
168+
if (relativeTo.Length == 0)
169+
{
170+
throw CommonExceptions.PathIsNotOfALegalForm(nameof(relativeTo));
171+
}
172+
173+
if (path == null)
174+
{
175+
throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL"));
176+
}
177+
178+
if (path.Length == 0)
179+
{
180+
throw CommonExceptions.PathIsNotOfALegalForm(nameof(path));
181+
}
182+
183+
relativeTo = GetFullPath(relativeTo);
184+
path = GetFullPath(path);
185+
186+
return Path.GetRelativePath(relativeTo, path);
187+
}
188+
#endif
158189
}
159190
}

tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockPathTests.cs

+18
Original file line numberDiff line numberDiff line change
@@ -557,5 +557,23 @@ public void Exists_ExistingFileOrDirectory_ShouldReturnTrue()
557557
Assert.IsFalse(result);
558558
}
559559
#endif
560+
561+
#if FEATURE_ADVANCED_PATH_OPERATIONS
562+
[Test]
563+
public void GetRelativePath_ShouldUseCurrentDirectoryFromMockFileSystem()
564+
{
565+
var fs = new MockFileSystem();
566+
567+
fs.AddDirectory("input");
568+
fs.AddDirectory("output");
569+
fs.Directory.SetCurrentDirectory("input");
570+
571+
fs.AddFile("input/a.txt", "foo");
572+
573+
var result = fs.Path.GetRelativePath("/input", "a.txt");
574+
575+
Assert.AreEqual("a.txt", result);
576+
}
577+
#endif
560578
}
561579
}

0 commit comments

Comments
 (0)