lucidiot/NullSharp
lucidiot
/
NullSharp
Archived
1
0
Fork 0
This repository has been archived on 2022-08-04. You can view files and clone it, but cannot push or open issues or pull requests.
NullSharp/NullSharpTests/NullStreamTests.cs

78 lines
3.2 KiB
C#

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using NullSharp;
namespace NullSharpTests {
class MockableNullStream : NullStream {
public MockableNullStream() : base() { }
public MockableNullStream(string endpoint) : base(endpoint) { }
public HttpClient GetClient() => this.Client;
public void SetClient(HttpClient value) => this.Client = value;
}
class MockHttpClient : HttpClient {
public HttpRequestMessage LastMessage;
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {
LastMessage = request;
return new Task<HttpResponseMessage>(() => new HttpResponseMessage());
}
}
public class NullStreamTests {
private MockableNullStream stream = new MockableNullStream();
[Fact]
public void DefaultEndpointTest() {
Assert.Equal("https://devnull-as-a-service.com/dev/null", stream.GetClient().BaseAddress.ToString());
Assert.Single(stream.GetClient().DefaultRequestHeaders.UserAgent);
Assert.Equal("NullSharp", stream.GetClient().DefaultRequestHeaders.UserAgent.ToString());
}
[Fact]
public void CustomEndpointTest() {
var customStream = new MockableNullStream("https://somewhere");
Assert.Equal("https://somewhere", customStream.GetClient().BaseAddress.ToString());
}
[Fact]
public void PropertiesTest() {
Assert.True(stream.CanWrite, "NullStream should be writable");
Assert.False(stream.CanRead, "NullStream should not be readable");
Assert.False(stream.CanSeek, "NullStream should not be seekable");
Assert.True(stream.CanTimeout, "NullStream should be able to time out");
}
[Fact]
public void TimeoutTest() {
stream.WriteTimeout = 1000000;
Assert.Equal(1000000, stream.WriteTimeout);
Assert.Equal(1000000, stream.GetClient().Timeout.TotalMilliseconds);
}
[Fact]
public void NotSupportedTest() {
Assert.Throws<NotSupportedException>(() => stream.Length);
Assert.Throws<NotSupportedException>(() => stream.SetLength(42));
Assert.Throws<NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => stream.Position);
Assert.Throws<NotSupportedException>(() => stream.Position = 42);
Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] {}, 0, 10));
}
[Fact]
public void WriteTest() {
stream.SetClient(new MockHttpClient() { BaseAddress = new Uri(NullStream.DefaultEndpoint) });
var data = new byte[] {13, 37};
stream.Write(data, 1, 1);
var request = ((MockHttpClient)stream.GetClient()).LastMessage;
Assert.Equal("https://devnull-as-a-service.com/dev/null", request.RequestUri.ToString());
Assert.IsType<ByteArrayContent>(request.Content);
Assert.Equal(new ByteArrayContent(new byte[] {37}), request.Content);
}
}
}