How to use MockCosmosState class of ImageGallery.Tests.Mocks.Cosmos package

Best Coyote code snippet using ImageGallery.Tests.Mocks.Cosmos.MockCosmosState

UnitTests.cs

Source:UnitTests.cs Github

copy

Full Screen

...16 [TestMethod]17 public async Task TestConcurrentAccountRequestsAsync()18 {19 var logger = new MockLogger();20 var cosmosState = new MockCosmosState(logger);21 var client = new MockImageGalleryClient(cosmosState, logger);22 await client.InitializeCosmosDbAsync();23 // Try create a new account, and wait for it to be created before proceeding with the test.24 var account = new Account("0", "alice", "alice@coyote.com");25 var result = await client.CreateAccountAsync(account);26 Assert.IsTrue(result);27 var updatedAccount = new Account("0", "alice", "alice@microsoft.com");28 // Try update the account and delete it concurrently, which can cause a data race and a bug.29 var updateTask = client.UpdateAccountAsync(updatedAccount);30 var deleteTask = client.DeleteAccountAsync(updatedAccount.Id);31 // Wait for the two concurrent requests to complete.32 await Task.WhenAll(updateTask, deleteTask);33 // Bug: the update request can nondeterministically fail due to an unhandled exception (500 error code).34 // See the `Update` handler in the account controller for more info.35 _ = updateTask.Result;36 var deleteAccountRes = deleteTask.Result;37 // deleteAccountRes.EnsureSuccessStatusCode();38 Assert.IsTrue(deleteAccountRes);39 }40 [TestMethod]41 public async Task TestConcurrentAccountAndImageRequestsAsync()42 {43 var logger = new MockLogger();44 var cosmosState = new MockCosmosState(logger);45 var client = new MockImageGalleryClient(cosmosState, logger);46 IDatabaseProvider databaseProvider = await client.InitializeCosmosDbAsync();47 // Try create a new account, and wait for it to be created before proceeding with the test.48 var account = new Account("0", "alice", "alice@coyote.com");49 await client.CreateAccountAsync(account);50 // Try store the image and delete the account concurrently, which can cause a data race and a bug.51 var image = new Image(account.Id, "beach", Encoding.Default.GetBytes("waves"));52 var storeImageTask = client.CreateOrUpdateImageAsync(image);53 var deleteAccountTask = client.DeleteAccountAsync(account.Id);54 // Wait for the two concurrent requests to complete.55 await Task.WhenAll(storeImageTask, deleteAccountTask);56 // BUG: The above two concurrent requests can race and result into the image being stored57 // in an "orphan" container in Azure Storage, even if the associated account was deleted.58 // Check that the image was deleted from Azure Storage....

Full Screen

Full Screen

MockDatabaseProvider.cs

Source:MockDatabaseProvider.cs Github

copy

Full Screen

...14 /// </summary>15 internal class MockDatabaseProvider : IDatabaseProvider16 {17 private readonly string DatabaseName;18 private readonly MockCosmosState CosmosState;19 private readonly MockLogger Logger;20 internal MockDatabaseProvider(string databaseName, MockCosmosState cosmosState, MockLogger logger)21 {22 this.DatabaseName = databaseName;23 this.CosmosState = cosmosState;24 this.Logger = logger;25 }26 public async Task<IContainerProvider> CreateContainerAsync(string id, string partitionKeyPath)27 {28 // Used to model asynchrony in the request.29 await Task.Yield();30 this.Logger.LogInformation("Creating container '{0}' in database '{1}'.", id, this.DatabaseName);31 this.CosmosState.EnsureDatabaseExists(this.DatabaseName);32 var database = this.CosmosState.Databases[this.DatabaseName];33 if (string.IsNullOrEmpty(id))34 {35 throw MockCosmosState.CreateCosmosClientException(36 $"The container name cannot be empty",37 HttpStatusCode.BadRequest);38 }39 this.CosmosState.EnsureContainerDoesNotExistInDatabase(database, id);40 database[id] = new ConcurrentDictionary<PartitionKey, ConcurrentDictionary<string, object>>();41 return new MockContainerProvider(this.DatabaseName, id, this.CosmosState, this.Logger);42 }43 public async Task<IContainerProvider> CreateContainerIfNotExistsAsync(string id, string partitionKeyPath)44 {45 await Task.Yield();46 this.Logger.LogInformation("Creating container '{0}' in database '{1}' if it does not exist.", id, this.DatabaseName);47 this.CosmosState.EnsureDatabaseExists(this.DatabaseName);48 var database = this.CosmosState.Databases[this.DatabaseName];49 if (string.IsNullOrEmpty(id))50 {51 throw MockCosmosState.CreateCosmosClientException(52 $"The container name cannot be empty",53 HttpStatusCode.BadRequest);54 }55 if (!database.ContainsKey(id))56 {57 database[id] = new ConcurrentDictionary<PartitionKey, ConcurrentDictionary<string, object>>();58 }59 return new MockContainerProvider(this.DatabaseName, id, this.CosmosState, this.Logger);60 }61 public IContainerProvider GetContainer(string id)62 {63 this.Logger.LogInformation("Getting container '{0}' from database '{1}'.", id, this.DatabaseName);64 this.CosmosState.EnsureDatabaseExists(this.DatabaseName);65 var database = this.CosmosState.Databases[this.DatabaseName];...

Full Screen

Full Screen

MockClientProvider.cs

Source:MockClientProvider.cs Github

copy

Full Screen

...12 /// Mock implementation of an Azure Cosmos DB client provider.13 /// </summary>14 internal class MockClientProvider : IClientProvider15 {16 private readonly MockCosmosState CosmosState;17 private readonly MockLogger Logger;18 internal MockClientProvider(MockCosmosState cosmosState, MockLogger logger)19 {20 this.CosmosState = cosmosState;21 this.Logger = logger;22 }23 public async Task<IDatabaseProvider> CreateDatabaseAsync(string id)24 {25 // Used to model asynchrony in the request.26 await Task.Yield();27 this.Logger.LogInformation("Creating database '{0}'.", id);28 this.CosmosState.EnsureDatabaseDoesNotExist(id);29 this.CosmosState.Databases[id] = new ConcurrentDictionary<string,30 ConcurrentDictionary<PartitionKey, ConcurrentDictionary<string, object>>>();31 return new MockDatabaseProvider(id, this.CosmosState, this.Logger);32 }...

Full Screen

Full Screen

MockCosmosState

Using AI Code Generation

copy

Full Screen

1using ImageGallery.Tests.Mocks.Cosmos;2using Microsoft.AspNetCore.Hosting;3using Microsoft.AspNetCore.TestHost;4using Microsoft.Extensions.Configuration;5using Microsoft.Extensions.DependencyInjection;6using System;7using System.Collections.Generic;8using System.Linq;9using System.Net.Http;10using System.Text;11using System.Threading.Tasks;12using Xunit;13{14 {15 private readonly TestServer _server;16 private readonly HttpClient _client;17 public ImageGalleryTests()18 {19 _server = new TestServer(new WebHostBuilder()20 .UseStartup<Startup>()21 .ConfigureServices(services =>22 {23 var descriptor = services.SingleOrDefault(24 typeof(ICosmosStateRepository));25 if (descriptor != null)26 {27 services.Remove(descriptor);28 }29 services.AddSingleton<ICosmosStateRepository, MockCosmosState>();30 })31 .ConfigureAppConfiguration((builderContext, config) =>32 {33 config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);34 })35 );36 _client = _server.CreateClient();37 }38 public async Task TestGetImages()39 {40 var response = await _client.GetAsync("/api/images");41 response.EnsureSuccessStatusCode();42 var stringResponse = await response.Content.ReadAsStringAsync();43 Assert.Contains("image1", stringResponse);44 Assert.Contains("image2", stringResponse);45 Assert.Contains("image3", stringResponse);46 Assert.Contains("image4", stringResponse);47 Assert.Contains("image5", stringResponse);48 }49 }50}51using ImageGallery.Tests.Mocks.Cosmos;52using Microsoft.AspNetCore.Hosting;53using Microsoft.AspNetCore.TestHost;54using Microsoft.Extensions.Configuration;55using Microsoft.Extensions.DependencyInjection;56using System;57using System.Collections.Generic;58using System.Linq;59using System.Net.Http;60using System.Text;61using System.Threading.Tasks;62using Xunit;63{64 {65 private readonly TestServer _server;66 private readonly HttpClient _client;67 public ImageGalleryTests()68 {69 _server = new TestServer(new WebHostBuilder()70 .UseStartup<Startup>()

Full Screen

Full Screen

MockCosmosState

Using AI Code Generation

copy

Full Screen

1using ImageGallery.Tests.Mocks.Cosmos;2using Microsoft.Azure.Cosmos;3using Microsoft.Azure.Cosmos.Fluent;4using Microsoft.Extensions.Logging;5using System;6using System.Collections.Generic;7using System.Linq;8using System.Text;9using System.Threading.Tasks;10{11 {12 public List<MockContainer> Containers { get; set; }13 public List<MockDatabase> Databases { get; set; }14 public List<MockCosmosClient> Clients { get; set; }15 public List<MockCosmosClientBuilder> ClientBuilders { get; set; }16 public MockCosmosState()17 {18 Containers = new List<MockContainer>();19 Databases = new List<MockDatabase>();20 Clients = new List<MockCosmosClient>();21 ClientBuilders = new List<MockCosmosClientBuilder>();22 }23 }24}25using ImageGallery.Tests.Mocks.Cosmos;26using Microsoft.Azure.Cosmos;27using System;28using System.Collections.Generic;29using System.Linq;30using System.Text;31using System.Threading.Tasks;32{33 {34 public string Id { get; set; }35 public string DatabaseId { get; set; }36 public List<MockItem> Items { get; set; }37 public MockContainer(string id, string databaseId)38 {39 Id = id;40 DatabaseId = databaseId;41 Items = new List<MockItem>();42 }43 }44}45using ImageGallery.Tests.Mocks.Cosmos;46using System;47using System.Collections.Generic;48using System.Linq;49using System.Text;50using System.Threading.Tasks;51{52 {53 public string Id { get; set; }54 public string ContainerId { get; set; }55 public string DatabaseId { get; set; }56 public object Item { get; set; }57 }58}59using ImageGallery.Tests.Mocks.Cosmos;60using Microsoft.Azure.Cosmos;

Full Screen

Full Screen

MockCosmosState

Using AI Code Generation

copy

Full Screen

1using ImageGallery.Tests.Mocks.Cosmos;2using ImageGallery.Models;3using Microsoft.AspNetCore.Mvc;4using Microsoft.AspNetCore.Mvc.RazorPages;5using Microsoft.Extensions.Logging;6using System;7using System.Collections.Generic;8using System.Linq;9using System.Threading.Tasks;10{11 {12 private readonly ILogger<IndexModel> _logger;13 private readonly MockCosmosState _cosmosState;14 public IndexModel(ILogger<IndexModel> logger, MockCosmosState cosmosState)15 {16 _logger = logger;17 _cosmosState = cosmosState;18 }19 public List<Image> Images { get; set; }20 public async Task OnGetAsync()21 {22 Images = await _cosmosState.GetImagesAsync();23 }24 public async Task<IActionResult> OnPostDeleteAsync(string id)25 {26 await _cosmosState.DeleteImageAsync(id);27 return RedirectToPage();28 }29 }30}31using ImageGallery.Tests.Mocks.Cosmos;32using ImageGallery.Models;33using Microsoft.AspNetCore.Mvc;34using Microsoft.AspNetCore.Mvc.RazorPages;35using Microsoft.Extensions.Logging;36using System;37using System.Collections.Generic;38using System.Linq;39using System.Threading.Tasks;40{41 {42 private readonly ILogger<IndexModel> _logger;43 private readonly MockCosmosState _cosmosState;44 public IndexModel(ILogger<IndexModel> logger, MockCosmosState cosmosState)45 {46 _logger = logger;47 _cosmosState = cosmosState;48 }49 public List<Image> Images { get; set; }50 public async Task OnGetAsync()51 {52 Images = await _cosmosState.GetImagesAsync();53 }54 public async Task<IActionResult> OnPostDeleteAsync(string id)55 {56 await _cosmosState.DeleteImageAsync(id);57 return RedirectToPage();58 }59 }60}61using ImageGallery.Tests.Mocks.Cosmos;62using ImageGallery.Models;63using Microsoft.AspNetCore.Mvc;64using Microsoft.AspNetCore.Mvc.RazorPages;65using Microsoft.Extensions.Logging;66using System;67using System.Collections.Generic;68using System.Linq;

Full Screen

Full Screen

MockCosmosState

Using AI Code Generation

copy

Full Screen

1using Microsoft.AspNetCore.Mvc.Testing;2using System;3using System.Net.Http;4using System.Threading.Tasks;5using Xunit;6using Xunit.Abstractions;7{8 {9 private readonly WebApplicationFactory<Startup> _factory;10 private readonly ITestOutputHelper _output;11 public ImageGalleryTests(WebApplicationFactory<Startup> factory, ITestOutputHelper output)12 {13 _factory = factory;14 _output = output;15 }16 public async Task Test1()17 {18 var client = _factory.CreateClient();19 var response = await client.GetAsync("/");20 response.EnsureSuccessStatusCode();21 var responseString = await response.Content.ReadAsStringAsync();22 _output.WriteLine(responseString);23 }24 }25}

Full Screen

Full Screen

MockCosmosState

Using AI Code Generation

copy

Full Screen

1using ImageGallery.Tests.Mocks.Cosmos;2using Microsoft.Extensions.DependencyInjection;3using Microsoft.Extensions.Logging;4using Microsoft.Extensions.Options;5using System;6using System.Collections.Generic;7using System.Linq;8using System.Text;9using System.Threading.Tasks;10using Xunit;11{12 {13 public async Task TestCosmosState()14 {15 var services = new ServiceCollection();16 services.AddLogging();17 services.AddCosmosDb(MockCosmosState.CreateMockCosmosDbOptions());18 var sp = services.BuildServiceProvider();19 var logger = sp.GetService<ILoggerFactory>().CreateLogger<CosmosStateTests>();20 var cosmosDbService = sp.GetService<ICosmosDbService>();21 await cosmosDbService.AddItemAsync(newItem);22 var item = await cosmosDbService.GetItemAsync(newItem.Id);23 logger.LogInformation(item.Name);24 Assert.Equal(newItem.Name, item.Name);25 }26 }27}

Full Screen

Full Screen

MockCosmosState

Using AI Code Generation

copy

Full Screen

1using ImageGallery.Tests.Mocks.Cosmos;2using Microsoft.Azure.Cosmos;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Threading.Tasks;7{8 {9 private Container _container;10 public CosmosDBRepository(CosmosClient dbClient, string databaseName, string containerName)11 {12 _container = dbClient.GetContainer(databaseName, containerName);13 }14 public async Task AddItemAsync(T item)15 {16 await _container.CreateItemAsync<T>(item, new PartitionKey(item.GetType().GetProperty("Id").GetValue(item).ToString()));17 }18 public async Task DeleteItemAsync(string id)19 {20 await _container.DeleteItemAsync<T>(id, new PartitionKey(id));21 }22 public async Task<T> GetItemAsync(string id)23 {24 {25 ItemResponse<T> response = await _container.ReadItemAsync<T>(id, new PartitionKey(id));26 return response.Resource;27 }28 catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)29 {30 return null;31 }32 }33 public async Task<IEnumerable<T>> GetItemsAsync(string queryString)34 {35 var query = _container.GetItemQueryIterator<T>(new QueryDefinition(queryString));36 List<T> results = new List<T>();37 while (query.HasMoreResults)38 {39 var response = await query.ReadNextAsync();40 results.AddRange(response.ToList());41 }42 return results;43 }44 public async Task UpdateItemAsync(string id, T item)45 {46 await _container.UpsertItemAsync<T>(item, new PartitionKey(id));47 }48 }49}50using ImageGallery.Tests.Mocks.Cosmos;51using Microsoft.Azure.Cosmos;52using System;53using System.Collections.Generic;54using System.Linq;55using System.Threading.Tasks;56{57 {58 private Container _container;59 public CosmosDBRepository(CosmosClient dbClient, string databaseName, string containerName)60 {61 _container = dbClient.GetContainer(databaseName, containerName);62 }

Full Screen

Full Screen

MockCosmosState

Using AI Code Generation

copy

Full Screen

1var mockState = new MockCosmosState();2var mockStateProvider = new MockStateProvider();3mockStateProvider.Add(mockState);4var stateProvider = mockStateProvider.Object;5var mockLogger = new Mock<ILogger<ImageGalleryFunction>>().Object;6var mockContext = new Mock<ExecutionContext>().Object;7var mockReq = new Mock<HttpRequest>();8mockReq.Setup(req => req.Query).Returns(new QueryCollection(new Dictionary<string, string> { { "name", "test" } }));9var mockRes = new Mock<HttpResponse>();10var mockResObj = new Mock<HttpResponseObject>();11mockRes.Setup(res => res.Object).Returns(mockResObj.Object);12var mockResObjWriter = new Mock<TextWriter>();13mockResObj.Setup(obj => obj.Body).Returns(mockResObjWriter.Object);14var mockResObjWriterStream = new Mock<MemoryStream>();15mockResObjWriter.Setup(obj => obj.BaseStream).Returns(mockResObjWriterStream.Object);16var mockResWriter = new Mock<HttpResponseWriter>();17mockRes.Setup(res => res.Writer).Returns(mockResWriter.Object);18var mockResWriterStream = new Mock<MemoryStream>();19mockResWriter.Setup(w => w.BaseStream).Returns(mockResWriterStream.Object);20mockReq.Setup(req => req.CreateResponse()).Returns(mockRes.Object);21var req = mockReq.Object;22var res = mockRes.Object;23var context = mockContext;24var logger = mockLogger;25var state = stateProvider;26await ImageGalleryFunction.Run(req, res, state, logger, context);27Assert.Equal(200, res.StatusCode);28mockResObjWriterStream.Verify(w => w.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);29mockResObjWriterStream.Verify(w => w.WriteAsync(It.Is<byte[]>(b => b.Length > 0), It.IsAny<int>(), It.IsAny<int>()), Times.Once);30mockResObjWriterStream.Verify(w => w.WriteAsync(It.Is<byte[]>(b => Encoding.UTF8.GetString(b) == "Hello test"), It.IsAny<int>(), It.IsAny<int>()), Times.Once);31mockResWriterStream.Verify(w => w.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);32mockResWriterStream.Verify(w => w.WriteAsync(It.Is<byte[]>(b => b.Length > 0), It.IsAny<int>(), It.IsAny<int>()), Times.Once);33mockResWriterStream.Verify(w => w.WriteAsync(It.Is<byte

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Coyote automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful