/// <summary> /// This method gets the estimate from MBE. /// </summary> /// <param name="claimId">Represents the claim id.</param> /// <returns>The serialized estimate.</returns> public async Task <string> GetEstimageForClaim(string claimId) { var estimateInputDataForMbe = new Dictionary <string, string> { { "claimId", claimId } }; var estimateInputData = JsonConvert.SerializeObject(estimateInputDataForMbe); var estimateInputContentJson = new StringContent(estimateInputData, Encoding.UTF8, "application/json"); HttpResponseMessage estimateResponse = await DownloadEstimateFromMbe(estimateInputContentJson); Console.WriteLine("[ {0} ] : GET ESTIMATE : Received response from MBE with reason phrase : [ {1} ] ", ApiHelpers.GetCurrentTimeStamp(DateTime.Now), estimateResponse.ReasonPhrase); if (_errorStatus.Contains(estimateResponse.ReasonPhrase, StringComparer.OrdinalIgnoreCase)) { await InMemoryStorage.Instance().FetchDriverToken(_mbeUrl); estimateResponse = await DownloadEstimateFromMbe(estimateInputContentJson); } if (estimateResponse.ReasonPhrase == "Not Found") { return(null); } string downloadEstimateContent = await estimateResponse.Content.ReadAsStringAsync(); return(downloadEstimateContent); }
/// <summary> /// Async tast to post claim video from MBE using GetVideoUrlForClaim() /// Uses AXN token and Generate DRIVERS token if expires /// </summary> /// <param name="claimData">Represents the claim data.</param> /// <returns></returns> public async Task <string> GetClaimVideo(object claimData) { VideoInput videoData = new VideoInput { claim = claimData, videoVersion = 1, userAgent = "" }; string claimJsonData = JsonConvert.SerializeObject(videoData); var claimContentJson = new StringContent(claimJsonData, Encoding.UTF8, "application/json"); var videoRsponse = await GetVideoUrlForClaim(claimContentJson); Console.WriteLine("[ {0} ] : GET VIDEO : Response received from MBE with reason phrase as : [ {1} ] ", ApiHelpers.GetCurrentTimeStamp(DateTime.Now), videoRsponse.ReasonPhrase); if (_errorStatus.Contains(videoRsponse.ReasonPhrase, StringComparer.OrdinalIgnoreCase)) { await InMemoryStorage.Instance().FetchDriverToken(_mbeUrl); videoRsponse = await GetVideoUrlForClaim(claimContentJson); } if (videoRsponse.ReasonPhrase == "Not Found") { return(null); } string videoResult = await videoRsponse.Content.ReadAsStringAsync(); return(videoResult); }
/// <summary> /// This method gets a get by it's ID. /// </summary> /// <returns>>The existing claim.</returns> /// <param name="claimId">Claim identifier.</param> public async Task <string> GetClaim(string claimId) { if (string.IsNullOrEmpty(claimId)) { throw new ArgumentNullException(nameof(claimId), "Cannot be null or empty."); } var claimResponse = await GetClaimFromMbe(claimId); Console.WriteLine("[ {0} ] : GET claim by ID : MBE endpoint returned with response phrase : [ {1} ] ", ApiHelpers.GetCurrentTimeStamp(DateTime.Now), claimResponse.ReasonPhrase); if (_errorStatus.Contains(claimResponse.ReasonPhrase, StringComparer.OrdinalIgnoreCase)) { await InMemoryStorage.Instance().FetchAccessToken(_mbeUrl); claimResponse = await GetClaimFromMbe(claimId); } else if (claimResponse.ReasonPhrase == "Not Found") { return(null); } var claimResult = await claimResponse.Content.ReadAsStringAsync(); Console.WriteLine("[ {0} ] : GET claim by ID : response received from MBE is : [ {1} ] ", ApiHelpers.GetCurrentTimeStamp(DateTime.Now), claimResult); return(claimResult); }
/// <summary> /// This method updates the vehivle VIN from a claim. /// </summary> /// <param name="vinInputData">Represents the vin input data.</param> /// <returns>The vehicle updation VIN response.</returns> public async Task <string> UpdateVehicleVin(vehicleUpdateInput vinInputData) { var jsonData = JsonConvert.SerializeObject(vinInputData); var jsonContent = new StringContent(jsonData, Encoding.UTF8, "application/json"); var vinDecodeData = await UpdateVehicleVintoMbe(jsonContent); Console.WriteLine("[ {0} ] : UPDATE VEHICLE : Response received from MBE with reason phrase as : [ {1} ]", ApiHelpers.GetCurrentTimeStamp(DateTime.Now), vinDecodeData.ReasonPhrase); if (_errorStatus.Contains(vinDecodeData.ReasonPhrase, StringComparer.OrdinalIgnoreCase)) { await InMemoryStorage.Instance().FetchDriverToken(_mbeUrl); vinDecodeData = await UpdateVehicleVintoMbe(jsonContent); } if (vinDecodeData.ReasonPhrase == "Not Found") { return(null); } var vinDecodeResults = vinDecodeData.Content.ReadAsStringAsync(); return(vinDecodeResults.Result); }
public static async Task StartAsync(int port) { IPAddress localAddr = await EndpointUtils.GetIPAsync(); IExpiryProvider expiryProvider = new StorageExpiryProvider(); IStorage storage = new InMemoryStorage(expiryProvider); IRequestProcessor requestProcessor = new RequestProcessor(storage); IProcessor processor = new SocketProcessor(); IListener server = new Listener(localAddr, port, processor, requestProcessor); server.Start(); var reset = new ManualResetEventSlim(); Console.CancelKeyPress += (sender, e) => { reset.Set(); }; reset.Wait(); // dispose components storage.Dispose(); server.Dispose(); }
public void OnRemoved() { // ths stateset is being removed. // TODO: we do this since InMemoryCache is static type. we might consider making it instance object // of something. InMemoryStorage.DropCache(Analyzer); }
public StorageService(StorageType storageType) { switch (storageType) { case StorageType.PlayerPrefs: StorageInstance = PlayerPrefsStorage.GetInstance(); Api = new PlayerPrefsApi(); break; case StorageType.FileStorage: StorageInstance = FileStorageStorage.GetInstance(); Api = new FileStorageApi(); break; case StorageType.InMemory: StorageInstance = InMemoryStorage.GetInstance(); Api = new InMemoryStorageApi(); break; default: throw new ArgumentOutOfRangeException(nameof(storageType), storageType, null); } OnChangeValue += StorageInstance.OnKeyValueUpdated; }
private ValueTask <ImmutableArray <DiagnosticData> > DeserializeDiagnosticsAsync( IPersistentStorageService persistentService, DiagnosticDataSerializer serializer, Project project, TextDocument?document, object key, string stateKey, CancellationToken cancellationToken ) { Contract.ThrowIfFalse(document == null || document.Project == project); if ( InMemoryStorage.TryGetValue(_owner.Analyzer, (key, stateKey), out var entry) && serializer.Version == entry.Version ) { return(ValueTaskFactory.FromResult(entry.Diagnostics)); } return(serializer.DeserializeAsync( persistentService, project, document, stateKey, cancellationToken )); }
public BotDomain(ISender sender, IReceiver receiver, IUserStorage storage, InMemoryStorage storageInMemory, Reminder reminder) { _sender = sender; _receiver = receiver; _storage = storage; _storageInMemory = storageInMemory; _reminder = reminder; List <Telegram.Storage.Core.UserItem> userItems = _storage.GetUsers(); foreach (var item in userItems) { DomainStatusEnum domainStatusEnum = DomainStatusEnum.User_Greeting; if (item.Status.Equals(StatusEnum.Admin)) { domainStatusEnum = DomainStatusEnum.Admin_Greeteng_Notification; } _storageInMemory.AddUser(new DomainUserItem() { ChatId = item.ChatId, DateOfRegistration = item.DateOfRegistration, FirstName = item.FirstName, Id = item.Id, Message = item.Message, Status = item.Status, DomainStatus = domainStatusEnum }); } _receiver.MessageReceived += Receiver_MeesageReciver; }
private Tuple <CollectionStorage, InMemoryStorage> CreateStorage() { var collectionStorage = new CollectionStorage(); var storage = new InMemoryStorage(collectionStorage); return(new Tuple <CollectionStorage, InMemoryStorage>(collectionStorage, storage)); }
public void InitializeTest() { var memoryStorage = new InMemoryStorage(); memoryStorage.Clear(); Assert.AreEqual(memoryStorage.Count(), 0); }
public void TestAddMessage() { var storage = new InMemoryStorage(); var context1 = new MessageContext() { Id = Guid.NewGuid(), Type = "request" }; var context2 = new MessageContext() { Id = Guid.NewGuid(), Type = "request" }; storage.Persist(CreateBeginRequestMessage(context1)); storage.Persist(CreateBeginRequestMessage(context2)); storage.Persist(CreateEndRequestMessage(context2)); storage.Persist(CreateEndRequestMessage(context1)); Guid[] idsToCheck = { context1.Id, context2.Id }; foreach (Guid requestId in idsToCheck) { var messages = storage.GetMessagesByRequestId(requestId); Assert.Equal(2, messages.Count()); foreach (IMessage m in messages) { Assert.Equal(requestId, m.Context.Id); } } // TODO - test store's other query mechanisms }
public async Task Contains_WorksCorrectly() { const int port = 9995; const string key = "key"; bool containsFromClientApi; bool containsFromStorage; IExpiryProvider expiryProvider = new StorageExpiryProvider(); using (IStorage storage = new InMemoryStorage(expiryProvider)) { var processor = new SocketProcessor(); var requestProcessor = new RequestProcessor(storage); using (IListener server = new Listener(IPAddress.Any, port, processor, requestProcessor)) { server.Start(); IKronosClient client = KronosClientFactory.CreateClient(localHost, port); containsFromClientApi = await client.ContainsAsync(key); containsFromStorage = storage.Contains(key); } } Assert.False(containsFromClientApi); Assert.Equal(containsFromClientApi, containsFromStorage); }
private Task <StrongBox <ImmutableArray <DiagnosticData> > > DeserializeAsync(DiagnosticDataSerializer serializer, object documentOrProject, object key, string stateKey, CancellationToken cancellationToken) { // when VS is loading new solution, we will try to find out all diagnostics persisted from previous VS session. // in that situation, it is possible that we have a lot of deserialization returning empty result. previously we used to // return default(ImmutableArray) for such case, but it turns out async/await framework has allocation issues with returning // default(value type), so we are using StrongBox to return no data as null. async/await has optimization where it will return // cached empty task if given value is null for reference type. (see AsyncMethodBuilder.GetTaskForResult) // // right now, we can't use Nullable either, since it is not one of value type the async/await will reuse cached task. in future, // if they do, we can change it to return Nullable<ImmutableArray> // // after initial deserialization, we track actual document/project that actually have diagnostics so no data won't be a common // case. // check cache first if (InMemoryStorage.TryGetValue(_owner.Analyzer, (key, stateKey), out var entry) && serializer.Version == entry.Version) { if (entry.Diagnostics.Length == 0) { // if there is no result, use cached task return(s_emptyResultTaskCache); } return(Task.FromResult(new StrongBox <ImmutableArray <DiagnosticData> >(entry.Diagnostics))); } // try to deserialize it return(serializer.DeserializeAsync(documentOrProject, stateKey, cancellationToken)); }
public async Task Insert_And_Count_WorksCorrectly() { const int port = 9997; const string key = "key"; byte[] data = Encoding.UTF8.GetBytes("lorem ipsum"); DateTime expiry = DateTime.MaxValue; int countFromClientApi; int countFromStorage; IExpiryProvider expiryProvider = new StorageExpiryProvider(); using (IStorage storage = new InMemoryStorage(expiryProvider)) { var processor = new SocketProcessor(); var requestProcessor = new RequestProcessor(storage); using (IListener server = new Listener(IPAddress.Any, port, processor, requestProcessor)) { server.Start(); IKronosClient client = KronosClientFactory.CreateClient(localHost, port); await client.InsertAsync(key, data, expiry); countFromClientApi = await client.CountAsync(); countFromStorage = storage.Count; } } Assert.Equal(countFromClientApi, 1); Assert.Equal(countFromClientApi, countFromStorage); }
public void OldEventsAreResentAfterFailure() { var firstEventGroup = new[] { new Event("TEST1", new List <KeyValuePair <string, object> >()) }; var secondEventGroup = new[] { new Event("TEST2", new List <KeyValuePair <string, object> >()) }; var senderMock = new Mock <IEventSender>(); var storageMock = new InMemoryStorage <IList <Event> >(); var storingEventSenderProxy = new StoringEventSenderProxy(senderMock.Object, storageMock); senderMock.Setup(s => s.SendEvents(firstEventGroup, It.IsAny <Action <bool> >())).Callback <IList <Event>, Action <bool> >((e, c) => c(false)); storingEventSenderProxy.SendEvents(firstEventGroup, isSuccess => { Assert.False(isSuccess); }); var successfullySent = new List <IList <Event> >(); senderMock.Setup(s => s.SendEvents(It.IsAny <IList <Event> >(), It.IsAny <Action <bool> >())) .Callback <IList <Event>, Action <bool> >((e, c) => { successfullySent.Add(e); c(true); }); storingEventSenderProxy.SendEvents(secondEventGroup, isSuccess => { Assert.True(isSuccess); }); Assert.Contains(firstEventGroup, successfullySent); Assert.Contains(secondEventGroup, successfullySent); Assert.Equal(2, successfullySent.Count); }
static void Main(string[] args) { const string buildUrl = "http://*****:*****@"C:\Users\Daniel\Documents\Visual Studio 2013\Projects\OwinSelfHost\Cache\"); var inMemoryStorage = new InMemoryStorage(); var client = builder .WithLoading(inMemoryStorage) .WithSaving(inMemoryStorage) .Build(); //builder.Splitter.Routes( // r => r.Logic(p => p.Contains("product")).Route(r => r.CacheToFile("fdff").EndPoint("fdsfdf")) // ); var logger = new RestClientLogger(client); using (var server = new Server(buildUrl, logger)) { System.Console.WriteLine("Press any key to close"); System.Console.ReadKey(); } }
public static void Main(string[] args) { const string connectionString = "Server=ProductiveDeveloperCode.database.windows.net;Database=TelegramDB;User Id=ProductiveDeveloper;Password=fDx-Vbt-Lvr-7Vg;"; SqlStorage sqlStorage = new SqlStorage(connectionString); InMemoryStorage inMemoryStorage = new InMemoryStorage(); TelegramReceiver reciver = new TelegramReceiver("984957183:AAECP59aHpYez0iBzmw_QBMb-sxMRgO5vpM"); TelegramSender telegramSender = new TelegramSender(reciver.botClient); Reminder reminder = new Reminder(telegramSender); BotDomain botDomain = new BotDomain(telegramSender, reciver, sqlStorage, inMemoryStorage, reminder); Console.WriteLine(reciver.GetHelloFromBot()); reciver.Run(); while (true) { Thread.Sleep(1800000); reminder.RemindersUpdate(); } }
public SearchProductsByTitleSteps() { _inMemoryStorage = new InMemoryStorage(); var queryFactory = new FindProductsByTitleQueryFactory(_inMemoryStorage); _controller = new ProductSearchController(queryFactory); }
public void Count_Users_Storage_InMemory_Tests_Method() { InMemoryStorage inMemoryStorage = new InMemoryStorage(); DomainUserItem user = new DomainUserItem() { ChatId = 12345678, DateOfRegistration = DateTimeOffset.Now, FirstName = "Null", Id = Guid.NewGuid(), Message = "Null", Status = StatusEnum.Null }; inMemoryStorage.AddUser(user); List <IDomainUserItem> userItems = inMemoryStorage.GetUsers(); Assert.AreEqual(1, userItems.Count); DomainUserItem user_2 = new DomainUserItem() { ChatId = 12345678, DateOfRegistration = DateTimeOffset.Now, FirstName = "Null", Id = Guid.NewGuid(), Message = "Null", Status = StatusEnum.Null }; inMemoryStorage.AddUser(user_2); userItems = inMemoryStorage.GetUsers(); Assert.AreEqual(2, userItems.Count); }
private ValueTask AddToInMemoryStorageAsync(VersionStamp serializerVersion, Project project, TextDocument?document, object key, string stateKey, ImmutableArray <DiagnosticData> diagnostics) { Contract.ThrowIfFalse(document == null || document.Project == project); // if serialization fail, hold it in the memory InMemoryStorage.Cache(_owner.Analyzer, (key, stateKey), new CacheEntry(serializerVersion, diagnostics)); return(default);
public void Remove_User_Storage_InMemory_Tests_Method() { InMemoryStorage inMemoryStorage = new InMemoryStorage(); Guid guid = Guid.NewGuid(); DomainUserItem user = new DomainUserItem() { ChatId = 12345678, DateOfRegistration = DateTimeOffset.Now, FirstName = "Null", Id = guid, Message = "Null", Status = StatusEnum.Null }; Guid guid2 = Guid.NewGuid(); DomainUserItem user2 = new DomainUserItem() { ChatId = 12345678, DateOfRegistration = DateTimeOffset.Now, FirstName = "Null", Id = guid2, Message = "Null", Status = StatusEnum.Null }; inMemoryStorage.AddUser(user); inMemoryStorage.AddUser(user2); Assert.AreEqual(inMemoryStorage.Count, 2); inMemoryStorage.RemoveUser(guid); Assert.AreEqual(inMemoryStorage.Count, 1); Assert.AreNotEqual(inMemoryStorage.GetUser(guid2).Id, guid); }
public void Clear_Users_Storage_InMemory_Tests_Method() { InMemoryStorage inMemoryStorage = new InMemoryStorage(); Guid guid = Guid.NewGuid(); DomainUserItem user = new DomainUserItem() { ChatId = 12345678, DateOfRegistration = DateTimeOffset.Now, FirstName = "Null", Id = guid, Message = "Null", Status = StatusEnum.Null }; Guid guid2 = Guid.NewGuid(); DomainUserItem user2 = new DomainUserItem() { ChatId = 12345678, DateOfRegistration = DateTimeOffset.Now, FirstName = "Null", Id = guid2, Message = "Null", Status = StatusEnum.Null }; inMemoryStorage.AddUser(user); inMemoryStorage.AddUser(user2); Assert.AreEqual(2, inMemoryStorage.Count); inMemoryStorage.Clear(); Assert.AreEqual(0, inMemoryStorage.Count); }
public void Add_User_Storage_InMemory_Tests_Method() { InMemoryStorage inMemoryStorage = new InMemoryStorage(); Guid guid = Guid.NewGuid(); DateTimeOffset date = DateTimeOffset.Now; DomainUserItem user = new DomainUserItem() { ChatId = 12345678, DateOfRegistration = date, FirstName = "Null", Id = guid, Message = "Null", Status = StatusEnum.Null }; inMemoryStorage.AddUser(user); List <IDomainUserItem> userItems = inMemoryStorage.GetUsers(); Assert.AreEqual(1, userItems.Count); foreach (var item in userItems) { Assert.AreEqual(item, user); } Assert.AreEqual(1, inMemoryStorage.Count); }
public void Test() { //var connectionString = "Data Source=lonweb1t.ashmore.local;Initial Catalog=AIMS_Data_QA;Persist Security Info=True;User ID=WPSuperUser;Password=Password1;MultipleActiveResultSets=True"; var connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Aims;Integrated Security=True"; var connectionFactory = new SqlConnectionFactory(connectionString); var dataManagerFactory = new DataManagerFactory(); var monitor = new Monitor(); var countryRepositoryStorage = new InMemoryStorage <CountryRepository>(); var countryManager = new CountryManager(countryRepositoryStorage); var securityStorage = new InMemoryStorage <SecurityRepository>(); var securityManager = new SecurityManager(securityStorage, monitor); var issuerRepositoryStorage = new InMemoryStorage <IssuerRepository>(); var issuerManager = new IssuerManager(monitor, issuerRepositoryStorage); var repositoryManager = new RepositoryManager(monitor, countryManager, securityManager, null, issuerManager); var modelBuilder = new ModelBuilder(); var manager = new Core.ModelManager(connectionFactory, dataManagerFactory, repositoryManager, modelBuilder); var commonSerializer = new Aims.Data.Server.Serializer(); var serializer = new Serializer(commonSerializer); var deserializer = new Deserializer(connectionFactory, dataManagerFactory, repositoryManager); var facade = new Facade(manager, commonSerializer, serializer, deserializer, connectionFactory, dataManagerFactory, repositoryManager); //ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings("Aims", @"Data Source=localhost\SQLEXPRESS;Initial Catalog=Aims;Integrated Security=True")); //ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings("AimsEntities", @"metadata=res://*/AimsModel.csdl|res://*/AimsModel.ssdl|res://*/AimsModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=lonweb1t.ashmore.local;Initial Catalog=AIMS_Data_QA;Persist Security Info=True;User ID=WPSuperUser;Password=Password1;MultipleActiveResultSets=True'")); //var found = facade.GetIssuerSecurities("SB", 1000, "RUSBERBPN __"); var model = facade.GetRootModel("RUSBERBPN"); //facade.GetIssuerSharesBySecurityShortName("RUSBERBPN"); }
public async Task CreateEntityDefinitionTest() { var storage = new InMemoryStorage(); var client = new ProjectClient(storage); Guid entityDefinitionId = Guid.NewGuid(); var entityDefinitionRequest = new CreateEntityDefinitionRequest() { Id = entityDefinitionId, Name = "Entity", Fields = new FieldDefinition[] {}, }; var entityDefinition = await client.CreateEntityDefinitionAsync(entityDefinitionRequest); Assert.NotNull(entityDefinition); Assert.Equal(entityDefinitionId, entityDefinition.Id); var retreived = await client.GetEntityDefinitionAsync(entityDefinitionId); Assert.NotNull(retreived); Assert.Equal(entityDefinitionRequest.Name, retreived.Name); }
internal static InMemoryStorage GetInstance() { if (tokenStorage == null) { tokenStorage = new InMemoryStorage(); } return(tokenStorage); }
private static IStorage CreateStorage() { ICleaner cleaner = Substitute.For <ICleaner>(); IScheduler scheduler = Substitute.For <IScheduler>(); IStorage storage = new InMemoryStorage(cleaner, scheduler); return(storage); }
public void ShouldBeAbleToReturnFalseWhenRemovingUserById() { InMemoryStorage storage = new InMemoryStorage(); var result = storage.RemoveUserById(-1); Assert.False(result); }
public void InMemoryStorageClassTest() { InMemoryStorage storage = new InMemoryStorage(); Tomato tomato = new Tomato(); storage.SetVegetableMinimumQuantity(tomato, 5); Assert.Equal(5, storage.GetVegetableMinimumQuantity(tomato)); }
public HttpClientChannelResource(IStorage storage, JsonSerializer jsonSerializer) { // TODO: This hack is needed to get around signalr problem jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); // TODO: Really shouldn't be here _store = (InMemoryStorage)storage; _jsonSerializer = jsonSerializer; }
public void SelfInitializing( InMemoryStorage inMemoryStorage, ILibraryService realServiceWhileRecording, ILibraryService realServiceDuringPlayback, int count1ForBook1WhileRecording, int count1ForBook1DuringPlayback, int count2ForBook1DuringPlayback, int count1ForBook2DuringPlayback) { "establish" .x(() => { inMemoryStorage = new InMemoryStorage(); realServiceWhileRecording = A.Fake<ILibraryService>(); realServiceDuringPlayback = A.Fake<ILibraryService>(); A.CallTo(() => realServiceWhileRecording.GetCount("9780345813923")) .ReturnsNextFromSequence(11, 10); A.CallTo(() => realServiceWhileRecording.GetCount("9781593078225")) .Returns(3); }); "when self initializing a fake" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var fakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceWhileRecording).RecordedBy(recorder)); count1ForBook1WhileRecording = fakeService.GetCount("9780345813923"); fakeService.GetCount("9781593078225"); fakeService.GetCount("9780345813923"); } using (var recorder = new RecordingManager(inMemoryStorage)) { var playbackFakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceDuringPlayback).RecordedBy(recorder)); count1ForBook1DuringPlayback = playbackFakeService.GetCount("9780345813923"); count1ForBook2DuringPlayback = playbackFakeService.GetCount("9781593078225"); count2ForBook1DuringPlayback = playbackFakeService.GetCount("9780345813923"); } }); "it should forward calls to the wrapped service while recording" .x(() => A.CallTo(() => realServiceWhileRecording.GetCount("9780345813923")) .MustHaveHappened(Repeated.Exactly.Twice)); "it should return the result while recording" .x(() => count1ForBook1WhileRecording.Should().Be(11)); "it should not forward calls to the wrapped service during playback" .x(() => A.CallTo(realServiceDuringPlayback).MustNotHaveHappened()); "it should return the recorded result for the first set of arguments" .x(() => count1ForBook1DuringPlayback.Should().Be(11)); "it should return the recorded result for the second set of arguments" .x(() => count1ForBook2DuringPlayback.Should().Be(3)); "it should return the second recorded result when arguments are repeated" .x(() => count2ForBook1DuringPlayback.Should().Be(10)); }
public static void SelfInitializingIgnoresParameterValues( InMemoryStorage inMemoryStorage, ILibraryService realServiceWhileRecording, ILibraryService realServiceDuringPlayback, IEnumerable<int> countsWhileRecording, IEnumerable<int> countsDuringPlayback) { "Given a call storage object" .x(() => inMemoryStorage = new InMemoryStorage()); "And a real service to wrap while recording" .x(() => { realServiceWhileRecording = A.Fake<ILibraryService>(); A.CallTo(() => realServiceWhileRecording.GetCount("1")) .Returns(0x1); A.CallTo(() => realServiceWhileRecording.GetCount("2")) .Returns(0x2); }); "And a real service to wrap while playing back" .x(() => realServiceDuringPlayback = A.Fake<ILibraryService>()); "When I use a self-initialized fake in recording mode to get the counts for book 2 and 1" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var fakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceWhileRecording).RecordedBy(recorder)); countsWhileRecording = new List<int> { fakeService.GetCount("2"), fakeService.GetCount("1") }; } }); "And I use a self-initialized fake in playback mode to get the counts for book 1 and 2" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var playbackFakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceDuringPlayback).RecordedBy(recorder)); countsDuringPlayback = new List<int> { playbackFakeService.GetCount("1"), playbackFakeService.GetCount("2"), }; } }); "Then the recording fake returns the wrapped service's results" .x(() => countsWhileRecording.Should().Equal(0x2, 0x1)); // These results demonstrate that the self-initialized fake relies on a script // defined by which methods are called, without regard to the arguments // passed to the methods. "And the playback fake returns results in 'recorded order'" .x(() => countsDuringPlayback.Should().Equal(0x2, 0x1)); }
public static void SelfInitializing( InMemoryStorage inMemoryStorage, ILibraryService realServiceWhileRecording, ILibraryService realServiceDuringPlayback, IEnumerable<int> countsWhileRecording, IEnumerable<int> countsDuringPlayback) { "Given a call storage object" .x(() => inMemoryStorage = new InMemoryStorage()); "And a real service to wrap while recording" .x(() => { realServiceWhileRecording = A.Fake<ILibraryService>(); A.CallTo(() => realServiceWhileRecording.GetCount("1")) .ReturnsNextFromSequence(0x1A, 0x1B); A.CallTo(() => realServiceWhileRecording.GetCount("2")) .Returns(0x2); }); "And a real service to wrap while playing back" .x(() => realServiceDuringPlayback = A.Fake<ILibraryService>()); "When I use a self-initialized fake in recording mode to get the counts for book 1, 2, and 1 again" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var fakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceWhileRecording).RecordedBy(recorder)); countsWhileRecording = new List<int> { fakeService.GetCount("1"), fakeService.GetCount("2"), fakeService.GetCount("1") }; } }); "And I use a self-initialized fake in playback mode to get the counts for book 1, 2, and 1 again" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var playbackFakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceDuringPlayback).RecordedBy(recorder)); countsDuringPlayback = new List<int> { playbackFakeService.GetCount("1"), playbackFakeService.GetCount("2"), playbackFakeService.GetCount("1") }; } }); "Then the recording fake forwards calls to the wrapped service" .x(() => A.CallTo(() => realServiceWhileRecording.GetCount("1")) .MustHaveHappened(Repeated.Exactly.Twice)); "And the recording fake returns the wrapped service's results" .x(() => countsWhileRecording.Should().Equal(0x1A, 0x2, 0x1B)); "And the playback fake does not forward calls to the wrapped service" .x(() => A.CallTo(realServiceDuringPlayback).MustNotHaveHappened()); "And the playback fake returns the recorded results" .x(() => countsDuringPlayback.Should().Equal(0x1A, 0x2, 0x1B)); }
public static void SelfInitializingThrowsIfTooManyCallsEncountered( InMemoryStorage inMemoryStorage, ILibraryService realServiceWhileRecording, ILibraryService realServiceDuringPlayback, Exception exception) { "Given a call storage object" .x(() => inMemoryStorage = new InMemoryStorage()); "And a real service to wrap while recording" .x(() => realServiceWhileRecording = A.Fake<ILibraryService>()); "And a real service to wrap while playing back" .x(() => realServiceDuringPlayback = A.Fake<ILibraryService>()); "When I use a self-initialized fake in recording mode to get the count and title for book 1" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var fakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceWhileRecording).RecordedBy(recorder)); fakeService.GetCount("1"); fakeService.GetTitle("1"); } }); "And I use a self-initialized fake in playback mode to get the count and title and count for book 1" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var playbackFakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceDuringPlayback).RecordedBy(recorder)); playbackFakeService.GetCount("1"); playbackFakeService.GetTitle("1"); exception = Record.Exception(() => playbackFakeService.GetCount("1")); } }); // This result demonstrates that the self-initialized fake relies on a script // defined by which methods are called, and is completely inflexible with // regard to the number of repetitions of the calls. "Then the playback fake throws a recording exception" .x(() => exception.Should().BeAnExceptionOfType<RecordingException>()); }
public static void SelfInitializingExceptionWhileRecording( InMemoryStorage inMemoryStorage, ILibraryService realServiceWhileRecording, ILibraryService realServiceDuringPlayback, Exception originalException, Exception exceptionWhileRecording, Exception exceptionWhilePlayingBack) { "Given a call storage object" .x(() => inMemoryStorage = new InMemoryStorage()); "And a real service to wrap while recording" .x(() => realServiceWhileRecording = A.Fake<ILibraryService>()); "And the real service throws an exception when getting the title for book 1" .x(() => { A.CallTo(() => realServiceWhileRecording.GetTitle("1")) .Throws(originalException = new InvalidOperationException()); }); "And a real service to wrap while playing back" .x(() => realServiceDuringPlayback = A.Fake<ILibraryService>()); "When I use a self-initialized fake in recording mode to get the title for book 1" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var fakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceWhileRecording).RecordedBy(recorder)); exceptionWhileRecording = Record.Exception(() => fakeService.GetTitle("1")); } }); "And I use a self-initialized fake in playback mode to get the title for book 1" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var fakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceDuringPlayback).RecordedBy(recorder)); exceptionWhilePlayingBack = Record.Exception(() => fakeService.GetTitle("1")); } }); "Then the recording fake throws the original exception" .x(() => exceptionWhileRecording.Should().BeSameAs(originalException)); "But the playback fake throws a recording exception" .x(() => exceptionWhilePlayingBack.Should().BeAnExceptionOfType<RecordingException>()); }
public static void SelfInitializingOutAndRef( InMemoryStorage inMemoryStorage, ILibraryService realServiceWhileRecording, ILibraryService realServiceDuringPlayback, int @out, int @ref) { "Given a call storage object" .x(() => inMemoryStorage = new InMemoryStorage()); "And a real service to wrap while recording" .x(() => { realServiceWhileRecording = A.Fake<ILibraryService>(); int localOut; int localRef = 0; A.CallTo(() => realServiceWhileRecording.TryToSetSomeOutAndRefParameters(out localOut, ref localRef)) .WithAnyArguments() .Returns(true) .AssignsOutAndRefParameters(19, 8); }); "And a real service to wrap while playing back" .x(() => realServiceDuringPlayback = A.Fake<ILibraryService>()); "When I use a self-initialized fake in recording mode to try to set some out and ref parameters" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var fakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceWhileRecording).RecordedBy(recorder)); int localOut; int localRef = 0; fakeService.TryToSetSomeOutAndRefParameters(out localOut, ref localRef); } }); "And I use a self-initialized fake in playback mode to try to set some out and ref parameters" .x(() => { using (var recorder = new RecordingManager(inMemoryStorage)) { var playbackFakeService = A.Fake<ILibraryService>(options => options .Wrapping(realServiceDuringPlayback).RecordedBy(recorder)); playbackFakeService.TryToSetSomeOutAndRefParameters(out @out, ref @ref); } }); "Then the playback fake sets the out parameter to the value seen in recording mode" .x(() => @out.Should().Be(19)); "And it sets the ref parameter to the value seen in recording mode" .x(() => @ref.Should().Be(8)); }