Linux下如何临时保护文件防删除?C#单元测试遇阻
跨平台测试文件删除失败抛出异常的问题
我需要为一段代码编写单元测试,要求该代码在无法删除文件时抛出FileServiceException。
待测试代码
public void DeleteFile(string path) { try { if (File.Exists(path)) { File.Delete(path); } } catch (Exception e) { throw FileServiceException.BecauseCouldNotDeleteFile(e); } }
最初的测试用例(Windows正常,Linux CI/CD失效)
[Fact] public void DeleteFile_Throws_ExceptionIfFileCannotBeDeleted() { var filePath = $"{Path.GetTempPath()}{Guid.NewGuid()}.jpeg"; using var file = File.Create(filePath); Assert.Throws<FileServiceException>(() =>_service.DeleteFile(filePath)); // 测试后清理文件 _service.DeleteFile(filePath); }
尝试的解决方案及问题
方案1:设置UnixFileMode.None或FileAttributes.Hidden
尝试通过设置文件权限或属性让文件无法删除,但无效:
[Fact] public void DeleteFile_Throws_ExceptionIfFileCannotBeDeleted() { var filePath = $"{Path.GetTempPath()}{Guid.NewGuid()}.jpeg"; File.Create(filePath); File.SetUnixFileMode(filePath, UnixFileMode.None); Assert.Throws<IOException>(() =>_service.DeleteFile(filePath)); // 测试后清理文件 _service.DeleteFile(filePath); }
方案2:同时设置FileAttributes.ReadOnly和UnixFileMode.None
补充尝试同时设置只读属性和无权限,但查看属性时FileAttributes仍为Normal,未生效:
[Fact] public void DeleteFile_Throws_ExceptionIfFileCannotBeDeleted() { var filePath = $"{Path.GetTempPath()}{Guid.NewGuid()}.jpeg"; using var file = File.Create(filePath); File.SetAttributes(filePath, FileAttributes.ReadOnly); File.SetUnixFileMode(filePath, UnixFileMode.None); Assert.Throws<FileServiceException>(() =>_service.DeleteFile(filePath)); // 测试后清理文件 _service.DeleteFile(filePath); }
方案3:执行Shell命令修改权限
尝试直接调用Shell命令设置文件不可变、移除所有权限,同样无效:
System.Diagnostics.Process.Start("chmod", $"000 {filePath}"); System.Diagnostics.Process.Start("sudo", $"chattr +i {filePath}");
最终结果
经过多种尝试后,我最终放弃了该部分测试。
内容的提问来源于stack exchange,提问作者kwerie
相关产品推荐
相关产品推荐

