OSDN Git Service

ApiResponse.ReadAsLazyJsonメソッドを追加
authorKimura Youichi <kim.upsilon@bucyou.net>
Sun, 10 Dec 2023 09:54:30 +0000 (18:54 +0900)
committerKimura Youichi <kim.upsilon@bucyou.net>
Sun, 10 Dec 2023 09:55:36 +0000 (18:55 +0900)
OpenTween.Tests/Connection/ApiResponseTest.cs
OpenTween/Connection/ApiResponse.cs

index a1ff5ee..c281c59 100644 (file)
@@ -115,5 +115,36 @@ namespace OpenTween.Connection
             );
             Assert.Equal("### Invalid JSON Response ###", ex.ResponseText);
         }
+
+        [Fact]
+        public async Task ReadAsLazyJson_Test()
+        {
+            using var responseContent = new StringContent("""{"foo":123}""");
+            using var responseMessage = new HttpResponseMessage
+            {
+                StatusCode = HttpStatusCode.OK,
+                Content = responseContent,
+            };
+            using var response = new ApiResponse(responseMessage);
+
+            using var lazyJson = response.ReadAsLazyJson<TestJson>();
+            Assert.Equal(new() { Foo = 123 }, await lazyJson.LoadJsonAsync());
+        }
+
+        [Fact]
+        public async Task ReadAsLazyJson_DisposeTest()
+        {
+            using var responseContent = new StringContent("""{"foo":123}""");
+            using var responseMessage = new HttpResponseMessage
+            {
+                StatusCode = HttpStatusCode.OK,
+                Content = responseContent,
+            };
+            using var response = new ApiResponse(responseMessage);
+            using var lazyJson = response.ReadAsLazyJson<TestJson>();
+            response.Dispose(); // ApiResponse を先に破棄しても LazyJson に影響しないことをテストする
+
+            Assert.Equal(new() { Foo = 123 }, await lazyJson.LoadJsonAsync());
+        }
     }
 }
index 3eabcb6..7ba0ba2 100644 (file)
@@ -38,6 +38,7 @@ namespace OpenTween.Connection
         public bool IsDisposed { get; private set; }
 
         private readonly HttpResponseMessage responseMessage;
+        private bool preventDisposeResponse;
 
         public ApiResponse(HttpResponseMessage responseMessage)
             => this.responseMessage = responseMessage;
@@ -47,7 +48,9 @@ namespace OpenTween.Connection
             if (this.IsDisposed)
                 return;
 
-            this.responseMessage.Dispose();
+            if (!this.preventDisposeResponse)
+                this.responseMessage.Dispose();
+
             this.IsDisposed = true;
         }
 
@@ -95,5 +98,12 @@ namespace OpenTween.Connection
                 throw new TwitterApiException("Invalid JSON", ex) { ResponseText = responseText };
             }
         }
+
+        public LazyJson<T> ReadAsLazyJson<T>()
+        {
+            this.preventDisposeResponse = true;
+
+            return new(this.responseMessage);
+        }
     }
 }