-
-
Notifications
You must be signed in to change notification settings - Fork 15
Added incomplete test coverage for bug 547. #549
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
Open
tacosontitan
wants to merge
7
commits into
Crypter-File-Transfer:stable
Choose a base branch
from
tacosoncontributing:bug547-test
base: stable
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0cc543c
Fixed a bug in Crypter.Core with TransferUploadService permitting job…
tacosontitan 54a940a
Marked the Users repository in Crypter.Core as virtual to support moc…
tacosontitan 9a20dce
Created shared classes for testing asynchronous operations when worki…
tacosontitan 754336e
Created a dummy background job client to allow assertion of results w…
tacosontitan e589544
Created a test fixture for TransferUploadService to test the fix for …
tacosontitan 1f0268e
Fixed a bug with TransferUploadService to handle unlocated recipients…
tacosontitan a641e81
Merge branch 'bug547' into bug547-test
tacosontitan 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
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
38 changes: 38 additions & 0 deletions
38
Crypter.Test/Core_Tests/Models/DummyBackgroundJobClient.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,38 @@ | ||
|
|
||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using Hangfire; | ||
| using Hangfire.Annotations; | ||
| using Hangfire.Common; | ||
| using Hangfire.States; | ||
|
|
||
| namespace Crypter.Test.Core_Tests.Models | ||
| { | ||
| /// <summary> | ||
| /// A dummy implementation of <see cref="IBackgroundJobClient"/> that can be used for testing. | ||
| /// </summary> | ||
| internal sealed class DummyBackgroundJobClient : | ||
| IBackgroundJobClient | ||
| { | ||
| /// <summary> | ||
| /// Gets a list of jobs that have been created. | ||
| /// </summary> | ||
| /// <remarks>This is used to help with assertions related to the Enqueue extension method.</remarks> | ||
| public List<Job> Jobs { get; set; } = new(); | ||
|
|
||
| public bool ChangeState( | ||
| [NotNull] string jobId, | ||
| [NotNull] IState state, | ||
| [CanBeNull] string expectedState) => | ||
| throw new NotImplementedException("This method is not currently needed to support testing of Crypter."); | ||
|
|
||
| public string Create( | ||
| [NotNull] Job job, | ||
| [NotNull] IState state) | ||
| { | ||
| Jobs.Add(job); | ||
| return Guid.NewGuid().ToString(); | ||
| } | ||
| } | ||
| } |
228 changes: 228 additions & 0 deletions
228
Crypter.Test/Core_Tests/Services_Tests/TransferUploadService_Tests.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,228 @@ | ||
| /* | ||
| * Copyright (C) 2023 Crypter File Transfer | ||
| * | ||
| * This file is part of the Crypter file transfer project. | ||
| * | ||
| * Crypter is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU Affero General Public License as published by | ||
| * the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * The Crypter source code is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU Affero General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Affero General Public License | ||
| * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| * | ||
| * You can be released from the requirements of the aforementioned license | ||
| * by purchasing a commercial license. Buying such a license is mandatory | ||
| * as soon as you develop commercial activities involving the Crypter source | ||
| * code without disclosing the source code of your own applications. | ||
| * | ||
| * Contact the current copyright holder to discuss commercial license options. | ||
| */ | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Linq.Expressions; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Crypter.Common.Contracts.Features.Metrics; | ||
| using Crypter.Common.Contracts.Features.Transfer; | ||
| using Crypter.Common.Enums; | ||
| using Crypter.Common.Monads; | ||
| using Crypter.Core; | ||
| using Crypter.Core.Entities; | ||
| using Crypter.Core.Repositories; | ||
| using Crypter.Core.Services; | ||
| using Crypter.Test.Core_Tests.Models; | ||
| using Crypter.Test.Shared; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Moq; | ||
| using NUnit.Framework; | ||
|
|
||
| namespace Crypter.Test.Core_Tests.Services_Tests | ||
| { | ||
| [TestFixture] | ||
| public class TransferUploadService_Tests | ||
| { | ||
| private Random _random; | ||
| private DataContext _dataContext; | ||
| private TransferUploadService _uploadService; | ||
| private ITransferRepository _transferStorageService; | ||
| private IServerMetricsService _serverMetricsService; | ||
| private DummyBackgroundJobClient _backgroundJobClient; | ||
| private IHangfireBackgroundService _hangfireBackgroundService; | ||
|
|
||
| [OneTimeSetUp] | ||
| public void OneTimeSetUp() | ||
| { | ||
| _random = new Random(); | ||
| _dataContext = GenerateMockDataContext(); | ||
| _backgroundJobClient = GenerateMockBackgroundJobClient(); | ||
| _serverMetricsService = GenerateMockServerMetricsService(); | ||
| _transferStorageService = GenerateMockTransferStorageService(); | ||
| _hangfireBackgroundService = GenerateMockHangfireBackgroundService(); | ||
|
|
||
| // This must happen last. | ||
| _uploadService = GenerateMockUploadService(); | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task Upload_File_Transfer_Async_Null_User_Does_Not_Enqueue_Client() | ||
| { | ||
| Guid senderId = Guid.Empty; | ||
| string recipientUsername = string.Empty; | ||
| Stream mockStream = GenerateMockStream(); | ||
| UploadFileTransferRequest request = GenerateMockRequest(); | ||
| _ = await _uploadService.UploadFileTransferAsync( | ||
| senderId, | ||
| recipientUsername, | ||
| request, | ||
| mockStream | ||
| ); | ||
|
|
||
| Assert.IsEmpty(_backgroundJobClient.Jobs); | ||
| } | ||
|
|
||
| private TransferUploadService GenerateMockUploadService() | ||
| { | ||
| var uploadService = new TransferUploadService( | ||
| context: _dataContext, | ||
| serverMetricsService: _serverMetricsService, | ||
| transferStorageService: _transferStorageService, | ||
| hangfireBackgroundService: _hangfireBackgroundService, | ||
| backgroundJobClient: _backgroundJobClient, | ||
| hashIdService: null | ||
| ); | ||
|
|
||
| return uploadService; | ||
| } | ||
|
|
||
| private Stream GenerateMockStream() | ||
| { | ||
| byte[] buffer = new byte[1024]; | ||
| int scale = _random.Next(100, 1000); | ||
| Stream mockStream = new MemoryStream(buffer); | ||
| while (scale > 0) | ||
| { | ||
| int bytesToWrite = Math.Min(buffer.Length, scale); | ||
| _random.NextBytes(buffer); | ||
| mockStream.Write(buffer, 0, bytesToWrite); | ||
| scale -= bytesToWrite; | ||
| } | ||
|
|
||
| return mockStream; | ||
| } | ||
|
|
||
| /// NOTE: This method is <see langword="static"/> because it doesn't access instance members. | ||
| private static DataContext GenerateMockDataContext() | ||
| { | ||
| DbSet<UserEntity> users = GenerateMockUsers(); | ||
| Mock<DataContext> mockDataContext = new(); | ||
| _ = mockDataContext.Setup(context => context.Users).Returns(users); | ||
| return mockDataContext.Object; | ||
| } | ||
|
|
||
| /// NOTE: This method is <see langword="static"/> because it doesn't access instance members. | ||
| private static DummyBackgroundJobClient GenerateMockBackgroundJobClient() => new(); | ||
|
|
||
| /// NOTE: This method is <see langword="static"/> because it doesn't access instance members. | ||
| private static IServerMetricsService GenerateMockServerMetricsService() | ||
| { | ||
| Mock<IServerMetricsService> mockServerMetricsService = new(); | ||
| _ = mockServerMetricsService.Setup(service => | ||
| service.GetAggregateDiskMetricsAsync(CancellationToken.None)) | ||
| .Returns( | ||
| Task.FromResult( | ||
| new PublicStorageMetricsResponse( | ||
| allocated: int.MaxValue, | ||
| available: int.MaxValue | ||
| ) | ||
| ) | ||
| ); | ||
|
|
||
| return mockServerMetricsService.Object; | ||
| } | ||
|
|
||
| /// NOTE: This method is <see langword="static"/> because it doesn't access instance members. | ||
| private static ITransferRepository GenerateMockTransferStorageService() | ||
| { | ||
| Mock<ITransferRepository> mockTransferStorageService = new(); | ||
| _ = mockTransferStorageService.Setup(service => service.SaveTransferAsync( | ||
| It.IsAny<Guid>(), | ||
| It.IsAny<TransferItemType>(), | ||
| It.IsAny<TransferUserType>(), | ||
| It.IsAny<Stream>() | ||
| )).Returns(Task.FromResult(true)); | ||
| return mockTransferStorageService.Object; | ||
| } | ||
|
|
||
| /// NOTE: This method is <see langword="static"/> because it doesn't access instance members. | ||
| private static IHangfireBackgroundService GenerateMockHangfireBackgroundService() | ||
| { | ||
| Mock<IHangfireBackgroundService> mockHangfireBackgroundService = new(); | ||
| _ = mockHangfireBackgroundService.Setup(service => service.SendTransferNotificationAsync( | ||
| It.IsAny<Guid>(), | ||
| It.IsAny<TransferItemType>() | ||
| )).Returns(Task.CompletedTask); | ||
| return mockHangfireBackgroundService.Object; | ||
| } | ||
|
|
||
| /// NOTE: This method is <see langword="static"/> because it doesn't access instance members. | ||
| private static DbSet<UserEntity> GenerateMockUsers() | ||
| { | ||
| IEnumerable<UserEntity> users = GenerateUsers(); | ||
| IQueryable<UserEntity> usersQueryable = users.AsQueryable(); | ||
|
|
||
| Mock<DbSet<UserEntity>> usersDbSet = new(); | ||
|
|
||
| _ = usersDbSet.As<IAsyncEnumerable<UserEntity>>() | ||
| .Setup(m => m.GetAsyncEnumerator(It.IsAny<CancellationToken>())) | ||
| .Returns(new TestAsyncEnumerator<UserEntity>(usersQueryable.GetEnumerator())); | ||
|
|
||
| _ = usersDbSet.As<IQueryable<UserEntity>>() | ||
| .Setup(m => m.Provider) | ||
| .Returns(new TestAsyncQueryProvider<UserEntity>(usersQueryable.Provider)); | ||
|
|
||
| _ = usersDbSet.As<IQueryable<UserEntity>>().Setup(m => m.Expression).Returns(usersQueryable.Expression); | ||
| _ = usersDbSet.As<IQueryable<UserEntity>>().Setup(m => m.ElementType).Returns(usersQueryable.ElementType); | ||
| _ = usersDbSet.As<IQueryable<UserEntity>>().Setup(m => m.GetEnumerator()).Returns(() => usersQueryable.GetEnumerator()); | ||
| return usersDbSet.Object; | ||
| } | ||
|
|
||
| /// NOTE: This method is <see langword="static"/> because it doesn't access instance members. | ||
| private static IEnumerable<UserEntity> GenerateUsers() => Enumerable.Range(0, 10).Select( | ||
| index => new UserEntity( | ||
| id: Guid.NewGuid(), | ||
| username: $"user{index}", | ||
| emailAddress: $"user{index}@example.com", | ||
| passwordHash: null, | ||
| passwordSalt: null, | ||
| serverPasswordVersion: 1, | ||
| clientPasswordVersion: 1, | ||
| emailVerified: true, | ||
| created: DateTime.Now.AddDays(-index), | ||
| lastLogin: DateTime.Now.AddMinutes(-index) | ||
| ) | ||
| ); | ||
|
|
||
| private static UploadFileTransferRequest GenerateMockRequest() | ||
| { | ||
| UploadFileTransferRequest request = new( | ||
| fileName: "sample.txt", | ||
| "text/plain", | ||
| publicKey: null, | ||
| keyExchangeNonce: null, | ||
| proof: null, | ||
| lifetimeHours: 3 | ||
| ); | ||
|
|
||
| return request; | ||
| } | ||
| } | ||
| } | ||
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,67 @@ | ||
| /* | ||
| * Copyright (C) 2023 Crypter File Transfer | ||
| * | ||
| * This file is part of the Crypter file transfer project. | ||
| * | ||
| * Crypter is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU Affero General Public License as published by | ||
| * the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * The Crypter source code is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU Affero General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Affero General Public License | ||
| * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| * | ||
| * You can be released from the requirements of the aforementioned license | ||
| * by purchasing a commercial license. Buying such a license is mandatory | ||
| * as soon as you develop commercial activities involving the Crypter source | ||
| * code without disclosing the source code of your own applications. | ||
| * | ||
| * Contact the current copyright holder to discuss commercial license options. | ||
| */ | ||
|
|
||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Linq.Expressions; | ||
| using System.Threading; | ||
|
|
||
| namespace Crypter.Test.Shared | ||
| { | ||
| /// <summary> | ||
| /// Represents a test async enumerable. | ||
| /// </summary> | ||
| /// <typeparam name="T">The type of the elements in the enumerable.</typeparam> | ||
| internal class TestAsyncEnumerable<T> : EnumerableQuery<T>, IAsyncEnumerable<T>, IQueryable<T> | ||
| { | ||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="TestAsyncEnumerable{T}"/> class. | ||
| /// </summary> | ||
| /// <param name="enumerable">The enumerable to use.</param> | ||
| public TestAsyncEnumerable(IEnumerable<T> enumerable) | ||
| : base(enumerable) | ||
| { } | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="TestAsyncEnumerable{T}"/> class. | ||
| /// </summary> | ||
| /// <param name="expression">The expression representing the enumerable.</param> | ||
| public TestAsyncEnumerable(Expression expression) | ||
| : base(expression) | ||
| { } | ||
|
|
||
| /// <inheritdoc/> | ||
| public IAsyncEnumerator<T> GetEnumerator() => | ||
| new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator()); | ||
|
|
||
| /// <inheritdoc/> | ||
| public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) => | ||
| new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator()); | ||
|
|
||
| /// <inheritdoc/> | ||
| IQueryProvider IQueryable.Provider => new TestAsyncQueryProvider<T>(this); | ||
| } | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thinking out loud, it could be the case later on that something does end up getting scheduled to occur after an upload is processed. Doing some kind of analytics has been on my mind for a while.
What do you think about taking the approach of verifying
_backgroundJobClient.Enqueuewas not called with parameters that would schedule a transfer notification?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Personally, I believe this is a bit over my head due to my lack of experience in the repository.
Since
Enqueueis an extension method, I'm not sure how we could verify whether or not it was called. I believe it simply callsCreateso long as the source of invocation isn'tnull, so we could technically build something into that, but there's no guarantee thatEnqueueis what invoked it without looking at the stack trace (unless there's something critical missing from my current understanding).