From 876888094080fbd9e990b27d0d6095a383383926 Mon Sep 17 00:00:00 2001 From: Tony Li Date: Thu, 23 Feb 2023 13:45:35 +1300 Subject: [PATCH] Fix #20191: both the success and failure blocks may get called --- .../Classes/Services/PostCategoryService.m | 15 +++++++---- .../WordPressTest/PostCategoryServiceTests.m | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/WordPress/Classes/Services/PostCategoryService.m b/WordPress/Classes/Services/PostCategoryService.m index 0b6bef831d30..5451af41593a 100644 --- a/WordPress/Classes/Services/PostCategoryService.m +++ b/WordPress/Classes/Services/PostCategoryService.m @@ -31,18 +31,23 @@ - (void)syncCategoriesForBlog:(Blog *)blog id remote = [self remoteForBlog:blog]; NSManagedObjectID *blogID = blog.objectID; [remote getCategoriesWithSuccess:^(NSArray *categories) { + NSError * __block error = nil; [[ContextManager sharedInstance] performAndSaveUsingBlock:^(NSManagedObjectContext *context) { Blog *blog = (Blog *)[context existingObjectWithID:blogID error:nil]; if (!blog) { - if (failure) { - failure([self serviceErrorNoBlog]); - } + error = [self serviceErrorNoBlog]; return; } [self mergeCategories:categories forBlog:blog inContext:context]; } completion: ^{ - if (success) { - success(); + if (error) { + if (failure) { + failure(error); + } + } else { + if (success) { + success(); + } } } onQueue: dispatch_get_main_queue()]; } failure:failure]; diff --git a/WordPress/WordPressTest/PostCategoryServiceTests.m b/WordPress/WordPressTest/PostCategoryServiceTests.m index 297bd8316a5b..7bf9ceca8bbc 100644 --- a/WordPress/WordPressTest/PostCategoryServiceTests.m +++ b/WordPress/WordPressTest/PostCategoryServiceTests.m @@ -126,4 +126,30 @@ - (void)testThatCreateCategoryWithNameWorks failure:^(NSError * _Nonnull error) {}]; } +- (void)testSyncSuccessShouldBeCalledOnce +{ + TaxonomyServiceRemoteREST *remote = self.service.remoteForStubbing; + + XCTestExpectation *completion = [self expectationWithDescription:@"Only the success block is called"]; + OCMStub([remote getCategoriesWithSuccess:[OCMArg invokeBlock] + failure:[OCMArg isNotNil]]); + [self.service syncCategoriesForBlog:self.blog + success:^{ [completion fulfill]; } + failure:^(NSError * _Nonnull error) {[completion fulfill]; }]; + [self waitForExpectations:@[completion] timeout:1]; +} + +- (void)testSyncFailureShouldBeCalledOnce +{ + TaxonomyServiceRemoteREST *remote = self.service.remoteForStubbing; + + XCTestExpectation *completion = [self expectationWithDescription:@"Only the failure block is called"]; + OCMStub([remote getCategoriesWithSuccess:[OCMArg isNotNil] + failure:[OCMArg invokeBlock]]); + [self.service syncCategoriesForBlog:self.blog + success:^{ [completion fulfill]; } + failure:^(NSError * _Nonnull error) {[completion fulfill]; }]; + [self waitForExpectations:@[completion] timeout:1]; +} + @end