33using System . IO ;
44using System . Linq ;
55using System . Net ;
6+ using System . Net . Sockets ;
67using System . Text ;
78using System . Threading ;
89using System . Threading . Tasks ;
@@ -18,7 +19,7 @@ public WebRequesterMock WebRequesterMock
1819 }
1920 public WebRequesterFactoryMock ( ServiceResponseMock response )
2021 {
21- this . WebRequesterMock = new WebRequesterMock ( response ) ;
22+ this . WebRequesterMock = new WebRequesterMock ( response ) ;
2223 }
2324 public IWebRequester Create ( )
2425 {
@@ -48,7 +49,7 @@ public System.Threading.Tasks.Task<IServerResponse> Get(Uri url)
4849
4950 class ServiceResponseMock : IServerResponse
5051 {
51- private Stream mStream ;
52+ private TestableStream mStream ;
5253 private StreamWriter mStreamWriter ;
5354 private Uri mUrl ;
5455 private HttpStatusCode mStatusCode ;
@@ -87,6 +88,11 @@ public void WriteTestTextToStream(string text)
8788 mStreamWriter . Write ( text ) ;
8889 mStreamWriter . Flush ( ) ;
8990 }
91+
92+ public void DistantConnectionClose ( )
93+ {
94+ mStream . Throws ( new SocketException ( 10054 ) ) ;
95+ }
9096 }
9197
9298 class GetIsCalledEventArgs : EventArgs
@@ -103,6 +109,13 @@ class TestableStream : Stream
103109 {
104110 long _pos = 0 ;
105111 System . Collections . Concurrent . BlockingCollection < string > _texts = new System . Collections . Concurrent . BlockingCollection < string > ( ) ;
112+ private CancellationTokenSource _cancellationTokenSource ;
113+ private Exception _throw ;
114+
115+ public TestableStream ( )
116+ {
117+ _cancellationTokenSource = new CancellationTokenSource ( ) ;
118+ }
106119
107120 public override bool CanRead
108121 {
@@ -143,11 +156,23 @@ public override long Position
143156
144157 public override int Read ( byte [ ] buffer , int offset , int count )
145158 {
146- string s = _texts . Take ( ) ;
147-
148- byte [ ] encodedText = Encoding . UTF8 . GetBytes ( s ) ;
149- encodedText . CopyTo ( buffer , offset ) ;
150- return encodedText . Length ;
159+ try
160+ {
161+ var s = _texts . Take ( _cancellationTokenSource . Token ) ;
162+ byte [ ] encodedText = Encoding . UTF8 . GetBytes ( s ) ;
163+ encodedText . CopyTo ( buffer , offset ) ;
164+ return encodedText . Length ;
165+ }
166+ catch ( OperationCanceledException )
167+ {
168+ if ( _throw != null )
169+ {
170+ var ex = _throw ;
171+ _throw = null ;
172+ throw ex ;
173+ }
174+ return 0 ;
175+ }
151176 }
152177
153178 public override long Seek ( long offset , SeekOrigin origin )
@@ -166,6 +191,12 @@ public override void Write(byte[] buffer, int offset, int count)
166191 _texts . Add ( s ) ;
167192 //_texts.CompleteAdding();
168193 }
194+
195+ public void Throws ( Exception exception )
196+ {
197+ _cancellationTokenSource . Cancel ( ) ;
198+ _throw = exception ;
199+ }
169200 }
170201
171202
0 commit comments