/// <summary> /// Verify that running a one-shot push replication will complete when run against a /// mock server that returns 500 Internal Server errors on every request. /// </summary> /// <remarks> /// Verify that running a one-shot push replication will complete when run against a /// mock server that returns 500 Internal Server errors on every request. /// </remarks> /// <exception cref="System.Exception"></exception> public virtual void TestOneShotReplicationErrorNotification() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); Uri remote = GetReplicationURL(); manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient)); Replication pusher = database.CreatePushReplication(remote); RunReplication(pusher); NUnit.Framework.Assert.IsTrue(pusher.GetLastError() != null); }
/// <summary> /// Verify that running a continuous push replication will emit a change while /// in an error state when run against a mock server that returns 500 Internal Server /// errors on every request. /// </summary> /// <remarks> /// Verify that running a continuous push replication will emit a change while /// in an error state when run against a mock server that returns 500 Internal Server /// errors on every request. /// </remarks> /// <exception cref="System.Exception"></exception> public virtual void TestContinuousReplicationErrorNotification() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); Uri remote = GetReplicationURL(); manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient)); Replication pusher = database.CreatePushReplication(remote); pusher.SetContinuous(true); // add replication observer CountDownLatch countDownLatch = new CountDownLatch(1); LiteTestCase.ReplicationErrorObserver replicationErrorObserver = new LiteTestCase.ReplicationErrorObserver (countDownLatch); pusher.AddChangeListener(replicationErrorObserver); // start replication pusher.Start(); bool success = countDownLatch.Await(30, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); pusher.Stop(); }
/// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerInvalidJson() { Uri testURL = GetReplicationURL(); CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); ChangeTrackerClient client = new _ChangeTrackerClient_290(mockHttpClient); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, 0, client); BackgroundTask task = new _BackgroundTask_311(changeTracker); task.Execute(); try { // expected behavior: // when: // mockHttpClient throws IOExceptions -> it should start high and then back off and numTimesExecute should be low for (int i = 0; i < 30; i++) { int numTimesExectutedAfter10seconds = 0; try { Sharpen.Thread.Sleep(1000); // take a snapshot of num times the http client was called after 10 seconds if (i == 10) { numTimesExectutedAfter10seconds = mockHttpClient.GetCapturedRequests().Count; } // take another snapshot after 20 seconds have passed if (i == 20) { // by now it should have backed off, so the delta between 10s and 20s should be small int delta = mockHttpClient.GetCapturedRequests().Count - numTimesExectutedAfter10seconds; NUnit.Framework.Assert.IsTrue(delta < 25); } } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } } finally { changeTracker.Stop(); } }
public _HttpClientFactory_741(CustomizableMockHttpClient mockHttpClient) { this.mockHttpClient = mockHttpClient; }
public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); return mockHttpClient; }
public _ChangeTrackerClient_234(CountDownLatch changeTrackerFinishedSignal, CustomizableMockHttpClient mockHttpClient) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.mockHttpClient = mockHttpClient; }
/// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerBackoffInvalidJson() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderReturnInvalidChangesFeedJson(); TestChangeTrackerBackoff(mockHttpClient); }
/// <summary>Create a responder chain with a "sentinal".</summary> /// <remarks> /// Create a responder chain with a "sentinal". /// If and when the responders passed into responders are consumed, then the sentinal /// will handle all remaining requests to the responder chain. /// This is the version you want to use if you don't know ahead of time how many /// requests this responderchain will need to handle. /// </remarks> /// <param name="responders"> /// a list of responders, which will be "consumed" as soon /// as they respond to a request. /// </param> /// <param name="sentinal"> /// the final responder in the chain, which is "sticky" and won't /// be removed after handling a request. /// </param> public ResponderChain(Queue<CustomizableMockHttpClient.Responder> responders, CustomizableMockHttpClient.Responder sentinal) { this.responders = responders; this.sentinal = sentinal; }
/// <summary>https://github.com/couchbase/couchbase-lite-android/issues/247</summary> /// <exception cref="System.Exception"></exception> public virtual void RunPushReplicationWithTransientError(int statusCode, string statusMsg , bool expectReplicatorError) { IDictionary<string, object> properties1 = new Dictionary<string, object>(); properties1.Put("doc1", "testPushReplicationTransientError"); CreateDocWithProperties(properties1); CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); CustomizableMockHttpClient.Responder sentinal = CustomizableMockHttpClient.FakeBulkDocsResponder (); Queue<CustomizableMockHttpClient.Responder> responders = new List<CustomizableMockHttpClient.Responder >(); responders.AddItem(CustomizableMockHttpClient.TransientErrorResponder(statusCode, statusMsg)); ResponderChain responderChain = new ResponderChain(responders, sentinal); mockHttpClient.SetResponder("_bulk_docs", responderChain); // create a replication observer to wait until replication finishes CountDownLatch replicationDoneSignal = new CountDownLatch(1); LiteTestCase.ReplicationFinishedObserver replicationFinishedObserver = new LiteTestCase.ReplicationFinishedObserver (replicationDoneSignal); // create replication and add observer manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient)); Replication pusher = database.CreatePushReplication(GetReplicationURL()); pusher.AddChangeListener(replicationFinishedObserver); // save the checkpoint id for later usage string checkpointId = pusher.RemoteCheckpointDocID(); // kick off the replication pusher.Start(); // wait for it to finish bool success = replicationDoneSignal.Await(60, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); Log.D(Tag, "replicationDoneSignal finished"); if (expectReplicatorError == true) { NUnit.Framework.Assert.IsNotNull(pusher.GetLastError()); } else { NUnit.Framework.Assert.IsNull(pusher.GetLastError()); } // workaround for the fact that the replicationDoneSignal.wait() call will unblock before all // the statements in Replication.stopped() have even had a chance to execute. // (specifically the ones that come after the call to notifyChangeListeners()) Sharpen.Thread.Sleep(500); string localLastSequence = database.LastSequenceWithCheckpointId(checkpointId); if (expectReplicatorError == true) { NUnit.Framework.Assert.IsNull(localLastSequence); } else { NUnit.Framework.Assert.IsNotNull(localLastSequence); } }
/// <exception cref="System.Exception"></exception> public virtual void TestOnlineOfflinePusher() { Uri remote = GetReplicationURL(); // mock sync gateway CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); mockHttpClient.AddResponderRevDiffsSmartResponder(); HttpClientFactory mockHttpClientFactory = MockFactoryFactory(mockHttpClient); manager.SetDefaultHttpClientFactory(mockHttpClientFactory); // create a replication observer CountDownLatch replicationDoneSignal = new CountDownLatch(1); LiteTestCase.ReplicationFinishedObserver replicationFinishedObserver = new LiteTestCase.ReplicationFinishedObserver (replicationDoneSignal); // create a push replication Replication pusher = database.CreatePushReplication(remote); Log.D(Database.Tag, "created pusher: " + pusher); pusher.AddChangeListener(replicationFinishedObserver); pusher.SetContinuous(true); pusher.Start(); for (int i = 0; i < 5; i++) { Log.D(Database.Tag, "testOnlineOfflinePusher, i: " + i); string docFieldName = "testOnlineOfflinePusher" + i; // put the replication offline PutReplicationOffline(pusher); // add a response listener to wait for a bulk_docs request from the pusher CountDownLatch gotBulkDocsRequest = new CountDownLatch(1); CustomizableMockHttpClient.ResponseListener bulkDocsListener = new _ResponseListener_1334 (docFieldName, gotBulkDocsRequest); mockHttpClient.AddResponseListener(bulkDocsListener); // add a document string docFieldVal = "foo" + i; IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put(docFieldName, docFieldVal); CreateDocumentWithProperties(database, properties); // put the replication online, which should trigger it to send outgoing bulk_docs request PutReplicationOnline(pusher); // wait until we get a bulk docs request Log.D(Database.Tag, "waiting for bulk docs request with " + docFieldName); bool succeeded = gotBulkDocsRequest.Await(90, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(succeeded); Log.D(Database.Tag, "got bulk docs request with " + docFieldName); mockHttpClient.RemoveResponseListener(bulkDocsListener); mockHttpClient.ClearCapturedRequests(); } Log.D(Database.Tag, "calling pusher.stop()"); pusher.Stop(); Log.D(Database.Tag, "called pusher.stop()"); // wait for replication to finish Log.D(Database.Tag, "waiting for replicationDoneSignal"); bool didNotTimeOut = replicationDoneSignal.Await(90, TimeUnit.Seconds); Log.D(Database.Tag, "done waiting for replicationDoneSignal. didNotTimeOut: " + didNotTimeOut); NUnit.Framework.Assert.IsTrue(didNotTimeOut); NUnit.Framework.Assert.IsFalse(pusher.IsRunning()); }
/// <summary>Regression test for issue couchbase/couchbase-lite-android#174</summary> /// <exception cref="System.Exception"></exception> public virtual void TestAllLeafRevisionsArePushed() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderRevDiffsAllMissing(); mockHttpClient.SetResponseDelayMilliseconds(250); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_1165(mockHttpClient ); manager.SetDefaultHttpClientFactory(mockHttpClientFactory); Document doc = database.CreateDocument(); SavedRevision rev1a = doc.CreateRevision().Save(); SavedRevision rev2a = CreateRevisionWithRandomProps(rev1a, false); SavedRevision rev3a = CreateRevisionWithRandomProps(rev2a, false); // delete the branch we've been using, then create a new one to replace it SavedRevision rev4a = rev3a.DeleteDocument(); SavedRevision rev2b = CreateRevisionWithRandomProps(rev1a, true); NUnit.Framework.Assert.AreEqual(rev2b.GetId(), doc.GetCurrentRevisionId()); // sync with remote DB -- should push both leaf revisions Replication push = database.CreatePushReplication(GetReplicationURL()); RunReplication(push); NUnit.Framework.Assert.IsNull(push.GetLastError()); // find the _revs_diff captured request and decode into json bool foundRevsDiff = false; IList<HttpWebRequest> captured = mockHttpClient.GetCapturedRequests(); foreach (HttpWebRequest httpRequest in captured) { if (httpRequest is HttpPost) { HttpPost httpPost = (HttpPost)httpRequest; if (httpPost.GetURI().ToString().EndsWith("_revs_diff")) { foundRevsDiff = true; IDictionary<string, object> jsonMap = CustomizableMockHttpClient.GetJsonMapFromRequest (httpPost); // assert that it contains the expected revisions IList<string> revisionIds = (IList)jsonMap.Get(doc.GetId()); NUnit.Framework.Assert.AreEqual(2, revisionIds.Count); NUnit.Framework.Assert.IsTrue(revisionIds.Contains(rev4a.GetId())); NUnit.Framework.Assert.IsTrue(revisionIds.Contains(rev2b.GetId())); } } } NUnit.Framework.Assert.IsTrue(foundRevsDiff); }
private HttpClientFactory MockFactoryFactory(CustomizableMockHttpClient mockHttpClient ) { return new _HttpClientFactory_128(mockHttpClient); }
public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); CustomizableMockHttpClient.Responder sentinal = this.DefaultChangesResponder(); Queue<CustomizableMockHttpClient.Responder> responders = new List<CustomizableMockHttpClient.Responder >(); responders.AddItem(this.DefaultChangesResponder()); responders.AddItem(CustomizableMockHttpClient.TransientErrorResponder(errorCode, statusMessage)); ResponderChain responderChain = new ResponderChain(responders, sentinal); mockHttpClient.SetResponder("_changes", responderChain); return mockHttpClient; }
public HttpClient GetHttpClient() { if (useMockReplicator) { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.SetResponder("_changes", new _Responder_62()); return mockHttpClient; } else { return new DefaultHttpClient(); } }
/// <summary>Regression test for https://github.com/couchbase/couchbase-lite-java-core/issues/72 /// </summary> /// <exception cref="System.Exception"></exception> public virtual void TestPusherBatching() { // create a bunch (INBOX_CAPACITY * 2) local documents int numDocsToSend = Replication.InboxCapacity * 2; for (int i = 0; i < numDocsToSend; i++) { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("testPusherBatching", i); CreateDocumentWithProperties(database, properties); } // kick off a one time push replication to a mock CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); HttpClientFactory mockHttpClientFactory = MockFactoryFactory(mockHttpClient); Uri remote = GetReplicationURL(); manager.SetDefaultHttpClientFactory(mockHttpClientFactory); Replication pusher = database.CreatePushReplication(remote); RunReplication(pusher); NUnit.Framework.Assert.IsNull(pusher.GetLastError()); int numDocsSent = 0; // verify that only INBOX_SIZE documents are included in any given bulk post request IList<HttpWebRequest> capturedRequests = mockHttpClient.GetCapturedRequests(); foreach (HttpWebRequest capturedRequest in capturedRequests) { if (capturedRequest is HttpPost) { HttpPost capturedPostRequest = (HttpPost)capturedRequest; if (capturedPostRequest.GetURI().GetPath().EndsWith("_bulk_docs")) { ArrayList docs = CustomizableMockHttpClient.ExtractDocsFromBulkDocsPost(capturedRequest ); string msg = "# of bulk docs pushed should be <= INBOX_CAPACITY"; NUnit.Framework.Assert.IsTrue(msg, docs.Count <= Replication.InboxCapacity); numDocsSent += docs.Count; } } } NUnit.Framework.Assert.AreEqual(numDocsToSend, numDocsSent); }
/// <summary>https://github.com/couchbase/couchbase-lite-java-core/issues/95</summary> /// <exception cref="System.Exception"></exception> public virtual void TestPushReplicationCanMissDocs() { NUnit.Framework.Assert.AreEqual(0, database.GetLastSequenceNumber()); IDictionary<string, object> properties1 = new Dictionary<string, object>(); properties1.Put("doc1", "testPushReplicationCanMissDocs"); Document doc1 = CreateDocWithProperties(properties1); IDictionary<string, object> properties2 = new Dictionary<string, object>(); properties1.Put("doc2", "testPushReplicationCanMissDocs"); Document doc2 = CreateDocWithProperties(properties2); UnsavedRevision doc2UnsavedRev = doc2.CreateRevision(); InputStream attachmentStream = GetAsset("attachment.png"); doc2UnsavedRev.SetAttachment("attachment.png", "image/png", attachmentStream); SavedRevision doc2Rev = doc2UnsavedRev.Save(); NUnit.Framework.Assert.IsNotNull(doc2Rev); CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); mockHttpClient.SetResponder("_bulk_docs", new _Responder_1506()); mockHttpClient.SetResponder(doc2.GetId(), new _Responder_1514(doc2)); // create a replication obeserver to wait until replication finishes CountDownLatch replicationDoneSignal = new CountDownLatch(1); LiteTestCase.ReplicationFinishedObserver replicationFinishedObserver = new LiteTestCase.ReplicationFinishedObserver (replicationDoneSignal); // create replication and add observer manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient)); Replication pusher = database.CreatePushReplication(GetReplicationURL()); pusher.AddChangeListener(replicationFinishedObserver); // save the checkpoint id for later usage string checkpointId = pusher.RemoteCheckpointDocID(); // kick off the replication pusher.Start(); // wait for it to finish bool success = replicationDoneSignal.Await(60, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); Log.D(Tag, "replicationDoneSignal finished"); // we would expect it to have recorded an error because one of the docs (the one without the attachment) // will have failed. NUnit.Framework.Assert.IsNotNull(pusher.GetLastError()); // workaround for the fact that the replicationDoneSignal.wait() call will unblock before all // the statements in Replication.stopped() have even had a chance to execute. // (specifically the ones that come after the call to notifyChangeListeners()) Sharpen.Thread.Sleep(500); string localLastSequence = database.LastSequenceWithCheckpointId(checkpointId); Log.D(Tag, "database.lastSequenceWithCheckpointId(): " + localLastSequence); Log.D(Tag, "doc2.getCurrentRevision().getSequence(): " + doc2.GetCurrentRevision( ).GetSequence()); string msg = "Since doc1 failed, the database should _not_ have had its lastSequence bumped" + " to doc2's sequence number. If it did, it's bug: github.com/couchbase/couchbase-lite-java-core/issues/95"; NUnit.Framework.Assert.IsFalse(msg, System.Convert.ToString(doc2.GetCurrentRevision ().GetSequence()).Equals(localLastSequence)); NUnit.Framework.Assert.IsNull(localLastSequence); NUnit.Framework.Assert.IsTrue(doc2.GetCurrentRevision().GetSequence() > 0); }
// Reproduces issue #167 // https://github.com/couchbase/couchbase-lite-android/issues/167 /// <exception cref="System.Exception"></exception> public virtual void TestPushPurgedDoc() { int numBulkDocRequests = 0; HttpPost lastBulkDocsRequest = null; IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("testName", "testPurgeDocument"); Document doc = CreateDocumentWithProperties(database, properties); NUnit.Framework.Assert.IsNotNull(doc); CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderRevDiffsAllMissing(); mockHttpClient.SetResponseDelayMilliseconds(250); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_169(mockHttpClient ); Uri remote = GetReplicationURL(); manager.SetDefaultHttpClientFactory(mockHttpClientFactory); Replication pusher = database.CreatePushReplication(remote); pusher.SetContinuous(true); CountDownLatch replicationCaughtUpSignal = new CountDownLatch(1); pusher.AddChangeListener(new _ChangeListener_199(replicationCaughtUpSignal)); pusher.Start(); // wait until that doc is pushed bool didNotTimeOut = replicationCaughtUpSignal.Await(60, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(didNotTimeOut); // at this point, we should have captured exactly 1 bulk docs request numBulkDocRequests = 0; foreach (HttpWebRequest capturedRequest in mockHttpClient.GetCapturedRequests()) { if (capturedRequest is HttpPost && ((HttpPost)capturedRequest).GetURI().ToString( ).EndsWith("_bulk_docs")) { lastBulkDocsRequest = (HttpPost)capturedRequest; numBulkDocRequests += 1; } } NUnit.Framework.Assert.AreEqual(1, numBulkDocRequests); // that bulk docs request should have the "start" key under its _revisions IDictionary<string, object> jsonMap = CustomizableMockHttpClient.GetJsonMapFromRequest ((HttpPost)lastBulkDocsRequest); IList docs = (IList)jsonMap.Get("docs"); IDictionary<string, object> onlyDoc = (IDictionary)docs[0]; IDictionary<string, object> revisions = (IDictionary)onlyDoc.Get("_revisions"); NUnit.Framework.Assert.IsTrue(revisions.ContainsKey("start")); // now add a new revision, which will trigger the pusher to try to push it properties = new Dictionary<string, object>(); properties.Put("testName2", "update doc"); UnsavedRevision unsavedRevision = doc.CreateRevision(); unsavedRevision.SetUserProperties(properties); unsavedRevision.Save(); // but then immediately purge it doc.Purge(); // wait for a while to give the replicator a chance to push it // (it should not actually push anything) Sharpen.Thread.Sleep(5 * 1000); // we should not have gotten any more _bulk_docs requests, because // the replicator should not have pushed anything else. // (in the case of the bug, it was trying to push the purged revision) numBulkDocRequests = 0; foreach (HttpWebRequest capturedRequest_1 in mockHttpClient.GetCapturedRequests()) { if (capturedRequest_1 is HttpPost && ((HttpPost)capturedRequest_1).GetURI().ToString ().EndsWith("_bulk_docs")) { numBulkDocRequests += 1; } } NUnit.Framework.Assert.AreEqual(1, numBulkDocRequests); pusher.Stop(); }
/// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerBackoffExceptions() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); TestChangeTrackerBackoff(mockHttpClient); }
/// <summary>https://github.com/couchbase/couchbase-lite-android/issues/66</summary> /// <exception cref="System.Exception"></exception> public virtual void TestPushUpdatedDocWithoutReSendingAttachments() { NUnit.Framework.Assert.AreEqual(0, database.GetLastSequenceNumber()); IDictionary<string, object> properties1 = new Dictionary<string, object>(); properties1.Put("dynamic", 1); Document doc = CreateDocWithProperties(properties1); SavedRevision doc1Rev = doc.GetCurrentRevision(); // Add attachment to document UnsavedRevision doc2UnsavedRev = doc.CreateRevision(); InputStream attachmentStream = GetAsset("attachment.png"); doc2UnsavedRev.SetAttachment("attachment.png", "image/png", attachmentStream); SavedRevision doc2Rev = doc2UnsavedRev.Save(); NUnit.Framework.Assert.IsNotNull(doc2Rev); CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); // http://url/db/foo (foo==docid) mockHttpClient.SetResponder(doc.GetId(), new _Responder_1593(doc)); // create replication and add observer manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient)); Replication pusher = database.CreatePushReplication(GetReplicationURL()); RunReplication(pusher); IList<HttpWebRequest> captured = mockHttpClient.GetCapturedRequests(); foreach (HttpWebRequest httpRequest in captured) { // verify that there are no PUT requests with attachments if (httpRequest is HttpPut) { HttpPut httpPut = (HttpPut)httpRequest; HttpEntity entity = httpPut.GetEntity(); } } //assertFalse("PUT request with updated doc properties contains attachment", entity instanceof MultipartEntity); mockHttpClient.ClearCapturedRequests(); Document oldDoc = database.GetDocument(doc.GetId()); UnsavedRevision aUnsavedRev = oldDoc.CreateRevision(); IDictionary<string, object> prop = new Dictionary<string, object>(); prop.PutAll(oldDoc.GetProperties()); prop.Put("dynamic", (int)oldDoc.GetProperty("dynamic") + 1); aUnsavedRev.SetProperties(prop); SavedRevision savedRev = aUnsavedRev.Save(); mockHttpClient.SetResponder(doc.GetId(), new _Responder_1630(doc, savedRev)); string json = string.Format("{\"%s\":{\"missing\":[\"%s\"],\"possible_ancestors\":[\"%s\",\"%s\"]}}" , doc.GetId(), savedRev.GetId(), doc1Rev.GetId(), doc2Rev.GetId()); mockHttpClient.SetResponder("_revs_diff", new _Responder_1642(mockHttpClient, json )); pusher = database.CreatePushReplication(GetReplicationURL()); RunReplication(pusher); captured = mockHttpClient.GetCapturedRequests(); foreach (HttpWebRequest httpRequest_1 in captured) { // verify that there are no PUT requests with attachments if (httpRequest_1 is HttpPut) { HttpPut httpPut = (HttpPut)httpRequest_1; HttpEntity entity = httpPut.GetEntity(); NUnit.Framework.Assert.IsFalse("PUT request with updated doc properties contains attachment" , entity is MultipartEntity); } } }
/// <exception cref="System.Exception"></exception> private void TestChangeTrackerBackoff(CustomizableMockHttpClient mockHttpClient) { Uri testURL = GetReplicationURL(); CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); ChangeTrackerClient client = new _ChangeTrackerClient_234(changeTrackerFinishedSignal , mockHttpClient); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, false, 0, client); changeTracker.Start(); // sleep for a few seconds Sharpen.Thread.Sleep(5 * 1000); // make sure we got less than 10 requests in those 10 seconds (if it was hammering, we'd get a lot more) NUnit.Framework.Assert.IsTrue(mockHttpClient.GetCapturedRequests().Count < 25); NUnit.Framework.Assert.IsTrue(changeTracker.backoff.GetNumAttempts() > 0); mockHttpClient.ClearResponders(); mockHttpClient.AddResponderReturnEmptyChangesFeed(); // at this point, the change tracker backoff should cause it to sleep for about 3 seconds // and so lets wait 3 seconds until it wakes up and starts getting valid responses Sharpen.Thread.Sleep(3 * 1000); // now find the delta in requests received in a 2s period int before = mockHttpClient.GetCapturedRequests().Count; Sharpen.Thread.Sleep(2 * 1000); int after = mockHttpClient.GetCapturedRequests().Count; // assert that the delta is high, because at this point the change tracker should // be hammering away NUnit.Framework.Assert.IsTrue((after - before) > 25); // the backoff numAttempts should have been reset to 0 NUnit.Framework.Assert.IsTrue(changeTracker.backoff.GetNumAttempts() == 0); changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } }
public _Responder_1642(CustomizableMockHttpClient mockHttpClient, string json) { this.mockHttpClient = mockHttpClient; this.json = json; }
public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); int statusCode = 500; mockHttpClient.AddResponderFailAllRequests(statusCode); return mockHttpClient; }
/// <summary>https://github.com/couchbase/couchbase-lite-java-core/issues/188</summary> /// <exception cref="System.Exception"></exception> public virtual void TestServerDoesNotSupportMultipart() { NUnit.Framework.Assert.AreEqual(0, database.GetLastSequenceNumber()); IDictionary<string, object> properties1 = new Dictionary<string, object>(); properties1.Put("dynamic", 1); Document doc = CreateDocWithProperties(properties1); SavedRevision doc1Rev = doc.GetCurrentRevision(); // Add attachment to document UnsavedRevision doc2UnsavedRev = doc.CreateRevision(); InputStream attachmentStream = GetAsset("attachment.png"); doc2UnsavedRev.SetAttachment("attachment.png", "image/png", attachmentStream); SavedRevision doc2Rev = doc2UnsavedRev.Save(); NUnit.Framework.Assert.IsNotNull(doc2Rev); CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); Queue<CustomizableMockHttpClient.Responder> responders = new List<CustomizableMockHttpClient.Responder >(); //first http://url/db/foo (foo==docid) //Reject multipart PUT with response code 415 responders.AddItem(new _Responder_1691()); // second http://url/db/foo (foo==docid) // second call should be plain json, return good response responders.AddItem(new _Responder_1701(doc)); ResponderChain responderChain = new ResponderChain(responders); mockHttpClient.SetResponder(doc.GetId(), responderChain); // create replication and add observer manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient)); Replication pusher = database.CreatePushReplication(GetReplicationURL()); RunReplication(pusher); IList<HttpWebRequest> captured = mockHttpClient.GetCapturedRequests(); int entityIndex = 0; foreach (HttpWebRequest httpRequest in captured) { // verify that there are no PUT requests with attachments if (httpRequest is HttpPut) { HttpPut httpPut = (HttpPut)httpRequest; HttpEntity entity = httpPut.GetEntity(); if (entityIndex++ == 0) { NUnit.Framework.Assert.IsTrue("PUT request with attachment is not multipart", entity is MultipartEntity); } else { NUnit.Framework.Assert.IsFalse("PUT request with attachment is multipart", entity is MultipartEntity); } } } }
/// <exception cref="System.Exception"></exception> public virtual void TestHeaders() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_741(mockHttpClient ); Uri remote = GetReplicationURL(); manager.SetDefaultHttpClientFactory(mockHttpClientFactory); Replication puller = database.CreatePullReplication(remote); IDictionary<string, object> headers = new Dictionary<string, object>(); headers.Put("foo", "bar"); puller.SetHeaders(headers); puller.Start(); Sharpen.Thread.Sleep(2000); puller.Stop(); bool foundFooHeader = false; IList<HttpWebRequest> requests = mockHttpClient.GetCapturedRequests(); foreach (HttpWebRequest request in requests) { Header[] requestHeaders = request.GetHeaders("foo"); foreach (Header requestHeader in requestHeaders) { foundFooHeader = true; NUnit.Framework.Assert.AreEqual("bar", requestHeader.GetValue()); } } NUnit.Framework.Assert.IsTrue(foundFooHeader); manager.SetDefaultHttpClientFactory(null); }
/// <summary>https://github.com/couchbase/couchbase-lite-java-core/issues/55</summary> /// <exception cref="System.Exception"></exception> public virtual void TestContinuousPushReplicationGoesIdle() { // make sure we are starting empty NUnit.Framework.Assert.AreEqual(0, database.GetLastSequenceNumber()); // add docs IDictionary<string, object> properties1 = new Dictionary<string, object>(); properties1.Put("doc1", "testContinuousPushReplicationGoesIdle"); Document doc1 = CreateDocWithProperties(properties1); // create a mock http client that serves as a mocked out sync gateway CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); // replication to do initial sync up - has to be continuous replication so the checkpoint id // matches the next continuous replication we're gonna do later. manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient)); Replication firstPusher = database.CreatePushReplication(GetReplicationURL()); firstPusher.SetContinuous(true); string checkpointId = firstPusher.RemoteCheckpointDocID(); // save the checkpoint id for later usage // intercept checkpoint PUT request and return a 201 response with expected json mockHttpClient.SetResponder("_local", new _Responder_1762(checkpointId)); // start the continuous replication CountDownLatch replicationIdleSignal = new CountDownLatch(1); LiteTestCase.ReplicationIdleObserver replicationIdleObserver = new LiteTestCase.ReplicationIdleObserver (replicationIdleSignal); firstPusher.AddChangeListener(replicationIdleObserver); firstPusher.Start(); // wait until we get an IDLE event bool successful = replicationIdleSignal.Await(30, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(successful); StopReplication(firstPusher); // the last sequence should be "1" at this point. we will use this later string lastSequence = database.LastSequenceWithCheckpointId(checkpointId); NUnit.Framework.Assert.AreEqual("1", lastSequence); // start a second continuous replication Replication secondPusher = database.CreatePushReplication(GetReplicationURL()); secondPusher.SetContinuous(true); string secondPusherCheckpointId = secondPusher.RemoteCheckpointDocID(); NUnit.Framework.Assert.AreEqual(checkpointId, secondPusherCheckpointId); // when this goes to fetch the checkpoint, return the last sequence from the previous replication mockHttpClient.SetResponder("_local", new _Responder_1793(secondPusherCheckpointId , lastSequence)); // start second replication replicationIdleSignal = new CountDownLatch(1); replicationIdleObserver = new LiteTestCase.ReplicationIdleObserver(replicationIdleSignal ); secondPusher.AddChangeListener(replicationIdleObserver); secondPusher.Start(); // wait until we get an IDLE event successful = replicationIdleSignal.Await(30, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(successful); StopReplication(secondPusher); }
public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.SetResponder("_changes", new _Responder_136()); return mockHttpClient; }
/// <exception cref="System.Exception"></exception> public virtual void DisabledTestCheckpointingWithServerError() { string remoteCheckpointDocId; string lastSequenceWithCheckpointIdInitial; string lastSequenceWithCheckpointIdFinal; Uri remote = GetReplicationURL(); // add docs string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis()); CreateDocumentsForPushReplication(docIdTimestamp); // do push replication against mock replicator that fails to save remote checkpoint CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient)); Replication pusher = database.CreatePushReplication(remote); remoteCheckpointDocId = pusher.RemoteCheckpointDocID(); lastSequenceWithCheckpointIdInitial = database.LastSequenceWithCheckpointId(remoteCheckpointDocId ); RunReplication(pusher); IList<HttpWebRequest> capturedRequests = mockHttpClient.GetCapturedRequests(); foreach (HttpWebRequest capturedRequest in capturedRequests) { if (capturedRequest is HttpPost) { HttpPost capturedPostRequest = (HttpPost)capturedRequest; } } // sleep to allow for any "post-finished" activities on the replicator related to checkpointing Sharpen.Thread.Sleep(2000); // make sure local checkpoint is not updated lastSequenceWithCheckpointIdFinal = database.LastSequenceWithCheckpointId(remoteCheckpointDocId ); string msg = "since the mock replicator rejected the PUT to _local/remoteCheckpointDocId, we " + "would expect lastSequenceWithCheckpointIdInitial == lastSequenceWithCheckpointIdFinal"; NUnit.Framework.Assert.AreEqual(msg, lastSequenceWithCheckpointIdFinal, lastSequenceWithCheckpointIdInitial ); Log.D(Tag, "replication done"); }
public _ChangeTrackerClient_290(CustomizableMockHttpClient mockHttpClient) { this.mockHttpClient = mockHttpClient; }
/// <exception cref="System.Exception"></exception> public virtual void TestOnlineOfflinePusher() { Uri remote = GetReplicationURL(); // mock sync gateway CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderFakeLocalDocumentUpdate404(); mockHttpClient.AddResponderRevDiffsSmartResponder(); HttpClientFactory mockHttpClientFactory = MockFactoryFactory(mockHttpClient); manager.SetDefaultHttpClientFactory(mockHttpClientFactory); // create a push replication Replication pusher = database.CreatePushReplication(remote); Log.D(Database.Tag, "created pusher: " + pusher); pusher.SetContinuous(true); pusher.Start(); for (int i = 0; i < 5; i++) { Log.D(Database.Tag, "testOnlineOfflinePusher, i: " + i); // put the replication offline PutReplicationOffline(pusher); // add a document string docFieldName = "testOnlineOfflinePusher" + i; string docFieldVal = "foo" + i; IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put(docFieldName, docFieldVal); CreateDocumentWithProperties(database, properties); // add a response listener to wait for a bulk_docs request from the pusher CountDownLatch gotBulkDocsRequest = new CountDownLatch(1); CustomizableMockHttpClient.ResponseListener bulkDocsListener = new _ResponseListener_1145 (gotBulkDocsRequest); mockHttpClient.AddResponseListener(bulkDocsListener); // put the replication online, which should trigger it to send outgoing bulk_docs request PutReplicationOnline(pusher); // wait until we get a bulk docs request Log.D(Database.Tag, "waiting for bulk docs request"); bool succeeded = gotBulkDocsRequest.Await(120, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(succeeded); Log.D(Database.Tag, "got bulk docs request, verifying captured requests"); mockHttpClient.RemoveResponseListener(bulkDocsListener); // workaround bug https://github.com/couchbase/couchbase-lite-android/issues/219 Sharpen.Thread.Sleep(2000); // make sure that doc was pushed out in a bulk docs request bool foundExpectedDoc = false; IList<HttpWebRequest> capturedRequests = mockHttpClient.GetCapturedRequests(); foreach (HttpWebRequest capturedRequest in capturedRequests) { Log.D(Database.Tag, "captured request: " + capturedRequest); if (capturedRequest is HttpPost) { HttpPost capturedPostRequest = (HttpPost)capturedRequest; Log.D(Database.Tag, "capturedPostRequest: " + capturedPostRequest.GetURI().GetPath ()); if (capturedPostRequest.GetURI().GetPath().EndsWith("_bulk_docs")) { ArrayList docs = CustomizableMockHttpClient.ExtractDocsFromBulkDocsPost(capturedRequest ); NUnit.Framework.Assert.AreEqual(1, docs.Count); IDictionary<string, object> doc = (IDictionary)docs[0]; Log.D(Database.Tag, "doc from captured request: " + doc); Log.D(Database.Tag, "docFieldName: " + docFieldName); Log.D(Database.Tag, "expected docFieldVal: " + docFieldVal); Log.D(Database.Tag, "actual doc.get(docFieldName): " + doc.Get(docFieldName)); NUnit.Framework.Assert.AreEqual(docFieldVal, doc.Get(docFieldName)); foundExpectedDoc = true; } } } NUnit.Framework.Assert.IsTrue(foundExpectedDoc); mockHttpClient.ClearCapturedRequests(); } }