/// <summary> /// Initializes a new instance of the <see cref="ItemBenchmark"/> class. /// </summary> public ItemBenchmark() { this.clientForTests = MockDocumentClient.CreateMockCosmosClient(); this.container = this.clientForTests.GetDatabase("myDB").GetContainer("myColl"); this.baseItem = JObject.Parse(File.ReadAllText("samplepayload.json")); this.baseStream = File.OpenRead("samplepayload.json"); }
public void ValidateUriGenerationForResources() { string databaseId = "db1234"; string crId = "cr42"; string spId = "sp9001"; string trId = "tr9002"; string udfId = "udf9003"; CosmosClient mockClient = MockDocumentClient.CreateMockCosmosClient(); CosmosDatabaseCore db = new CosmosDatabaseCore(mockClient, databaseId); Assert.AreEqual(db.LinkUri.OriginalString, "/dbs/" + databaseId); CosmosContainerCore container = new CosmosContainerCore(db, crId); Assert.AreEqual(container.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId); CosmosStoredProcedureCore sp = new CosmosStoredProcedureCore(container, spId); Assert.AreEqual(sp.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/sprocs/" + spId); CosmosTrigger tr = new CosmosTrigger(container, trId); Assert.AreEqual(tr.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/triggers/" + trId); CosmosUserDefinedFunction udf = new CosmosUserDefinedFunction(container, udfId); Assert.AreEqual(udf.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/udfs/" + udfId); }
private static CosmosClient GetMockedClient() { DocumentClient documentClient = new MockDocumentClient(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder("http://localhost", Guid.NewGuid().ToString()); return(cosmosClientBuilder.Build(documentClient)); }
/// <summary> /// Initializes a new instance of the <see cref="ItemBenchmark"/> class. /// </summary> public ItemBenchmark() { this.clientForTests = MockDocumentClient.CreateMockCosmosClient(); this.container = this.clientForTests.GetDatabase("myDB").GetContainer("myColl"); this.baseItem = JObject.Parse(File.ReadAllText("samplepayload.json")); using (FileStream tmp = File.OpenRead("samplepayload.json")) { using (MemoryStream ms = new MemoryStream()) { tmp.CopyTo(ms); this.payloadBytes = ms.ToArray(); } } }
public async Task PopulateMissingRange() { DocumentServiceLeaseStoreManagerOptions options = new DocumentServiceLeaseStoreManagerOptions { HostName = Guid.NewGuid().ToString() }; DocumentServiceLeaseCore lease = new DocumentServiceLeaseCore() { LeaseToken = "0", Owner = Guid.NewGuid().ToString() }; Mock <DocumentServiceLeaseUpdater> mockUpdater = new Mock <DocumentServiceLeaseUpdater>(); Func <Func <DocumentServiceLease, DocumentServiceLease>, bool> validateUpdater = (Func <DocumentServiceLease, DocumentServiceLease> updater) => { // Simulate dirty read from db DocumentServiceLease afterUpdateLease = updater(lease); return(afterUpdateLease.FeedRange != null); }; mockUpdater.Setup(c => c.UpdateLeaseAsync( It.IsAny <DocumentServiceLease>(), It.IsAny <string>(), It.IsAny <PartitionKey>(), It.Is <Func <DocumentServiceLease, DocumentServiceLease> >(f => validateUpdater(f)))) .ReturnsAsync(lease); Mock <ContainerInternal> containerMock = new Mock <ContainerInternal>(); Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>(); containerMock.Setup(c => c.ClientContext).Returns(mockContext.Object); containerMock.Setup(c => c.LinkUri).Returns("http://localhot"); containerMock.Setup(c => c.GetCachedRIDAsync(It.IsAny <bool>(), It.IsAny <CancellationToken>())).ReturnsAsync("test"); MockDocumentClient mockDocumentClient = new MockDocumentClient(); mockContext.Setup(c => c.DocumentClient).Returns(mockDocumentClient); DocumentServiceLeaseManagerCosmos documentServiceLeaseManagerCosmos = new DocumentServiceLeaseManagerCosmos( containerMock.Object, Mock.Of <ContainerInternal>(), mockUpdater.Object, options, Mock.Of <RequestOptionsFactory>()); DocumentServiceLease afterAcquire = await documentServiceLeaseManagerCosmos.AcquireAsync(lease); Assert.IsNotNull(afterAcquire.FeedRange); }
/// <summary> /// Creates a CosmosClient with a mock TransportHandler that will capture and detect Exceptions happening inside ProcessChangesAsync. /// Since we want to be Exception-less, this will help detect if the Store Model is throwing or not. /// </summary> /// <param name="goThroughGateway">Whether or not to run the scenario using Gateway. If false, Direct will be used.</param> private static async Task <MockTransportHandler> TransportHandlerRunScenario(int responseStatusCode, bool goThroughGateway = true) { Func <HttpRequestMessage, Task <HttpResponseMessage> > sendFunc = async httpRequest => await Task.FromResult(new HttpResponseMessage((HttpStatusCode)responseStatusCode) { Content = new StringContent("{}"), RequestMessage = httpRequest }); Func <Uri, DocumentServiceRequest, StoreResponse> sendDirectFunc = (uri, request) => new StoreResponse() { ResponseBody = Stream.Null, Status = responseStatusCode, ResponseHeaderNames = Array.Empty <string>(), ResponseHeaderValues = Array.Empty <string>() }; // This is needed because in order to Mock a TransportClient we previously need an instance of CosmosClient CosmosClient internalClient = MockDocumentClient.CreateMockCosmosClient(); internalClient.DocumentClient.GatewayStoreModel = MockGatewayStoreModel(sendFunc); internalClient.DocumentClient.StoreModel = MockServerStoreModel(internalClient.DocumentClient.Session, sendDirectFunc); RetryHandler retryHandler = new RetryHandler(internalClient.DocumentClient.ResetSessionTokenRetryPolicy); MockTransportHandler transportHandler = new MockTransportHandler(internalClient); CosmosClient client = MockDocumentClient.CreateMockCosmosClient( (builder) => { builder .AddCustomHandlers(retryHandler, transportHandler); }); try { if (goThroughGateway) { CosmosDatabaseResponse response = await client.Databases.CreateDatabaseAsync("test"); } else { CosmosItemResponse <dynamic> response = await client.Databases["test"].Containers["test"].Items.CreateItemAsync <dynamic>(partitionKey: "id", item: new { id = "id" }); } } catch (CosmosException) { // Swallow CosmosExceptions as the point is to test the TransportHandler } return(transportHandler); }
/// <summary> /// Initializes a new instance of the <see cref="MockedItemBenchmark"/> class. /// </summary> public MockedItemBenchmarkHelper(bool useCustomSerializer = false) { this.TestClient = MockDocumentClient.CreateMockCosmosClient(useCustomSerializer); this.TestContainer = this.TestClient.GetDatabase("myDB").GetContainer("myColl"); using (FileStream tmp = File.OpenRead("samplepayload.json")) using (MemoryStream ms = new MemoryStream()) { tmp.CopyTo(ms); this.TestItemBytes = ms.ToArray(); } using (MemoryStream ms = new MemoryStream(this.TestItemBytes)) { string payloadContent = File.ReadAllText("samplepayload.json"); this.TestItem = JsonConvert.DeserializeObject <ToDoActivity>(payloadContent); } }
/// <summary> /// Initializes a new instance of the <see cref="MockedItemBenchmark"/> class. /// </summary> public MockedItemBenchmarkHelper( bool useCustomSerializer = false, bool includeDiagnosticsToString = false, bool useBulk = false, bool?isClientTelemetryEnabled = null) { this.TestClient = MockDocumentClient.CreateMockCosmosClient(useCustomSerializer, isClientTelemetryEnabled, (builder) => builder.WithBulkExecution(useBulk)); this.TestContainer = this.TestClient.GetDatabase("myDB").GetContainer("myColl"); this.IncludeDiagnosticsToString = includeDiagnosticsToString; using (FileStream tmp = File.OpenRead("samplepayload.json")) using (MemoryStream ms = new MemoryStream()) { tmp.CopyTo(ms); this.TestItemBytes = ms.ToArray(); } using (MemoryStream ms = new MemoryStream(this.TestItemBytes)) { string payloadContent = File.ReadAllText("samplepayload.json"); this.TestItem = JsonConvert.DeserializeObject <ToDoActivity>(payloadContent); } }
public async Task ShouldUseFeedRangeEpk() { int itemCount = 5; string pkRangeId = "0"; DateTime startTime = DateTime.UtcNow; Documents.Routing.Range <string> range = new Documents.Routing.Range <string>("AA", "BB", true, false); FeedRangeEpk feedRange = new FeedRangeEpk(range); DocumentServiceLeaseCoreEpk documentServiceLeaseCore = new DocumentServiceLeaseCoreEpk() { LeaseToken = pkRangeId, FeedRange = feedRange }; Mock <ContainerInternal> containerMock = new Mock <ContainerInternal>(); Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>(); mockContext.Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny <string>(), It.Is <Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.Is <Documents.OperationType>(rt => rt == Documents.OperationType.ReadFeed), It.Is <ChangeFeedRequestOptions>(cfo => cfo.PageSizeHint == itemCount), It.Is <ContainerInternal>(o => o == containerMock.Object), It.Is <FeedRange>(fr => fr is FeedRangeEpk), It.IsAny <Stream>(), It.IsAny <Action <RequestMessage> >(), It.IsAny <CosmosDiagnosticsContext>(), It.IsAny <ITrace>(), It.IsAny <CancellationToken>() ) ).ReturnsAsync(new ResponseMessage(System.Net.HttpStatusCode.OK)); containerMock.Setup(c => c.ClientContext).Returns(mockContext.Object); containerMock.Setup(c => c.LinkUri).Returns("http://localhot"); MockDocumentClient mockDocumentClient = new MockDocumentClient(); mockContext.Setup(c => c.DocumentClient).Returns(mockDocumentClient); ChangeFeedPartitionKeyResultSetIteratorCore iterator = ChangeFeedPartitionKeyResultSetIteratorCore.Create( lease: documentServiceLeaseCore, continuationToken: null, maxItemCount: itemCount, container: containerMock.Object, startTime: startTime, startFromBeginning: false); ResponseMessage response = await iterator.ReadNextAsync(); Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode); mockContext.Verify(c => c.ProcessResourceOperationStreamAsync( It.IsAny <string>(), It.Is <Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.Is <Documents.OperationType>(rt => rt == Documents.OperationType.ReadFeed), It.Is <ChangeFeedRequestOptions>(cfo => cfo.PageSizeHint == itemCount), It.Is <ContainerInternal>(o => o == containerMock.Object), It.Is <FeedRange>(fr => fr is FeedRangeEpk), It.IsAny <Stream>(), It.IsAny <Action <RequestMessage> >(), It.IsAny <CosmosDiagnosticsContext>(), It.IsAny <ITrace>(), It.IsAny <CancellationToken>() ), Times.Once); }
public async Task ShouldUseFeedRangeEpk() { int itemCount = 5; string pkRangeId = "0"; DateTime startTime = DateTime.UtcNow; Documents.Routing.Range <string> range = new Documents.Routing.Range <string>("AA", "BB", true, false); FeedRangeEpk feedRange = new FeedRangeEpk(range); DocumentServiceLeaseCoreEpk documentServiceLeaseCore = new DocumentServiceLeaseCoreEpk() { LeaseToken = pkRangeId, FeedRange = feedRange }; Mock <ContainerInternal> containerMock = new Mock <ContainerInternal>(); Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>(); mockContext.Setup(x => x.OperationHelperAsync <ResponseMessage>( It.Is <string>(str => str.Contains("Change Feed Processor")), It.IsAny <RequestOptions>(), It.IsAny <Func <ITrace, Task <ResponseMessage> > >(), It.IsAny <Func <ResponseMessage, OpenTelemetryAttributes> >(), It.Is <TraceComponent>(tc => tc == TraceComponent.ChangeFeed), It.IsAny <TraceLevel>())) .Returns <string, RequestOptions, Func <ITrace, Task <ResponseMessage> >, Func <ResponseMessage, OpenTelemetryAttributes>, TraceComponent, TraceLevel>( (operationName, requestOptions, func, oTelFunc, comp, level) => { using (ITrace trace = Trace.GetRootTrace(operationName, comp, level)) { return(func(trace)); } }); mockContext.Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny <string>(), It.Is <Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.Is <Documents.OperationType>(rt => rt == Documents.OperationType.ReadFeed), It.Is <ChangeFeedRequestOptions>(cfo => cfo.PageSizeHint == itemCount), It.Is <ContainerInternal>(o => o == containerMock.Object), It.Is <FeedRange>(fr => fr is FeedRangeEpk), It.IsAny <Stream>(), It.IsAny <Action <RequestMessage> >(), It.Is <ITrace>(t => !(t is NoOpTrace)), It.IsAny <CancellationToken>() ) ).ReturnsAsync(new ResponseMessage(System.Net.HttpStatusCode.OK)); containerMock.Setup(c => c.ClientContext).Returns(mockContext.Object); containerMock.Setup(c => c.LinkUri).Returns("http://localhot"); MockDocumentClient mockDocumentClient = new MockDocumentClient(); mockContext.Setup(c => c.DocumentClient).Returns(mockDocumentClient); ChangeFeedPartitionKeyResultSetIteratorCore iterator = ChangeFeedPartitionKeyResultSetIteratorCore.Create( lease: documentServiceLeaseCore, continuationToken: null, maxItemCount: itemCount, container: containerMock.Object, startTime: startTime, startFromBeginning: false); ResponseMessage response = await iterator.ReadNextAsync(); Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode); mockContext.Verify(c => c.ProcessResourceOperationStreamAsync( It.IsAny <string>(), It.Is <Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.Is <Documents.OperationType>(rt => rt == Documents.OperationType.ReadFeed), It.Is <ChangeFeedRequestOptions>(cfo => cfo.PageSizeHint == itemCount), It.Is <ContainerInternal>(o => o == containerMock.Object), It.Is <FeedRange>(fr => fr is FeedRangeEpk), It.IsAny <Stream>(), It.IsAny <Action <RequestMessage> >(), It.Is <ITrace>(t => !(t is NoOpTrace)), It.IsAny <CancellationToken>() ), Times.Once); }