Skip to content

Commit

Permalink
code smells
Browse files Browse the repository at this point in the history
  • Loading branch information
qdraw committed Dec 11, 2023
1 parent fee53a0 commit 3dbf7ce
Show file tree
Hide file tree
Showing 23 changed files with 77 additions and 101 deletions.
10 changes: 4 additions & 6 deletions starsky/starskytest/Controllers/AccountControllerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,7 @@ public async Task AccountController_NoLogin_Login_And_newAccount_Test()
// Test login
Assert.AreEqual(true,httpContext.User.Identity?.IsAuthenticated);

// The logout is mocked so this will not actual log it out
// controller.Logout() not crashing is good enough;
// The logout is mocked so this will not actual log it out and controller.Logout() not crashing is good enough
controller.Logout();

// And clean afterwards
Expand Down Expand Up @@ -568,8 +567,8 @@ public async Task AccountController_newAccount_TryToOverwrite_ButItKeepsTheSameP
Assert.IsNotNull(httpContext);
Assert.AreEqual(true,httpContext.User.Identity?.IsAuthenticated);

// The logout is mocked so this will not actual log it out;
// controller.Logout() not crashing is good enough;
// The logout is mocked so this will not actual log it out
// controller.Logout() not crashing is good enough
controller.LogoutJson();


Expand All @@ -589,8 +588,7 @@ public async Task AccountController_newAccount_TryToOverwrite_ButItKeepsTheSameP
// Test login
Assert.AreEqual(true,httpContext.User.Identity?.IsAuthenticated);

// The logout is mocked so this will not actual log it out;
// controller.Logout() not crashing is good enough;
// The logout is mocked so this will not actual log it out and controller.Logout() not crashing is good enough;
controller.LogoutJson();

// Clean afterwards
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ private static IStorage ArrangeStorage()
var storage =
new FakeIStorage(folderPaths, inputSubPaths,
new List<byte[]>{FakeCreateAn.CreateAnImage.Bytes.ToArray(),
FakeCreateAn.CreateAnXmp.Bytes, Array.Empty<byte>()});
FakeCreateAn.CreateAnXmp.Bytes.ToArray(), Array.Empty<byte>()});
return storage;
}

Expand Down
17 changes: 2 additions & 15 deletions starsky/starskytest/Controllers/GeoControllerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,10 @@ namespace starskytest.Controllers
[TestClass]
public sealed class GeoControllerTest
{
private readonly IQuery _query;
private readonly IExifTool _exifTool;
private readonly AppSettings _appSettings;
private readonly CreateAnImage _createAnImage;
private readonly IUpdateBackgroundTaskQueue _bgTaskQueue;
private readonly IReadMeta _readmeta;
private readonly IServiceScopeFactory _scopeFactory;
private IMemoryCache _memoryCache;
private readonly IMemoryCache _memoryCache;

public GeoControllerTest()
{
Expand All @@ -47,10 +43,6 @@ public GeoControllerTest()

var builderDb = new DbContextOptionsBuilder<ApplicationDbContext>();
builderDb.UseInMemoryDatabase(nameof(ExportControllerTest));
var options = builderDb.Options;
var context = new ApplicationDbContext(options);
_query = new Query(context, new AppSettings(), null,
new FakeIWebLogger(), _memoryCache);

// Inject Fake Exiftool; dependency injection
var services = new ServiceCollection();
Expand Down Expand Up @@ -85,12 +77,7 @@ public GeoControllerTest()
// build the service
var serviceProvider = services.BuildServiceProvider();
// get the service
_appSettings = serviceProvider.GetRequiredService<AppSettings>();

// inject fake exiftool
_exifTool = new FakeExifTool(new FakeIStorage(),_appSettings );

_readmeta = serviceProvider.GetRequiredService<IReadMeta>();

_scopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();

// get the background helper
Expand Down
2 changes: 1 addition & 1 deletion starsky/starskytest/Controllers/UploadControllerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ private static ControllerContext RequestWithSidecar()
{
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers.Add("Content-Type", "application/octet-stream");
httpContext.Request.Body = new MemoryStream(CreateAnXmp.Bytes);
httpContext.Request.Body = new MemoryStream(CreateAnXmp.Bytes.ToArray());

var actionContext = new ActionContext(httpContext, new RouteData(), new ControllerActionDescriptor());
return new ControllerContext(actionContext);
Expand Down
3 changes: 2 additions & 1 deletion starsky/starskytest/FakeCreateAn/CreateAnXmp.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Text;

Expand Down Expand Up @@ -31,6 +32,6 @@ public static class CreateAnXmp
"1.0</stEvt:softwareAgent></rdf:li></rdf:Seq></xmpMM:History></rdf:Description></rdf:RDF>" +
"</x:xmpmeta>";

public static readonly byte[] Bytes = Encoding.ASCII.GetBytes(XmpString);
public static readonly ImmutableArray<byte> Bytes = Encoding.ASCII.GetBytes(XmpString).ToImmutableArray();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ public static class CreateAnZipFile12

public static readonly ImmutableArray<byte> Bytes = Base64Helper.TryParse(Base64CreateAnZipFile12String).ToImmutableArray();

public static readonly Dictionary<string, string> Content = new Dictionary<string, string>
public static readonly ImmutableDictionary<string, string> Content =
new Dictionary<string, string>
{
{ "file1.txt", "This is file 1.\n" },
{ "file2.txt", "This is file 2.\n" }
};
}.ToImmutableDictionary();
}
}

3 changes: 2 additions & 1 deletion starsky/starskytest/FakeMocks/FakeICacheEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ public class FakeICacheEntry : ICacheEntry
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}

protected virtual void Dispose(bool disposing)
{
Dispose();
// do nothing
}

public object Key { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ public bool EnableRaisingEvents

public bool IsDisposed { get; set; }
void IDisposable.Dispose()
{
GC.SuppressFinalize(this);
IsDisposed = true;
Dispose(true);
}

protected virtual void Dispose(bool disposing)
{
GC.SuppressFinalize(this);
IsDisposed = true;
Expand Down
8 changes: 7 additions & 1 deletion starsky/starskytest/FakeMocks/FakeIFtpWebRequestFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,14 @@ public class FakeIFtpWebResponse : IFtpWebResponse
public void Dispose()
{
GC.SuppressFinalize(this);
// done
Dispose(true);
}

protected virtual void Dispose(bool disposing)
{
GC.SuppressFinalize(this);
}


public Stream GetResponseStream()
{
Expand Down
15 changes: 5 additions & 10 deletions starsky/starskytest/FakeMocks/FakeIQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ public bool RemoveCacheParentItem(string directoryName)

public string? GetSubPathByHash(string fileHash)
{
return _content.FirstOrDefault(p => p.FileHash == fileHash)?.FilePath;
return _content.Find(p => p.FileHash == fileHash)?.FilePath;
}

public Task<string?> GetSubPathByHashAsync(string fileHash)
Expand Down Expand Up @@ -309,7 +309,7 @@ public async Task<FileIndexItem> AddItemAsync(FileIndexItem fileIndexItem)
{
_content.Add(fileIndexItem);
await Task.Delay(new Random().Next(1, 5));
if ( _content.FirstOrDefault(p =>
if ( _content.Find(p =>
p.FilePath == fileIndexItem.FilePath) != null ) return fileIndexItem;

_content.Add(fileIndexItem);
Expand All @@ -327,7 +327,7 @@ public async Task<List<FileIndexItem>> AddRangeAsync(List<FileIndexItem> fileInd

public FileIndexItem UpdateItem(FileIndexItem updateStatusContent)
{
var item = _content.FirstOrDefault(p =>
var item = _content.Find(p =>
p.FilePath == updateStatusContent.FilePath);
if ( item == null ) return updateStatusContent;
var index = _content.IndexOf(item);
Expand All @@ -348,12 +348,7 @@ public Task<List<FileIndexItem>> UpdateItemAsync(List<FileIndexItem> updateStatu
}
return Task.FromResult(updateStatusContentList);
}

public List<FileIndexItem> UpdateItem(List<FileIndexItem> updateStatusContentList)
{
throw new NotImplementedException();
}


public RelativeObjects GetNextPrevInFolder(string currentFolder)
{
return new RelativeObjects();
Expand Down Expand Up @@ -401,7 +396,7 @@ public async Task<List<FileIndexItem>> AddParentItemsAsync(string subPath)
var toAddList = new List<FileIndexItem>();

var indexItems = _content
.Where(p => pathListShouldExist.Any(f => f == p.FilePath)).ToList();
.Where(p => pathListShouldExist.Exists(f => f == p.FilePath)).ToList();

// ReSharper disable once ForeachCanBeConvertedToQueryUsingAnotherGetEnumerator
foreach ( var pathShouldExist in pathListShouldExist )
Expand Down
2 changes: 1 addition & 1 deletion starsky/starskytest/FakeMocks/FakeIUserManger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public ChangeSecretResult ChangeSecret(string credentialTypeCode, string identif
public Task<ValidateResult> ValidateAsync(string credentialTypeCode, string identifier, string secret)
{
var validateResult = new ValidateResult();
var result = _userOverviewModel.Users.FirstOrDefault(p => p.Credentials?.FirstOrDefault()?.Identifier == identifier);
var result = _userOverviewModel.Users.Find(p => p.Credentials?.FirstOrDefault()?.Identifier == identifier);
if ( result?.Credentials?.FirstOrDefault()?.Secret == secret )
{
validateResult.Success = true;
Expand Down
4 changes: 2 additions & 2 deletions starsky/starskytest/FakeMocks/FakeReadMeta.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace starskytest.FakeMocks
{
public class FakeReadMeta : IReadMeta
{
public FileIndexItem ReadExifAndXmpFromFile(string path)
public FileIndexItem ReadExifAndXmpFromFile(string subPath)
{
return new FileIndexItem
{
Expand All @@ -16,7 +16,7 @@ public FileIndexItem ReadExifAndXmpFromFile(string path)
};
}

public List<FileIndexItem> ReadExifAndXmpFromFileAddFilePathHash(List<string> subPathArray,
public List<FileIndexItem> ReadExifAndXmpFromFileAddFilePathHash(List<string> subPathList,
List<string> fileHashes = null)
{
var createAnImage = new CreateAnImage();
Expand Down
3 changes: 1 addition & 2 deletions starsky/starskytest/Helpers/FileStreamingHelperTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ public async Task StreamFileExeption()
var httpContext = new DefaultHttpContext(); // or mock a `HttpContext`
httpContext.Request.Headers["token"] = "fake_token_here"; //Set header

var ms = new MemoryStream();
await FileStreamingHelper.StreamFile(httpContext.Request,_appSettings, new FakeSelectorStorage(new FakeIStorage()));
}

Expand All @@ -77,7 +76,7 @@ public async Task StreamFilemultipart()
var httpContext = new DefaultHttpContext(); // or mock a `HttpContext`
httpContext.Request.Headers["token"] = "fake_token_here"; //Set header
httpContext.Request.ContentType = "multipart/form-data";
var ms = new MemoryStream();

await FileStreamingHelper.StreamFile(httpContext.Request,_appSettings,new FakeSelectorStorage(new FakeIStorage()));
}

Expand Down
2 changes: 1 addition & 1 deletion starsky/starskytest/Services/ReadMetaTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ public void ShouldPickXmpFile()
new List<string> { "/test.dng", "/test.xmp" }, new List<byte[]>
{
CreateAnImage.Bytes.ToArray(),
CreateAnXmp.Bytes
CreateAnXmp.Bytes.ToArray()
});
var readMeta = new ReadMeta(storage, new AppSettings(), null!, new FakeIWebLogger());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private void Setup()
DependenciesFolder = Path.Combine(new CreateAnImage().BasePath, "tmp-dependencies"),
};

// create a temp folder;
// create a temp folder
if ( !new StorageHostFullPathFilesystem().ExistFolder(_appSettings.DependenciesFolder) )
{
new StorageHostFullPathFilesystem().CreateDirectory(_appSettings
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,28 +35,18 @@ public GeoCliTest()
[TestMethod]
public async Task GeoCliInput_Notfound()
{
var fakeIHttpProvider = new FakeIHttpProvider(new Dictionary<string, HttpContent>
{
});
var httpClientHelper = new HttpClientHelper(fakeIHttpProvider, _serviceScopeFactory, new FakeIWebLogger());

var console = new FakeConsoleWrapper();
var geoCli = new GeoCli(new FakeIGeoReverseLookup(), new FakeIGeoLocationWrite(),
new FakeSelectorStorage(new FakeIStorage(new List<string>{})), new AppSettings(),
console, new FakeIGeoFileDownload(), new FakeExifToolDownload(), new FakeIWebLogger());
await geoCli.CommandLineAsync(new List<string> {"-p",}.ToArray());

Assert.IsTrue(console.WrittenLines.LastOrDefault().Contains("not found"));
Assert.IsTrue(console.WrittenLines.LastOrDefault()?.Contains("not found"));
}

[TestMethod]
public async Task GeoCliInput_RelativeUrl_HappyFlow()
{
var fakeIHttpProvider = new FakeIHttpProvider(new Dictionary<string, HttpContent>
{
});
var httpClientHelper = new HttpClientHelper(fakeIHttpProvider, _serviceScopeFactory, new FakeIWebLogger());

var relativeParentFolder = new AppSettings().DatabasePathToFilePath(
new StructureService(new FakeIStorage(), new AppSettings().Structure)
.ParseSubfolders(0),false);
Expand All @@ -82,11 +72,6 @@ public async Task GeoCliInput_RelativeUrl_HappyFlow()
[TestMethod]
public async Task GeoCliInput_AbsolutePath_HappyFlow()
{
var fakeIHttpProvider = new FakeIHttpProvider(new Dictionary<string, HttpContent>
{
});
var httpClientHelper = new HttpClientHelper(fakeIHttpProvider, _serviceScopeFactory, new FakeIWebLogger());

var storage = new FakeIStorage(new List<string> {"/"},
new List<string> {"/test.jpg"},
new List<byte[]> {CreateAnImage.Bytes.ToArray()});
Expand Down
Loading

0 comments on commit 3dbf7ce

Please sign in to comment.