//[Test] public void WindowsSkipsInstallWhenSettingsGitExists() { DefaultEnvironment.OnMac = false; DefaultEnvironment.OnWindows = true; var filesystem = Substitute.For <IFileSystem>(); filesystem.FileExists(Arg.Any <string>()).Returns(true); filesystem.DirectoryExists(Arg.Any <string>()).Returns(true); filesystem.DirectorySeparatorChar.Returns('\\'); Environment.FileSystem = filesystem; var gitInstallationPath = "c:/Program Files/Git".ToNPath(); var gitExecutablePath = gitInstallationPath.Combine("cmd/git.exe"); var gitLfsInstallationPath = gitInstallationPath; var gitLfsExecutablePath = gitLfsInstallationPath.Combine("mingw32/libexec/git-core/git-lfs.exe"); var installDetails = new GitInstaller.GitInstallDetails(gitInstallationPath, Environment.IsWindows) { GitPackageFeed = $"http://localhost:{server.Port}/unity/git/windows/{GitInstaller.GitInstallDetails.GitPackageName}", GitLfsPackageFeed = $"http://localhost:{server.Port}/unity/git/windows/{GitInstaller.GitInstallDetails.GitLfsPackageName}", }; var ret = new string[] { gitLfsExecutablePath }; filesystem.GetFiles(Arg.Any <string>(), Arg.Is <string>(installDetails.GitLfsExecutablePath.FileName), Arg.Any <SearchOption>()) .Returns(ret); var settings = Substitute.For <ISettings>(); var settingsRet = gitExecutablePath.ToString(); settings.Get(Arg.Is <string>(Constants.GitInstallPathKey), Arg.Any <string>()).Returns(settingsRet); var installer = new GitInstaller(Environment, ProcessManager, TaskManager.Token, installDetails); var result = installer.SetupGitIfNeeded(); Assert.AreEqual(gitInstallationPath, result.GitInstallationPath); Assert.AreEqual(gitLfsInstallationPath, result.GitLfsInstallationPath); Assert.AreEqual(gitExecutablePath, result.GitExecutablePath); Assert.AreEqual(gitLfsExecutablePath, result.GitLfsExecutablePath); }
public async Task UpdateUser_GivenUserSubmit_ReturnsUserResource() { var userRepository = Substitute.For <IUserRepository>(); var roleRepository = Substitute.For <IRoleRepository>(); var teamRepository = Substitute.For <ITeamRepository>(); var ldapRepository = Substitute.For <ILdapAuthenticationModeRepository>(); var ldapConnectionService = Substitute.For <ILdapConnectionService>(); var guid = Guid.NewGuid(); var userModelMock = new UserModel { UserName = "******", Id = guid.ToString(), FirstName = "Test User Firstname", Surname = "Test User Surname", Email = "Test User Email" }; var userSubmit = new UserSubmit() { Uuid = guid, Username = userModelMock.UserName, Name = userModelMock.FirstName, Surname = userModelMock.Surname, Email = userModelMock.Email }; userRepository.UpdateAsync(Arg.Any <UserModel>()).Returns(userModelMock); userRepository.GetByIdAsync(Arg.Any <Guid>(), Arg.Any <bool>()).Returns(userModelMock); var userService = new UserService(userRepository, roleRepository, teamRepository, ldapRepository, mapper, ldapConnectionService); var userResource = await userService.UpdateAsync(userSubmit, Guid.NewGuid()); Assert.NotNull(userResource); Assert.True(userResource.Uuid.ToString() == userModelMock.Id, $"User resource Id: '{userResource.Uuid}' does not match expected value: '{userModelMock.Id}'"); Assert.True(userResource.Name == userModelMock.FirstName, $"User resource name: '{userResource.Name}' does not match expected value: '{userModelMock.FirstName}'"); Assert.True(userResource.Surname == userModelMock.Surname, $"User resource surname: '{userResource.Surname}' does not match expected value: '{userModelMock.Surname}'"); Assert.True(userResource.Username == userModelMock.UserName, $"User resource username: '******' does not match expected value: '{userModelMock.UserName}'"); Assert.True(userResource.Email == userModelMock.Email, $"User resource email: '{userResource.Email}' does not match expected value: '{userModelMock.Email}'"); }
public void SimonSolvedWithWrongAnswersTest(IMiniGameEventManager miniGameEventManager, string miniGameId, int inputCount, int inputSequenceCount, int failureThreshold) { bool miniGameSolved = false; int wrongAnswerCount = 0; int correctAnswerCount = 0; bool miniGameFailed = false; miniGameEventManager.OnMiniGameInputReceived( Arg.Any <string>(), Arg.Do <InputResults>(x => { if (x.Equals(InputResults.FAIL)) { wrongAnswerCount++; } if (x.Equals(InputResults.PASS)) { correctAnswerCount++; } }), Arg.Any <int>() ); miniGameEventManager.When(x => x.OnMiniGameFailed(miniGameId)).Do(x => miniGameFailed = true); miniGameEventManager.When(x => x.OnMiniGameSolved(miniGameId)).Do(x => miniGameSolved = true); Simon simon = new Simon(miniGameEventManager, miniGameId, inputCount, inputSequenceCount, failureThreshold); int[] inputSequence = simon.GetInputSequence(); simon.VerifyInput(simon.GetInputIds().Length + 1); foreach (int input in inputSequence) { simon.VerifyInput(input); } Assert.IsTrue(miniGameSolved); Assert.IsTrue(!miniGameFailed); Assert.AreEqual(simon.GetInputSequence().Length, correctAnswerCount); Assert.AreEqual(simon.GetFailureCount(), wrongAnswerCount); }
public void Delete_Command_Variable_Should_Throw_With_Invalid_Command_Name() { // Arrange batchRepository.DoesBatchExist(Arg.Any <string>()) .Returns(true); stepRepository.Get(Arg.Any <string>(), Arg.Any <string>()) .Returns(new Step()); commandRepository.Get(Arg.Any <ulong>(), Arg.Any <string>()).ReturnsNull(); var request = new DeleteCommandVariableRequest { CommandName = TestCommandName }; // Act / Assert var exception = Assert.ThrowsAsync <HttpError>(() => Sut.Delete(request)); exception.ErrorCode.Should().Be(HttpStatusCode.NotFound.ToString()); exception.Message.Should().Be("Command TestCommand not found"); }
public void AttemptsToAquireLockIfOtherProcessIsNoLongerRunning() { var log = new InMemoryLog(); var lockIo = Substitute.For <ILockIo>(); var name = Guid.NewGuid().ToString(); var processFinder = Substitute.For <IProcessFinder>(); processFinder.ProcessIsRunning(Arg.Any <int>(), Arg.Any <string>()).Returns(false); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder, log); var fileLock = new FileLock { ProcessId = -1, ThreadId = -2, ProcessName = Guid.NewGuid().ToString() }; lockIo.LockExists(Arg.Any <string>()).Returns(true); var result = semaphore.ShouldAquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AquireLockAction.AquireLock)); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == "Process -1, thread -2 had lock, but appears to have crashed. Taking lock."); }
public void ShouldNotCreateAssemblyInfoFileForUnknownSourceCodeAndEnsureAssemblyInfo() { var fileSystem = Substitute.For <IFileSystem>(); var workingDir = Path.GetTempPath(); var assemblyInfoFile = new HashSet <string> { "VersionAssemblyInfo.js" }; var fullPath = Path.Combine(workingDir, assemblyInfoFile.First()); var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); var arguments = new Arguments { EnsureAssemblyInfo = true, UpdateAssemblyInfo = true, UpdateAssemblyInfoFileName = assemblyInfoFile }; using (new AssemblyInfoFileUpdate(arguments, workingDir, variables, fileSystem)) { fileSystem.Received(0).WriteAllText(fullPath, Arg.Any <string>()); } }
public void PropagatesErrorIfUpdateFails() { var timeEntry = Models.TimeEntry.Builder.Create(12) .SetStart(Now) .SetSyncStatus(SyncStatus.InSync) .SetDescription("") .SetUserId(11) .SetWorkspaceId(10) .SetAt(Now) .Build(); var timeEntryObservable = Observable.Return(timeEntry); var errorObservable = Observable.Throw <IDatabaseTimeEntry>(new DatabaseOperationException <IDatabaseTimeEntry>(new Exception())); Repository.GetById(Arg.Is(timeEntry.Id)).Returns(timeEntryObservable); Repository.Update(Arg.Any <long>(), Arg.Any <IDatabaseTimeEntry>()).Returns(errorObservable); var observer = Substitute.For <IObserver <Unit> >(); TimeEntriesSource.SoftDelete(timeEntry).Subscribe(observer); observer.Received().OnError(Arg.Any <DatabaseOperationException <IDatabaseTimeEntry> >()); }
public void IgnoresEmailIfNullOrEmpty() { var coreSettings = new CoreSettings { EnableAutomaticReports = true }; var endpoint = Substitute.For <IAnalyticsEndpoint>(); var client = new AnalyticsClient(endpoint); client.Initialize(coreSettings); client.RecordBugReport("blabla"); endpoint.DidNotReceiveWithAnyArgs().UpdateEmail(Arg.Any <string>()); client.RecordBugReport("blabla", String.Empty); endpoint.DidNotReceiveWithAnyArgs().UpdateEmail(Arg.Any <string>()); client.RecordBugReport("blabla", " "); endpoint.DidNotReceiveWithAnyArgs().UpdateEmail(null); }
public async Task PostRegister_ShouldRegisterUser() { var passwordHash = "abcdef"; var token = "123456"; var userGuid = new Guid(); _userService.RegisterUserAsync(Arg.Any <User>(), passwordHash, token, userGuid) .Returns(Task.FromResult(IdentityResult.Success)); var request = new RegisterRequestModel { Name = "Example User", Email = "*****@*****.**", MasterPasswordHash = passwordHash, MasterPasswordHint = "example", Token = token, OrganizationUserId = userGuid }; await _sut.PostRegister(request); await _userService.Received(1).RegisterUserAsync(Arg.Any <User>(), passwordHash, token, userGuid); }
public void Setup() { _fc = Substitute.For <IFieldConfiguration>(); _f = Substitute.For <IForm <TestFieldViewModel, IFormTemplate> >(); _f.Template.BeginField(_label, _field, _validation, _metadata, Arg.Any <IReadonlyFieldConfiguration>(), Arg.Any <bool>()).Returns(_beginHtml); _f.Template.Field(_label, _field, _validation, _metadata, Arg.Any <IReadonlyFieldConfiguration>(), Arg.Any <bool>()).Returns(_html); _f.Template.EndField().Returns(_endHtml); _g = Substitute.For <IFieldGenerator>(); _g.GetLabelHtml(Arg.Any <IReadonlyFieldConfiguration>()).Returns(_label); _g.GetFieldHtml(Arg.Any <IReadonlyFieldConfiguration>()).Returns(_field); _g.GetValidationHtml(Arg.Any <IReadonlyFieldConfiguration>()).Returns(_validation); _g.Metadata.Returns(_metadata); _g.GetFieldId().Returns(FieldId); var autoSubstitute = AutoSubstituteContainer.Create(); var helper = autoSubstitute.Resolve <HtmlHelper <TestFieldViewModel> >(); _f.HtmlHelper.Returns(helper); _f.GetFieldGenerator(Arg.Any <Expression <Func <TestFieldViewModel, string> > >()).Returns(_g); }
private string SetupExistingChannel() { Repository.Client.RootDocument.Returns(new RootResource { Links = new LinkCollection().Add("Channels", "DOES_NOT_MATTER") }); var projectName = $"Project-{Guid.NewGuid()}"; var project = new ProjectResource() { Links = new LinkCollection() }; project.Links.Add("Channels", "DOES_NOT_MATTER"); Repository.Projects.FindByName(projectName).Returns(project); var lifecycleName = $"Lifecycle-{Guid.NewGuid()}"; Repository.Lifecycles.FindOne(Arg.Any <Func <LifecycleResource, bool> >()) .Returns(new LifecycleResource { Id = lifecycleName }); var channelName = $"Channel-{Guid.NewGuid()}"; var channel = new ChannelResource() { Id = Guid.NewGuid().ToString(), Name = channelName }; Repository.Projects.GetChannels(Arg.Any <ProjectResource>()) .Returns(new ResourceCollection <ChannelResource>(new[] { channel }, new LinkCollection())); CommandLineArgs.Add($"--channel={channelName}"); CommandLineArgs.Add($"--project={projectName}"); CommandLineArgs.Add($"--lifecycle={lifecycleName}"); CommandLineArgs.Add("--update-existing"); return(channelName); }
public async Task Given_ValidInputs_When_Sort_Returns_SortedProducts() { // Arrange. _productSort1.SupportedSortOptions.Returns(new List <SortOptions> { SortOptions.ASCENDING, SortOptions.DESCENDING }); _productSort2.SupportedSortOptions.Returns(new List <SortOptions> { SortOptions.HIGH, SortOptions.LOW }); var products = _fixture.CreateMany <Product>(5).ToList(); _productsRepository.Get(Arg.Any <string>()).Returns(products); _productSort1.Sort(Arg.Any <SortOptions>(), Arg.Is <List <Product> >(products)).Returns(products); // Act. var result = await _sut.Sort("ASCENDING"); // Assert. result.SequenceEqual(products); }
public void Should_create_exchange_queue_and_put_error_to_queue() { // Arrange var durableConnection = Substitute.For <IDurableConnection>(); var model = Substitute.For <IModel>(); durableConnection.CreateChannel().Returns(model); var basicProperies = Substitute.For <IBasicProperties>(); model.CreateBasicProperties().Returns(basicProperies); var handler = new ConsumerErrorHandler(durableConnection, Substitute.For <ISerializer>(), Substitute.For <IRabbitWatcher>()); // Action handler.HandleError(new BasicDeliverEventArgs { Body = new byte[0], BasicProperties = basicProperies }, new Exception()); // Assert model.Received().BasicPublish(Arg.Any <string>(), string.Empty, basicProperies, Arg.Any <byte[]>()); }
public void Execute_ProperlyHandlesSitauationWhenKeysAreNotUsed() { var licenseDialog = Substitute.For <ILicenseDialog>(); var remoteMetaData = Substitute.For <IRemoteMetaData>(); remoteMetaData.GetAppInfo().Returns(new App() { UseKeys = false }); var localMetaData = Substitute.For <ILocalMetaData>(); var command = new ValidateLicenseCommand(licenseDialog, remoteMetaData, localMetaData, _cache, _logger, _issueReporter); command.Prepare(_statusMonitor); command.Execute(CancellationToken.Empty); Assert.AreEqual(command.KeySecret, null); remoteMetaData.DidNotReceive().GetKeySecret(Arg.Any <string>(), Arg.Any <string>()); licenseDialog.DidNotReceive().Display(Arg.Any <LicenseDialogMessageType>()); }
public void Should_Log_All_Analyzer_Errors_And_Throw() { // Given var fixture = new ScriptRunnerFixture(); fixture.ScriptAnalyzer = Substitute.For <IScriptAnalyzer>(); fixture.ScriptAnalyzer.Analyze(Arg.Any <FilePath>()) .Returns(new ScriptAnalyzerResult(new ScriptInformation(fixture.Script), new List <string>(), new List <ScriptAnalyzerError> { new ScriptAnalyzerError("/Working/script1.cake", 2, "Error in script 1"), new ScriptAnalyzerError("/Working/script2.cake", 7, "Error in script 2") })); var runner = fixture.CreateScriptRunner(); // When var exception = Record.Exception(() => runner.Run(fixture.Host, fixture.Script)); // Then AssertEx.IsCakeException(exception, "Errors occurred while analyzing script."); Assert.Contains(fixture.Log.Entries, x => x.Level == LogLevel.Error && x.Message == "/Working/script1.cake:2: Error in script 1"); Assert.Contains(fixture.Log.Entries, x => x.Level == LogLevel.Error && x.Message == "/Working/script2.cake:7: Error in script 2"); }
public void ProcessItem_ItemDoesNotExistInAllowedItems_DoesNotThrowException() { Guid itemGuid = Guid.NewGuid(); IItemData remoteData = Substitute.For <IItemData>(); remoteData.Id.Returns(itemGuid); GetSubstitute <IItemComparer>().Compare(Arg.Any <IItemData>(), Arg.Any <IItemData>()).Returns(CreateComparisonResult()); var contentItemInstaller = CreateInstance <ContentItemInstaller>(); contentItemInstaller.AllowedItems.Add(itemGuid); try { contentItemInstaller.ProcessItem(new PullItemModel { Preview = true }, Substitute.For <IItemData>(), remoteData); } catch (Exception ex) { Assert.True(false, $"A {ex.GetType()} exception was thrown: {ex.Message}"); } }
public void Get_headers_when_blocks_are_missing() { var svc = Build.A.SerializationService().WithEth().TestObject; var session = Substitute.For <ISession>(); var syncManager = Substitute.For <ISyncServer>(); var transactionPool = Substitute.For <ITxPool>(); syncManager.Find(null, Arg.Any <int>(), Arg.Any <int>(), Arg.Any <bool>()).Throws(new ArgumentNullException()); Block genesisBlock = Build.A.Block.Genesis.TestObject; syncManager.Head.Returns(genesisBlock.Header); syncManager.Genesis.Returns(genesisBlock.Header); var handler = new Eth62ProtocolHandler( session, svc, new NodeStatsManager(new StatsConfig(), LimboLogs.Instance), syncManager, LimboLogs.Instance, new PerfService(LimboLogs.Instance), transactionPool); handler.Init(); var msg = new GetBlockHeadersMessage(); msg.StartingBlockNumber = 1920000; msg.MaxHeaders = 3; msg.Skip = 1; msg.Reverse = 1; var statusMsg = new StatusMessage(); statusMsg.GenesisHash = genesisBlock.Hash; handler.HandleMessage(new Packet(Protocol.Eth, statusMsg.PacketType, svc.Serialize(statusMsg))); handler.HandleMessage(new Packet(Protocol.Eth, msg.PacketType, svc.Serialize(msg))); syncManager.Received().FindHeader(1920000); }
public async void GivenRequestForStudies_WhenRetrievingQueriableExtendedQueryTags_ReturnsStudyTags(QueryResource resourceType) { var request = new QueryResourceRequest( Substitute.For <IEnumerable <KeyValuePair <string, StringValues> > >(), resourceType, TestUidGenerator.Generate(), TestUidGenerator.Generate()); List <ExtendedQueryTagStoreEntry> storeEntries = new List <ExtendedQueryTagStoreEntry>() { new ExtendedQueryTagStoreEntry(1, "00741000", "CS", null, QueryTagLevel.Instance, ExtendedQueryTagStatus.Ready), new ExtendedQueryTagStoreEntry(2, "0040A121", "DA", null, QueryTagLevel.Series, ExtendedQueryTagStatus.Ready), new ExtendedQueryTagStoreEntry(3, "00101005", "PN", null, QueryTagLevel.Study, ExtendedQueryTagStatus.Ready), }; var list = QueryTagService.CoreQueryTags.Concat(storeEntries.Select(item => new QueryTag(item))).ToList(); _queryStore.QueryAsync(Arg.Any <QueryExpression>(), Arg.Any <CancellationToken>()).ReturnsForAnyArgs(new QueryResult(new List <VersionedInstanceIdentifier>())); await _queryService.QueryAsync(request, CancellationToken.None); _queryParser.Received().Parse(request, Arg.Do <IReadOnlyCollection <QueryTag> >(x => Assert.Equal(x, list, QueryTagComparer.Default))); }
public void Should_Return_CodeLensResolve_Descriptor() { // Given var handlerMatcher = new ResolveCommandMatcher(_logger); var resolveHandler = Substitute.For <ICodeLensResolveHandler>(); var resolveHandler2 = Substitute.For <ICodeLensResolveHandler>(); resolveHandler.CanResolve(Arg.Any <CodeLens>()).Returns(false); resolveHandler2.CanResolve(Arg.Any <CodeLens>()).Returns(true); // When var result = handlerMatcher.FindHandler(new CodeLens() { Data = JToken.FromObject(new { handlerType = typeof(ICodeLensResolveHandler).FullName, data = new { a = 1 } }) }, new List <HandlerDescriptor> { new HandlerDescriptor(DocumentNames.CodeLensResolve, "Key", resolveHandler, resolveHandler.GetType(), typeof(CodeLens), null, null, () => { }), new HandlerDescriptor(DocumentNames.CodeLensResolve, "Key2", resolveHandler2, typeof(ICodeLensResolveHandler), typeof(CodeLens), null, null, () => { }), }) .ToArray(); // Then result.Should().NotBeNullOrEmpty(); result.Should().Contain(x => x.Handler == resolveHandler2); }
public void ValueWithRandomAdded_should_hold_passed_value_plus_random_value() { using (new IndirectionsContext()) { // Arrange var notifyingObject = new NotifyingObject(); var mockNext = Substitute.For <IndirectionFunc <Random, int> >(); mockNext(Arg.Any <Random>()).Returns(10); PRandom.Next().Body = mockNext; // Act notifyingObject.ValueWithRandomAdded = 32; var actual = notifyingObject.ValueWithRandomAdded; // Assert mockNext.Received(1)(Arg.Any <Random>()); Assert.AreEqual(42, actual); } }
public void ContainsDelegatesToUnderlyingDictionary() { // given var jsonObjectDict = Substitute.For <IDictionary <string, JsonValue> >(); jsonObjectDict.ContainsKey(Arg.Any <string>()).Returns(true); var target = JsonObjectValue.FromDictionary(jsonObjectDict); // when var obtained = target.ContainsKey("foo"); // then Assert.That(obtained, Is.True); _ = jsonObjectDict.Received(1).ContainsKey("foo"); // and when obtained = target.ContainsKey("bar"); // then Assert.That(obtained, Is.True); _ = jsonObjectDict.Received(1).ContainsKey("bar"); }
public void Should_Register_The_Context() { // Given var services = Substitute.For <ICakeServices>(); var builder = Substitute.For <ICakeRegistrationBuilder>(); services.RegisterType(Arg.Any <Type>()).Returns(builder); // Return a builder object when registering builder.AsSelf().Returns(builder); // Return same builder object when chaining builder.As(Arg.Any <Type>()).Returns(builder); // Return same builder object when chaining // When services.UseContext <FrostingContext>(); // Then Received.InOrder(() => { services.RegisterType <FrostingContext>(); builder.AsSelf(); builder.As <IFrostingContext>(); builder.Singleton(); }); }
public void SleepTimeIsDoubledAndResetAfterSuccess() { httpClient.SendTimeSyncRequest().Returns( // request 1 fails 2 times x => null, x => null, x => null, x => null, x => null, x => CreateValidTimeResponse(currentTime, 10), // request 2 fails 1 time x => null, // other requets do not fail x => CreateValidTimeResponse(currentTime, 10), x => CreateValidTimeResponse(currentTime, 10), x => CreateValidTimeResponse(currentTime, 10), x => CreateValidTimeResponse(currentTime, 10) ); // when var target = new BeaconSendingTimeSyncState(); target.Execute(context); // then httpClient.Received(11).SendTimeSyncRequest(); context.Received(6).Sleep(Arg.Any <int>()); Received.InOrder(() => { // sleeps for first request context.Sleep(1000); // start with 1 sec context.Sleep(2000); // double context.Sleep(4000); // double context.Sleep(8000); // double context.Sleep(16000); // double // sleeps for second request context.Sleep(1000); // start with 1 sec again }); }
public async void GetUser_CalledWithValidId_ReturnsOkWithUser() { IUnitOfWork _unitOfWork = Substitute.For <IUnitOfWork>(); ICookieManager _cookieManager = Substitute.For <ICookieManager>(); IUserStore <User> _usersStore = Substitute.For <IUserStore <User> >(); var Id = "1"; User user = new User { Id = Id }; _unitOfWork.Users.Get(Arg.Any <Expression <Func <User, bool> > >()).Returns(user); var usersController = new UsersController(_unitOfWork, new UserManager <User>(_usersStore, null, null, null, null, null, null, null, null), _cookieManager); var result = await usersController.GetUser(Id); var okObjectResult = Assert.IsType <OkObjectResult>(result); var returnValue = Assert.IsType <User>(okObjectResult.Value); Assert.Equal(Id, returnValue.Id); }
private IInteractionInvoker BuildInvoker(string fileName) { var invoker = Substitute.For <IInteractionInvoker>(); invoker.When(x => x.Invoke(Arg.Any <SaveFileInteraction>())).Do(info => { var interaction = info.Arg <SaveFileInteraction>(); interaction.FileName = fileName; interaction.Success = true; }); invoker.When(x => x.Invoke(Arg.Any <OpenFileInteraction>())).Do(info => { var interaction = info.Arg <OpenFileInteraction>(); interaction.FileName = fileName; interaction.Success = true; }); invoker.When(x => x.Invoke(Arg.Any <MessageInteraction>())).Do(info => info.Arg <MessageInteraction>().Response = MessageResponse.Yes); return(invoker); }
public async void GetRole_CalledWithValidId_ReturnsOkWithUserRole() { IUnitOfWork _unitOfWork = Substitute.For <IUnitOfWork>(); ICookieManager _cookieManager = Substitute.For <ICookieManager>(); IUserStore <User> _usersStore = Substitute.For <IUserStore <User> >(); var testId = "1"; var role = "Student"; _unitOfWork.Users.Get(Arg.Any <Expression <Func <User, bool> > >()).Returns(new User { Role = role }); var usersController = new UsersController(_unitOfWork, new UserManager <User>(_usersStore, null, null, null, null, null, null, null, null), _cookieManager); var result = await usersController.GetRole(testId); var okObjectResult = Assert.IsType <OkObjectResult>(result); var returnValue = Assert.IsType <string>(okObjectResult.Value); Assert.Equal(role, returnValue); }
public void DeletesLockIfOwnedBySomeoneElseAndLockHasTimedOut() { var lockIo = Substitute.For <ILockIo>(); var name = Guid.NewGuid().ToString(); var processFinder = Substitute.For <IProcessFinder>(); processFinder.ProcessIsRunning(Arg.Any <int>(), Arg.Any <string>()).Returns(true); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder); //not setting processid/threadid, therefore its someone elses var fileLock = new FileLock { Timestamp = (DateTime.Now.Subtract(TimeSpan.FromMinutes(5))).Ticks }; lockIo.ReadLock(Arg.Any <string>()).Returns(fileLock); lockIo.LockExists(Arg.Any <string>()).Returns(true); lockIo.WriteLock(Arg.Any <string>(), Arg.Any <FileLock>()).Returns(true); var result = semaphore.TryAcquireLock(); Assert.That(result, Is.True); lockIo.Received().DeleteLock(Arg.Any <string>()); lockIo.Received().WriteLock(Arg.Any <string>(), Arg.Any <FileLock>()); }
public async Task ProcessPostActionShouldSucceed() { // Arrange var settings = new ProcessHttpSettings { Uri = new Uri("https://blip.ai"), Method = HttpMethod.Post.ToString(), Body = "{\"plan\":\"Premium\",\"details\":{\"address\": \"Rua X\"}}", Headers = new Dictionary <string, string>() { { "Content-Type", "application/json" }, { "Authorization", "Key askçjdhaklsdghasklgdasd=" } }, ResponseBodyVariable = "httpResultBody", ResponseStatusVariable = "httpResultStatus", }; var target = GetTarget(); var httpResponseMessage = new HttpResponseMessage() { StatusCode = HttpStatusCode.Accepted, Content = new StringContent("Some result") }; HttpClient.SendAsync(Arg.Any <HttpRequestMessage>(), Arg.Any <CancellationToken>()).Returns(httpResponseMessage); // Act await target.ExecuteAsync(Context, JObject.FromObject(settings), CancellationToken); // Assert await HttpClient.Received(1).SendAsync( Arg.Is <HttpRequestMessage>( h => h.RequestUri.Equals(settings.Uri)), Arg.Any <CancellationToken>()); await Context.Received(1).SetVariableAsync(settings.ResponseStatusVariable, ((int)HttpStatusCode.Accepted).ToString(), Arg.Any <CancellationToken>()); await Context.Received(1).SetVariableAsync(settings.ResponseBodyVariable, "Some result", Arg.Any <CancellationToken>()); }
public void can_provide_custom_locator_holiday_dayOfWeek_strategy() { var mockHolidayStrategy = Substitute.For <IHolidayStrategy>(); mockHolidayStrategy.IsHoliDay(Arg.Any <DateTime>()).Returns(true); var mockDayOfWeekStartegy = Substitute.For <IWorkingDayOfWeekStrategy>(); mockDayOfWeekStartegy.IsWorkingDay(Arg.Any <DayOfWeek>()).Returns(true); WorkingDayCultureInfo workingdayCultureInfo = new WorkingDayCultureInfo() { LocateHolidayStrategy = (n) => { return(mockHolidayStrategy); }, LocateWorkingDayOfWeekStrategy = (n) => { return(mockDayOfWeekStartegy); } }; DateTime marchFirst = new DateTime(1991, 3, 1); Assert.IsTrue(marchFirst.IsHoliday(workingdayCultureInfo)); Assert.IsFalse(marchFirst.IsWorkingDay(workingdayCultureInfo)); mockHolidayStrategy.Received().IsHoliDay(marchFirst); mockDayOfWeekStartegy.Received().IsWorkingDay(marchFirst.DayOfWeek); }
public async Task ProcessPostActionWithoutValidSettingsShouldFailed() { // Arrange var settings = new ProcessHttpSettings { Method = HttpMethod.Post.ToString(), Body = "{\"plan\":\"Premium\",\"details\":{\"address\": \"Rua X\"}}", Headers = new Dictionary <string, string>() { { "Content-Type", "application/json" }, { "Authorization", "Key askçjdhaklsdghasklgdasd=" } }, }; var target = GetTarget(); var httpResponseMessage = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent("Error") }; HttpClient.SendAsync(Arg.Any <HttpRequestMessage>(), Arg.Any <CancellationToken>()).Returns(httpResponseMessage); // Act try { await target.ExecuteAsync(Context, JObject.FromObject(settings), CancellationToken); throw new Exception(); } catch (ValidationException exception) { // Assert await HttpClient.DidNotReceive().SendAsync( Arg.Is <HttpRequestMessage>( h => h.RequestUri.Equals(settings.Uri)), Arg.Any <CancellationToken>()); } }