diff --git a/src/Downloader.Test/ConfigAwait.cs b/src/Downloader.Test/ConfigAwait.cs deleted file mode 100644 index b2a85fe..0000000 --- a/src/Downloader.Test/ConfigAwait.cs +++ /dev/null @@ -1,4 +0,0 @@ -using Fody; - -[assembly: ConfigureAwait(false)] -namespace Downloader.Test; \ No newline at end of file diff --git a/src/Downloader.Test/Downloader.Test.csproj b/src/Downloader.Test/Downloader.Test.csproj index a4e13a4..a763b35 100644 --- a/src/Downloader.Test/Downloader.Test.csproj +++ b/src/Downloader.Test/Downloader.Test.csproj @@ -1,7 +1,7 @@  - netcoreapp3.1;net6.0; + netcoreapp3.1;net6.0;net7.0 false true Sign.snk @@ -25,20 +25,22 @@ all - all runtime; build; native; contentfiles; analyzers; buildtransitive - - all runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/Downloader.Test/FodyWeavers.xml b/src/Downloader.Test/FodyWeavers.xml index 216d734..2df8def 100644 --- a/src/Downloader.Test/FodyWeavers.xml +++ b/src/Downloader.Test/FodyWeavers.xml @@ -1,4 +1,3 @@  - \ No newline at end of file diff --git a/src/Downloader.Test/FodyWeavers.xsd b/src/Downloader.Test/FodyWeavers.xsd index 23fce48..68c9423 100644 --- a/src/Downloader.Test/FodyWeavers.xsd +++ b/src/Downloader.Test/FodyWeavers.xsd @@ -4,11 +4,6 @@ - - - - - diff --git a/src/Downloader.Test/Helper/AssertHelper.cs b/src/Downloader.Test/Helper/AssertHelper.cs index 12bdeb9..3a41398 100644 --- a/src/Downloader.Test/Helper/AssertHelper.cs +++ b/src/Downloader.Test/Helper/AssertHelper.cs @@ -1,4 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Xunit; using System; using System.Linq; @@ -14,7 +14,7 @@ public static void DoesNotThrow(Action action) where T : Exception } catch (T) { - Assert.Fail("Expected no {0} to be thrown", typeof(T).Name); + Assert.Fail($"Expected no {typeof(T).Name} to be thrown"); } catch { @@ -24,12 +24,37 @@ public static void DoesNotThrow(Action action) where T : Exception public static void AreEquals(Chunk source, Chunk destination) { - Assert.IsNotNull(source); - Assert.IsNotNull(destination); + Assert.NotNull(source); + Assert.NotNull(destination); foreach (var prop in typeof(Chunk).GetProperties().Where(p => p.CanRead && p.CanWrite)) { - Assert.AreEqual(prop.GetValue(source), prop.GetValue(destination), prop.Name); + Assert.Equal(prop.GetValue(source), prop.GetValue(destination)); + } + } + + public static void AreEquals(DownloadPackage source, DownloadPackage destination) + { + Assert.NotNull(source); + Assert.NotNull(destination); + Assert.NotNull(source.Chunks); + Assert.NotNull(destination.Chunks); + Assert.Equal(source.FileName, destination.FileName); + Assert.Equal(source.ReceivedBytesSize, destination.ReceivedBytesSize); + Assert.Equal(source.TotalFileSize, destination.TotalFileSize); + Assert.Equal(source.IsSaving, destination.IsSaving); + Assert.Equal(source.IsSaveComplete, destination.IsSaveComplete); + Assert.Equal(source.SaveProgress, destination.SaveProgress); + Assert.Equal(source.Chunks?.Length, destination.Chunks?.Length); + Assert.Equal(source.IsSupportDownloadInRange, destination.IsSupportDownloadInRange); + Assert.Equal(source.InMemoryStream, destination.InMemoryStream); + Assert.Equal(source.Storage.Path, destination.Storage.Path); + //Assert.Equal(source.Storage.Length, destination.Storage.Length); + Assert.True(source.Urls.SequenceEqual(destination.Urls)); + + for (int i = 0; i < source.Chunks.Length; i++) + { + AreEquals(source.Chunks[i], destination.Chunks[i]); } } } diff --git a/src/Downloader.Test/HelperTests/AssertHelperTest.cs b/src/Downloader.Test/HelperTests/AssertHelperTest.cs index 1189594..93e24c3 100644 --- a/src/Downloader.Test/HelperTests/AssertHelperTest.cs +++ b/src/Downloader.Test/HelperTests/AssertHelperTest.cs @@ -1,13 +1,12 @@ using Downloader.Test.Helper; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using Xunit; namespace Downloader.Test.HelperTests; -[TestClass] public class AssertHelperTest { - [TestMethod] + [Fact] public void TestDoesNotThrowWhenThrowExp() { void ThrowException() => throw new DivideByZeroException("TEST"); @@ -15,7 +14,7 @@ public void TestDoesNotThrowWhenThrowExp() AssertHelper.DoesNotThrow(ThrowException); } - [TestMethod] + [Fact] public void TestChunksAreEquals() { // arrange @@ -41,10 +40,10 @@ public void TestChunksAreEquals() AssertHelper.AreEquals(chunk1, chunk2); // assert - Assert.AreNotEqual(chunk1, chunk2); + Assert.NotEqual(chunk1, chunk2); } - [TestMethod] + [Fact] public void TestChunksAreNotEquals() { // arrange @@ -70,7 +69,7 @@ public void TestChunksAreNotEquals() void testAssertHelper() => AssertHelper.AreEquals(chunk1, chunk2); // assert - Assert.ThrowsException(testAssertHelper); - Assert.AreNotEqual(chunk1, chunk2); + Assert.ThrowsAny(testAssertHelper); + Assert.NotEqual(chunk1, chunk2); } } diff --git a/src/Downloader.Test/HelperTests/DummyDataTest.cs b/src/Downloader.Test/HelperTests/DummyDataTest.cs index 66b4ac2..57fbcc8 100644 --- a/src/Downloader.Test/HelperTests/DummyDataTest.cs +++ b/src/Downloader.Test/HelperTests/DummyDataTest.cs @@ -1,81 +1,79 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; +using Xunit; -namespace Downloader.Test.HelperTests +namespace Downloader.Test.HelperTests; + +public class DummyDataTest { - [TestClass] - public class DummyDataTest + [Fact] + public void GenerateOrderedBytesTest() + { + // arrange + int size = 1024; + byte[] bytes = Enumerable.Range(0, size).Select(i => (byte)i).ToArray(); + + // act + var dummyData = DummyData.GenerateOrderedBytes(size); + + // assert + Assert.Equal(size, dummyData.Length); + Assert.True(dummyData.SequenceEqual(bytes)); + } + + [Fact] + public void GenerateOrderedBytesLessThan1Test() { - [TestMethod] - public void GenerateOrderedBytesTest() - { - // arrange - int size = 1024; - byte[] bytes = Enumerable.Range(0, size).Select(i => (byte)i).ToArray(); - - // act - var dummyData = DummyData.GenerateOrderedBytes(size); - - // assert - Assert.AreEqual(size, dummyData.Length); - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - } - - [TestMethod] - public void GenerateOrderedBytesLessThan1Test() - { - // arrange - int size = 0; - - // act - void act() => DummyData.GenerateOrderedBytes(size); - - // assert - Assert.ThrowsException(act); - } - - [TestMethod] - public void GenerateRandomBytesTest() - { - // arrange - int size = 1024; - - // act - var dummyData = DummyData.GenerateRandomBytes(size); - - // assert - Assert.AreEqual(size, dummyData.Length); - Assert.IsTrue(dummyData.Any(i => i > 0)); - } - - [TestMethod] - public void GenerateRandomBytesLessThan1Test() - { - // arrange - int size = 0; - - // act - void act() => DummyData.GenerateRandomBytes(size); - - // assert - Assert.ThrowsException(act); - } - - [TestMethod] - public void GenerateSingleBytesTest() - { - // arrange - int size = 1024; - byte fillByte = 13; - - // act - var dummyData = DummyData.GenerateSingleBytes(size, fillByte); - - // assert - Assert.AreEqual(size, dummyData.Length); - Assert.IsTrue(dummyData.All(i => i == fillByte)); - } + // arrange + int size = 0; + + // act + void act() => DummyData.GenerateOrderedBytes(size); + + // assert + Assert.ThrowsAny(act); + } + + [Fact] + public void GenerateRandomBytesTest() + { + // arrange + int size = 1024; + + // act + var dummyData = DummyData.GenerateRandomBytes(size); + + // assert + Assert.Equal(size, dummyData.Length); + Assert.Contains(dummyData, i => i > 0); + } + + [Fact] + public void GenerateRandomBytesLessThan1Test() + { + // arrange + int size = 0; + + // act + void act() => DummyData.GenerateRandomBytes(size); + + // assert + Assert.ThrowsAny(act); + } + + [Fact] + public void GenerateSingleBytesTest() + { + // arrange + int size = 1024; + byte fillByte = 13; + + // act + var dummyData = DummyData.GenerateSingleBytes(size, fillByte); + + // assert + Assert.Equal(size, dummyData.Length); + Assert.True(dummyData.All(i => i == fillByte)); } } diff --git a/src/Downloader.Test/HelperTests/DummyFileControllerTest.cs b/src/Downloader.Test/HelperTests/DummyFileControllerTest.cs index 8b801bf..d51d8ba 100644 --- a/src/Downloader.Test/HelperTests/DummyFileControllerTest.cs +++ b/src/Downloader.Test/HelperTests/DummyFileControllerTest.cs @@ -1,314 +1,312 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; +using Xunit; -namespace Downloader.Test.HelperTests +namespace Downloader.Test.HelperTests; + +public class DummyFileControllerTest { - [TestClass] - public class DummyFileControllerTest - { - private readonly string contentType = "application/octet-stream"; - private WebHeaderCollection headers; + private readonly string contentType = "application/octet-stream"; + private WebHeaderCollection headers; - [TestMethod] - public void GetFileTest() - { - // arrange - int size = 1024; - byte[] bytes = new byte[size]; - string url = DummyFileHelper.GetFileUrl(size); - var dummyData = DummyData.GenerateOrderedBytes(size); - - // act - ReadAndGetHeaders(url, bytes); - - // assert - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - } + [Fact] + public void GetFileTest() + { + // arrange + int size = 1024; + byte[] bytes = new byte[size]; + string url = DummyFileHelper.GetFileUrl(size); + var dummyData = DummyData.GenerateOrderedBytes(size); + + // act + ReadAndGetHeaders(url, bytes); + + // assert + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + } - [TestMethod] - public void GetFileWithNameTest() - { - // arrange - int size = 2048; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithNameUrl(filename, size); - var dummyData = DummyData.GenerateOrderedBytes(size); - - // act - ReadAndGetHeaders(url, bytes); - - // assert - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - } + [Fact] + public void GetFileWithNameTest() + { + // arrange + int size = 2048; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithNameUrl(filename, size); + var dummyData = DummyData.GenerateOrderedBytes(size); + + // act + ReadAndGetHeaders(url, bytes); + + // assert + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + } - [TestMethod] - public void GetSingleByteFileWithNameTest() - { - // arrange - int size = 2048; - byte fillByte = 13; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithNameUrl(filename, size, fillByte); - var dummyData = DummyData.GenerateSingleBytes(size, fillByte); - - // act - ReadAndGetHeaders(url, bytes); - - // assert - Assert.IsTrue(bytes.All(i => i == fillByte)); - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - } + [Fact] + public void GetSingleByteFileWithNameTest() + { + // arrange + int size = 2048; + byte fillByte = 13; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithNameUrl(filename, size, fillByte); + var dummyData = DummyData.GenerateSingleBytes(size, fillByte); + + // act + ReadAndGetHeaders(url, bytes); + + // assert + Assert.True(bytes.All(i => i == fillByte)); + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + } - [TestMethod] - public void GetFileWithoutHeaderTest() - { - // arrange - int size = 2048; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithoutHeaderUrl(filename, size); - var dummyData = DummyData.GenerateOrderedBytes(size); - - // act - ReadAndGetHeaders(url, bytes); - - // assert - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.IsNull(headers["Content-Length"]); - Assert.IsNull(headers["Content-Type"]); - } + [Fact] + public void GetFileWithoutHeaderTest() + { + // arrange + int size = 2048; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithoutHeaderUrl(filename, size); + var dummyData = DummyData.GenerateOrderedBytes(size); + + // act + ReadAndGetHeaders(url, bytes); + + // assert + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Null(headers["Content-Length"]); + Assert.Null(headers["Content-Type"]); + } - [TestMethod] - public void GetSingleByteFileWithoutHeaderTest() - { - // arrange - int size = 2048; - byte fillByte = 13; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithoutHeaderUrl(filename, size, fillByte); - var dummyData = DummyData.GenerateSingleBytes(size, fillByte); - - // act - ReadAndGetHeaders(url, bytes); - - // assert - Assert.IsTrue(bytes.All(i => i == fillByte)); - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.IsNull(headers["Content-Length"]); - Assert.IsNull(headers["Content-Type"]); - } + [Fact] + public void GetSingleByteFileWithoutHeaderTest() + { + // arrange + int size = 2048; + byte fillByte = 13; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithoutHeaderUrl(filename, size, fillByte); + var dummyData = DummyData.GenerateSingleBytes(size, fillByte); + + // act + ReadAndGetHeaders(url, bytes); + + // assert + Assert.True(bytes.All(i => i == fillByte)); + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Null(headers["Content-Length"]); + Assert.Null(headers["Content-Type"]); + } - [TestMethod] - public void GetFileWithContentDispositionTest() - { - // arrange - int size = 1024; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithContentDispositionUrl(filename, size); - var dummyData = DummyData.GenerateOrderedBytes(size); - - // act - ReadAndGetHeaders(url, bytes); - - // assert - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - Assert.IsTrue(headers["Content-Disposition"].Contains($"filename={filename};")); - } + [Fact] + public void GetFileWithContentDispositionTest() + { + // arrange + int size = 1024; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithContentDispositionUrl(filename, size); + var dummyData = DummyData.GenerateOrderedBytes(size); + + // act + ReadAndGetHeaders(url, bytes); + + // assert + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + Assert.True(headers["Content-Disposition"].Contains($"filename={filename};")); + } - [TestMethod] - public void GetSingleByteFileWithContentDispositionTest() - { - // arrange - int size = 1024; - byte fillByte = 13; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithContentDispositionUrl(filename, size, fillByte); - var dummyData = DummyData.GenerateSingleBytes(size, fillByte); - - // act - ReadAndGetHeaders(url, bytes); - - // assert - Assert.IsTrue(bytes.All(i => i == fillByte)); - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - Assert.IsTrue(headers["Content-Disposition"].Contains($"filename={filename};")); - } + [Fact] + public void GetSingleByteFileWithContentDispositionTest() + { + // arrange + int size = 1024; + byte fillByte = 13; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithContentDispositionUrl(filename, size, fillByte); + var dummyData = DummyData.GenerateSingleBytes(size, fillByte); + + // act + ReadAndGetHeaders(url, bytes); + + // assert + Assert.True(bytes.All(i => i == fillByte)); + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + Assert.True(headers["Content-Disposition"].Contains($"filename={filename};")); + } - [TestMethod] - public void GetFileWithRangeTest() - { - // arrange - int size = 1024; - byte[] bytes = new byte[size]; - string url = DummyFileHelper.GetFileUrl(size); - var dummyData = DummyData.GenerateOrderedBytes(size); - - // act - ReadAndGetHeaders(url, bytes, justFirst512Bytes: true); - - // assert - Assert.IsTrue(dummyData.Take(512).SequenceEqual(bytes.Take(512))); - Assert.AreEqual(contentType, headers["Content-Type"]); - Assert.AreEqual("512", headers["Content-Length"]); - Assert.AreEqual("bytes 0-511/1024", headers["Content-Range"]); - Assert.AreEqual("bytes", headers["Accept-Ranges"]); - } + [Fact] + public void GetFileWithRangeTest() + { + // arrange + int size = 1024; + byte[] bytes = new byte[size]; + string url = DummyFileHelper.GetFileUrl(size); + var dummyData = DummyData.GenerateOrderedBytes(size); + + // act + ReadAndGetHeaders(url, bytes, justFirst512Bytes: true); + + // assert + Assert.True(dummyData.Take(512).SequenceEqual(bytes.Take(512))); + Assert.Equal(contentType, headers["Content-Type"]); + Assert.Equal("512", headers["Content-Length"]); + Assert.Equal("bytes 0-511/1024", headers["Content-Range"]); + Assert.Equal("bytes", headers["Accept-Ranges"]); + } - [TestMethod] - public void GetFileWithNoAcceptRangeTest() - { - // arrange - int size = 1024; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithNoAcceptRangeUrl(filename, size); - var dummyData = DummyData.GenerateOrderedBytes(size); - - // act - ReadAndGetHeaders(url, bytes, justFirst512Bytes: true); - - // assert - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - Assert.IsNull(headers["Accept-Ranges"]); - } + [Fact] + public void GetFileWithNoAcceptRangeTest() + { + // arrange + int size = 1024; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithNoAcceptRangeUrl(filename, size); + var dummyData = DummyData.GenerateOrderedBytes(size); + + // act + ReadAndGetHeaders(url, bytes, justFirst512Bytes: true); + + // assert + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + Assert.Null(headers["Accept-Ranges"]); + } - [TestMethod] - public void GetSingleByteFileWithNoAcceptRangeTest() - { - // arrange - int size = 1024; - byte fillByte = 13; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithNoAcceptRangeUrl(filename, size, fillByte); - var dummyData = DummyData.GenerateSingleBytes(size, fillByte); - - // act - ReadAndGetHeaders(url, bytes, justFirst512Bytes: true); - - // assert - Assert.IsTrue(bytes.All(i => i == fillByte)); - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - Assert.IsNull(headers["Accept-Ranges"]); - } + [Fact] + public void GetSingleByteFileWithNoAcceptRangeTest() + { + // arrange + int size = 1024; + byte fillByte = 13; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithNoAcceptRangeUrl(filename, size, fillByte); + var dummyData = DummyData.GenerateSingleBytes(size, fillByte); + + // act + ReadAndGetHeaders(url, bytes, justFirst512Bytes: true); + + // assert + Assert.True(bytes.All(i => i == fillByte)); + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + Assert.Null(headers["Accept-Ranges"]); + } - [TestMethod] - public void GetFileWithNameOnRedirectTest() - { - // arrange - int size = 2048; - byte[] bytes = new byte[size]; - string filename = "testfilename.dat"; - string url = DummyFileHelper.GetFileWithNameOnRedirectUrl(filename, size); - var dummyData = DummyData.GenerateOrderedBytes(size); - - // act - ReadAndGetHeaders(url, bytes); - - // assert - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - Assert.AreNotEqual(url, headers[nameof(WebResponse.ResponseUri)]); - } + [Fact] + public void GetFileWithNameOnRedirectTest() + { + // arrange + int size = 2048; + byte[] bytes = new byte[size]; + string filename = "testfilename.dat"; + string url = DummyFileHelper.GetFileWithNameOnRedirectUrl(filename, size); + var dummyData = DummyData.GenerateOrderedBytes(size); + + // act + ReadAndGetHeaders(url, bytes); + + // assert + Assert.True(dummyData.SequenceEqual(bytes)); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + Assert.NotEqual(url, headers[nameof(WebResponse.ResponseUri)]); + } - [TestMethod] - public void GetFileWithFailureAfterOffsetTest() - { - // arrange - int size = 10240; - int failureOffset = size / 2; - byte[] bytes = new byte[size]; - string url = DummyFileHelper.GetFileWithFailureAfterOffset(size, failureOffset); - - // act - void getHeaders() => ReadAndGetHeaders(url, bytes, false); - - // assert - Assert.ThrowsException(getHeaders); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - Assert.AreEqual(0, bytes[size - 1]); - } + [Fact] + public void GetFileWithFailureAfterOffsetTest() + { + // arrange + int size = 10240; + int failureOffset = size / 2; + byte[] bytes = new byte[size]; + string url = DummyFileHelper.GetFileWithFailureAfterOffset(size, failureOffset); + + // act + void getHeaders() => ReadAndGetHeaders(url, bytes, false); + + // assert + Assert.ThrowsAny(getHeaders); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + Assert.Equal(0, bytes[size - 1]); + } - [TestMethod] - public void GetFileWithTimeoutAfterOffsetTest() - { - // arrange - int size = 10240; - int timeoutOffset = size / 2; - byte[] bytes = new byte[size]; - string url = DummyFileHelper.GetFileWithTimeoutAfterOffset(size, timeoutOffset); - - // act - void getHeaders() => ReadAndGetHeaders(url, bytes, false); - - // assert - Assert.ThrowsException(getHeaders); - Assert.AreEqual(size.ToString(), headers["Content-Length"]); - Assert.AreEqual(contentType, headers["Content-Type"]); - Assert.AreEqual(0, bytes[size - 1]); - } + [Fact] + public void GetFileWithTimeoutAfterOffsetTest() + { + // arrange + int size = 10240; + int timeoutOffset = size / 2; + byte[] bytes = new byte[size]; + string url = DummyFileHelper.GetFileWithTimeoutAfterOffset(size, timeoutOffset); + + // act + void getHeaders() => ReadAndGetHeaders(url, bytes, false); + + // assert + Assert.ThrowsAny(getHeaders); + Assert.Equal(size.ToString(), headers["Content-Length"]); + Assert.Equal(contentType, headers["Content-Type"]); + Assert.Equal(0, bytes[size - 1]); + } - private void ReadAndGetHeaders(string url, byte[] bytes, bool justFirst512Bytes = false) + private void ReadAndGetHeaders(string url, byte[] bytes, bool justFirst512Bytes = false) + { + try { - try - { - HttpWebRequest request = WebRequest.CreateHttp(url); - request.Timeout = 10000; // 10sec - if (justFirst512Bytes) - request.AddRange(0, 511); - - using HttpWebResponse downloadResponse = request.GetResponse() as HttpWebResponse; - var respStream = downloadResponse.GetResponseStream(); - - // keep response headers - downloadResponse.Headers.Add(nameof(WebResponse.ResponseUri), downloadResponse.ResponseUri.ToString()); - headers = downloadResponse.Headers; - - // read stream data - var readCount = 1; - var offset = 0; - while (readCount > 0) - { - var count = bytes.Length - offset; - if (count <= 0) - break; - - readCount = respStream.Read(bytes, offset, count); - offset += readCount; - } - } - catch (Exception exp) + HttpWebRequest request = WebRequest.CreateHttp(url); + request.Timeout = 10000; // 10sec + if (justFirst512Bytes) + request.AddRange(0, 511); + + using HttpWebResponse downloadResponse = request.GetResponse() as HttpWebResponse; + var respStream = downloadResponse.GetResponseStream(); + + // keep response headers + downloadResponse.Headers.Add(nameof(WebResponse.ResponseUri), downloadResponse.ResponseUri.ToString()); + headers = downloadResponse.Headers; + + // read stream data + var readCount = 1; + var offset = 0; + while (readCount > 0) { - Console.Error.WriteLine(exp.Message); - Debugger.Break(); - throw; + var count = bytes.Length - offset; + if (count <= 0) + break; + + readCount = respStream.Read(bytes, offset, count); + offset += readCount; } } + catch (Exception exp) + { + Console.Error.WriteLine(exp.Message); + Debugger.Break(); + throw; + } } } diff --git a/src/Downloader.Test/HelperTests/DummyLazyStreamTest.cs b/src/Downloader.Test/HelperTests/DummyLazyStreamTest.cs index d7be260..bf447fd 100644 --- a/src/Downloader.Test/HelperTests/DummyLazyStreamTest.cs +++ b/src/Downloader.Test/HelperTests/DummyLazyStreamTest.cs @@ -1,83 +1,81 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Linq; +using Xunit; -namespace Downloader.Test.HelperTests +namespace Downloader.Test.HelperTests; + +public class DummyLazyStreamTest { - [TestClass] - public class DummyLazyStreamTest + [Fact] + public void GenerateOrderedBytesStreamTest() + { + // arrange + int size = 1024; + byte[] bytes = Enumerable.Range(0, size).Select(i => (byte)i).ToArray(); + var memBuffer = new MemoryStream(); + + // act + var dummyData = new DummyLazyStream(DummyDataType.Order, size).ToArray(); + + // assert + Assert.Equal(size, dummyData.Length); + Assert.True(dummyData.SequenceEqual(bytes)); + } + + [Fact] + public void GenerateOrderedBytesStreamLessThan1Test() { - [TestMethod] - public void GenerateOrderedBytesStreamTest() - { - // arrange - int size = 1024; - byte[] bytes = Enumerable.Range(0, size).Select(i => (byte)i).ToArray(); - var memBuffer = new MemoryStream(); - - // act - var dummyData = new DummyLazyStream(DummyDataType.Order, size).ToArray(); - - // assert - Assert.AreEqual(size, dummyData.Length); - Assert.IsTrue(dummyData.SequenceEqual(bytes)); - } - - [TestMethod] - public void GenerateOrderedBytesStreamLessThan1Test() - { - // arrange - int size = 0; - - // act - void act() => new DummyLazyStream(DummyDataType.Order, size); - - // assert - Assert.ThrowsException(act); - } - - [TestMethod] - public void GenerateRandomBytesStreamTest() - { - // arrange - int size = 1024; - - // act - var dummyData = new DummyLazyStream(DummyDataType.Random, size).ToArray(); - - // assert - Assert.AreEqual(size, dummyData.Length); - Assert.IsTrue(dummyData.Any(i => i > 0)); - } - - [TestMethod] - public void GenerateRandomBytesLessThan1Test() - { - // arrange - int size = 0; - - // act - void act() => new DummyLazyStream(DummyDataType.Random, size); - - // assert - Assert.ThrowsException(act); - } - - [TestMethod] - public void GenerateSingleBytesTest() - { - // arrange - int size = 1024; - byte fillByte = 13; - - // act - var dummyData = new DummyLazyStream(DummyDataType.Single, size, fillByte).ToArray(); - - // assert - Assert.AreEqual(size, dummyData.Length); - Assert.IsTrue(dummyData.All(i => i == fillByte)); - } + // arrange + int size = 0; + + // act + void act() => new DummyLazyStream(DummyDataType.Order, size); + + // assert + Assert.ThrowsAny(act); + } + + [Fact] + public void GenerateRandomBytesStreamTest() + { + // arrange + int size = 1024; + + // act + var dummyData = new DummyLazyStream(DummyDataType.Random, size).ToArray(); + + // assert + Assert.Equal(size, dummyData.Length); + Assert.Contains(dummyData, i => i > 0); + } + + [Fact] + public void GenerateRandomBytesLessThan1Test() + { + // arrange + int size = 0; + + // act + void act() => new DummyLazyStream(DummyDataType.Random, size); + + // assert + Assert.ThrowsAny(act); + } + + [Fact] + public void GenerateSingleBytesTest() + { + // arrange + int size = 1024; + byte fillByte = 13; + + // act + var dummyData = new DummyLazyStream(DummyDataType.Single, size, fillByte).ToArray(); + + // assert + Assert.Equal(size, dummyData.Length); + Assert.True(dummyData.All(i => i == fillByte)); } } diff --git a/src/Downloader.Test/HelperTests/ExceptionHelperTest.cs b/src/Downloader.Test/HelperTests/ExceptionHelperTest.cs index eb7ffae..370841d 100644 --- a/src/Downloader.Test/HelperTests/ExceptionHelperTest.cs +++ b/src/Downloader.Test/HelperTests/ExceptionHelperTest.cs @@ -1,110 +1,108 @@ using Downloader.Test.Helper; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Net; using System.Net.Http; +using Xunit; -namespace Downloader.Test.HelperTests +namespace Downloader.Test.HelperTests; + +public class ExceptionHelperTest { - [TestClass] - public class ExceptionHelperTest + [Fact] + public void HasSourceFromThisNamespaceTest() { - [TestMethod] - public void HasSourceFromThisNamespaceTest() - { - // arrange - var exception = ExceptionThrower.GetException(); - var exceptionSource = exception.Source; - var currentNamespace = "Downloader.Test"; - - // act - bool hasThisNamespace = exception.HasSource(currentNamespace); - - // assert - Assert.IsTrue(hasThisNamespace, - $"Exception.Source: {exceptionSource}, CurrentNamespace: {currentNamespace}"); - } - - [TestMethod] - public void HasSourceFromNonOccurrenceNamespaceTest() - { - // arrange - var exception = ExceptionThrower.GetException(); - - // act - bool hasSocketsNamespace = exception.HasSource("System.Net.Sockets"); - bool hasSecurityNamespace = exception.HasSource("System.Net.Security"); - - // assert - Assert.IsFalse(hasSocketsNamespace); - Assert.IsFalse(hasSecurityNamespace); - } - - [TestMethod] - public void HasTypeOfWebExceptionTest() - { - // arrange - var exception = ExceptionThrower.GetWebException(); - - // act - bool hasTypeOfWebExp = exception.HasTypeOf(typeof(WebException)); - - // assert - Assert.IsTrue(hasTypeOfWebExp); - } - - [TestMethod] - public void HasTypeOfInnerExceptionsTest() - { - // arrange - var exception = ExceptionThrower.GetWebException(); - - // act - bool hasTypeOfMultipleTypes = exception.HasTypeOf(typeof(DivideByZeroException), - typeof(ArgumentNullException), typeof(HttpRequestException)); - - // assert - Assert.IsTrue(hasTypeOfMultipleTypes); - } - - [TestMethod] - public void HasTypeOfNonOccurrenceExceptionsTest() - { - // arrange - var exception = ExceptionThrower.GetWebException(); - - // act - bool hasTypeOfMultipleTypes = exception.HasTypeOf(typeof(DivideByZeroException), - typeof(ArgumentNullException), typeof(InvalidCastException)); - - // assert - Assert.IsFalse(hasTypeOfMultipleTypes); - } - - [TestMethod] - public void IsMomentumErrorTestWhenNoWebException() - { - // arrange - var exception = ExceptionThrower.GetException(); - - // act - bool isMomentumError = exception.IsMomentumError(); - - // assert - Assert.IsFalse(isMomentumError); - } - - [TestMethod] - public void IsMomentumErrorTestOnWebException() - { - // arrange - var exception = ExceptionThrower.GetWebException(); - - // act - bool isMomentumError = exception.IsMomentumError(); - - // assert - Assert.IsTrue(isMomentumError); - } + // arrange + var exception = ExceptionThrower.GetException(); + var exceptionSource = exception.Source; + var currentNamespace = "Downloader.Test"; + + // act + bool hasThisNamespace = exception.HasSource(currentNamespace); + + // assert + Assert.True(hasThisNamespace, + $"Exception.Source: {exceptionSource}, CurrentNamespace: {currentNamespace}"); + } + + [Fact] + public void HasSourceFromNonOccurrenceNamespaceTest() + { + // arrange + var exception = ExceptionThrower.GetException(); + + // act + bool hasSocketsNamespace = exception.HasSource("System.Net.Sockets"); + bool hasSecurityNamespace = exception.HasSource("System.Net.Security"); + + // assert + Assert.False(hasSocketsNamespace); + Assert.False(hasSecurityNamespace); + } + + [Fact] + public void HasTypeOfWebExceptionTest() + { + // arrange + var exception = ExceptionThrower.GetWebException(); + + // act + bool hasTypeOfWebExp = exception.HasTypeOf(typeof(WebException)); + + // assert + Assert.True(hasTypeOfWebExp); + } + + [Fact] + public void HasTypeOfInnerExceptionsTest() + { + // arrange + var exception = ExceptionThrower.GetWebException(); + + // act + bool hasTypeOfMultipleTypes = exception.HasTypeOf(typeof(DivideByZeroException), + typeof(ArgumentNullException), typeof(HttpRequestException)); + + // assert + Assert.True(hasTypeOfMultipleTypes); + } + + [Fact] + public void HasTypeOfNonOccurrenceExceptionsTest() + { + // arrange + var exception = ExceptionThrower.GetWebException(); + + // act + bool hasTypeOfMultipleTypes = exception.HasTypeOf(typeof(DivideByZeroException), + typeof(ArgumentNullException), typeof(InvalidCastException)); + + // assert + Assert.False(hasTypeOfMultipleTypes); + } + + [Fact] + public void IsMomentumErrorTestWhenNoWebException() + { + // arrange + var exception = ExceptionThrower.GetException(); + + // act + bool isMomentumError = exception.IsMomentumError(); + + // assert + Assert.False(isMomentumError); + } + + [Fact] + public void IsMomentumErrorTestOnWebException() + { + // arrange + var exception = ExceptionThrower.GetWebException(); + + // act + bool isMomentumError = exception.IsMomentumError(); + + // assert + Assert.True(isMomentumError); } } diff --git a/src/Downloader.Test/IntegrationTests/DownloadIntegrationTest.cs b/src/Downloader.Test/IntegrationTests/DownloadIntegrationTest.cs index 605300b..beb9c6e 100644 --- a/src/Downloader.Test/IntegrationTests/DownloadIntegrationTest.cs +++ b/src/Downloader.Test/IntegrationTests/DownloadIntegrationTest.cs @@ -1,6 +1,4 @@ using Downloader.DummyHttpServer; -using Fody; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using System; using System.IO; @@ -8,20 +6,17 @@ using System.Net; using System.Threading; using System.Threading.Tasks; +using Xunit; namespace Downloader.Test.IntegrationTests; -[ConfigureAwait(false)] public abstract class DownloadIntegrationTest { protected DownloadConfiguration Config { get; set; } protected string URL { get; set; } = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb); protected string Filename => Path.GetTempFileName(); - [TestInitialize] - public abstract void InitialTest(); - - [TestMethod] + [Fact] public async Task DownloadUrlWithFilenameOnMemoryTest() { // arrange @@ -35,20 +30,20 @@ public async Task DownloadUrlWithFilenameOnMemoryTest() }; // act - using var memoryStream = await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + using var memoryStream = await downloader.DownloadFileTaskAsync(URL); // assert - Assert.IsTrue(downloadCompletedSuccessfully); - Assert.IsNotNull(memoryStream); - Assert.IsTrue(downloader.Package.IsSaveComplete); - Assert.IsNull(downloader.Package.FileName); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, memoryStream.Length); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(100.0, downloader.Package.SaveProgress); - Assert.IsTrue(DummyFileHelper.File16Kb.AreEqual(memoryStream)); + Assert.True(downloadCompletedSuccessfully); + Assert.NotNull(memoryStream); + Assert.True(downloader.Package.IsSaveComplete); + Assert.Null(downloader.Package.FileName); + Assert.Equal(DummyFileHelper.FileSize16Kb, memoryStream.Length); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(100.0, downloader.Package.SaveProgress); + Assert.True(DummyFileHelper.File16Kb.AreEqual(memoryStream)); } - [TestMethod] + [Fact] public async Task DownloadAndReadFileOnDownloadFileCompletedEventTest() { // arrange @@ -70,20 +65,20 @@ public async Task DownloadAndReadFileOnDownloadFileCompletedEventTest() }; // act - await downloader.DownloadFileTaskAsync(URL, destFilename).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL, destFilename); // assert - Assert.IsTrue(downloadCompletedSuccessfully); - Assert.IsNotNull(downloadedBytes); - Assert.AreEqual(destFilename, downloader.Package.FileName); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloadedBytes.Length); - Assert.IsTrue(DummyFileHelper.File16Kb.SequenceEqual(downloadedBytes)); + Assert.True(downloadCompletedSuccessfully); + Assert.NotNull(downloadedBytes); + Assert.Equal(destFilename, downloader.Package.FileName); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloadedBytes.Length); + Assert.True(DummyFileHelper.File16Kb.SequenceEqual(downloadedBytes)); File.Delete(destFilename); } - [TestMethod] + [Fact] public async Task Download16KbWithoutFilenameOnDirectoryTest() { // arrange @@ -93,42 +88,41 @@ public async Task Download16KbWithoutFilenameOnDirectoryTest() File.Delete(filename); // act - await downloader.DownloadFileTaskAsync(URL, dir).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL, dir); // assert - Assert.IsTrue(downloader.Package.IsSaveComplete); - Assert.IsTrue(File.Exists(downloader.Package.FileName)); - Assert.IsNotNull(downloader.Package.FileName); - Assert.IsTrue(downloader.Package.FileName.StartsWith(DummyFileHelper.TempDirectory)); - Assert.AreEqual(filename, downloader.Package.FileName); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.IsTrue(DummyFileHelper.File16Kb.AreEqual(File.OpenRead(downloader.Package.FileName))); + Assert.True(downloader.Package.IsSaveComplete); + Assert.True(File.Exists(downloader.Package.FileName)); + Assert.NotNull(downloader.Package.FileName); + Assert.StartsWith(DummyFileHelper.TempDirectory, downloader.Package.FileName); + Assert.Equal(filename, downloader.Package.FileName); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.True(DummyFileHelper.File16Kb.AreEqual(File.OpenRead(downloader.Package.FileName))); File.Delete(downloader.Package.FileName); } - [TestMethod] + [Fact] public async Task Download16KbWithFilenameTest() { // arrange var downloader = new DownloadService(Config); // act - await downloader.DownloadFileTaskAsync(URL, Path.GetTempFileName()).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL, Path.GetTempFileName()); // assert - Assert.IsTrue(File.Exists(downloader.Package.FileName)); - Assert.IsNotNull(downloader.Package.FileName); - Assert.IsTrue(downloader.Package.FileName.StartsWith(DummyFileHelper.TempDirectory)); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.IsTrue(DummyFileHelper.File16Kb.AreEqual(File.OpenRead(downloader.Package.FileName))); + Assert.True(File.Exists(downloader.Package.FileName)); + Assert.NotNull(downloader.Package.FileName); + Assert.StartsWith(DummyFileHelper.TempDirectory, downloader.Package.FileName); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.True(DummyFileHelper.File16Kb.AreEqual(File.OpenRead(downloader.Package.FileName))); File.Delete(downloader.Package.FileName); } - [TestMethod] - [Timeout(20_000)] + [Fact(Timeout = 20_000)] public async Task Download1KbWhenAnotherBiggerFileExistTest() { // arrange @@ -140,34 +134,34 @@ public async Task Download1KbWhenAnotherBiggerFileExistTest() // write file bigger than download file await File.WriteAllBytesAsync(file.FullName, DummyData.GenerateSingleBytes(2048, 250)); // override file with downloader - await downloader.DownloadFileTaskAsync(url1KbFile, file.FullName).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(url1KbFile, file.FullName); // assert - Assert.IsTrue(File.Exists(file.FullName)); - Assert.AreEqual(file.FullName, downloader.Package.FileName); - Assert.AreEqual(DummyFileHelper.FileSize1Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize1Kb, file.Length); - Assert.IsTrue(DummyFileHelper.File1Kb.AreEqual(file.OpenRead())); + Assert.True(File.Exists(file.FullName)); + Assert.Equal(file.FullName, downloader.Package.FileName); + Assert.Equal(DummyFileHelper.FileSize1Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize1Kb, file.Length); + Assert.True(DummyFileHelper.File1Kb.AreEqual(file.OpenRead())); file.Delete(); } - [TestMethod] + [Fact] public async Task Download16KbOnMemoryTest() { // arrange var downloader = new DownloadService(Config); // act - var fileBytes = await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + var fileBytes = await downloader.DownloadFileTaskAsync(URL); // assert - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, fileBytes.Length); - Assert.IsTrue(DummyFileHelper.File16Kb.AreEqual(fileBytes)); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, fileBytes.Length); + Assert.True(DummyFileHelper.File16Kb.AreEqual(fileBytes)); } - [TestMethod] + [Fact] public async Task DownloadProgressChangedTest() { // arrange @@ -177,17 +171,17 @@ public async Task DownloadProgressChangedTest() downloader.DownloadProgressChanged += (s, e) => Interlocked.Increment(ref progressCounter); // act - await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL); // assert // Note: some times received bytes on read stream method was less than block size! - Assert.IsTrue(progressChangedCount <= progressCounter); - Assert.AreEqual(100.0, downloader.Package.SaveProgress); - Assert.IsTrue(downloader.Package.IsSaveComplete); - Assert.IsFalse(downloader.Package.IsSaving); + Assert.True(progressChangedCount <= progressCounter); + Assert.Equal(100.0, downloader.Package.SaveProgress); + Assert.True(downloader.Package.IsSaveComplete); + Assert.False(downloader.Package.IsSaving); } - [TestMethod] + [Fact] public async Task StopResumeDownloadTest() { // arrange @@ -211,32 +205,32 @@ public async Task StopResumeDownloadTest() if (expectedStopCount > stopCount) { // Stopping after start of downloading - await downloader.CancelTaskAsync().ConfigureAwait(false); + await downloader.CancelTaskAsync(); stopCount++; } }; // act - await downloader.DownloadFileTaskAsync(URL, Path.GetTempFileName()).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL, Path.GetTempFileName()); while (expectedStopCount > downloadFileExecutionCounter++) { // resume download from stopped point. - await downloader.DownloadFileTaskAsync(downloader.Package).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(downloader.Package); } var stream = File.ReadAllBytes(downloader.Package.FileName); // assert - Assert.IsTrue(File.Exists(downloader.Package.FileName)); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(expectedStopCount, stopCount); - Assert.AreEqual(expectedStopCount, cancellationsOccurrenceCount); - Assert.IsTrue(downloadCompletedSuccessfully); - Assert.IsTrue(DummyFileHelper.File16Kb.SequenceEqual(stream.ToArray())); + Assert.True(File.Exists(downloader.Package.FileName)); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(expectedStopCount, stopCount); + Assert.Equal(expectedStopCount, cancellationsOccurrenceCount); + Assert.True(downloadCompletedSuccessfully); + Assert.True(DummyFileHelper.File16Kb.SequenceEqual(stream.ToArray())); File.Delete(downloader.Package.FileName); } - [TestMethod] + [Fact] public async Task PauseResumeDownloadTest() { // arrange @@ -259,21 +253,21 @@ public async Task PauseResumeDownloadTest() }; // act - await downloader.DownloadFileTaskAsync(URL, Path.GetTempFileName()).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL, Path.GetTempFileName()); var stream = File.ReadAllBytes(downloader.Package.FileName); // assert - Assert.IsFalse(downloader.IsPaused); - Assert.IsTrue(File.Exists(downloader.Package.FileName)); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(expectedPauseCount, pauseCount); - Assert.IsTrue(downloadCompletedSuccessfully); - Assert.IsTrue(DummyFileHelper.File16Kb.SequenceEqual(stream.ToArray())); + Assert.False(downloader.IsPaused); + Assert.True(File.Exists(downloader.Package.FileName)); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(expectedPauseCount, pauseCount); + Assert.True(downloadCompletedSuccessfully); + Assert.True(DummyFileHelper.File16Kb.SequenceEqual(stream.ToArray())); File.Delete(downloader.Package.FileName); } - [TestMethod] + [Fact] public async Task StopResumeDownloadFromLastPositionTest() { // arrange @@ -298,20 +292,20 @@ public async Task StopResumeDownloadFromLastPositionTest() }; // act - await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL); while (expectedStopCount > downloadFileExecutionCounter++) { // resume download from stopped point. - await downloader.DownloadFileTaskAsync(downloader.Package).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(downloader.Package); } // assert - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, totalProgressedByteSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, totalReceivedBytes); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, totalProgressedByteSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, totalReceivedBytes); } - [TestMethod] + [Fact] public async Task StopResumeDownloadOverFirstPackagePositionTest() { // arrange @@ -325,12 +319,12 @@ public async Task StopResumeDownloadOverFirstPackagePositionTest() if (--cancellationCount > 0) { // Stopping after start of downloading - await downloader.CancelTaskAsync().ConfigureAwait(false); + await downloader.CancelTaskAsync(); } }; // act - var result = await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + var result = await downloader.DownloadFileTaskAsync(URL); // check point of package for once time var firstCheckPointPackage = JsonConvert.SerializeObject(downloader.Package); @@ -340,19 +334,19 @@ public async Task StopResumeDownloadOverFirstPackagePositionTest() var restoredPackage = JsonConvert.DeserializeObject(firstCheckPointPackage); // resume download from first stopped point. - result = await downloader.DownloadFileTaskAsync(restoredPackage).ConfigureAwait(false); + result = await downloader.DownloadFileTaskAsync(restoredPackage); } // assert - Assert.IsTrue(downloader.Package.IsSaveComplete); - Assert.IsFalse(downloader.Package.IsSaving); - Assert.IsFalse(isSavingStateOnCancel); - Assert.IsTrue(isSavingStateBeforCancel); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, result.Length); + Assert.True(downloader.Package.IsSaveComplete); + Assert.False(downloader.Package.IsSaving); + Assert.False(isSavingStateOnCancel); + Assert.True(isSavingStateBeforCancel); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, result.Length); } - [TestMethod] + [Fact] public async Task TestTotalReceivedBytesWhenResumeDownload() { // arrange @@ -370,24 +364,24 @@ public async Task TestTotalReceivedBytesWhenResumeDownload() if (canStopDownload && totalDownloadSize > DummyFileHelper.FileSize16Kb / 2) { // Stopping after start of downloading - await downloader.CancelTaskAsync().ConfigureAwait(false); + await downloader.CancelTaskAsync(); canStopDownload = false; } }; // act - await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); - await downloader.DownloadFileTaskAsync(downloader.Package).ConfigureAwait(false); // resume download from stopped point. + await downloader.DownloadFileTaskAsync(URL); + await downloader.DownloadFileTaskAsync(downloader.Package); // resume download from stopped point. // assert - Assert.IsTrue(downloader.Package.IsSaveComplete); - Assert.IsFalse(downloader.IsCancelled); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, totalDownloadSize); - Assert.AreEqual(100.0, lastProgressPercentage); + Assert.True(downloader.Package.IsSaveComplete); + Assert.False(downloader.IsCancelled); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, totalDownloadSize); + Assert.Equal(100.0, lastProgressPercentage); } - [TestMethod] + [Fact] public async Task TestTotalReceivedBytesOnResumeDownloadWhenLostDownloadedData() { // arrange @@ -411,18 +405,18 @@ public async Task TestTotalReceivedBytesOnResumeDownloadWhenLostDownloadedData() }; // act - await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL); downloader.Package.Storage.Dispose(); // set position to zero - await downloader.DownloadFileTaskAsync(downloader.Package).ConfigureAwait(false); // resume download from stopped point. + await downloader.DownloadFileTaskAsync(downloader.Package); // resume download from stopped point. // assert - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, totalDownloadSize); - Assert.AreEqual(100.0, lastProgressPercentage); - Assert.AreEqual(100.0, downloader.Package.SaveProgress); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, totalDownloadSize); + Assert.Equal(100.0, lastProgressPercentage); + Assert.Equal(100.0, downloader.Package.SaveProgress); } - [TestMethod] + [Fact] //[Timeout(17_000)] public async Task SpeedLimitTest() { @@ -438,14 +432,14 @@ public async Task SpeedLimitTest() }; // act - await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL); // assert - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.IsTrue(averageSpeed <= Config.MaximumBytesPerSecond * 1.5, $"Average Speed: {averageSpeed} , Speed Limit: {Config.MaximumBytesPerSecond}"); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.True(averageSpeed <= Config.MaximumBytesPerSecond * 1.5, $"Average Speed: {averageSpeed} , Speed Limit: {Config.MaximumBytesPerSecond}"); } - [TestMethod] + [Fact] public async Task DynamicSpeedLimitTest() { // arrange @@ -467,44 +461,44 @@ public async Task DynamicSpeedLimitTest() }; // act - await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL); averageSpeed /= progressCounter; // assert - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.IsTrue(averageSpeed <= expectedAverageSpeed * upperTolerance, + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.True(averageSpeed <= expectedAverageSpeed * upperTolerance, $"Avg Speed: {averageSpeed} , Expected Avg Speed Limit: {expectedAverageSpeed * upperTolerance}, " + $"Progress Count: {progressCounter}"); } - [TestMethod] + [Fact] public async Task TestSizeWhenDownloadOnMemoryStream() { // arrange var downloader = new DownloadService(Config); // act - using var stream = await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + using var stream = await downloader.DownloadFileTaskAsync(URL); // assert - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, stream.Length); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, stream.Length); } - [TestMethod] + [Fact] public async Task TestTypeWhenDownloadOnMemoryStream() { // arrange var downloader = new DownloadService(Config); // act - using var stream = await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + using var stream = await downloader.DownloadFileTaskAsync(URL); // assert - Assert.IsTrue(stream is MemoryStream); + Assert.True(stream is MemoryStream); } - [TestMethod] + [Fact] public async Task TestContentWhenDownloadOnMemoryStream() { // arrange @@ -515,11 +509,10 @@ public async Task TestContentWhenDownloadOnMemoryStream() var memStream = stream as MemoryStream; // assert - Assert.IsTrue(DummyFileHelper.File16Kb.SequenceEqual(memStream.ToArray())); + Assert.True(DummyFileHelper.File16Kb.SequenceEqual(memStream.ToArray())); } - [TestMethod] - [Timeout(60_000)] + [Fact(Timeout = 60_000)] public async Task Download256BytesRangeOfFileTest() { // arrange @@ -534,15 +527,15 @@ public async Task Download256BytesRangeOfFileTest() var bytes = ((MemoryStream)stream).ToArray(); // assert - Assert.IsNotNull(stream); - Assert.AreEqual(totalSize, stream.Length); - Assert.AreEqual(totalSize, downloader.Package.TotalFileSize); - Assert.AreEqual(100.0, downloader.Package.SaveProgress); + Assert.NotNull(stream); + Assert.Equal(totalSize, stream.Length); + Assert.Equal(totalSize, downloader.Package.TotalFileSize); + Assert.Equal(100.0, downloader.Package.SaveProgress); for (int i = 0; i < totalSize; i++) - Assert.AreEqual((byte)i, bytes[i]); + Assert.Equal((byte)i, bytes[i]); } - [TestMethod] + [Fact] public async Task DownloadNegetiveRangeOfFileTest() { // arrange @@ -553,19 +546,19 @@ public async Task DownloadNegetiveRangeOfFileTest() var downloader = new DownloadService(Config); // act - using var stream = await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + using var stream = await downloader.DownloadFileTaskAsync(URL); var bytes = ((MemoryStream)stream).ToArray(); // assert - Assert.IsNotNull(stream); - Assert.AreEqual(totalSize, stream.Length); - Assert.AreEqual(totalSize, downloader.Package.TotalFileSize); - Assert.AreEqual(100.0, downloader.Package.SaveProgress); + Assert.NotNull(stream); + Assert.Equal(totalSize, stream.Length); + Assert.Equal(totalSize, downloader.Package.TotalFileSize); + Assert.Equal(100.0, downloader.Package.SaveProgress); for (int i = 0; i < totalSize; i++) - Assert.AreEqual((byte)i, bytes[i]); + Assert.Equal((byte)i, bytes[i]); } - [TestMethod] + [Fact] public async Task TestDownloadParallelVsHalfOfChunks() { // arrange @@ -578,21 +571,20 @@ public async Task TestDownloadParallelVsHalfOfChunks() }; // act - using var stream = await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); + using var stream = await downloader.DownloadFileTaskAsync(URL); var bytes = ((MemoryStream)stream).ToArray(); // assert - Assert.IsTrue(maxParallelCountTasks >= actualMaxParallelCountTasks); - Assert.IsNotNull(stream); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, stream.Length); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(100.0, downloader.Package.SaveProgress); + Assert.True(maxParallelCountTasks >= actualMaxParallelCountTasks); + Assert.NotNull(stream); + Assert.Equal(DummyFileHelper.FileSize16Kb, stream.Length); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(100.0, downloader.Package.SaveProgress); for (int i = 0; i < DummyFileHelper.FileSize16Kb; i++) - Assert.AreEqual((byte)i, bytes[i]); + Assert.Equal((byte)i, bytes[i]); } - [TestMethod] - [Timeout(10000)] + [Fact(Timeout = 10_000)] public async Task TestResumeImmediatelyAfterCanceling() { // arrange @@ -614,23 +606,23 @@ public async Task TestResumeImmediatelyAfterCanceling() }; // act - await downloader.DownloadFileTaskAsync(URL).ConfigureAwait(false); - using var stream = await downloader.DownloadFileTaskAsync(downloader.Package).ConfigureAwait(false); // resume + await downloader.DownloadFileTaskAsync(URL); + using var stream = await downloader.DownloadFileTaskAsync(downloader.Package); // resume // assert - Assert.IsTrue(stopped); - Assert.IsTrue(lastProgressPercentage > 50); - Assert.IsTrue(downloader.Package.IsSaveComplete); - Assert.IsFalse(downloader.IsCancelled); + Assert.True(stopped); + Assert.True(lastProgressPercentage > 50); + Assert.True(downloader.Package.IsSaveComplete); + Assert.False(downloader.IsCancelled); } - [TestMethod] + [Fact] public async Task KeepFileWhenDownloadFailedTest() { await KeepOrRemoveFileWhenDownloadFailedTest(false); } - [TestMethod] + [Fact] public async Task RemoveFileWhenDownloadFailedTest() { await KeepOrRemoveFileWhenDownloadFailedTest(true); @@ -646,22 +638,22 @@ private async Task KeepOrRemoveFileWhenDownloadFailedTest(bool clearFileAfterFai var url = DummyFileHelper.GetFileWithFailureAfterOffset(DummyFileHelper.FileSize16Kb, DummyFileHelper.FileSize16Kb / 2); // act - await downloadService.DownloadFileTaskAsync(url, filename).ConfigureAwait(false); + await downloadService.DownloadFileTaskAsync(url, filename); // assert - Assert.AreEqual(filename, downloadService.Package.FileName); - Assert.IsFalse(downloadService.Package.IsSaveComplete); - Assert.IsFalse(downloadService.Package.IsSaving); - Assert.AreNotEqual(clearFileAfterFailure, File.Exists(filename)); + Assert.Equal(filename, downloadService.Package.FileName); + Assert.False(downloadService.Package.IsSaveComplete); + Assert.False(downloadService.Package.IsSaving); + Assert.NotEqual(clearFileAfterFailure, File.Exists(filename)); } - [TestMethod] + [Fact] public async Task TestRetryDownloadAfterTimeout() { await testRetryDownloadAfterFailure(true); } - [TestMethod] + [Fact] public async Task TestRetryDownloadAfterFailure() { await testRetryDownloadAfterFailure(false); @@ -685,22 +677,22 @@ private async Task testRetryDownloadAfterFailure(bool timeout) downloadService.DownloadFileCompleted += (s, e) => error = e.Error; // act - var stream = await downloadService.DownloadFileTaskAsync(url).ConfigureAwait(false); + var stream = await downloadService.DownloadFileTaskAsync(url); var retryCount = downloadService.Package.Chunks.Sum(chunk => chunk.FailoverCount); // assert - Assert.IsFalse(downloadService.Package.IsSaveComplete); - Assert.IsFalse(downloadService.Package.IsSaving); - Assert.AreEqual(DownloadStatus.Failed, downloadService.Package.Status); - Assert.IsTrue(Config.MaxTryAgainOnFailover <= retryCount); - Assert.IsNotNull(error); - Assert.IsInstanceOfType(error, typeof(WebException)); - Assert.AreEqual(failureOffset, stream.Length); + Assert.False(downloadService.Package.IsSaveComplete); + Assert.False(downloadService.Package.IsSaving); + Assert.Equal(DownloadStatus.Failed, downloadService.Package.Status); + Assert.True(Config.MaxTryAgainOnFailover <= retryCount); + Assert.NotNull(error); + Assert.IsType(error); + Assert.Equal(failureOffset, stream.Length); await stream.DisposeAsync(); } - [TestMethod] + [Fact] public async Task DownloadMultipleFilesWithOneDownloaderInstanceTest() { // arrange @@ -713,17 +705,17 @@ public async Task DownloadMultipleFilesWithOneDownloaderInstanceTest() var downloader = new DownloadService(Config); // act - var file1 = await downloader.DownloadFileTaskAsync(url1).ConfigureAwait(false); - var file2 = await downloader.DownloadFileTaskAsync(url2).ConfigureAwait(false); - var file3 = await downloader.DownloadFileTaskAsync(url3).ConfigureAwait(false); + var file1 = await downloader.DownloadFileTaskAsync(url1); + var file2 = await downloader.DownloadFileTaskAsync(url2); + var file3 = await downloader.DownloadFileTaskAsync(url3); // assert - Assert.AreEqual(size1, file1.Length); - Assert.AreEqual(size2, file2.Length); - Assert.AreEqual(size3, file3.Length); + Assert.Equal(size1, file1.Length); + Assert.Equal(size2, file2.Length); + Assert.Equal(size3, file3.Length); } - [TestMethod] + [Fact] public async Task TestStopDownloadWithCancellationToken() { // arrange @@ -742,16 +734,16 @@ public async Task TestStopDownloadWithCancellationToken() }; // act - await downloader.DownloadFileTaskAsync(URL, cancelltionTokenSource.Token).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(URL, cancelltionTokenSource.Token); // assert - Assert.IsTrue(downloadCancelled); - Assert.IsTrue(downloader.IsCancelled); - Assert.IsTrue(downloader.Status == DownloadStatus.Stopped); - Assert.IsTrue(downloadProgress > 10); + Assert.True(downloadCancelled); + Assert.True(downloader.IsCancelled); + Assert.True(downloader.Status == DownloadStatus.Stopped); + Assert.True(downloadProgress > 10); } - [TestMethod] + [Fact] public async Task TestResumeDownloadWithAnotherUrl() { // arrange @@ -774,29 +766,29 @@ public async Task TestResumeDownloadWithAnotherUrl() }; // act - await downloader.DownloadFileTaskAsync(url1).ConfigureAwait(false); + await downloader.DownloadFileTaskAsync(url1); await downloader.DownloadFileTaskAsync(downloader.Package, url2); // resume download with new url2. // assert - Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, totalDownloadSize); - Assert.AreEqual(downloader.Package.Storage.Length, DummyFileHelper.FileSize16Kb); - Assert.AreEqual(100.0, downloader.Package.SaveProgress); + Assert.Equal(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize); + Assert.Equal(DummyFileHelper.FileSize16Kb, totalDownloadSize); + Assert.Equal(downloader.Package.Storage.Length, DummyFileHelper.FileSize16Kb); + Assert.Equal(100.0, downloader.Package.SaveProgress); } - [TestMethod] + [Fact] public async Task DownloadAFileFrom8UrlsWith8ChunksTest() { await DownloadAFileFromMultipleUrlsWithMultipleChunksTest(8, 8); } - [TestMethod] + [Fact] public async Task DownloadAFileFrom2UrlsWith8ChunksTest() { await DownloadAFileFromMultipleUrlsWithMultipleChunksTest(2, 8); } - [TestMethod] + [Fact] public async Task DownloadAFileFrom8UrlsWith2ChunksTest() { await DownloadAFileFromMultipleUrlsWithMultipleChunksTest(8, 2); @@ -815,19 +807,19 @@ public async Task DownloadAFileFromMultipleUrlsWithMultipleChunksTest(int urlsCo .ToArray(); // act - using var stream = await downloader.DownloadFileTaskAsync(urls).ConfigureAwait(false); + using var stream = await downloader.DownloadFileTaskAsync(urls); var bytes = ((MemoryStream)stream).ToArray(); // assert - Assert.IsNotNull(stream); - Assert.AreEqual(totalSize, stream.Length); - Assert.AreEqual(totalSize, downloader.Package.TotalFileSize); - Assert.AreEqual(100.0, downloader.Package.SaveProgress); + Assert.NotNull(stream); + Assert.Equal(totalSize, stream.Length); + Assert.Equal(totalSize, downloader.Package.TotalFileSize); + Assert.Equal(100.0, downloader.Package.SaveProgress); for (int i = 0; i < totalSize; i++) { var chunkIndex = (byte)(i / chunkSize); var expectedByte = (chunkIndex % urlsCount) + 1; - Assert.AreEqual(expectedByte, bytes[i]); + Assert.Equal(expectedByte, bytes[i]); } } diff --git a/src/Downloader.Test/IntegrationTests/DownloadServiceTest.cs b/src/Downloader.Test/IntegrationTests/DownloadServiceTest.cs index d2643d2..b074725 100644 --- a/src/Downloader.Test/IntegrationTests/DownloadServiceTest.cs +++ b/src/Downloader.Test/IntegrationTests/DownloadServiceTest.cs @@ -1,6 +1,5 @@ using Downloader.DummyHttpServer; using Downloader.Test.Helper; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,23 +7,28 @@ using System.IO; using System.Linq; using System.Net; -using System.Threading; using System.Threading.Tasks; +using Xunit; namespace Downloader.Test.IntegrationTests; -[TestClass] -public class DownloadServiceTest : DownloadService +public class DownloadServiceTest : DownloadService, IAsyncLifetime { private string Filename { get; set; } - [TestCleanup] - public void Cleanup() + public Task InitializeAsync() + { + return Task.CompletedTask; + } + + public virtual Task DisposeAsync() { Package?.Clear(); Package?.Storage?.Dispose(); if (!string.IsNullOrWhiteSpace(Filename)) File.Delete(Filename); + + return Task.CompletedTask; } private DownloadConfiguration GetDefaultConfig() @@ -46,7 +50,7 @@ private DownloadConfiguration GetDefaultConfig() }; } - [TestMethod] + [Fact] public async Task CancelAsyncTest() { // arrange @@ -60,13 +64,13 @@ public async Task CancelAsyncTest() await DownloadFileTaskAsync(address); // assert - Assert.IsTrue(IsCancelled); - Assert.IsNotNull(eventArgs); - Assert.IsTrue(eventArgs.Cancelled); - Assert.AreEqual(typeof(TaskCanceledException), eventArgs.Error.GetType()); + Assert.True(IsCancelled); + Assert.NotNull(eventArgs); + Assert.True(eventArgs.Cancelled); + Assert.Equal(typeof(TaskCanceledException), eventArgs.Error.GetType()); } - [TestMethod] + [Fact] public async Task CancelTaskAsyncTest() { // arrange @@ -80,14 +84,13 @@ public async Task CancelTaskAsyncTest() await DownloadFileTaskAsync(address); // assert - Assert.IsTrue(IsCancelled); - Assert.IsNotNull(eventArgs); - Assert.IsTrue(eventArgs.Cancelled); - Assert.AreEqual(typeof(TaskCanceledException), eventArgs.Error.GetType()); + Assert.True(IsCancelled); + Assert.NotNull(eventArgs); + Assert.True(eventArgs.Cancelled); + Assert.Equal(typeof(TaskCanceledException), eventArgs.Error.GetType()); } - [TestMethod] - //[Timeout(10000)] + [Fact(Timeout = 30_000)] public async Task CompletesWithErrorWhenBadUrlTest() { // arrange @@ -104,12 +107,12 @@ public async Task CompletesWithErrorWhenBadUrlTest() await DownloadFileTaskAsync(address, Filename); // assert - Assert.IsFalse(IsBusy); - Assert.IsNotNull(onCompletionException); - Assert.AreEqual(typeof(WebException), onCompletionException.GetType()); + Assert.False(IsBusy); + Assert.NotNull(onCompletionException); + Assert.Equal(typeof(WebException), onCompletionException.GetType()); } - [TestMethod] + [Fact] public async Task ClearTest() { // arrange @@ -119,10 +122,10 @@ public async Task ClearTest() await Clear(); // assert - Assert.IsFalse(IsCancelled); + Assert.False(IsCancelled); } - [TestMethod] + [Fact] public async Task TestPackageSituationAfterDispose() { // arrange @@ -139,12 +142,12 @@ public async Task TestPackageSituationAfterDispose() Dispose(); // assert - Assert.IsNotNull(Package.Chunks); - Assert.AreEqual(sampleDataLength, Package.Storage.Length); - Assert.AreEqual(sampleDataLength * 64, Package.TotalFileSize); + Assert.NotNull(Package.Chunks); + Assert.Equal(sampleDataLength, Package.Storage.Length); + Assert.Equal(sampleDataLength * 64, Package.TotalFileSize); } - [TestMethod] + [Fact] public async Task TestPackageChunksDataAfterDispose() { // arrange @@ -165,16 +168,16 @@ public async Task TestPackageChunksDataAfterDispose() var stream = Package.Storage.OpenRead(); // assert - Assert.IsNotNull(Package.Chunks); + Assert.NotNull(Package.Chunks); for (int i = 0; i < Package.Chunks.Length; i++) { var buffer = new byte[chunkSize]; await stream.ReadAsync(buffer, 0, chunkSize); - Assert.IsTrue(dummyData.SequenceEqual(buffer)); + Assert.True(dummyData.SequenceEqual(buffer)); } } - [TestMethod] + [Fact] public async Task CancelPerformanceTest() { // arrange @@ -193,13 +196,13 @@ public async Task CancelPerformanceTest() watch.Stop(); // assert - Assert.IsTrue(eventArgs?.Cancelled); - Assert.IsTrue(watch.ElapsedMilliseconds < 1000); - Assert.AreEqual(4, Options.ParallelCount); - Assert.AreEqual(8, Options.ChunkCount); + Assert.True(eventArgs?.Cancelled); + Assert.True(watch.ElapsedMilliseconds < 1000); + Assert.Equal(4, Options.ParallelCount); + Assert.Equal(8, Options.ChunkCount); } - [TestMethod] + [Fact] public async Task ResumePerformanceTest() { // arrange @@ -227,13 +230,13 @@ public async Task ResumePerformanceTest() await DownloadFileTaskAsync(Package); // assert - Assert.IsFalse(eventArgs?.Cancelled); - Assert.IsTrue(watch.ElapsedMilliseconds < 1000); - Assert.AreEqual(4, Options.ParallelCount); - Assert.AreEqual(8, Options.ChunkCount); + Assert.False(eventArgs?.Cancelled); + Assert.True(watch.ElapsedMilliseconds < 1000); + Assert.Equal(4, Options.ParallelCount); + Assert.Equal(8, Options.ChunkCount); } - [TestMethod] + [Fact] public async Task PauseResumeTest() { // arrange @@ -254,13 +257,13 @@ public async Task PauseResumeTest() await DownloadFileTaskAsync(address); // assert - Assert.IsTrue(paused); - Assert.IsFalse(cancelled); - Assert.AreEqual(4, Options.ParallelCount); - Assert.AreEqual(8, Options.ChunkCount); + Assert.True(paused); + Assert.False(cancelled); + Assert.Equal(4, Options.ParallelCount); + Assert.Equal(8, Options.ChunkCount); } - [TestMethod] + [Fact] public async Task CancelAfterPauseTest() { // arrange @@ -285,18 +288,18 @@ public async Task CancelAfterPauseTest() await DownloadFileTaskAsync(address); // assert - Assert.IsTrue(pauseStateBeforeCancel); - Assert.IsFalse(cancelStateBeforeCancel); - Assert.IsFalse(pauseStateAfterCancel); - Assert.IsTrue(cancelStateAfterCancel); - Assert.AreEqual(4, Options.ParallelCount); - Assert.AreEqual(8, Options.ChunkCount); - Assert.AreEqual(8, Options.ChunkCount); - Assert.IsFalse(Package.IsSaveComplete); - Assert.IsTrue(eventArgs.Cancelled); + Assert.True(pauseStateBeforeCancel); + Assert.False(cancelStateBeforeCancel); + Assert.False(pauseStateAfterCancel); + Assert.True(cancelStateAfterCancel); + Assert.Equal(4, Options.ParallelCount); + Assert.Equal(8, Options.ChunkCount); + Assert.Equal(8, Options.ChunkCount); + Assert.False(Package.IsSaveComplete); + Assert.True(eventArgs.Cancelled); } - [TestMethod] + [Fact] public async Task DownloadParallelNotSupportedUrlTest() { // arrange @@ -313,16 +316,16 @@ public async Task DownloadParallelNotSupportedUrlTest() await DownloadFileTaskAsync(address); // assert - Assert.IsFalse(Package.IsSupportDownloadInRange); - Assert.AreEqual(1, Options.ParallelCount); - Assert.AreEqual(1, Options.ChunkCount); - Assert.IsFalse(eventArgs?.Cancelled); - Assert.IsTrue(Package.IsSaveComplete); - Assert.IsNull(eventArgs?.Error); - Assert.AreEqual(1, actualChunksCount); + Assert.False(Package.IsSupportDownloadInRange); + Assert.Equal(1, Options.ParallelCount); + Assert.Equal(1, Options.ChunkCount); + Assert.False(eventArgs?.Cancelled); + Assert.True(Package.IsSaveComplete); + Assert.Null(eventArgs?.Error); + Assert.Equal(1, actualChunksCount); } - [TestMethod] + [Fact] public async Task ResumeNotSupportedUrlTest() { // arrange @@ -353,18 +356,18 @@ public async Task ResumeNotSupportedUrlTest() await DownloadFileTaskAsync(Package); // resume the downlaod after canceling // assert - Assert.IsTrue(isCancelled); - Assert.IsFalse(Package.IsSupportDownloadInRange); - Assert.AreEqual(1, Options.ParallelCount); - Assert.AreEqual(1, Options.ChunkCount); - Assert.IsFalse(eventArgs?.Cancelled); - Assert.IsTrue(Package.IsSaveComplete); - Assert.IsNull(eventArgs?.Error); - Assert.AreEqual(1, actualChunksCount); - Assert.AreEqual(100, maxProgressPercentage); + Assert.True(isCancelled); + Assert.False(Package.IsSupportDownloadInRange); + Assert.Equal(1, Options.ParallelCount); + Assert.Equal(1, Options.ChunkCount); + Assert.False(eventArgs?.Cancelled); + Assert.True(Package.IsSaveComplete); + Assert.Null(eventArgs?.Error); + Assert.Equal(1, actualChunksCount); + Assert.Equal(100, maxProgressPercentage); } - [TestMethod] + [Fact] public async Task ActiveChunksTest() { // arrange @@ -379,15 +382,15 @@ public async Task ActiveChunksTest() await DownloadFileTaskAsync(address); // assert - Assert.AreEqual(4, Options.ParallelCount); - Assert.AreEqual(8, Options.ChunkCount); - Assert.IsTrue(Package.IsSupportDownloadInRange); - Assert.IsTrue(Package.IsSaveComplete); + Assert.Equal(4, Options.ParallelCount); + Assert.Equal(8, Options.ChunkCount); + Assert.True(Package.IsSupportDownloadInRange); + Assert.True(Package.IsSaveComplete); foreach (var activeChunks in allActiveChunksCount) - Assert.IsTrue(activeChunks >= 1 && activeChunks <= 4); + Assert.True(activeChunks >= 1 && activeChunks <= 4); } - [TestMethod] + [Fact] public async Task ActiveChunksWithRangeNotSupportedUrlTest() { // arrange @@ -402,15 +405,15 @@ public async Task ActiveChunksWithRangeNotSupportedUrlTest() await DownloadFileTaskAsync(address); // assert - Assert.AreEqual(1, Options.ParallelCount); - Assert.AreEqual(1, Options.ChunkCount); - Assert.IsFalse(Package.IsSupportDownloadInRange); - Assert.IsTrue(Package.IsSaveComplete); + Assert.Equal(1, Options.ParallelCount); + Assert.Equal(1, Options.ChunkCount); + Assert.False(Package.IsSupportDownloadInRange); + Assert.True(Package.IsSaveComplete); foreach (var activeChunks in allActiveChunksCount) - Assert.IsTrue(activeChunks >= 1 && activeChunks <= 4); + Assert.True(activeChunks >= 1 && activeChunks <= 4); } - [TestMethod] + [Fact] public async Task ActiveChunksAfterCancelResumeWithNotSupportedUrlTest() { // arrange @@ -439,17 +442,17 @@ public async Task ActiveChunksAfterCancelResumeWithNotSupportedUrlTest() await DownloadFileTaskAsync(Package); // resume the downlaod after canceling // assert - Assert.IsTrue(isCancelled); - Assert.IsFalse(Package.IsSupportDownloadInRange); - Assert.IsTrue(Package.IsSaveComplete); - Assert.AreEqual(1, actualChunksCount); - Assert.AreEqual(1, Options.ParallelCount); - Assert.AreEqual(1, Options.ChunkCount); + Assert.True(isCancelled); + Assert.False(Package.IsSupportDownloadInRange); + Assert.True(Package.IsSaveComplete); + Assert.Equal(1, actualChunksCount); + Assert.Equal(1, Options.ParallelCount); + Assert.Equal(1, Options.ChunkCount); foreach (var activeChunks in allActiveChunksCount) - Assert.IsTrue(activeChunks >= 1 && activeChunks <= 4); + Assert.True(activeChunks >= 1 && activeChunks <= 4); } - [TestMethod] + [Fact] public async Task TestPackageDataAfterCompletionWithSuccess() { // arrange @@ -461,16 +464,16 @@ public async Task TestPackageDataAfterCompletionWithSuccess() await DownloadFileTaskAsync(url); // assert - Assert.AreEqual(url, Package.Urls.First()); - Assert.IsTrue(states.DownloadSuccessfullCompleted); - Assert.IsTrue(states.DownloadProgressIsCorrect); - Assert.IsNull(states.DownloadError); - Assert.IsTrue(Package.IsSaveComplete); - Assert.IsFalse(Package.IsSaving); - Assert.IsNull(Package.Chunks); + Assert.Equal(url, Package.Urls.First()); + Assert.True(states.DownloadSuccessfullCompleted); + Assert.True(states.DownloadProgressIsCorrect); + Assert.Null(states.DownloadError); + Assert.True(Package.IsSaveComplete); + Assert.False(Package.IsSaving); + Assert.Null(Package.Chunks); } - [TestMethod] + [Fact] public async Task TestPackageStatusAfterCompletionWithSuccess() { // arrange @@ -499,28 +502,19 @@ public async Task TestPackageStatusAfterCompletionWithSuccess() await DownloadFileTaskAsync(url); // assert - Assert.IsTrue(Package.IsSaveComplete); - Assert.IsFalse(Package.IsSaving); - Assert.AreEqual(DownloadStatus.Completed, Package.Status); - Assert.AreEqual(DownloadStatus.Running, createdStatus); - Assert.AreEqual(DownloadStatus.Running, runningStatus); - Assert.AreEqual(DownloadStatus.Paused, pausedStatus); - Assert.AreEqual(DownloadStatus.Running, resumeStatus); - Assert.AreEqual(DownloadStatus.Completed, completedStatus); - } - - [TestMethod] - public async Task TestSerializePackageAfterCancelOnMemory() - { - await TestSerializePackageAfterCancel(true); - } - - [TestMethod] - public async Task TestSerializePackageAfterCancelOnFile() - { - await TestSerializePackageAfterCancel(false); + Assert.True(Package.IsSaveComplete); + Assert.False(Package.IsSaving); + Assert.Equal(DownloadStatus.Completed, Package.Status); + Assert.Equal(DownloadStatus.Running, createdStatus); + Assert.Equal(DownloadStatus.Running, runningStatus); + Assert.Equal(DownloadStatus.Paused, pausedStatus); + Assert.Equal(DownloadStatus.Running, resumeStatus); + Assert.Equal(DownloadStatus.Completed, completedStatus); } + [Theory] + [InlineData(true)] + [InlineData(false)] public async Task TestSerializePackageAfterCancel(bool onMemory) { // arrange @@ -547,25 +541,14 @@ public async Task TestSerializePackageAfterCancel(bool onMemory) } // assert - Assert.IsTrue(IsCancelled); - Assert.IsNotNull(package); - Assert.IsFalse(string.IsNullOrWhiteSpace(packageText)); - - Cleanup(); - } - - [TestMethod] - public async Task TestResumeFromSerializedPackageOnMemory() - { - await TestResumeFromSerializedPackage(true); - } - - [TestMethod] - public async Task TestResumeFromSerializedPackageOnFile() - { - await TestResumeFromSerializedPackage(false); + Assert.True(IsCancelled); + Assert.NotNull(package); + Assert.False(string.IsNullOrWhiteSpace(packageText)); } + [Theory] + [InlineData(true)] + [InlineData(false)] public async Task TestResumeFromSerializedPackage(bool onMemory) { // arrange @@ -603,16 +586,14 @@ public async Task TestResumeFromSerializedPackage(bool onMemory) await DownloadFileTaskAsync(reversedPackage); // assert - Assert.IsFalse(IsCancelled); - Assert.IsNotNull(package); - Assert.IsNotNull(reversedPackage); - Assert.IsTrue(reversedPackage.IsSaveComplete); - Assert.IsFalse(string.IsNullOrWhiteSpace(packageText)); - - Cleanup(); + Assert.False(IsCancelled); + Assert.NotNull(package); + Assert.NotNull(reversedPackage); + Assert.True(reversedPackage.IsSaveComplete); + Assert.False(string.IsNullOrWhiteSpace(packageText)); } - [TestMethod] + [Fact] public async Task TestPackageStatusAfterCancellation() { // arrange @@ -638,17 +619,16 @@ public async Task TestPackageStatusAfterCancellation() await DownloadFileTaskAsync(url); // assert - Assert.IsFalse(Package.IsSaveComplete); - Assert.IsFalse(Package.IsSaving); - Assert.AreEqual(DownloadStatus.Stopped, Package.Status); - Assert.AreEqual(DownloadStatus.Running, createdStatus); - Assert.AreEqual(DownloadStatus.Running, runningStatus); - Assert.AreEqual(DownloadStatus.Stopped, cancelledStatus); - Assert.AreEqual(DownloadStatus.Stopped, completedStatus); + Assert.False(Package.IsSaveComplete); + Assert.False(Package.IsSaving); + Assert.Equal(DownloadStatus.Stopped, Package.Status); + Assert.Equal(DownloadStatus.Running, createdStatus); + Assert.Equal(DownloadStatus.Running, runningStatus); + Assert.Equal(DownloadStatus.Stopped, cancelledStatus); + Assert.Equal(DownloadStatus.Stopped, completedStatus); } - [TestMethod] - [Timeout(5000)] + [Fact(Timeout = 5000)] public async Task TestResumeDownloadImmedietalyAfterCancellationAsync() { // arrange @@ -681,14 +661,13 @@ public async Task TestResumeDownloadImmedietalyAfterCancellationAsync() await tcs.Task; // assert - Assert.IsTrue(Package.IsSaveComplete); - Assert.IsFalse(Package.IsSaving); - Assert.AreEqual(DownloadStatus.Completed, Package.Status); - Assert.IsTrue(secondStartProgressPercent > 50, $"progress percent is {secondStartProgressPercent}"); + Assert.True(Package.IsSaveComplete); + Assert.False(Package.IsSaving); + Assert.Equal(DownloadStatus.Completed, Package.Status); + Assert.True(secondStartProgressPercent > 50, $"progress percent is {secondStartProgressPercent}"); } - [TestMethod] - [Timeout(5000)] + [Fact(Timeout = 5000)] public async Task TestStopDownloadOnClearWhenRunning() { // arrange @@ -704,14 +683,13 @@ public async Task TestStopDownloadOnClearWhenRunning() await DownloadFileTaskAsync(url); // assert - Assert.IsFalse(Package.IsSaveComplete); - Assert.IsFalse(Package.IsSaving); - Assert.AreEqual(DownloadStatus.Stopped, completedState); - Assert.AreEqual(DownloadStatus.Stopped, Package.Status); + Assert.False(Package.IsSaveComplete); + Assert.False(Package.IsSaving); + Assert.Equal(DownloadStatus.Stopped, completedState); + Assert.Equal(DownloadStatus.Stopped, Package.Status); } - [TestMethod] - [Timeout(5000)] + [Fact(Timeout = 5000)] public async Task TestStopDownloadOnClearWhenPaused() { // arrange @@ -730,13 +708,13 @@ public async Task TestStopDownloadOnClearWhenPaused() await DownloadFileTaskAsync(url); // assert - Assert.IsFalse(Package.IsSaveComplete); - Assert.IsFalse(Package.IsSaving); - Assert.AreEqual(DownloadStatus.Stopped, completedState); - Assert.AreEqual(DownloadStatus.Stopped, Package.Status); + Assert.False(Package.IsSaveComplete); + Assert.False(Package.IsSaving); + Assert.Equal(DownloadStatus.Stopped, completedState); + Assert.Equal(DownloadStatus.Stopped, Package.Status); } - [TestMethod] + [Fact] public async Task TestMinimumSizeOfChunking() { // arrange @@ -757,13 +735,13 @@ public async Task TestMinimumSizeOfChunking() await DownloadFileTaskAsync(url); // assert - Assert.IsTrue(Package.IsSaveComplete); - Assert.AreEqual(1, activeChunks); - Assert.AreEqual(1, progressIds.Count); - Assert.AreEqual(1, chunkCounts); + Assert.True(Package.IsSaveComplete); + Assert.Equal(1, activeChunks); + Assert.Single(progressIds); + Assert.Equal(1, chunkCounts); } - [TestMethod] + [Fact] public async Task TestCreatePathIfNotExist() { // arrange @@ -778,8 +756,8 @@ public async Task TestCreatePathIfNotExist() await DownloadFileTaskAsync(url, dir); // assert - Assert.IsTrue(Package.IsSaveComplete); - Assert.IsTrue(Package.FileName.StartsWith(dir.FullName)); - Assert.IsTrue(File.Exists(Package.FileName), "FileName: " + Package.FileName); - } + Assert.True(Package.IsSaveComplete); + Assert.StartsWith(dir.FullName, Package.FileName); + Assert.True(File.Exists(Package.FileName), "FileName: " + Package.FileName); + } } \ No newline at end of file diff --git a/src/Downloader.Test/IntegrationTests/ParallelDownloadIntegrationTest.cs b/src/Downloader.Test/IntegrationTests/ParallelDownloadIntegrationTest.cs index 6603547..e82a88e 100644 --- a/src/Downloader.Test/IntegrationTests/ParallelDownloadIntegrationTest.cs +++ b/src/Downloader.Test/IntegrationTests/ParallelDownloadIntegrationTest.cs @@ -1,12 +1,8 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +namespace Downloader.Test.IntegrationTests; -namespace Downloader.Test.IntegrationTests; - -[TestClass] public class ParallelDownloadIntegrationTest : DownloadIntegrationTest { - [TestInitialize] - public override void InitialTest() + public ParallelDownloadIntegrationTest() { Config = new DownloadConfiguration { ParallelDownload = true, diff --git a/src/Downloader.Test/IntegrationTests/SerialDownloadIntegrationTest.cs b/src/Downloader.Test/IntegrationTests/SerialDownloadIntegrationTest.cs index 1165ec7..1e9fac5 100644 --- a/src/Downloader.Test/IntegrationTests/SerialDownloadIntegrationTest.cs +++ b/src/Downloader.Test/IntegrationTests/SerialDownloadIntegrationTest.cs @@ -1,12 +1,8 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +namespace Downloader.Test.IntegrationTests; -namespace Downloader.Test.IntegrationTests; - -[TestClass] public class SerialDownloadIntegrationTest : DownloadIntegrationTest { - [TestInitialize] - public override void InitialTest() + public SerialDownloadIntegrationTest() { Config = new DownloadConfiguration { ParallelDownload = false, diff --git a/src/Downloader.Test/IntegrationTests/ThrottledStreamTest.cs b/src/Downloader.Test/IntegrationTests/ThrottledStreamTest.cs index a181019..7b0c247 100644 --- a/src/Downloader.Test/IntegrationTests/ThrottledStreamTest.cs +++ b/src/Downloader.Test/IntegrationTests/ThrottledStreamTest.cs @@ -1,42 +1,22 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; namespace Downloader.Test.IntegrationTests; -[TestClass] public class ThrottledStreamTest { - [TestMethod] - public async Task TestStreamReadSpeed() - { - await TestReadStreamSpeed(1, false); - } - - [TestMethod] - public async Task TestStreamReadSpeedAsync() - { - await TestReadStreamSpeed(1, true); - } - - [TestMethod] - public async Task TestStreamReadByDynamicSpeed() - { - await TestReadStreamSpeed(2, false); - } - - [TestMethod] - public async Task TestStreamReadByDynamicSpeedAsync() - { - await TestReadStreamSpeed(2, true); - } - - private static async Task TestReadStreamSpeed(int speedX = 1, bool asAsync = false) + [Theory] + [InlineData(1, false)] // TestStreamReadSpeed + [InlineData(1, true)] // TestStreamReadSpeedAsync + [InlineData(2, false)] // TestStreamReadByDynamicSpeed + [InlineData(2, true)] // TestStreamReadByDynamicSpeedAsync + public async Task TestReadStreamSpeed(int speedX, bool asAsync) { // arrange var limitationCoefficient = 0.9; // 90% @@ -72,11 +52,11 @@ private static async Task TestReadStreamSpeed(int speedX = 1, bool asAsync = fal stopWatcher.Stop(); // assert - Assert.IsTrue(stopWatcher.ElapsedMilliseconds >= totalExpectedTime, + Assert.True(stopWatcher.ElapsedMilliseconds >= totalExpectedTime, $"expected duration is: {totalExpectedTime}ms , but actual duration is: {stopWatcher.ElapsedMilliseconds}ms"); } - [TestMethod] + [Fact] public void TestStreamWriteSpeed() { // arrange @@ -93,11 +73,11 @@ public void TestStreamWriteSpeed() stopWatcher.Stop(); // assert - Assert.IsTrue(stopWatcher.ElapsedMilliseconds + tolerance >= expectedTime, + Assert.True(stopWatcher.ElapsedMilliseconds + tolerance >= expectedTime, $"actual duration is: {stopWatcher.ElapsedMilliseconds}ms"); } - [TestMethod] + [Fact] public async Task TestStreamWriteSpeedAsync() { // arrange @@ -110,15 +90,15 @@ public async Task TestStreamWriteSpeedAsync() var stopWatcher = Stopwatch.StartNew(); // act - await stream.WriteAsync(randomBytes, 0, randomBytes.Length).ConfigureAwait(false); + await stream.WriteAsync(randomBytes, 0, randomBytes.Length); stopWatcher.Stop(); // assert - Assert.IsTrue(stopWatcher.ElapsedMilliseconds + tolerance >= expectedTime, + Assert.True(stopWatcher.ElapsedMilliseconds + tolerance >= expectedTime, $"actual duration is: {stopWatcher.ElapsedMilliseconds}ms"); } - [TestMethod] + [Fact] public void TestNegativeBandwidth() { // arrange @@ -131,10 +111,10 @@ void CreateThrottledStream() } // assert - Assert.ThrowsException(CreateThrottledStream); + Assert.ThrowsAny(CreateThrottledStream); } - [TestMethod] + [Fact] public void TestZeroBandwidth() { // arrange @@ -144,28 +124,14 @@ public void TestZeroBandwidth() using var throttledStream = new ThrottledStream(new MemoryStream(), maximumBytesPerSecond); // assert - Assert.AreEqual(long.MaxValue, throttledStream.BandwidthLimit); - } - - [TestMethod] - public void TestStreamIntegrityWithSpeedMoreThanSize() - { - TestStreamIntegrity(500, 1024); - } - - [TestMethod] - public void TestStreamIntegrityWithMaximumSpeed() - { - TestStreamIntegrity(4096, long.MaxValue); - } - - [TestMethod] - public void TestStreamIntegrityWithSpeedLessThanSize() - { - TestStreamIntegrity(247, 77); + Assert.Equal(long.MaxValue, throttledStream.BandwidthLimit); } - private static void TestStreamIntegrity(int streamSize, long maximumBytesPerSecond) + [Theory] + [InlineData(500, 1024)] // TestStreamIntegrityWithSpeedMoreThanSize + [InlineData(4096, long.MaxValue)] // TestStreamIntegrityWithMaximumSpeed + [InlineData(247, 77)] // TestStreamIntegrityWithSpeedLessThanSize + public void TestStreamIntegrity(int streamSize, long maximumBytesPerSecond) { // arrange byte[] data = DummyData.GenerateOrderedBytes(streamSize); @@ -178,8 +144,8 @@ private static void TestStreamIntegrity(int streamSize, long maximumBytesPerSeco stream.Read(copiedData, 0, copiedData.Length); // assert - Assert.AreEqual(streamSize, data.Length); - Assert.AreEqual(streamSize, copiedData.Length); - Assert.IsTrue(data.SequenceEqual(copiedData)); + Assert.Equal(streamSize, data.Length); + Assert.Equal(streamSize, copiedData.Length); + Assert.True(data.SequenceEqual(copiedData)); } } diff --git a/src/Downloader.Test/UnitTests/BandwidthTest.cs b/src/Downloader.Test/UnitTests/BandwidthTest.cs index 59f8f25..d58360c 100644 --- a/src/Downloader.Test/UnitTests/BandwidthTest.cs +++ b/src/Downloader.Test/UnitTests/BandwidthTest.cs @@ -1,39 +1,37 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class BandwidthTest { - [TestClass] - public class BandwidthTest + [Fact] + public void TestCalculateAverageSpeed() { - [TestMethod] - public void TestCalculateAverageSpeed() - { - // arrange - int delayTime = 50; - int receivedBytesPerDelay = 250; - int testElapsedTime = 4000; // 4s - int repeatCount = testElapsedTime / delayTime; - Bandwidth calculator = new Bandwidth(); - var speedHistory = new List(); - - // act - for (int i = 0; i < repeatCount; i++) - { - Thread.Sleep(delayTime); - calculator.CalculateSpeed(receivedBytesPerDelay); - speedHistory.Add(calculator.Speed); - } + // arrange + int delayTime = 50; + int receivedBytesPerDelay = 250; + int testElapsedTime = 4000; // 4s + int repeatCount = testElapsedTime / delayTime; + Bandwidth calculator = new Bandwidth(); + var speedHistory = new List(); - // assert - var expectedAverageSpeed = Math.Ceiling(speedHistory.Average()); - var actualAverageSpeed = Math.Ceiling(calculator.AverageSpeed); - var theoryAverageSpeed = 1000 / delayTime * receivedBytesPerDelay; - Assert.IsTrue(expectedAverageSpeed < actualAverageSpeed, $"Actual Average Speed is: {actualAverageSpeed} , Expected Average Speed is: {expectedAverageSpeed}"); - Assert.IsTrue(actualAverageSpeed < theoryAverageSpeed, $"Actual Average Speed is: {actualAverageSpeed} , Theory Average Speed is: {theoryAverageSpeed}"); + // act + for (int i = 0; i < repeatCount; i++) + { + Thread.Sleep(delayTime); + calculator.CalculateSpeed(receivedBytesPerDelay); + speedHistory.Add(calculator.Speed); } + + // assert + var expectedAverageSpeed = Math.Ceiling(speedHistory.Average()); + var actualAverageSpeed = Math.Ceiling(calculator.AverageSpeed); + var theoryAverageSpeed = 1000 / delayTime * receivedBytesPerDelay; + Assert.True(expectedAverageSpeed < actualAverageSpeed, $"Actual Average Speed is: {actualAverageSpeed} , Expected Average Speed is: {expectedAverageSpeed}"); + Assert.True(actualAverageSpeed < theoryAverageSpeed, $"Actual Average Speed is: {actualAverageSpeed} , Theory Average Speed is: {theoryAverageSpeed}"); } } diff --git a/src/Downloader.Test/UnitTests/ChunkDownloaderOnFileTest.cs b/src/Downloader.Test/UnitTests/ChunkDownloaderOnFileTest.cs index e58463b..f6a7912 100644 --- a/src/Downloader.Test/UnitTests/ChunkDownloaderOnFileTest.cs +++ b/src/Downloader.Test/UnitTests/ChunkDownloaderOnFileTest.cs @@ -1,25 +1,21 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class ChunkDownloaderOnFileTest : ChunkDownloaderTest { - [TestClass] - public class ChunkDownloaderOnFileTest : ChunkDownloaderTest + public ChunkDownloaderOnFileTest() { - [TestInitialize] - public override void InitialTest() - { - var path = Path.GetTempFileName(); - Configuration = new DownloadConfiguration { - BufferBlockSize = 1024, - ChunkCount = 16, - ParallelDownload = true, - MaxTryAgainOnFailover = 100, - MinimumSizeOfChunking = 16, - Timeout = 100, - }; - Storage = new ConcurrentStream(path, DummyFileHelper.FileSize16Kb); - } + var path = Path.GetTempFileName(); + Configuration = new DownloadConfiguration { + BufferBlockSize = 1024, + ChunkCount = 16, + ParallelDownload = true, + MaxTryAgainOnFailover = 100, + MinimumSizeOfChunking = 16, + Timeout = 100, + }; + Storage = new ConcurrentStream(path, DummyFileHelper.FileSize16Kb); } } diff --git a/src/Downloader.Test/UnitTests/ChunkDownloaderOnMemoryTest.cs b/src/Downloader.Test/UnitTests/ChunkDownloaderOnMemoryTest.cs index 58852f6..402487a 100644 --- a/src/Downloader.Test/UnitTests/ChunkDownloaderOnMemoryTest.cs +++ b/src/Downloader.Test/UnitTests/ChunkDownloaderOnMemoryTest.cs @@ -1,22 +1,17 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +namespace Downloader.Test.UnitTests; -namespace Downloader.Test.UnitTests +public class ChunkDownloaderOnMemoryTest : ChunkDownloaderTest { - [TestClass] - public class ChunkDownloaderOnMemoryTest : ChunkDownloaderTest + public ChunkDownloaderOnMemoryTest() { - [TestInitialize] - public override void InitialTest() - { - Configuration = new DownloadConfiguration { - BufferBlockSize = 1024, - ChunkCount = 16, - ParallelDownload = true, - MaxTryAgainOnFailover = 100, - MinimumSizeOfChunking = 16, - Timeout = 100, - }; - Storage = new ConcurrentStream(); - } + Configuration = new DownloadConfiguration { + BufferBlockSize = 1024, + ChunkCount = 16, + ParallelDownload = true, + MaxTryAgainOnFailover = 100, + MinimumSizeOfChunking = 16, + Timeout = 100, + }; + Storage = new ConcurrentStream(); } } diff --git a/src/Downloader.Test/UnitTests/ChunkDownloaderTest.cs b/src/Downloader.Test/UnitTests/ChunkDownloaderTest.cs index 88a2210..6a807ac 100644 --- a/src/Downloader.Test/UnitTests/ChunkDownloaderTest.cs +++ b/src/Downloader.Test/UnitTests/ChunkDownloaderTest.cs @@ -1,176 +1,171 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; -using System.Drawing; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public abstract class ChunkDownloaderTest { - public abstract class ChunkDownloaderTest + protected DownloadConfiguration Configuration { get; set; } + protected ConcurrentStream Storage { get; set; } + protected int Size { get; set; } = DummyFileHelper.FileSize16Kb; + + [Fact] + public async Task ReadStreamTest() { - protected DownloadConfiguration Configuration { get; set; } - protected ConcurrentStream Storage { get; set; } - protected int Size { get; set; } = DummyFileHelper.FileSize16Kb; + // arrange + var randomlyBytes = DummyData.GenerateRandomBytes(Size); + var chunk = new Chunk(0, Size - 1) { Timeout = 100 }; + var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); + using var memoryStream = new MemoryStream(randomlyBytes); + + // act + await chunkDownloader.ReadStream(memoryStream, new PauseTokenSource().Token, new CancellationToken()); + + // assert + var chunkStream = Storage.OpenRead(); + Assert.Equal(memoryStream.Length, Storage.Length); + for (int i = 0; i < Size; i++) + { + Assert.Equal(randomlyBytes[i], chunkStream.ReadByte()); + } - [TestInitialize] - public abstract void InitialTest(); + chunkDownloader.Chunk.Clear(); + } - [TestMethod] - public async Task ReadStreamTest() - { - // arrange - var randomlyBytes = DummyData.GenerateRandomBytes(Size); - var chunk = new Chunk(0, Size - 1) { Timeout = 100 }; - var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); - using var memoryStream = new MemoryStream(randomlyBytes); - - // act - await chunkDownloader.ReadStream(memoryStream, new PauseTokenSource().Token, new CancellationToken()).ConfigureAwait(false); - - // assert - var chunkStream = Storage.OpenRead(); - Assert.AreEqual(memoryStream.Length, Storage.Length); - for (int i = 0; i < Size; i++) + [Fact] + public async Task PauseResumeReadStreamTest() + { + // arrange + var randomlyBytes = DummyData.GenerateRandomBytes(Size); + var chunk = new Chunk(0, Size - 1) { Timeout = 100 }; + var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); + using var memoryStream = new MemoryStream(randomlyBytes); + var pauseToken = new PauseTokenSource(); + var pauseCount = 0; + + // act + chunkDownloader.DownloadProgressChanged += (sender, e) => { + if (pauseCount < 10) { - Assert.AreEqual(randomlyBytes[i], chunkStream.ReadByte()); + pauseToken.Pause(); + pauseCount++; + pauseToken.Resume(); } + }; + await chunkDownloader.ReadStream(memoryStream, pauseToken.Token, new CancellationToken()) + ; + Storage.Flush(); + + // assert + Assert.Equal(memoryStream.Length, Storage.Length); + Assert.Equal(10, pauseCount); + var chunkStream = Storage.OpenRead(); + for (int i = 0; i < Size; i++) + Assert.Equal(randomlyBytes[i], chunkStream.ReadByte()); + + chunkDownloader.Chunk.Clear(); + } - chunkDownloader.Chunk.Clear(); - } - - [TestMethod] - public async Task PauseResumeReadStreamTest() - { - // arrange - var randomlyBytes = DummyData.GenerateRandomBytes(Size); - var chunk = new Chunk(0, Size - 1) { Timeout = 100 }; - var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); - using var memoryStream = new MemoryStream(randomlyBytes); - var pauseToken = new PauseTokenSource(); - var pauseCount = 0; - - // act - chunkDownloader.DownloadProgressChanged += (sender, e) => { - if (pauseCount < 10) - { - pauseToken.Pause(); - pauseCount++; - pauseToken.Resume(); - } - }; - await chunkDownloader.ReadStream(memoryStream, pauseToken.Token, new CancellationToken()) - .ConfigureAwait(false); - Storage.Flush(); - - // assert - Assert.AreEqual(memoryStream.Length, Storage.Length); - Assert.AreEqual(10, pauseCount); - var chunkStream = Storage.OpenRead(); - for (int i = 0; i < Size; i++) - Assert.AreEqual(randomlyBytes[i], chunkStream.ReadByte()); - - chunkDownloader.Chunk.Clear(); - } - - [TestMethod] - public async Task ReadStreamProgressEventsTest() - { - // arrange - var eventCount = 0; - var receivedBytes = new List(); - var source = DummyData.GenerateRandomBytes(Size); - using var sourceMemoryStream = new MemoryStream(source); - var chunk = new Chunk(0, Size - 1) { Timeout = 100 }; - var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); - chunkDownloader.DownloadProgressChanged += (s, e) => { - eventCount++; - receivedBytes.AddRange(e.ReceivedBytes); - }; - - // act - await chunkDownloader.ReadStream(sourceMemoryStream, new PauseTokenSource().Token, new CancellationToken()).ConfigureAwait(false); - - // assert - Assert.AreEqual(Size / Configuration.BufferBlockSize, eventCount); - Assert.AreEqual(chunkDownloader.Chunk.Length, receivedBytes.Count); - Assert.IsTrue(source.SequenceEqual(receivedBytes)); - - chunkDownloader.Chunk.Clear(); - } + [Fact] + public async Task ReadStreamProgressEventsTest() + { + // arrange + var eventCount = 0; + var receivedBytes = new List(); + var source = DummyData.GenerateRandomBytes(Size); + using var sourceMemoryStream = new MemoryStream(source); + var chunk = new Chunk(0, Size - 1) { Timeout = 100 }; + var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); + chunkDownloader.DownloadProgressChanged += (s, e) => { + eventCount++; + receivedBytes.AddRange(e.ReceivedBytes); + }; + + // act + await chunkDownloader.ReadStream(sourceMemoryStream, new PauseTokenSource().Token, new CancellationToken()); + + // assert + Assert.Equal(Size / Configuration.BufferBlockSize, eventCount); + Assert.Equal(chunkDownloader.Chunk.Length, receivedBytes.Count); + Assert.True(source.SequenceEqual(receivedBytes)); + + chunkDownloader.Chunk.Clear(); + } - [TestMethod] - public async Task ReadStreamCanceledExceptionTest() - { - // arrange - var randomlyBytes = DummyData.GenerateRandomBytes(Size); - var chunk = new Chunk(0, Size - 1) { Timeout = 100 }; - var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); - using var memoryStream = new MemoryStream(randomlyBytes); - var canceledToken = new CancellationToken(true); - - // act - async Task CallReadStream() => await chunkDownloader - .ReadStream(new MemoryStream(), new PauseTokenSource().Token, canceledToken) - .ConfigureAwait(false); - - // assert - await Assert.ThrowsExceptionAsync(CallReadStream); - } + [Fact] + public async Task ReadStreamCanceledExceptionTest() + { + // arrange + var randomlyBytes = DummyData.GenerateRandomBytes(Size); + var chunk = new Chunk(0, Size - 1) { Timeout = 100 }; + var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); + using var memoryStream = new MemoryStream(randomlyBytes); + var canceledToken = new CancellationToken(true); + + // act + async Task CallReadStream() => await chunkDownloader + .ReadStream(new MemoryStream(), new PauseTokenSource().Token, canceledToken) + ; + + // assert + await Assert.ThrowsAnyAsync(CallReadStream); + } - [TestMethod] - public async Task ReadStreamTimeoutExceptionTest() - { - // arrange - var cts = new CancellationTokenSource(); - var randomlyBytes = DummyData.GenerateRandomBytes(Size); - var chunk = new Chunk(0, Size - 1) { Timeout = 0 }; - var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); - using var memoryStream = new MemoryStream(randomlyBytes); - using var slowStream = new ThrottledStream(memoryStream, Configuration.BufferBlockSize); - - // act - async Task CallReadStream() => await chunkDownloader - .ReadStream(slowStream, new PauseTokenSource().Token, cts.Token) - .ConfigureAwait(false); - - // assert - await Assert.ThrowsExceptionAsync(CallReadStream); - } + [Fact] + public async Task ReadStreamTimeoutExceptionTest() + { + // arrange + var cts = new CancellationTokenSource(); + var randomlyBytes = DummyData.GenerateRandomBytes(Size); + var chunk = new Chunk(0, Size - 1) { Timeout = 0 }; + var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); + using var memoryStream = new MemoryStream(randomlyBytes); + using var slowStream = new ThrottledStream(memoryStream, Configuration.BufferBlockSize); + + // act + async Task CallReadStream() => await chunkDownloader + .ReadStream(slowStream, new PauseTokenSource().Token, cts.Token) + ; + + // assert + await Assert.ThrowsAnyAsync(CallReadStream); + } - [TestMethod] - public async Task CancelReadStreamTest() - { - // arrange - var stoppedPosition = 0L; - var randomlyBytes = DummyData.GenerateRandomBytes(Size); - var cts = new CancellationTokenSource(); - var chunk = new Chunk(0, Size - 1) { Timeout = 1000 }; - var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); - using var memoryStream = new MemoryStream(randomlyBytes); - - // act - chunkDownloader.DownloadProgressChanged += (sender, e) => { - if (e.ProgressPercentage > 50) - { - cts.Cancel(); - stoppedPosition = e.ReceivedBytesSize; - } - }; - async Task act() => await chunkDownloader.ReadStream(memoryStream, new PauseTokenSource().Token, cts.Token).ConfigureAwait(false); - Storage.Flush(); - - // assert - await Assert.ThrowsExceptionAsync(act).ConfigureAwait(false); - Assert.IsFalse(memoryStream.CanRead); // stream has been closed - using var chunkStream = Storage.OpenRead(); - for (int i = 0; i < stoppedPosition; i++) - Assert.AreEqual(randomlyBytes[i], chunkStream.ReadByte()); - - chunkDownloader.Chunk.Clear(); - } + [Fact] + public async Task CancelReadStreamTest() + { + // arrange + var stoppedPosition = 0L; + var randomlyBytes = DummyData.GenerateRandomBytes(Size); + var cts = new CancellationTokenSource(); + var chunk = new Chunk(0, Size - 1) { Timeout = 1000 }; + var chunkDownloader = new ChunkDownloader(chunk, Configuration, Storage); + using var memoryStream = new MemoryStream(randomlyBytes); + + // act + chunkDownloader.DownloadProgressChanged += (sender, e) => { + if (e.ProgressPercentage > 50) + { + cts.Cancel(); + stoppedPosition = e.ReceivedBytesSize; + } + }; + async Task act() => await chunkDownloader.ReadStream(memoryStream, new PauseTokenSource().Token, cts.Token); + Storage.Flush(); + + // assert + await Assert.ThrowsAnyAsync(act); + Assert.False(memoryStream.CanRead); // stream has been closed + using var chunkStream = Storage.OpenRead(); + for (int i = 0; i < stoppedPosition; i++) + Assert.Equal(randomlyBytes[i], chunkStream.ReadByte()); + + chunkDownloader.Chunk.Clear(); } } \ No newline at end of file diff --git a/src/Downloader.Test/UnitTests/ChunkHubTest.cs b/src/Downloader.Test/UnitTests/ChunkHubTest.cs index ee1e20d..b5c6e4e 100644 --- a/src/Downloader.Test/UnitTests/ChunkHubTest.cs +++ b/src/Downloader.Test/UnitTests/ChunkHubTest.cs @@ -1,186 +1,140 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.Linq; +using System.Linq; +using Xunit; -namespace Downloader.Test.UnitTests -{ - [TestClass] - public class ChunkHubTest - { - private DownloadConfiguration _config; - - [TestInitialize] - public void InitialTests() - { - _config = new DownloadConfiguration() { - Timeout = 100, - MaxTryAgainOnFailover = 100, - BufferBlockSize = 1024 - }; - } - - [TestMethod] - public void ChunkFileByNegativePartsTest() - { - // act - var package = ChunkFileTest(-1); +namespace Downloader.Test.UnitTests; - // assert - Assert.AreEqual(1, package.Chunks.Length); - } - - [TestMethod] - public void ChunkFileByZeroPartsTest() - { - // act - var package = ChunkFileTest(0); - - // assert - Assert.AreEqual(1, package.Chunks.Length); - } - - [TestMethod] - public void ChunkFilePositive1PartsTest() - { - // act - var package = ChunkFileTest(1); - - // assert - Assert.AreEqual(1, package.Chunks.Length); - } - - [TestMethod] - public void ChunkFilePositive8PartsTest() - { - // act - var package = ChunkFileTest(8); - - // assert - Assert.AreEqual(8, package.Chunks.Length); - } +public class ChunkHubTest +{ + private DownloadConfiguration _config; - [TestMethod] - public void ChunkFilePositive256PartsTest() - { - // act - var package = ChunkFileTest(256); + public ChunkHubTest() + { + _config = new DownloadConfiguration() { + Timeout = 100, + MaxTryAgainOnFailover = 100, + BufferBlockSize = 1024 + }; + } - // assert - Assert.AreEqual(256, package.Chunks.Length); - } + [Theory] + [InlineData(-1, 1024)] // Chunk File By Negative Parts Test + [InlineData(0, 1024)] // Chunk File By Zero Parts Test + [InlineData(1, 1024)] // Chunk File Positive 1 Parts Test + public void SingleChunkFileTest(int chunkCount, long fileSize) + { + // act + using var package = ChunkFileTest(chunkCount, fileSize); - [TestMethod] - public void ChunkFileEqualSizePartsTest() - { - // act - var package = ChunkFileTest(1024); + // assert + Assert.Single(package.Chunks); + } - // assert - Assert.AreEqual(1024, package.Chunks.Length); - } + [Theory] + [InlineData(8, 1024)] + [InlineData(256, 1024)] + [InlineData(1024, 1024)] + [InlineData(64, 10679630)] + public void PositiveChunkFileTest(int chunkCount, long fileSize) + { + // act + using var package = ChunkFileTest(chunkCount, fileSize); - [TestMethod] - public void ChunkFilePartsMoreThanSizeTest() - { - // act - var package = ChunkFileTest(1030, 1024); + // assert + Assert.Equal(chunkCount, package.Chunks.Length); + Assert.Equal(fileSize, package.Chunks.Sum(chunk => chunk.Length)); + } - // assert - Assert.AreEqual(1024, package.Chunks.Length); - } + [Theory] + [InlineData(1030, 1024)] + public void ChunkFileMoreThanSizeTest(int chunkCount, long fileSize) + { + // act + using var package = ChunkFileTest(chunkCount, fileSize); - [TestMethod] - public void ChunkFileSizeTest() - { - // arrange - int fileSize = 10679630; + // assert + Assert.Equal(fileSize, package.Chunks.Length); + } - // act - var package = ChunkFileTest(64, fileSize); + [Fact] + public void ChunkFileWithRangeSizeTest() + { + // arrange + int fileSize = 10679630; + _config.RangeLow = 1024; + _config.RangeHigh = 9679630; + long totalBytes = _config.RangeHigh - _config.RangeLow + 1; + + // act + using var package = ChunkFileTest(64, totalBytes); + + // assert + Assert.Equal(totalBytes, package.Chunks.Sum(chunk => chunk.Length)); + Assert.True(fileSize >= package.Chunks.Sum(chunk => chunk.Length)); + Assert.Equal(package.Chunks.Last().End, _config.RangeHigh); + } - // assert - Assert.AreEqual(64, package.Chunks.Length); - Assert.AreEqual(fileSize, package.Chunks.Sum(chunk => chunk.Length)); - } + [Fact] + public void ChunkFileRangeBelowZeroTest() + { + // arrange + _config.RangeLow = -4096; + _config.RangeHigh = 2048; + long actualTotalSize = _config.RangeHigh + 1; + + // act + using var package = ChunkFileTest(64, actualTotalSize); + + // assert + Assert.Equal(actualTotalSize, package.Chunks.Sum(chunk => chunk.Length)); + Assert.Equal(0, package.Chunks.First().Start); + Assert.Equal(package.Chunks.Last().End, _config.RangeHigh); + } - [TestMethod] - public void ChunkFileRangeSizeTest() - { - // arrange - int fileSize = 10679630; - _config.RangeLow = 1024; - _config.RangeHigh = 9679630; - long totalBytes = _config.RangeHigh - _config.RangeLow + 1; - - // act - var package = ChunkFileTest(64, totalBytes); - - // assert - Assert.AreEqual(totalBytes, package.Chunks.Sum(chunk => chunk.Length)); - Assert.IsTrue(fileSize >= package.Chunks.Sum(chunk => chunk.Length)); - Assert.AreEqual(package.Chunks.Last().End, _config.RangeHigh); - } + [Fact] + public void ChunkFileZeroSizeTest() + { + // act + using var package = ChunkFileTest(64, 0); + + // assert + Assert.Single(package.Chunks); + Assert.Equal(0, package.Chunks[0].Start); + Assert.Equal(-1, package.Chunks[0].End); + Assert.Equal(0, package.Chunks[0].Length); + } - [TestMethod] - public void ChunkFileRangeBelowZeroTest() - { - // arrange - _config.RangeLow = -4096; - _config.RangeHigh = 2048; - long actualTotalSize = _config.RangeHigh + 1; - - // act - var package = ChunkFileTest(64, actualTotalSize); - - // assert - Assert.AreEqual(actualTotalSize, package.Chunks.Sum(chunk => chunk.Length)); - Assert.AreEqual(package.Chunks.First().Start, 0); - Assert.AreEqual(package.Chunks.Last().End, _config.RangeHigh); - } + [Theory] + [InlineData(8, 1024)] + [InlineData(256, 1024)] + [InlineData(1024, 1024)] + [InlineData(64, 10679630)] + public void PositiveChunkFileRangeTest(int chunkCount, long fileSize) + { + // act + using var package = ChunkFileTest(chunkCount, fileSize); - [TestMethod] - public void ChunkFileZeroSizeTest() - { - // act - var package = ChunkFileTest(64, 0); - - // assert - Assert.AreEqual(1, package.Chunks.Length); - Assert.AreEqual(0, package.Chunks[0].Start); - Assert.AreEqual(-1, package.Chunks[0].End); - Assert.AreEqual(0, package.Chunks[0].Length); - } + // assert + Assert.Equal(0, package.Chunks[0].Start); + Assert.Equal(fileSize - 1, package.Chunks.Last().End); - [TestMethod] - public void ChunkFileRangeTest() + for (int i = 1; i < package.Chunks.Length; i++) { - // arrange - int fileSize = 10679630; - - // act - var package = ChunkFileTest(64, fileSize); - - // assert - Assert.AreEqual(0, package.Chunks[0].Start); - for (int i = 1; i < package.Chunks.Length; i++) - { - Assert.AreEqual(package.Chunks[i].Start, package.Chunks[i - 1].End + 1); - } - Assert.AreEqual(package.Chunks.Last().End, fileSize - 1); + Assert.Equal(package.Chunks[i].Start, package.Chunks[i - 1].End + 1); } + } - private DownloadPackage ChunkFileTest(int chunkCount, long fileSize = 1024) - { - // arrange - var package = new DownloadPackage { - TotalFileSize = fileSize - }; - var chunkHub = new ChunkHub(_config); + private DownloadPackage ChunkFileTest(int chunkCount, long fileSize = 1024) + { + // arrange + var package = new DownloadPackage { + TotalFileSize = fileSize + }; + var chunkHub = new ChunkHub(_config); - // act - _config.ChunkCount = chunkCount; - chunkHub.SetFileChunks(package); + // act + _config.ChunkCount = chunkCount; + chunkHub.SetFileChunks(package); - return package; - } + return package; } } diff --git a/src/Downloader.Test/UnitTests/ChunkTest.cs b/src/Downloader.Test/UnitTests/ChunkTest.cs index 8720085..d5e48c8 100644 --- a/src/Downloader.Test/UnitTests/ChunkTest.cs +++ b/src/Downloader.Test/UnitTests/ChunkTest.cs @@ -1,193 +1,188 @@ using Downloader.DummyHttpServer; using Downloader.Test.Helper; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; -using System.IO; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class ChunkTest { - [TestClass] - public class ChunkTest + private readonly byte[] _testData = DummyData.GenerateOrderedBytes(1024); + + [Fact] + public void ClearTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 100 }; + chunk.CanTryAgainOnFailover(); + + // act + chunk.Clear(); + + // assert + Assert.Equal(0, chunk.Position); + Assert.Equal(0, chunk.FailoverCount); + } + + [Fact] + public void TestCanTryAgainOnFailoverWhenMaxIsZero() + { + // arrange + var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 100, MaxTryAgainOnFailover = 0 }; + + // act + var canTryAgainOnFailover = chunk.CanTryAgainOnFailover(); + + // assert + Assert.False(canTryAgainOnFailover); + Assert.Equal(1, chunk.FailoverCount); + } + + [Fact] + public void TestCanTryAgainOnFailoverWhenMaxIsOne() + { + // arrange + var chunk = new Chunk(0, 1) { MaxTryAgainOnFailover = 1 }; + + // act + var canTryAgainOnFailover = chunk.CanTryAgainOnFailover(); + + // assert + Assert.True(canTryAgainOnFailover); + Assert.Equal(1, chunk.FailoverCount); + } + + [Fact] + public void TestClearEffectLessOnTimeout() + { + // arrange + var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 1000 }; + + // act + chunk.Clear(); + + // assert + Assert.Equal(1000, chunk.Timeout); + } + + [Fact] + public void IsDownloadCompletedOnBeginTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size); + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.False(isDownloadCompleted); + } + + [Fact] + public void IsDownloadCompletedWhenNoStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { + Position = size - 1 + }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.False(isDownloadCompleted); + } + + [Fact] + public void IsDownloadCompletedWhenStorageNoDataTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Position = size - 1 }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.False(isDownloadCompleted); + } + + [Fact] + public void IsValidPositionWithStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size); + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.True(isValidPosition); + } + + [Fact] + public void IsValidPositionOnOverflowTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { + Position = _testData.Length + 1, + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.False(isValidPosition); + } + + [Fact] + public void IsValidPositionWhenNoStorageAndZeroPositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { + Position = 0 + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.True(isValidPosition); + } + + [Fact] + public void IsValidPositionOnZeroSizeTest() { - private readonly byte[] _testData = DummyData.GenerateOrderedBytes(1024); - - [TestMethod] - public void ClearTest() - { - // arrange - var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 100 }; - chunk.CanTryAgainOnFailover(); - - // act - chunk.Clear(); - - // assert - Assert.AreEqual(0, chunk.Position); - Assert.AreEqual(0, chunk.FailoverCount); - } - - [TestMethod] - public void TestCanTryAgainOnFailoverWhenMaxIsZero() - { - // arrange - var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 100, MaxTryAgainOnFailover = 0 }; - - // act - var canTryAgainOnFailover = chunk.CanTryAgainOnFailover(); - - // assert - Assert.IsFalse(canTryAgainOnFailover); - Assert.AreEqual(1, chunk.FailoverCount); - } - - [TestMethod] - public void TestCanTryAgainOnFailoverWhenMaxIsOne() - { - // arrange - var chunk = new Chunk(0, 1) { MaxTryAgainOnFailover = 1 }; - - // act - var canTryAgainOnFailover = chunk.CanTryAgainOnFailover(); - - // assert - Assert.IsTrue(canTryAgainOnFailover); - Assert.AreEqual(1, chunk.FailoverCount); - } - - [TestMethod] - public void TestClearEffectLessOnTimeout() - { - // arrange - var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 1000 }; - - // act - chunk.Clear(); - - // assert - Assert.AreEqual(1000, chunk.Timeout); - } - - [TestMethod] - public void IsDownloadCompletedOnBeginTest() - { - // arrange - var size = 1024; - var chunk = new Chunk(0, size); - - // act - bool isDownloadCompleted = chunk.IsDownloadCompleted(); - - // assert - Assert.IsFalse(isDownloadCompleted); - } - - [TestMethod] - public void IsDownloadCompletedWhenNoStorageTest() - { - // arrange - var size = 1024; - var chunk = new Chunk(0, size) { - Position = size - 1 - }; - - // act - bool isDownloadCompleted = chunk.IsDownloadCompleted(); - - // assert - Assert.IsFalse(isDownloadCompleted); - } - - [TestMethod] - public void IsDownloadCompletedWhenStorageNoDataTest() - { - // arrange - var size = 1024; - var chunk = new Chunk(0, size) { Position = size - 1 }; - - // act - bool isDownloadCompleted = chunk.IsDownloadCompleted(); - - // assert - Assert.IsFalse(isDownloadCompleted); - } - - [TestMethod] - public void IsValidPositionWithStorageTest() - { - // arrange - var size = 1024; - var chunk = new Chunk(0, size); - - // act - bool isValidPosition = chunk.IsValidPosition(); - - // assert - Assert.IsTrue(isValidPosition); - } - - [TestMethod] - public void IsValidPositionOnOverflowTest() - { - // arrange - var chunk = new Chunk(0, _testData.Length - 1) { - Position = _testData.Length + 1, - }; - - // act - bool isValidPosition = chunk.IsValidPosition(); - - // assert - Assert.IsFalse(isValidPosition); - } - - [TestMethod] - public void IsValidPositionWhenNoStorageAndZeroPositionTest() - { - // arrange - var chunk = new Chunk(0, 1024) { - Position = 0 - }; - - // act - bool isValidPosition = chunk.IsValidPosition(); - - // assert - Assert.IsTrue(isValidPosition); - } - - [TestMethod] - public void IsValidPositionOnZeroSizeTest() - { - // arrange - var chunk = new Chunk(0, -1) { Position = 0 }; - - // act - bool isValidPosition = chunk.IsValidPosition(); - - // assert - Assert.IsTrue(isValidPosition); - } - - [TestMethod] - public void ChunkSerializationTest() - { - // arrange - var chunk = new Chunk(1024, 1024 + _testData.Length) { - Position = 1, - Timeout = 1000, - MaxTryAgainOnFailover = 3000, - }; - - // act - var serializedChunk = JsonConvert.SerializeObject(chunk); - var deserializedChunk = JsonConvert.DeserializeObject(serializedChunk); - - // assert - AssertHelper.AreEquals(chunk, deserializedChunk); - - chunk.Clear(); - } + // arrange + var chunk = new Chunk(0, -1) { Position = 0 }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.True(isValidPosition); + } + + [Fact] + public void ChunkSerializationTest() + { + // arrange + var chunk = new Chunk(1024, 1024 + _testData.Length) { + Position = 1, + Timeout = 1000, + MaxTryAgainOnFailover = 3000, + }; + + // act + var serializedChunk = JsonConvert.SerializeObject(chunk); + var deserializedChunk = JsonConvert.DeserializeObject(serializedChunk); + + // assert + AssertHelper.AreEquals(chunk, deserializedChunk); + + chunk.Clear(); } } diff --git a/src/Downloader.Test/UnitTests/DownloadBuilderTest.cs b/src/Downloader.Test/UnitTests/DownloadBuilderTest.cs index 9a8b78d..9912f36 100644 --- a/src/Downloader.Test/UnitTests/DownloadBuilderTest.cs +++ b/src/Downloader.Test/UnitTests/DownloadBuilderTest.cs @@ -1,238 +1,235 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Text; using System.Threading.Tasks; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; +public class DownloadBuilderTest { - [TestClass] - public class DownloadBuilderTest + // arrange + private string url; + private string filename; + private string folder; + private string path; + + public DownloadBuilderTest() + { + // arrange + url = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb); + filename = "test.txt"; + folder = Path.GetTempPath().TrimEnd('\\', '/'); + path = Path.Combine(folder, filename); + } + + [Fact] + public void TestCorrect() + { + // act + IDownload download = DownloadBuilder.New() + .WithUrl(url) + .WithFileLocation(path) + .Configure(config => { + config.ParallelDownload = true; + }) + .Build(); + + // assert + Assert.Equal(folder, download.Folder); + Assert.Equal(filename, download.Filename); + } + + [Fact] + public void TestSetFolderAndName() + { + // act + IDownload download = DownloadBuilder.New() + .WithUrl(url) + .WithDirectory(folder) + .WithFileName(filename) + .Build(); + + // assert + Assert.Equal(folder, download.Folder); + Assert.Equal(filename, download.Filename); + } + + [Fact] + public void TestSetFolder() + { + // arrange + var dir = Path.GetTempPath(); + + // act + IDownload download = DownloadBuilder.New() + .WithUrl(url) + .WithDirectory(dir) + .Build(); + + // assert + Assert.Equal(dir, download.Folder); + Assert.Null(download.Filename); + } + + [Fact] + public void TestSetName() + { + // act + IDownload download = DownloadBuilder.New() + .WithUrl(url) + .WithFileLocation(path) + .WithFileName(filename) + .Build(); + + // assert + Assert.Equal(folder, download.Folder); + Assert.Equal(filename, download.Filename); + } + + [Fact] + public void TestUrlless() + { + // act + Action act = () => DownloadBuilder.New().WithFileLocation(path).Build(); + + // assert + Assert.ThrowsAny(act); + } + + [Fact] + public void TestPathless() + { + // act + IDownload result = DownloadBuilder.New() + .WithUrl(url) + .Build(); + + // assert + Assert.NotNull(result); + } + + [Fact] + public async Task TestPackageWhenNewUrl() + { + // arrange + DownloadPackage beforePackage = null; + IDownload download = DownloadBuilder.New() + .WithUrl(url) + .Build(); + + // act + beforePackage = download.Package; + await download.StartAsync(); + + // assert + Assert.NotNull(beforePackage); + Assert.NotNull(download.Package); + Assert.Equal(beforePackage, download.Package); + Assert.True(beforePackage.IsSaveComplete); + } + + [Fact] + public async Task TestPackageWhenResume() + { + // arrange + DownloadPackage package = new DownloadPackage() { + Urls = new[] { url }, + IsSupportDownloadInRange = true + }; + IDownload download = DownloadBuilder.New().Build(package); + DownloadPackage beforeStartPackage = download.Package; + + // act + await download.StartAsync(); + + // assert + Assert.NotNull(beforeStartPackage); + Assert.NotNull(download.Package); + Assert.Equal(beforeStartPackage, download.Package); + Assert.Equal(beforeStartPackage, package); + Assert.True(package.IsSaveComplete); + } + + [Fact] + public async Task TestPauseAndResume() + { + // arrange + var pauseCount = 0; + var downloader = DownloadBuilder.New() + .WithUrl(url) + .WithFileLocation(path) + .Build(); + + downloader.DownloadProgressChanged += (s, e) => { + if (pauseCount < 10) + { + downloader.Pause(); + pauseCount++; + downloader.Resume(); + } + }; + + // act + await downloader.StartAsync(); + + // assert + Assert.True(downloader.Package?.IsSaveComplete); + Assert.Equal(10, pauseCount); + Assert.True(File.Exists(path)); + + // clean up + File.Delete(path); + } + + [Fact] + public async Task TestOverwriteFileWithDownloadSameLocation() + { + // arrange + var content = "THIS IS TEST CONTENT WHICH MUST BE OVERWRITE WITH THE DOWNLOADER"; + var downloader = DownloadBuilder.New() + .WithUrl(url) + .WithFileLocation(path) + .Build(); + + // act + await File.WriteAllTextAsync(path, content); // create file + await downloader.StartAsync(); // overwrite file + var file = await File.ReadAllTextAsync(path); + + // assert + Assert.True(downloader.Package?.IsSaveComplete); + Assert.True(File.Exists(path)); + Assert.False(file.StartsWith(content)); + Assert.Equal(DummyFileHelper.FileSize16Kb, Encoding.ASCII.GetByteCount(file)); + + // clean up + File.Delete(path); + } + + [Fact] + public async Task TestOverwriteFileWithDownloadSameFileName() { // arrange - private string url; - private string filename; - private string folder; - private string path; - - public DownloadBuilderTest() - { - // arrange - url = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb); - filename = "test.txt"; - folder = Path.GetTempPath().TrimEnd('\\', '/'); - path = Path.Combine(folder, filename); - } - - [TestMethod] - public void TestCorrect() - { - // act - IDownload download = DownloadBuilder.New() - .WithUrl(url) - .WithFileLocation(path) - .Configure(config => { - config.ParallelDownload = true; - }) - .Build(); - - // assert - Assert.AreEqual(folder, download.Folder); - Assert.AreEqual(filename, download.Filename); - } - - [TestMethod] - public void TestSetFolderAndName() - { - // act - IDownload download = DownloadBuilder.New() - .WithUrl(url) - .WithDirectory(folder) - .WithFileName(filename) - .Build(); - - // assert - Assert.AreEqual(folder, download.Folder); - Assert.AreEqual(filename, download.Filename); - } - - [TestMethod] - public void TestSetFolder() - { - // arrange - var dir = Path.GetTempPath(); - - // act - IDownload download = DownloadBuilder.New() - .WithUrl(url) - .WithDirectory(dir) - .Build(); - - // assert - Assert.AreEqual(dir, download.Folder); - Assert.IsNull(download.Filename); - } - - [TestMethod] - public void TestSetName() - { - // act - IDownload download = DownloadBuilder.New() - .WithUrl(url) - .WithFileLocation(path) - .WithFileName(filename) - .Build(); - - // assert - Assert.AreEqual(folder, download.Folder); - Assert.AreEqual(filename, download.Filename); - } - - [TestMethod] - public void TestUrlless() - { - // act - Action act = () => DownloadBuilder.New().WithFileLocation(path).Build(); - - // assert - Assert.ThrowsException(act); - } - - [TestMethod] - public void TestPathless() - { - // act - IDownload result = DownloadBuilder.New() - .WithUrl(url) - .Build(); - - // assert - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task TestPackageWhenNewUrl() - { - // arrange - DownloadPackage beforePackage = null; - IDownload download = DownloadBuilder.New() - .WithUrl(url) - .Build(); - - // act - beforePackage = download.Package; - await download.StartAsync(); - - // assert - Assert.IsNotNull(beforePackage); - Assert.IsNotNull(download.Package); - Assert.AreEqual(beforePackage, download.Package); - Assert.IsTrue(beforePackage.IsSaveComplete); - } - - [TestMethod] - public async Task TestPackageWhenResume() - { - // arrange - DownloadPackage package = new DownloadPackage() { - Urls = new[] { url }, - IsSupportDownloadInRange = true - }; - IDownload download = DownloadBuilder.New().Build(package); - DownloadPackage beforeStartPackage = download.Package; - - // act - await download.StartAsync(); - - // assert - Assert.IsNotNull(beforeStartPackage); - Assert.IsNotNull(download.Package); - Assert.AreEqual(beforeStartPackage, download.Package); - Assert.AreEqual(beforeStartPackage, package); - Assert.IsTrue(package.IsSaveComplete); - } - - [TestMethod] - public async Task TestPauseAndResume() - { - // arrange - var pauseCount = 0; - var downloader = DownloadBuilder.New() - .WithUrl(url) - .WithFileLocation(path) - .Build(); - - downloader.DownloadProgressChanged += (s, e) => { - if (pauseCount < 10) - { - downloader.Pause(); - pauseCount++; - downloader.Resume(); - } - }; - - // act - await downloader.StartAsync(); - - // assert - Assert.IsTrue(downloader.Package?.IsSaveComplete); - Assert.AreEqual(10, pauseCount); - Assert.IsTrue(File.Exists(path)); - - // clean up - File.Delete(path); - } - - [TestMethod] - public async Task TestOverwriteFileWithDownloadSameLocation() - { - // arrange - var content = "THIS IS TEST CONTENT WHICH MUST BE OVERWRITE WITH THE DOWNLOADER"; - var downloader = DownloadBuilder.New() - .WithUrl(url) - .WithFileLocation(path) - .Build(); - - // act - await File.WriteAllTextAsync(path, content); // create file - await downloader.StartAsync(); // overwrite file - var file = await File.ReadAllTextAsync(path); - - // assert - Assert.IsTrue(downloader.Package?.IsSaveComplete); - Assert.IsTrue(File.Exists(path)); - Assert.IsFalse(file.StartsWith(content)); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, Encoding.ASCII.GetByteCount(file)); - - // clean up - File.Delete(path); - } - - [TestMethod] - public async Task TestOverwriteFileWithDownloadSameFileName() - { - // arrange - var content = "THIS IS TEST CONTENT WHICH MUST BE OVERWRITE WITH THE DOWNLOADER"; - var downloader = DownloadBuilder.New() - .WithUrl(url) - .WithDirectory(folder) - .WithFileName(filename) - .Build(); - - // act - await File.WriteAllTextAsync(path, content); // create file - await downloader.StartAsync(); // overwrite file - var file = await File.ReadAllTextAsync(path); - - // assert - Assert.IsTrue(downloader.Package?.IsSaveComplete); - Assert.IsTrue(File.Exists(path)); - Assert.IsFalse(file.StartsWith(content)); - Assert.AreEqual(DummyFileHelper.FileSize16Kb, Encoding.ASCII.GetByteCount(file)); - - // clean up - File.Delete(path); - } + var content = "THIS IS TEST CONTENT WHICH MUST BE OVERWRITE WITH THE DOWNLOADER"; + var downloader = DownloadBuilder.New() + .WithUrl(url) + .WithDirectory(folder) + .WithFileName(filename) + .Build(); + + // act + await File.WriteAllTextAsync(path, content); // create file + await downloader.StartAsync(); // overwrite file + var file = await File.ReadAllTextAsync(path); + + // assert + Assert.True(downloader.Package?.IsSaveComplete); + Assert.True(File.Exists(path)); + Assert.False(file.StartsWith(content)); + Assert.Equal(DummyFileHelper.FileSize16Kb, Encoding.ASCII.GetByteCount(file)); + + // clean up + File.Delete(path); } } diff --git a/src/Downloader.Test/UnitTests/DownloadConfigurationTest.cs b/src/Downloader.Test/UnitTests/DownloadConfigurationTest.cs index 6a49369..8986907 100644 --- a/src/Downloader.Test/UnitTests/DownloadConfigurationTest.cs +++ b/src/Downloader.Test/UnitTests/DownloadConfigurationTest.cs @@ -1,73 +1,71 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.Reflection; +using System.Reflection; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class DownloadConfigurationTest { - [TestClass] - public class DownloadConfigurationTest + [Fact] + public void MaximumSpeedPerChunkTest() { - [TestMethod] - public void MaximumSpeedPerChunkTest() - { - // arrange - var configuration = - new DownloadConfiguration { - MaximumBytesPerSecond = 10240, - ParallelDownload = true, - ChunkCount = 10 - }; + // arrange + var configuration = + new DownloadConfiguration { + MaximumBytesPerSecond = 10240, + ParallelDownload = true, + ChunkCount = 10 + }; - // act - var maxSpeed = configuration.MaximumSpeedPerChunk; + // act + var maxSpeed = configuration.MaximumSpeedPerChunk; - // assert - Assert.AreEqual(configuration.MaximumBytesPerSecond / configuration.ChunkCount, maxSpeed); - } + // assert + Assert.Equal(configuration.MaximumBytesPerSecond / configuration.ChunkCount, maxSpeed); + } - [TestMethod] - public void BufferBlockSizeTest() - { - // arrange - var configuration = - new DownloadConfiguration { - MaximumBytesPerSecond = 10240, - ParallelDownload = true, - ChunkCount = 10 - }; + [Fact] + public void BufferBlockSizeTest() + { + // arrange + var configuration = + new DownloadConfiguration { + MaximumBytesPerSecond = 10240, + ParallelDownload = true, + ChunkCount = 10 + }; - // act - configuration.BufferBlockSize = 10240 * 2; + // act + configuration.BufferBlockSize = 10240 * 2; - // assert - Assert.AreEqual(configuration.BufferBlockSize, configuration.MaximumSpeedPerChunk); - } + // assert + Assert.Equal(configuration.BufferBlockSize, configuration.MaximumSpeedPerChunk); + } - [TestMethod] - public void CloneTest() - { - // arrange - var configProperties = typeof(DownloadConfiguration).GetProperties(); - var config = new DownloadConfiguration() { - MaxTryAgainOnFailover = 100, - ParallelDownload = true, - ChunkCount = 1, - Timeout = 150, - BufferBlockSize = 2048, - MaximumBytesPerSecond = 1024, - RequestConfiguration = new RequestConfiguration(), - CheckDiskSizeBeforeDownload = false, - MinimumSizeOfChunking = 1024, - ClearPackageOnCompletionWithFailure = true, - }; + [Fact] + public void CloneTest() + { + // arrange + var configProperties = typeof(DownloadConfiguration).GetProperties(); + var config = new DownloadConfiguration() { + MaxTryAgainOnFailover = 100, + ParallelDownload = true, + ChunkCount = 1, + Timeout = 150, + BufferBlockSize = 2048, + MaximumBytesPerSecond = 1024, + RequestConfiguration = new RequestConfiguration(), + CheckDiskSizeBeforeDownload = false, + MinimumSizeOfChunking = 1024, + ClearPackageOnCompletionWithFailure = true, + }; - // act - var cloneConfig = config.Clone() as DownloadConfiguration; + // act + var cloneConfig = config.Clone() as DownloadConfiguration; - // assert - foreach (PropertyInfo property in configProperties) - { - Assert.AreEqual(property.GetValue(config), property.GetValue(cloneConfig)); - } + // assert + foreach (PropertyInfo property in configProperties) + { + Assert.Equal(property.GetValue(config), property.GetValue(cloneConfig)); } } } diff --git a/src/Downloader.Test/UnitTests/DownloadPackageTest.cs b/src/Downloader.Test/UnitTests/DownloadPackageTest.cs index 6a30a4e..5ec8123 100644 --- a/src/Downloader.Test/UnitTests/DownloadPackageTest.cs +++ b/src/Downloader.Test/UnitTests/DownloadPackageTest.cs @@ -1,126 +1,96 @@ using Downloader.DummyHttpServer; using Downloader.Test.Helper; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; using System.Threading.Tasks; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public abstract class DownloadPackageTest : IAsyncLifetime { - [TestClass] - public abstract class DownloadPackageTest + protected DownloadConfiguration Config { get; set; } + protected DownloadPackage Package { get; set; } + protected byte[] Data { get; set; } + + public virtual async Task InitializeAsync() + { + Config = new DownloadConfiguration() { ChunkCount = 8 }; + Data = DummyData.GenerateOrderedBytes(DummyFileHelper.FileSize16Kb); + Package.BuildStorage(false, 1024 * 1024); + new ChunkHub(Config).SetFileChunks(Package); + await Package.Storage.WriteAsync(0, Data, DummyFileHelper.FileSize16Kb); + Package.Storage.Flush(); + } + + public virtual Task DisposeAsync() + { + Package?.Dispose(); + return Task.CompletedTask; + } + + [Fact] + public void PackageSerializationTest() + { + // act + var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(Package); + Package.Storage.Dispose(); + var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject(serialized); + var destData = new byte[deserialized.TotalFileSize]; + deserialized.Storage.OpenRead().Read(destData, 0, destData.Length); + + // assert + AssertHelper.AreEquals(Package, deserialized); + Assert.True(Data.SequenceEqual(destData)); + + deserialized.Clear(); + deserialized.Storage.Dispose(); + } + + [Fact] + public void ClearChunksTest() + { + // act + Package.Clear(); + + // assert + Assert.Null(Package.Chunks); + } + + [Fact] + public void ClearPackageTest() { - protected DownloadConfiguration Config { get; set; } - protected DownloadPackage Package { get; set; } - protected byte[] Data { get; set; } - - [TestInitialize] - public virtual async Task Initial() - { - Config = new DownloadConfiguration() { ChunkCount = 8 }; - Data = DummyData.GenerateOrderedBytes(DummyFileHelper.FileSize16Kb); - Package.BuildStorage(false, 1024 * 1024); - new ChunkHub(Config).SetFileChunks(Package); - await Package.Storage.WriteAsync(0, Data, DummyFileHelper.FileSize16Kb); - Package.Storage.Flush(); - } - - [TestCleanup] - public virtual void Cleanup() - { - Package?.Clear(); - Package?.Storage?.Dispose(); - } - - [TestMethod] - public void PackageSerializationTest() - { - // act - var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(Package); - Package.Storage.Dispose(); - var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject(serialized); - - // assert - PackagesAreEqual(Package, deserialized); - - deserialized.Clear(); - deserialized.Storage.Dispose(); - } - - private void PackagesAreEqual(DownloadPackage source, DownloadPackage destination) - { - var destData = new byte[destination.TotalFileSize]; - destination.Storage.OpenRead().Read(destData, 0, destData.Length); - - Assert.IsNotNull(source); - Assert.IsNotNull(destination); - Assert.IsNotNull(source.Chunks); - Assert.IsNotNull(destination.Chunks); - Assert.AreEqual(source.FileName, destination.FileName); - Assert.AreEqual(source.ReceivedBytesSize, destination.ReceivedBytesSize); - Assert.AreEqual(source.TotalFileSize, destination.TotalFileSize); - Assert.AreEqual(source.IsSaving, destination.IsSaving); - Assert.AreEqual(source.IsSaveComplete, destination.IsSaveComplete); - Assert.AreEqual(source.SaveProgress, destination.SaveProgress); - Assert.AreEqual(source.Chunks?.Length, destination.Chunks?.Length); - Assert.AreEqual(source.IsSupportDownloadInRange, destination.IsSupportDownloadInRange); - Assert.AreEqual(source.InMemoryStream, destination.InMemoryStream); - Assert.AreEqual(source.Storage.Path, destination.Storage.Path); - Assert.AreEqual(Data.Length, destination.Storage.Length); - Assert.IsTrue(source.Urls.SequenceEqual(destination.Urls)); - Assert.IsTrue(Data.SequenceEqual(destData)); - - for (int i = 0; i < source.Chunks.Length; i++) - { - AssertHelper.AreEquals(source.Chunks[i], destination.Chunks[i]); - } - } - - [TestMethod] - public void ClearChunksTest() - { - // act - Package.Clear(); - - // assert - Assert.IsNull(Package.Chunks); - } - - [TestMethod] - public void ClearPackageTest() - { - // act - Package.Clear(); - - // assert - Assert.AreEqual(0, Package.ReceivedBytesSize); - } - - [TestMethod] - public void PackageValidateTest() - { - // arrange - Package.Chunks[0].Position = Package.Storage.Length; - - // act - Package.Validate(); - - // assert - Assert.AreEqual(0, Package.Chunks[0].Position); - } - - [TestMethod] - public void TestPackageValidateWhenDoesNotSupportDownloadInRange() - { - // arrange - Package.Chunks[0].Position = 1000; - Package.IsSupportDownloadInRange = false; - - // act - Package.Validate(); - - // assert - Assert.AreEqual(0, Package.Chunks[0].Position); - } + // act + Package.Clear(); + + // assert + Assert.Equal(0, Package.ReceivedBytesSize); + } + + [Fact] + public void PackageValidateTest() + { + // arrange + Package.Chunks[0].Position = Package.Storage.Length; + + // act + Package.Validate(); + + // assert + Assert.Equal(0, Package.Chunks[0].Position); + } + + [Fact] + public void TestPackageValidateWhenDoesNotSupportDownloadInRange() + { + // arrange + Package.Chunks[0].Position = 1000; + Package.IsSupportDownloadInRange = false; + + // act + Package.Validate(); + + // assert + Assert.Equal(0, Package.Chunks[0].Position); } } diff --git a/src/Downloader.Test/UnitTests/DownloadPackageTestOnFile.cs b/src/Downloader.Test/UnitTests/DownloadPackageTestOnFile.cs index 697302d..81b714e 100644 --- a/src/Downloader.Test/UnitTests/DownloadPackageTestOnFile.cs +++ b/src/Downloader.Test/UnitTests/DownloadPackageTestOnFile.cs @@ -1,65 +1,52 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Threading.Tasks; +using Xunit; -namespace Downloader.Test.UnitTests -{ - [TestClass] - public class DownloadPackageTestOnFile : DownloadPackageTest - { - private string _path; - - [TestInitialize] - public override async Task Initial() - { - _path = Path.GetTempFileName(); +namespace Downloader.Test.UnitTests; - Package = new DownloadPackage() { - FileName = _path, - Urls = new[] { DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb) }, - TotalFileSize = DummyFileHelper.FileSize16Kb - }; - - await base.Initial(); - } - - [TestCleanup] - public override void Cleanup() - { - base.Cleanup(); - File.Delete(_path); - } +public class DownloadPackageTestOnFile : DownloadPackageTest +{ + private string _path; - [TestMethod] - public void BuildStorageTest() - { - BuildStorageTest(false); - } + public override async Task InitializeAsync() + { + _path = Path.GetTempFileName(); - [TestMethod] - public void BuildStorageWithReserveSpaceTest() - { - BuildStorageTest(true); - } + Package = new DownloadPackage() { + FileName = _path, + Urls = new[] { DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb) }, + TotalFileSize = DummyFileHelper.FileSize16Kb + }; - private void BuildStorageTest(bool reserveSpace) - { - // arrange - _path = Path.GetTempFileName(); - Package = new DownloadPackage() { - FileName = _path, - Urls = new[] { DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb) }, - TotalFileSize = DummyFileHelper.FileSize16Kb - }; + await base.InitializeAsync(); + } - // act - Package.BuildStorage(reserveSpace, 1024 * 1024); - using var stream = Package.Storage.OpenRead(); + public override async Task DisposeAsync() + { + await base.DisposeAsync(); + File.Delete(_path); + } - // assert - Assert.IsInstanceOfType(stream, typeof(FileStream)); - Assert.AreEqual(reserveSpace ? DummyFileHelper.FileSize16Kb : 0, Package.Storage.Length); - } + [Theory] + [InlineData(true)] // BuildStorageWithReserveSpaceTest + [InlineData(false)] // BuildStorageTest + public void BuildStorageTest(bool reserveSpace) + { + // arrange + _path = Path.GetTempFileName(); + Package = new DownloadPackage() { + FileName = _path, + Urls = new[] { DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb) }, + TotalFileSize = DummyFileHelper.FileSize16Kb + }; + + // act + Package.BuildStorage(reserveSpace, 1024 * 1024); + using var stream = Package.Storage.OpenRead(); + + // assert + Assert.IsType(stream); + Assert.Equal(reserveSpace ? DummyFileHelper.FileSize16Kb : 0, Package.Storage.Length); } } diff --git a/src/Downloader.Test/UnitTests/DownloadPackageTestOnMemory.cs b/src/Downloader.Test/UnitTests/DownloadPackageTestOnMemory.cs index 0874650..fda02b8 100644 --- a/src/Downloader.Test/UnitTests/DownloadPackageTestOnMemory.cs +++ b/src/Downloader.Test/UnitTests/DownloadPackageTestOnMemory.cs @@ -1,21 +1,17 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class DownloadPackageTestOnMemory : DownloadPackageTest { - [TestClass] - public class DownloadPackageTestOnMemory : DownloadPackageTest + public override async Task InitializeAsync() { - [TestInitialize] - public override async Task Initial() - { - Package = new DownloadPackage() { - Urls = new[] { DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb) }, - TotalFileSize = DummyFileHelper.FileSize16Kb - }; + Package = new DownloadPackage() { + Urls = new[] { DummyFileHelper.GetFileWithNameUrl(DummyFileHelper.SampleFile16KbName, DummyFileHelper.FileSize16Kb) }, + TotalFileSize = DummyFileHelper.FileSize16Kb + }; - await base.Initial(); - } + await base.InitializeAsync(); } } diff --git a/src/Downloader.Test/UnitTests/FileHelperTest.cs b/src/Downloader.Test/UnitTests/FileHelperTest.cs index 7aa08bc..cca1ac5 100644 --- a/src/Downloader.Test/UnitTests/FileHelperTest.cs +++ b/src/Downloader.Test/UnitTests/FileHelperTest.cs @@ -1,242 +1,240 @@ -using System; -using System.IO; -using Downloader.DummyHttpServer; +using Downloader.DummyHttpServer; using Downloader.Test.Helper; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; +using Xunit; + +namespace Downloader.Test.UnitTests; -namespace Downloader.Test.UnitTests +public class FileHelperTest { - [TestClass] - public class FileHelperTest + [Fact] + public void CreateFileSpecialPathTest() { - [TestMethod] - public void CreateFileSpecialPathTest() - { - // arrange - string baseUrl = Path.Combine(DummyFileHelper.TempDirectory, "downloader", "test"); - string filename = Path.Combine(baseUrl, Guid.NewGuid().ToString("N") + ".test"); + // arrange + string baseUrl = Path.Combine(DummyFileHelper.TempDirectory, "downloader", "test"); + string filename = Path.Combine(baseUrl, Guid.NewGuid().ToString("N") + ".test"); - // act - FileHelper.CreateFile(filename).Dispose(); + // act + FileHelper.CreateFile(filename).Dispose(); - // assert - Assert.IsTrue(File.Exists(filename)); - - File.Delete(filename); - } - - [TestMethod] - public void CreateFileNoPathTest() - { - // arrange - string baseUrl = " "; - string filename = Path.Combine(baseUrl, Guid.NewGuid().ToString("N") + DummyFileHelper.TempFilesExtension); - - // act - var fileStream = FileHelper.CreateFile(filename); - - // assert - Assert.AreEqual(Stream.Null, fileStream); - } - - [TestMethod] - public void GetTempFileSpecialPathTest() - { - // arrange - string baseUrl = Path.Combine(DummyFileHelper.TempDirectory, "downloader", "test"); + // assert + Assert.True(File.Exists(filename)); - // act - string tempFile = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + File.Delete(filename); + } + + [Fact] + public void CreateFileNoPathTest() + { + // arrange + string baseUrl = " "; + string filename = Path.Combine(baseUrl, Guid.NewGuid().ToString("N") + DummyFileHelper.TempFilesExtension); + + // act + var fileStream = FileHelper.CreateFile(filename); + + // assert + Assert.Equal(Stream.Null, fileStream); + } + + [Fact] + public void GetTempFileSpecialPathTest() + { + // arrange + string baseUrl = Path.Combine(DummyFileHelper.TempDirectory, "downloader", "test"); + + // act + string tempFile = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + + // assert + Assert.StartsWith(baseUrl, tempFile); + + File.Delete(tempFile); + } + + [Fact] + public void GetTempFileNoPathTest() + { + // arrange + string baseUrl = " "; + string tempFolder = DummyFileHelper.TempDirectory; + + // act + string tempFile = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + + // assert + Assert.StartsWith(tempFolder, tempFile); + + File.Delete(tempFile); + } + + [Fact] + public void GetTempFileNullPathTest() + { + // arrange + string tempFolder = DummyFileHelper.TempDirectory; + + // act + string tempFile = FileHelper.GetTempFile(null, string.Empty); + + // assert + Assert.StartsWith(tempFolder, tempFile); + + File.Delete(tempFile); + } + + [Fact] + public void GetTempFileSpecialPathNonDuplicationTest() + { + // arrange + string baseUrl = Path.Combine(DummyFileHelper.TempDirectory, "downloader", "test"); + + // act + string tempFile1 = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + string tempFile2 = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + + // assert + Assert.NotEqual(tempFile1, tempFile2); + + File.Delete(tempFile1); + File.Delete(tempFile2); + } + + [Fact] + public void GetTempFileNoPathNonDuplicationTest() + { + // arrange + string baseUrl = " "; + + // act + string tempFile1 = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + string tempFile2 = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + + // assert + Assert.NotEqual(tempFile1, tempFile2); + + File.Delete(tempFile1); + File.Delete(tempFile2); + } + + [Fact] + public void GetTempFileNullPathNonDuplicationTest() + { + // act + string tempFile1 = FileHelper.GetTempFile(null, string.Empty); + string tempFile2 = FileHelper.GetTempFile(null, string.Empty); - // assert - Assert.IsTrue(tempFile.StartsWith(baseUrl)); - - File.Delete(tempFile); - } - - [TestMethod] - public void GetTempFileNoPathTest() - { - // arrange - string baseUrl = " "; - string tempFolder = DummyFileHelper.TempDirectory; + // assert + Assert.NotEqual(tempFile1, tempFile2); + + File.Delete(tempFile1); + File.Delete(tempFile2); + } + + [Fact] + public void GetTempFileSpecialPathCreationTest() + { + // arrange + string baseUrl = Path.Combine(DummyFileHelper.TempDirectory, "downloader", "test"); + + // act + string tempFile = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + + // assert + Assert.True(File.Exists(tempFile)); + + File.Delete(tempFile); + } + + [Fact] + public void GetTempFileNullPathCreationTest() + { + // act + string tempFile = FileHelper.GetTempFile(null, string.Empty); + + // assert + Assert.True(File.Exists(tempFile)); + + File.Delete(tempFile); + } + + [Fact] + public void GetTempFileNoPathCreationTest() + { + // arrange + string baseUrl = " "; + + // act + string tempFile = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); + + // assert + Assert.True(File.Exists(tempFile)); + + File.Delete(tempFile); + } + + [Fact] + public void GetAvailableFreeSpaceOnDiskTest() + { + // arrange + var mainDriveRoot = Path.GetPathRoot(DummyFileHelper.TempDirectory); + var mainDrive = new DriveInfo(mainDriveRoot ?? string.Empty); + var mainDriveAvailableFreeSpace = mainDrive.AvailableFreeSpace - 1024; + + // act + var availableFreeSpace = FileHelper.GetAvailableFreeSpaceOnDisk(DummyFileHelper.TempDirectory); + + // assert + Assert.True(mainDriveAvailableFreeSpace < availableFreeSpace); + } + + [Fact] + public void GetAvailableFreeSpaceOnDiskWhenUncPathTest() + { + // arrange + var mainDriveRoot = Path.GetPathRoot("\\UNC_Server_1234584456465487981231\\testFolder\\test.test"); + + // act + var availableFreeSpace = FileHelper.GetAvailableFreeSpaceOnDisk(mainDriveRoot); + + // assert + Assert.Equal(0, availableFreeSpace); + } + + [Fact] + public void ThrowIfNotEnoughSpaceTest() + { + // arrange + var mainDriveRoot = Path.GetPathRoot(DummyFileHelper.TempDirectory); + + // act + void ThrowIfNotEnoughSpaceMethod() => FileHelper.ThrowIfNotEnoughSpace(long.MaxValue, mainDriveRoot); + + // assert + Assert.ThrowsAny(ThrowIfNotEnoughSpaceMethod); + } + + [Fact] + public void ThrowIfNotEnoughSpaceWhenIsNullTest() + { + // act + void ThrowIfNotEnoughSpaceMethod() => FileHelper.ThrowIfNotEnoughSpace(long.MaxValue, null); + + // assert + AssertHelper.DoesNotThrow(ThrowIfNotEnoughSpaceMethod); + } + + [Fact] + public void ThrowIfNotEnoughSpaceWhenPathIsNullTest() + { + // arrange + var mainDriveRoot = Path.GetPathRoot(DummyFileHelper.TempDirectory); - // act - string tempFile = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); - - // assert - Assert.IsTrue(tempFile.StartsWith(tempFolder)); - - File.Delete(tempFile); - } - - [TestMethod] - public void GetTempFileNullPathTest() - { - // arrange - string tempFolder = DummyFileHelper.TempDirectory; + // act + void ThrowIfNotEnoughSpaceMethod() => FileHelper.ThrowIfNotEnoughSpace(1, mainDriveRoot, null); - // act - string tempFile = FileHelper.GetTempFile(null, string.Empty); - - // assert - Assert.IsTrue(tempFile.StartsWith(tempFolder)); - - File.Delete(tempFile); - } - - [TestMethod] - public void GetTempFileSpecialPathNonDuplicationTest() - { - // arrange - string baseUrl = Path.Combine(DummyFileHelper.TempDirectory, "downloader", "test"); - - // act - string tempFile1 = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); - string tempFile2 = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); - - // assert - Assert.AreNotEqual(tempFile1, tempFile2); - - File.Delete(tempFile1); - File.Delete(tempFile2); - } - - [TestMethod] - public void GetTempFileNoPathNonDuplicationTest() - { - // arrange - string baseUrl = " "; - - // act - string tempFile1 = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); - string tempFile2 = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); - - // assert - Assert.AreNotEqual(tempFile1, tempFile2); - - File.Delete(tempFile1); - File.Delete(tempFile2); - } - - [TestMethod] - public void GetTempFileNullPathNonDuplicationTest() - { - // act - string tempFile1 = FileHelper.GetTempFile(null, string.Empty); - string tempFile2 = FileHelper.GetTempFile(null, string.Empty); - - // assert - Assert.AreNotEqual(tempFile1, tempFile2); - - File.Delete(tempFile1); - File.Delete(tempFile2); - } - - [TestMethod] - public void GetTempFileSpecialPathCreationTest() - { - // arrange - string baseUrl = Path.Combine(DummyFileHelper.TempDirectory, "downloader", "test"); - - // act - string tempFile = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); - - // assert - Assert.IsTrue(File.Exists(tempFile)); - - File.Delete(tempFile); - } - - [TestMethod] - public void GetTempFileNullPathCreationTest() - { - // act - string tempFile = FileHelper.GetTempFile(null, string.Empty); - - // assert - Assert.IsTrue(File.Exists(tempFile)); - - File.Delete(tempFile); - } - - [TestMethod] - public void GetTempFileNoPathCreationTest() - { - // arrange - string baseUrl = " "; - - // act - string tempFile = FileHelper.GetTempFile(baseUrl, DummyFileHelper.TempFilesExtension); - - // assert - Assert.IsTrue(File.Exists(tempFile)); - - File.Delete(tempFile); - } - - [TestMethod] - public void GetAvailableFreeSpaceOnDiskTest() - { - // arrange - var mainDriveRoot = Path.GetPathRoot(DummyFileHelper.TempDirectory); - var mainDrive = new DriveInfo(mainDriveRoot ?? string.Empty); - var mainDriveAvailableFreeSpace = mainDrive.AvailableFreeSpace - 1024; - - // act - var availableFreeSpace = FileHelper.GetAvailableFreeSpaceOnDisk(DummyFileHelper.TempDirectory); - - // assert - Assert.IsTrue(mainDriveAvailableFreeSpace < availableFreeSpace); - } - - [TestMethod] - public void GetAvailableFreeSpaceOnDiskWhenUncPathTest() - { - // arrange - var mainDriveRoot = Path.GetPathRoot("\\UNC_Server_1234584456465487981231\\testFolder\\test.test"); - - // act - var availableFreeSpace = FileHelper.GetAvailableFreeSpaceOnDisk(mainDriveRoot); - - // assert - Assert.AreEqual(availableFreeSpace, 0); - } - - [TestMethod] - public void ThrowIfNotEnoughSpaceTest() - { - // arrange - var mainDriveRoot = Path.GetPathRoot(DummyFileHelper.TempDirectory); - - // act - void ThrowIfNotEnoughSpaceMethod() => FileHelper.ThrowIfNotEnoughSpace(long.MaxValue, mainDriveRoot); - - // assert - Assert.ThrowsException(ThrowIfNotEnoughSpaceMethod); - } - - [TestMethod] - public void ThrowIfNotEnoughSpaceWhenIsNullTest() - { - // act - void ThrowIfNotEnoughSpaceMethod() => FileHelper.ThrowIfNotEnoughSpace(long.MaxValue, null); - - // assert - AssertHelper.DoesNotThrow(ThrowIfNotEnoughSpaceMethod); - } - - [TestMethod] - public void ThrowIfNotEnoughSpaceWhenPathIsNullTest() - { - // arrange - var mainDriveRoot = Path.GetPathRoot(DummyFileHelper.TempDirectory); - - // act - void ThrowIfNotEnoughSpaceMethod() => FileHelper.ThrowIfNotEnoughSpace(1, mainDriveRoot, null); - - // assert - AssertHelper.DoesNotThrow(ThrowIfNotEnoughSpaceMethod); - } + // assert + AssertHelper.DoesNotThrow(ThrowIfNotEnoughSpaceMethod); } } diff --git a/src/Downloader.Test/UnitTests/PacketTest.cs b/src/Downloader.Test/UnitTests/PacketTest.cs index c6b6a88..257d2f4 100644 --- a/src/Downloader.Test/UnitTests/PacketTest.cs +++ b/src/Downloader.Test/UnitTests/PacketTest.cs @@ -1,52 +1,50 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class PacketTest { - [TestClass] - public class PacketTest + [Fact] + public void CreatePacketTest() { - [TestMethod] - public void CreatePacketTest() - { - // arrange - byte[] bytes = DummyData.GenerateOrderedBytes(1024); - long pos = 1234; - var len = 512; + // arrange + byte[] bytes = DummyData.GenerateOrderedBytes(1024); + long pos = 1234; + var len = 512; - // act - Packet packet = new Packet(pos, bytes, len); + // act + Packet packet = new Packet(pos, bytes, len); - // assert - Assert.AreEqual(len, packet.Length); - Assert.AreNotEqual(len, packet.Data.Length); - Assert.AreEqual(pos, packet.Position); - Assert.AreEqual(pos + len, packet.EndOffset); - Assert.IsTrue(packet.Data.SequenceEqual(bytes)); - } + // assert + Assert.Equal(len, packet.Length); + Assert.NotEqual(len, packet.Data.Length); + Assert.Equal(pos, packet.Position); + Assert.Equal(pos + len, packet.EndOffset); + Assert.True(packet.Data.SequenceEqual(bytes)); + } - [TestMethod] - public void MergePacketsTest() - { - // arrange - var packetLength = 512; - var startPosA = 1024; - var startPosB = 1024; - var dataA = DummyData.GenerateOrderedBytes(1024); - var dataB = DummyData.GenerateSingleBytes(1024, 8); - var packetA = new Packet(startPosA, dataA, packetLength); - var packetB = new Packet(startPosB, dataB, packetLength); - var concatData = dataA.Take(packetLength).Concat(dataB.Take(packetLength)); + [Fact] + public void MergePacketsTest() + { + // arrange + var packetLength = 512; + var startPosA = 1024; + var startPosB = 1024; + var dataA = DummyData.GenerateOrderedBytes(1024); + var dataB = DummyData.GenerateSingleBytes(1024, 8); + var packetA = new Packet(startPosA, dataA, packetLength); + var packetB = new Packet(startPosB, dataB, packetLength); + var concatData = dataA.Take(packetLength).Concat(dataB.Take(packetLength)); - // act - packetA.Merge(packetB); + // act + packetA.Merge(packetB); - // assert - Assert.AreEqual(packetLength, packetB.Length); - Assert.AreEqual(packetLength * 2, packetA.Length); - Assert.IsTrue(packetA.Data.SequenceEqual(concatData)); - } + // assert + Assert.Equal(packetLength, packetB.Length); + Assert.Equal(packetLength * 2, packetA.Length); + Assert.True(packetA.Data.SequenceEqual(concatData)); } } diff --git a/src/Downloader.Test/UnitTests/PauseTokenTest.cs b/src/Downloader.Test/UnitTests/PauseTokenTest.cs index ebaff1b..f046271 100644 --- a/src/Downloader.Test/UnitTests/PauseTokenTest.cs +++ b/src/Downloader.Test/UnitTests/PauseTokenTest.cs @@ -1,169 +1,164 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.Threading; +using System.Threading; using System.Threading.Tasks; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; +public class PauseTokenTest { - [TestClass] - public class PauseTokenTest - { - private PauseTokenSource _pauseTokenSource; - private volatile int actualPauseCount = 0; + private PauseTokenSource _pauseTokenSource; + private volatile int actualPauseCount = 0; - [TestInitialize] - public void Initialize() - { - _pauseTokenSource = new PauseTokenSource(); - } + public PauseTokenTest() + { + _pauseTokenSource = new PauseTokenSource(); + } - [TestMethod] - public async Task TestPauseTaskWithPauseToken() + [Fact] + public async Task TestPauseTaskWithPauseToken() + { + // arrange + var cts = new CancellationTokenSource(); + var pts = new PauseTokenSource(); + var expectedCount = 0; + var checkTokenStateIsNotPaused = false; + var checkTokenStateIsPaused = true; + var hasRunningTask = true; + var tasksAlreadyPaused = true; + + // act + pts.Pause(); + var tasks = new Task[] { + IncreaseAsync(pts.Token, cts.Token), + IncreaseAsync(pts.Token, cts.Token), + IncreaseAsync(pts.Token, cts.Token), + IncreaseAsync(pts.Token, cts.Token), + IncreaseAsync(pts.Token, cts.Token) + }; + var _ = Task.WhenAll(tasks); + + for (var i = 0; i < 10; i++) { - // arrange - var cts = new CancellationTokenSource(); - var pts = new PauseTokenSource(); - var expectedCount = 0; - var checkTokenStateIsNotPaused = false; - var checkTokenStateIsPaused = true; - var hasRunningTask = true; - var tasksAlreadyPaused = true; - - // act + await Task.Delay(1); + tasksAlreadyPaused &= (actualPauseCount == expectedCount); + pts.Resume(); + checkTokenStateIsNotPaused |= pts.IsPaused; + await Task.Delay(1); pts.Pause(); - var tasks = new Task[] { - IncreaseAsync(pts.Token, cts.Token), - IncreaseAsync(pts.Token, cts.Token), - IncreaseAsync(pts.Token, cts.Token), - IncreaseAsync(pts.Token, cts.Token), - IncreaseAsync(pts.Token, cts.Token) - }; - var _ = Task.WhenAll(tasks).ConfigureAwait(false); - - for (var i = 0; i < 10; i++) - { - await Task.Delay(1).ConfigureAwait(false); - tasksAlreadyPaused &= (actualPauseCount == expectedCount); - pts.Resume(); - checkTokenStateIsNotPaused |= pts.IsPaused; - await Task.Delay(1).ConfigureAwait(false); - pts.Pause(); - checkTokenStateIsPaused &= pts.IsPaused; - await Task.Delay(1).ConfigureAwait(false); - hasRunningTask &= (actualPauseCount > expectedCount); - expectedCount = actualPauseCount; - } - cts.Cancel(); - - // assert - Assert.IsTrue(expectedCount >= actualPauseCount, $"Expected: {expectedCount}, Actual: {actualPauseCount}"); - Assert.IsTrue(pts.IsPaused); - Assert.IsTrue(checkTokenStateIsPaused); - Assert.IsFalse(checkTokenStateIsNotPaused); - Assert.IsTrue(tasksAlreadyPaused); - Assert.IsTrue(hasRunningTask); + checkTokenStateIsPaused &= pts.IsPaused; + await Task.Delay(1); + hasRunningTask &= (actualPauseCount > expectedCount); + expectedCount = actualPauseCount; } + cts.Cancel(); + + // assert + Assert.True(expectedCount >= actualPauseCount, $"Expected: {expectedCount}, Actual: {actualPauseCount}"); + Assert.True(pts.IsPaused); + Assert.True(checkTokenStateIsPaused); + Assert.False(checkTokenStateIsNotPaused); + Assert.True(tasksAlreadyPaused); + Assert.True(hasRunningTask); + } - private async Task IncreaseAsync(PauseToken pause, CancellationToken cancel) + private async Task IncreaseAsync(PauseToken pause, CancellationToken cancel) + { + while (cancel.IsCancellationRequested == false) { - while (cancel.IsCancellationRequested == false) - { - await pause.WaitWhilePausedAsync(); - actualPauseCount++; - await Task.Yield(); - } + await pause.WaitWhilePausedAsync(); + actualPauseCount++; + await Task.Yield(); } + } - [TestMethod] - public async Task TestPauseAndResume() - { - // Verify that a task is not paused initially - Assert.IsFalse(_pauseTokenSource.IsPaused); + [Fact] + public async Task TestPauseAndResume() + { + // Verify that a task is not paused initially + Assert.False(_pauseTokenSource.IsPaused); - // Pause the token source - _pauseTokenSource.Pause(); + // Pause the token source + _pauseTokenSource.Pause(); - // Verify that a task is paused - Assert.IsTrue(_pauseTokenSource.IsPaused); + // Verify that a task is paused + Assert.True(_pauseTokenSource.IsPaused); - // Create a task that waits while the token source is paused - var pauseTask = Task.Run(async () => { - await _pauseTokenSource.WaitWhilePausedAsync(); - Assert.IsFalse(_pauseTokenSource.IsPaused); - }); + // Create a task that waits while the token source is paused + var pauseTask = Task.Run(async () => { + await _pauseTokenSource.WaitWhilePausedAsync(); + Assert.False(_pauseTokenSource.IsPaused); + }); - // Wait for a short period of time to ensure that the task is paused - await Task.Delay(100); - Assert.IsTrue(pauseTask.Status == TaskStatus.WaitingForActivation); + // Wait for a short period of time to ensure that the task is paused + await Task.Delay(100); + Assert.True(pauseTask.Status == TaskStatus.WaitingForActivation); - // Resume the token source - _pauseTokenSource.Resume(); + // Resume the token source + _pauseTokenSource.Resume(); - // Wait for the task to complete - await pauseTask; - } + // Wait for the task to complete + await pauseTask; + } - [TestMethod] - public async Task TestResumeWithoutPause() - { - // Verify that a task is not paused initially - Assert.IsFalse(_pauseTokenSource.IsPaused); + [Fact] + public async Task TestResumeWithoutPause() + { + // Verify that a task is not paused initially + Assert.False(_pauseTokenSource.IsPaused); - // Resume the token source without pausing first - _pauseTokenSource.Resume(); + // Resume the token source without pausing first + _pauseTokenSource.Resume(); - // Verify that a task is still not paused - Assert.IsFalse(_pauseTokenSource.IsPaused); + // Verify that a task is still not paused + Assert.False(_pauseTokenSource.IsPaused); - // Create a task that waits while the token source is paused - var pauseTask = Task.Run(async () => { - await _pauseTokenSource.WaitWhilePausedAsync(); - Assert.IsFalse(_pauseTokenSource.IsPaused); - }); + // Create a task that waits while the token source is paused + var pauseTask = Task.Run(async () => { + await _pauseTokenSource.WaitWhilePausedAsync(); + Assert.False(_pauseTokenSource.IsPaused); + }); - // Wait for a short period of time to ensure that the task is not paused - await Task.Delay(100); - Assert.IsTrue(pauseTask.IsCompleted); - } + // Wait for a short period of time to ensure that the task is not paused + await Task.Delay(100); + Assert.True(pauseTask.IsCompleted); + } - [TestMethod] - public async Task TestMultiplePauses() - { - // Verify that a task is not paused initially - Assert.IsFalse(_pauseTokenSource.IsPaused); + [Fact] + public async Task TestMultiplePauses() + { + // Verify that a task is not paused initially + Assert.False(_pauseTokenSource.IsPaused); - // Pause the token source multiple times - _pauseTokenSource.Pause(); - _pauseTokenSource.Pause(); + // Pause the token source multiple times + _pauseTokenSource.Pause(); + _pauseTokenSource.Pause(); - // Verify that a task is paused - Assert.IsTrue(_pauseTokenSource.IsPaused); + // Verify that a task is paused + Assert.True(_pauseTokenSource.IsPaused); - // Create a task that waits while the token source is paused - var pauseTask = Task.Run(async () => - { - await _pauseTokenSource.WaitWhilePausedAsync(); - Assert.IsFalse(_pauseTokenSource.IsPaused); - }); + // Create a task that waits while the token source is paused + var pauseTask = Task.Run(async () => { + await _pauseTokenSource.WaitWhilePausedAsync(); + Assert.False(_pauseTokenSource.IsPaused); + }); - // Wait for a short period of time to ensure that the task is paused - await Task.Delay(100); - Assert.IsTrue(pauseTask.Status == TaskStatus.WaitingForActivation); + // Wait for a short period of time to ensure that the task is paused + await Task.Delay(100); + Assert.True(pauseTask.Status == TaskStatus.WaitingForActivation); - // Resume the token source once - _pauseTokenSource.Resume(); + // Resume the token source once + _pauseTokenSource.Resume(); - // Wait for a short period of time to ensure that the task is still paused - await Task.Delay(100); - Assert.IsTrue(pauseTask.Status == TaskStatus.RanToCompletion); + // Wait for a short period of time to ensure that the task is still paused + await Task.Delay(100); + Assert.True(pauseTask.Status == TaskStatus.RanToCompletion); - // Resume the token source again - _pauseTokenSource.Resume(); + // Resume the token source again + _pauseTokenSource.Resume(); - // Wait for the task to complete - await pauseTask; + // Wait for the task to complete + await pauseTask; - // Verify that the task completed successfully - Assert.IsTrue(pauseTask.Status == TaskStatus.RanToCompletion); - } + // Verify that the task completed successfully + Assert.True(pauseTask.Status == TaskStatus.RanToCompletion); } } diff --git a/src/Downloader.Test/UnitTests/RequestTest.cs b/src/Downloader.Test/UnitTests/RequestTest.cs index 1a84d84..78eb7e5 100644 --- a/src/Downloader.Test/UnitTests/RequestTest.cs +++ b/src/Downloader.Test/UnitTests/RequestTest.cs @@ -1,593 +1,466 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Xunit; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading.Tasks; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class RequestTest { - [TestClass] - public class RequestTest - { - private const string EnglishText = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - private const string PersianText = "۰۱۲۳۴۵۶۷۸۹ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیًٌٍَُِّْؤئيإأآة»«:؛كٰ‌ٔء؟"; - private static readonly Encoding Latin1Encoding = Encoding.GetEncoding("iso-8859-1"); - - [TestMethod] - public void GetFileNameWhenNoUrlTest() - { - // arrange - var url = " "; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual("", actualFilename); - } - - [TestMethod] - public void GetFileNameWhenBadUrlTest() - { - // arrange - var url = "http://www.a.com/a/b/c/d/e/"; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual("", actualFilename); - } - - [TestMethod] - public void GetFileNameWhenBadUrlWithFilenameTest() - { - // arrange - var filename = "test"; - var url = "http://www.a.com/a/b/c/" + filename; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithJustFilenameTest() - { - // arrange - var filename = "test.xml"; - var url = filename; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithJustFilenameWithoutExtensionTest() - { - // arrange - var filename = "test"; - var url = filename; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithShortUrlTest() - { - // arrange - var filename = "test.xml"; - var url = "/" + filename; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithShortUrlAndQueryParamTest() - { - // arrange - var filename = "test.xml"; - var url = $"/{filename}?q=1"; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithShortUrlAndQueryParamsTest() - { - // arrange - var filename = "test.xml"; - var url = $"/{filename}?q=1&x=100.0&y=testName"; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithJustFilenameAndQueryParamsTest() - { - // arrange - var filename = "test.xml"; - var url = $"{filename}?q=1&x=100.0&y=testName"; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithUrlAndQueryParamsTest() - { - // arrange - var filename = "test.xml"; - var url = $"http://www.a.com/{filename}?q=1&x=1&filename=test"; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithUrlAndQueryParamsComplexTest() - { - // arrange - var filename = "Thor.Love.and.Thunder.2022.720p.WEBRip.800MB.x264-GalaxyRG[TGx].zip"; - var url = $"https://rs17.seedr.cc/get_zip_ngen_free/149605004/{filename}?st=XGSqYEtPiKmJcU-2PNNxjg&e=1663157407"; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetFileNameWithUrlAndQueryParamsAndFragmentIdentifierTest() - { - // arrange - var filename = "test.xml"; - var url = $"http://www.a.com/{filename}?q=1&x=3#aidjsf"; - - // act - var actualFilename = new Request(url).GetFileNameFromUrl(); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWhenNoUrlFileNameTest() - { - // arrange - var url = DummyFileHelper.GetFileWithContentDispositionUrl(DummyFileHelper.SampleFile1KbName, DummyFileHelper.FileSize1Kb); - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.AreEqual(DummyFileHelper.SampleFile1KbName, actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWhenNoUrlTest() - { - // arrange - var url = " "; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWhenBadUrlTest() - { - // arrange - var url = "http://www.a.com/a/b/c/d/e/"; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWhenBadUrlWithFilenameTest() - { - // arrange - var filename = "test"; - var url = "http://www.a.com/a/b/c/" + filename; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithJustFilenameTest() - { - // arrange - var filename = "test.xml"; - var url = filename; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithJustFilenameWithoutExtensionTest() - { - // arrange - var filename = "test"; - var url = filename; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithShortUrlTest() - { - // arrange - var filename = "test.xml"; - var url = "/" + filename; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithShortUrlAndQueryParamTest() - { - // arrange - var filename = "test.xml"; - var url = $"/{filename}?q=1"; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithShortUrlAndQueryParamsTest() - { - // arrange - var filename = "test.xml"; - var url = $"/{filename}?q=1&x=100.0&y=testName"; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithJustFilenameAndQueryParamsTest() - { - // arrange - var filename = "test.xml"; - var url = $"{filename}?q=1&x=100.0&y=testName"; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithUrlAndQueryParamsTest() - { - // arrange - var filename = "test.xml"; - var url = $"http://www.a.com/{filename}?q=1&x=1&filename=test"; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithUrlAndQueryParamsAndFragmentIdentifierTest() - { - // arrange - var filename = "test.xml"; - var url = $"http://www.a.com/{filename}?q=1&x=3#aidjsf"; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetUrlDispositionWithLongUrlTest() - { - // arrange - var filename = "excel_sample.xls"; - var url = $"https://raw.githubusercontent.com/bezzad/Downloader/master/src/Downloader.Test/Assets/{filename}?test=1"; - - // act - var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync().ConfigureAwait(false); - - // assert - Assert.IsNull(actualFilename); - } - - [TestMethod] - public async Task GetFileNameOnRedirectUrlTest() - { - // arrange - var filename = "test.zip"; - var url = DummyFileHelper.GetFileWithNameOnRedirectUrl(filename, DummyFileHelper.FileSize1Kb); - - // act - var actualFilename = await new Request(url).GetFileName().ConfigureAwait(false); - - // assert - Assert.AreEqual(filename, actualFilename); - } - - [TestMethod] - public void GetRedirectUrlByLocationTest() - { - // arrange - var filename = "test.zip"; - var url = DummyFileHelper.GetFileWithNameOnRedirectUrl(filename, DummyFileHelper.FileSize1Kb); - var redirectUrl = DummyFileHelper.GetFileWithNameUrl(filename, DummyFileHelper.FileSize1Kb); - var request = new Request(url); - - // act - var resp = WebRequest.Create(url).GetResponse(); - resp.Headers.Add("Location", redirectUrl); - var actualRedirectUrl = request.GetRedirectUrl(resp); - - // assert - Assert.AreNotEqual(url, redirectUrl); - Assert.AreNotEqual(request.Address.ToString(), redirectUrl); - Assert.AreEqual(redirectUrl, actualRedirectUrl.AbsoluteUri); - } - - [TestMethod] - public void GetRedirectUrlWithoutLocationTest() - { - // arrange - var filename = "test.zip"; - var url = DummyFileHelper.GetFileWithNameOnRedirectUrl(filename, DummyFileHelper.FileSize1Kb); - var redirectUrl = DummyFileHelper.GetFileWithNameUrl(filename, DummyFileHelper.FileSize1Kb); - var request = new Request(url); - - // act - var resp = WebRequest.Create(url).GetResponse(); - var actualRedirectUrl = request.GetRedirectUrl(resp); - - // assert - Assert.AreNotEqual(url, redirectUrl); - Assert.AreNotEqual(request.Address.ToString(), redirectUrl); - Assert.AreEqual(redirectUrl, actualRedirectUrl.AbsoluteUri); - } - - [TestMethod] - public async Task GetFileSizeTest() - { - // arrange - var url = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb); - var expectedSize = DummyFileHelper.FileSize16Kb; - - // act - var actualSize = await new Request(url).GetFileSize().ConfigureAwait(false); - - // assert - Assert.AreEqual(expectedSize, actualSize); - } - - [TestMethod] - public async Task IsSupportDownloadInRangeTest() - { - // arrange - var url = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb); - - // act - var actualCan = await new Request(url).IsSupportDownloadInRange().ConfigureAwait(false); - - // assert - Assert.IsTrue(actualCan); - } - - [TestMethod] - public void GetTotalSizeFromContentLengthTest() - { - // arrange - var length = 23432L; - var headers = new Dictionary() { { "Content-Length", length.ToString() } }; - var request = new Request("www.example.com"); - - // act - var actualLength = request.GetTotalSizeFromContentLength(headers); - - // assert - Assert.AreEqual(length, actualLength); - } - - [TestMethod] - public void GetTotalSizeFromContentLengthWhenNoHeaderTest() - { - // arrange - var length = -1; - var headers = new Dictionary(); - var request = new Request("www.example.com"); - - // act - var actualLength = request.GetTotalSizeFromContentLength(headers); - - // assert - Assert.AreEqual(length, actualLength); - } - - [TestMethod] - public void GetTotalSizeFromContentRangeTest() - { - TestGetTotalSizeFromContentRange(23432, "bytes 0-0/23432"); - } - - [TestMethod] - public void GetTotalSizeFromContentRangeWhenUnknownSizeTest() - { - TestGetTotalSizeFromContentRange(-1, "bytes 0-1000/*"); - } - - [TestMethod] - public void GetTotalSizeFromContentRangeWhenUnknownRangeTest() - { - TestGetTotalSizeFromContentRange(23529, "bytes */23529"); - } - - [TestMethod] - public void GetTotalSizeFromContentRangeWhenIncorrectTest() - { - TestGetTotalSizeFromContentRange(23589, "bytes -0/23589"); - } - - [TestMethod] - public void GetTotalSizeFromContentRangeWhenNoHeaderTest() - { - TestGetTotalSizeFromContentRange(-1, null); - } - - private void TestGetTotalSizeFromContentRange(long expectedLength, string contentRange) - { - // arrange - var request = new Request("www.example.com"); - var headers = new Dictionary(); - if (string.IsNullOrEmpty(contentRange) == false) - headers["Content-Range"] = contentRange; - - // act - var actualLength = request.GetTotalSizeFromContentRange(headers); - - // assert - Assert.AreEqual(expectedLength, actualLength); - } - - [TestMethod] - public void ToUnicodeFromEnglishToEnglishTest() - { - // arrange - byte[] inputRawBytes = Encoding.UTF8.GetBytes(EnglishText); - string inputEncodedText = Latin1Encoding.GetString(inputRawBytes); - Request requestInstance = new Request(""); - - // act - string decodedEnglishText = requestInstance.ToUnicode(inputEncodedText); - - // assert - Assert.AreEqual(EnglishText, decodedEnglishText); - } - - [TestMethod] - public void ToUnicodeFromPersianToPersianTest() - { - // arrange - byte[] inputRawBytes = Encoding.UTF8.GetBytes(PersianText); - string inputEncodedText = Latin1Encoding.GetString(inputRawBytes); - Request requestInstance = new Request(""); - - // act - string decodedEnglishText = requestInstance.ToUnicode(inputEncodedText); - - // assert - Assert.AreEqual(PersianText, decodedEnglishText); - } - - [TestMethod] - public void ToUnicodeFromAllToAllWithExtensionTest() - { - // arrange - string inputRawText = EnglishText + PersianText + ".ext"; - byte[] inputRawBytes = Encoding.UTF8.GetBytes(inputRawText); - string inputEncodedText = Latin1Encoding.GetString(inputRawBytes); - Request requestInstance = new Request(""); - - // act - string decodedEnglishText = requestInstance.ToUnicode(inputEncodedText); - - // assert - Assert.AreEqual(inputRawText, decodedEnglishText); - } - - [TestMethod] - public void GetRequestWithCredentialsTest() - { - // arrange - var requestConfig = new RequestConfiguration() { - Credentials = new NetworkCredential("username", "password") - }; - var request = new Request("http://test.com", requestConfig); - - // act - var httpRequest = request.GetRequest(); - - // assert - Assert.IsNotNull(httpRequest.Credentials); - } - - [TestMethod] - public void GetRequestWithNullCredentialsTest() - { - // arrange - var requestConfig = new RequestConfiguration(); - var request = new Request("http://test.com", requestConfig); - - // act - var httpRequest = request.GetRequest(); - - // assert - Assert.IsNull(httpRequest.Credentials); - } + private const string EnglishText = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private const string PersianText = "۰۱۲۳۴۵۶۷۸۹ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیًٌٍَُِّْؤئيإأآة»«:؛كٰ‌ٔء؟"; + private static readonly Encoding Latin1Encoding = Encoding.GetEncoding("iso-8859-1"); + + [Theory] + [InlineData(" ", "")] // When No Url + [InlineData("http://www.a.com/a/b/c/d/e/", "")] // When Bad Url + [InlineData("http://www.a.com/a/b/c/filename", "filename")] // When bad Url with filename + [InlineData("test.xml", "test.xml")] // When bad Url just a filename with extension + [InlineData("test", "test")] // When bad Url just a filename without extension + [InlineData("/test.xml", "test.xml")] // When short bad Url is same with the filename + [InlineData("/test.xml?q=123", "test.xml")] // When short bad Url with query string is same with the filename + [InlineData("/test.xml?q=1&x=100.0&y=testName", "test.xml")] // When bad short Url with query params is same with the filename + [InlineData("test.xml?q=1&x=100.0&y=testName", "test.xml")] // When bad Url with query params is same with the filename + [InlineData("http://www.a.com/test.xml?q=1&x=100.0&y=test", "test.xml")] // When complex Url with query params is same with the filename + [InlineData("https://rs17.seedr.cc/get_zip_ngen_free/149605004/test.xml?st=XGSqYEtPiKmJcU-2PNNxjg&e=1663157407", "test.xml")] // When complex Url with query params is same with the filename + + public void GetFileNameFromUrlTest(string url, string expectedFilename) + { + // act + var actualFilename = new Request(url).GetFileNameFromUrl(); + + // assert + Assert.Equal(expectedFilename, actualFilename); + } + + + + + + + [Fact] + public void GetFileNameWithUrlAndQueryParamsAndFragmentIdentifierTest() + { + // arrange + var filename = "test.xml"; + var url = $"http://www.a.com/{filename}?q=1&x=3#aidjsf"; + + // act + var actualFilename = new Request(url).GetFileNameFromUrl(); + + // assert + Assert.Equal(filename, actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWhenNoUrlFileNameTest() + { + // arrange + var url = DummyFileHelper.GetFileWithContentDispositionUrl(DummyFileHelper.SampleFile1KbName, DummyFileHelper.FileSize1Kb); + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Equal(DummyFileHelper.SampleFile1KbName, actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWhenNoUrlTest() + { + // arrange + var url = " "; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWhenBadUrlTest() + { + // arrange + var url = "http://www.a.com/a/b/c/d/e/"; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWhenBadUrlWithFilenameTest() + { + // arrange + var filename = "test"; + var url = "http://www.a.com/a/b/c/" + filename; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithJustFilenameTest() + { + // arrange + var filename = "test.xml"; + var url = filename; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithJustFilenameWithoutExtensionTest() + { + // arrange + var filename = "test"; + var url = filename; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithShortUrlTest() + { + // arrange + var filename = "test.xml"; + var url = "/" + filename; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithShortUrlAndQueryParamTest() + { + // arrange + var filename = "test.xml"; + var url = $"/{filename}?q=1"; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithShortUrlAndQueryParamsTest() + { + // arrange + var filename = "test.xml"; + var url = $"/{filename}?q=1&x=100.0&y=testName"; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithJustFilenameAndQueryParamsTest() + { + // arrange + var filename = "test.xml"; + var url = $"{filename}?q=1&x=100.0&y=testName"; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithUrlAndQueryParamsTest() + { + // arrange + var filename = "test.xml"; + var url = $"http://www.a.com/{filename}?q=1&x=1&filename=test"; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithUrlAndQueryParamsAndFragmentIdentifierTest() + { + // arrange + var filename = "test.xml"; + var url = $"http://www.a.com/{filename}?q=1&x=3#aidjsf"; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetUrlDispositionWithLongUrlTest() + { + // arrange + var filename = "excel_sample.xls"; + var url = $"https://raw.githubusercontent.com/bezzad/Downloader/master/src/Downloader.Test/Assets/{filename}?test=1"; + + // act + var actualFilename = await new Request(url).GetUrlDispositionFilenameAsync(); + + // assert + Assert.Null(actualFilename); + } + + [Fact] + public async Task GetFileNameOnRedirectUrlTest() + { + // arrange + var filename = "test.zip"; + var url = DummyFileHelper.GetFileWithNameOnRedirectUrl(filename, DummyFileHelper.FileSize1Kb); + + // act + var actualFilename = await new Request(url).GetFileName(); + + // assert + Assert.Equal(filename, actualFilename); + } + + [Fact] + public void GetRedirectUrlByLocationTest() + { + // arrange + var filename = "test.zip"; + var url = DummyFileHelper.GetFileWithNameOnRedirectUrl(filename, DummyFileHelper.FileSize1Kb); + var redirectUrl = DummyFileHelper.GetFileWithNameUrl(filename, DummyFileHelper.FileSize1Kb); + var request = new Request(url); + + // act + var resp = WebRequest.Create(url).GetResponse(); + resp.Headers.Add("Location", redirectUrl); + var actualRedirectUrl = request.GetRedirectUrl(resp); + + // assert + Assert.NotEqual(url, redirectUrl); + Assert.NotEqual(request.Address.ToString(), redirectUrl); + Assert.Equal(redirectUrl, actualRedirectUrl.AbsoluteUri); + } + + [Fact] + public void GetRedirectUrlWithoutLocationTest() + { + // arrange + var filename = "test.zip"; + var url = DummyFileHelper.GetFileWithNameOnRedirectUrl(filename, DummyFileHelper.FileSize1Kb); + var redirectUrl = DummyFileHelper.GetFileWithNameUrl(filename, DummyFileHelper.FileSize1Kb); + var request = new Request(url); + + // act + var resp = WebRequest.Create(url).GetResponse(); + var actualRedirectUrl = request.GetRedirectUrl(resp); + + // assert + Assert.NotEqual(url, redirectUrl); + Assert.NotEqual(request.Address.ToString(), redirectUrl); + Assert.Equal(redirectUrl, actualRedirectUrl.AbsoluteUri); + } + + [Fact] + public async Task GetFileSizeTest() + { + // arrange + var url = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb); + var expectedSize = DummyFileHelper.FileSize16Kb; + + // act + var actualSize = await new Request(url).GetFileSize(); + + // assert + Assert.Equal(expectedSize, actualSize); + } + + [Fact] + public async Task IsSupportDownloadInRangeTest() + { + // arrange + var url = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb); + + // act + var actualCan = await new Request(url).IsSupportDownloadInRange(); + + // assert + Assert.True(actualCan); + } + + [Fact] + public void GetTotalSizeFromContentLengthTest() + { + // arrange + var length = 23432L; + var headers = new Dictionary() { { "Content-Length", length.ToString() } }; + var request = new Request("www.example.com"); + + // act + var actualLength = request.GetTotalSizeFromContentLength(headers); + + // assert + Assert.Equal(length, actualLength); + } + + [Fact] + public void GetTotalSizeFromContentLengthWhenNoHeaderTest() + { + // arrange + var length = -1; + var headers = new Dictionary(); + var request = new Request("www.example.com"); + + // act + var actualLength = request.GetTotalSizeFromContentLength(headers); + + // assert + Assert.Equal(length, actualLength); + } + + [Fact] + public void GetTotalSizeFromContentRangeTest() + { + TestGetTotalSizeFromContentRange(23432, "bytes 0-0/23432"); + } + + [Fact] + public void GetTotalSizeFromContentRangeWhenUnknownSizeTest() + { + TestGetTotalSizeFromContentRange(-1, "bytes 0-1000/*"); + } + + [Fact] + public void GetTotalSizeFromContentRangeWhenUnknownRangeTest() + { + TestGetTotalSizeFromContentRange(23529, "bytes */23529"); + } + + [Fact] + public void GetTotalSizeFromContentRangeWhenIncorrectTest() + { + TestGetTotalSizeFromContentRange(23589, "bytes -0/23589"); + } + + [Fact] + public void GetTotalSizeFromContentRangeWhenNoHeaderTest() + { + TestGetTotalSizeFromContentRange(-1, null); + } + + private void TestGetTotalSizeFromContentRange(long expectedLength, string contentRange) + { + // arrange + var request = new Request("www.example.com"); + var headers = new Dictionary(); + if (string.IsNullOrEmpty(contentRange) == false) + headers["Content-Range"] = contentRange; + + // act + var actualLength = request.GetTotalSizeFromContentRange(headers); + + // assert + Assert.Equal(expectedLength, actualLength); + } + + [Fact] + public void ToUnicodeFromEnglishToEnglishTest() + { + // arrange + byte[] inputRawBytes = Encoding.UTF8.GetBytes(EnglishText); + string inputEncodedText = Latin1Encoding.GetString(inputRawBytes); + Request requestInstance = new Request(""); + + // act + string decodedEnglishText = requestInstance.ToUnicode(inputEncodedText); + + // assert + Assert.Equal(EnglishText, decodedEnglishText); + } + + [Fact] + public void ToUnicodeFromPersianToPersianTest() + { + // arrange + byte[] inputRawBytes = Encoding.UTF8.GetBytes(PersianText); + string inputEncodedText = Latin1Encoding.GetString(inputRawBytes); + Request requestInstance = new Request(""); + + // act + string decodedEnglishText = requestInstance.ToUnicode(inputEncodedText); + + // assert + Assert.Equal(PersianText, decodedEnglishText); + } + + [Fact] + public void ToUnicodeFromAllToAllWithExtensionTest() + { + // arrange + string inputRawText = EnglishText + PersianText + ".ext"; + byte[] inputRawBytes = Encoding.UTF8.GetBytes(inputRawText); + string inputEncodedText = Latin1Encoding.GetString(inputRawBytes); + Request requestInstance = new Request(""); + + // act + string decodedEnglishText = requestInstance.ToUnicode(inputEncodedText); + + // assert + Assert.Equal(inputRawText, decodedEnglishText); + } + + [Fact] + public void GetRequestWithCredentialsTest() + { + // arrange + var requestConfig = new RequestConfiguration() { + Credentials = new NetworkCredential("username", "password") + }; + var request = new Request("http://test.com", requestConfig); + + // act + var httpRequest = request.GetRequest(); + + // assert + Assert.NotNull(httpRequest.Credentials); + } + + [Fact] + public void GetRequestWithNullCredentialsTest() + { + // arrange + var requestConfig = new RequestConfiguration(); + var request = new Request("http://test.com", requestConfig); + + // act + var httpRequest = request.GetRequest(); + + // assert + Assert.Null(httpRequest.Credentials); } } \ No newline at end of file diff --git a/src/Downloader.Test/UnitTests/StorageTest.cs b/src/Downloader.Test/UnitTests/StorageTest.cs index 75b2542..d658648 100644 --- a/src/Downloader.Test/UnitTests/StorageTest.cs +++ b/src/Downloader.Test/UnitTests/StorageTest.cs @@ -1,256 +1,248 @@ using Downloader.DummyHttpServer; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using System; using System.Linq; using System.Threading.Tasks; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public abstract class StorageTest : IDisposable { - public abstract class StorageTest + protected const int DataLength = 2048; + protected readonly byte[] Data = DummyData.GenerateRandomBytes(DataLength); + protected virtual ConcurrentStream Storage { get; } + + public virtual void Dispose() { - protected const int DataLength = 2048; - protected readonly byte[] Data = DummyData.GenerateRandomBytes(DataLength); - protected virtual ConcurrentStream Storage { get; } + Storage?.Dispose(); + } - [TestInitialize] - public virtual void Initial() - { - // write pre-requirements of each tests - } + [Fact] + public async Task OpenReadLengthTest() + { + // arrange + await Storage.WriteAsync(0, Data, DataLength); + Storage.Flush(); - [TestCleanup] - public virtual void Cleanup() - { - Storage?.Dispose(); - } + // act + var reader = Storage.OpenRead(); - [TestMethod] - public async Task OpenReadLengthTest() - { - // arrange - await Storage.WriteAsync(0, Data, DataLength); - Storage.Flush(); + // assert + Assert.Equal(DataLength, reader.Length); + } - // act - var reader = Storage.OpenRead(); + [Fact] + public async Task OpenReadStreamTest() + { + // arrange + await Storage.WriteAsync(0, Data, DataLength); + Storage.Flush(); - // assert - Assert.AreEqual(DataLength, reader.Length); - } + // act + var reader = Storage.OpenRead(); - [TestMethod] - public async Task OpenReadStreamTest() + // assert + for (int i = 0; i < DataLength; i++) { - // arrange - await Storage.WriteAsync(0, Data, DataLength); - Storage.Flush(); - - // act - var reader = Storage.OpenRead(); - - // assert - for (int i = 0; i < DataLength; i++) - { - Assert.AreEqual(Data[i], reader.ReadByte()); - } + Assert.Equal(Data[i], reader.ReadByte()); } + } - [TestMethod] - public async Task SlowWriteTest() - { - // arrange - var data = new byte[] { 1 }; - var size = 1024; + [Fact] + public async Task SlowWriteTest() + { + // arrange + var data = new byte[] { 1 }; + var size = 1024; - // act - for (int i = 0; i < size; i++) - await Storage.WriteAsync(i, data, 1); + // act + for (int i = 0; i < size; i++) + await Storage.WriteAsync(i, data, 1); - Storage.Flush(); - var readerStream = Storage.OpenRead(); + Storage.Flush(); + var readerStream = Storage.OpenRead(); - // assert - Assert.AreEqual(size, Storage.Length); - for (int i = 0; i < size; i++) - Assert.AreEqual(1, readerStream.ReadByte()); - } + // assert + Assert.Equal(size, Storage.Length); + for (int i = 0; i < size; i++) + Assert.Equal(1, readerStream.ReadByte()); + } - [TestMethod] - public async Task WriteAsyncLengthTest() - { - // arrange - var length = DataLength / 2; + [Fact] + public async Task WriteAsyncLengthTest() + { + // arrange + var length = DataLength / 2; - // act - await Storage.WriteAsync(0, Data, length); - Storage.Flush(); + // act + await Storage.WriteAsync(0, Data, length); + Storage.Flush(); - // assert - Assert.AreEqual(length, Storage.Length); - } + // assert + Assert.Equal(length, Storage.Length); + } - [TestMethod] - public async Task WriteAsyncBytesTest() + [Fact] + public async Task WriteAsyncBytesTest() + { + // arrange + var length = DataLength / 2; + + // act + await Storage.WriteAsync(0, Data, length); + Storage.Flush(); + var reader = Storage.OpenRead(); + + // assert + for (int i = 0; i < length; i++) { - // arrange - var length = DataLength / 2; - - // act - await Storage.WriteAsync(0, Data, length); - Storage.Flush(); - var reader = Storage.OpenRead(); - - // assert - for (int i = 0; i < length; i++) - { - Assert.AreEqual(Data[i], reader.ReadByte()); - } + Assert.Equal(Data[i], reader.ReadByte()); } + } - [TestMethod] - public async Task WriteAsyncMultipleTimeTest() + [Fact] + public async Task WriteAsyncMultipleTimeTest() + { + // arrange + var count = 128; + var size = DataLength / count; + + // act + for (int i = 0; i < count; i++) { - // arrange - var count = 128; - var size = DataLength / count; - - // act - for (int i = 0; i < count; i++) - { - var startOffset = i * size; - await Storage.WriteAsync(startOffset, Data.Skip(startOffset).Take(size).ToArray(), size); - } - Storage.Flush(); - - // assert - var reader = Storage.OpenRead(); - for (int i = 0; i < DataLength; i++) - { - Assert.AreEqual(Data[i], reader.ReadByte()); - } + var startOffset = i * size; + await Storage.WriteAsync(startOffset, Data.Skip(startOffset).Take(size).ToArray(), size); } + Storage.Flush(); - [TestMethod] - public async Task WriteAsyncOutOfRangeExceptionTest() + // assert + var reader = Storage.OpenRead(); + for (int i = 0; i < DataLength; i++) { - // arrange - var length = DataLength + 1; + Assert.Equal(Data[i], reader.ReadByte()); + } + } - // act - var writeMethod = async () => await Storage.WriteAsync(0, Data, length); + [Fact] + public async Task WriteAsyncOutOfRangeExceptionTest() + { + // arrange + var length = DataLength + 1; - // assert - await Assert.ThrowsExceptionAsync(writeMethod); - } + // act + var writeMethod = async () => await Storage.WriteAsync(0, Data, length); - [TestMethod] - public async Task TestDispose() - { - // arrange - await Storage.WriteAsync(0, Data, DataLength); + // assert + await Assert.ThrowsAnyAsync(writeMethod); + } - // act - Storage.Dispose(); + [Fact] + public async Task TestDispose() + { + // arrange + await Storage.WriteAsync(0, Data, DataLength); - // assert - Assert.AreEqual(0, Storage.Length); - } + // act + Storage.Dispose(); - [TestMethod] - public async Task FlushTest() - { - // arrange - await Storage.WriteAsync(0, Data, DataLength); + // assert + Assert.Equal(0, Storage.Length); + } - // act - Storage.Flush(); + [Fact] + public async Task FlushTest() + { + // arrange + await Storage.WriteAsync(0, Data, DataLength); - // assert - Assert.AreEqual(Data.Length, Storage.Length); - } + // act + Storage.Flush(); - [TestMethod] - public async Task GetLengthTest() - { - // arrange - var data = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4 }; - await Storage.WriteAsync(0, data, 1); - Storage.Flush(); + // assert + Assert.Equal(Data.Length, Storage.Length); + } - // act - var actualLength = Storage.Length; + [Fact] + public async Task GetLengthTest() + { + // arrange + var data = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4 }; + await Storage.WriteAsync(0, data, 1); + Storage.Flush(); - // assert - Assert.AreEqual(1, actualLength); - } + // act + var actualLength = Storage.Length; - [TestMethod] - public async Task TestStreamExpandability() - { - // arrange - var data = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4 }; - await Storage.WriteAsync(0, data, data.Length); - Storage.Flush(); - - // act - var serializedStream = JsonConvert.SerializeObject(Storage); - var mutableStream = JsonConvert.DeserializeObject(serializedStream); - await mutableStream.WriteAsync(0, data, data.Length); - mutableStream.Flush(); - - // assert - Assert.AreEqual(data.Length * 2, mutableStream?.Length); - } + // assert + Assert.Equal(1, actualLength); + } + + [Fact] + public async Task TestStreamExpandability() + { + // arrange + var data = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4 }; + await Storage.WriteAsync(0, data, data.Length); + Storage.Flush(); + + // act + var serializedStream = JsonConvert.SerializeObject(Storage); + var mutableStream = JsonConvert.DeserializeObject(serializedStream); + await mutableStream.WriteAsync(0, data, data.Length); + mutableStream.Flush(); + + // assert + Assert.Equal(data.Length * 2, mutableStream?.Length); + } - [TestMethod] - public async Task TestDynamicBufferData() + [Fact] + public async Task TestDynamicBufferData() + { + // arrange + var size = 1024; // 1KB + + // act + for (int i = 0; i < size / 8; i++) { - // arrange - var size = 1024; // 1KB - - // act - for (int i = 0; i < size / 8; i++) - { - var data = new byte[10]; // zero bytes - Array.Fill(data, (byte)i); - await Storage.WriteAsync(i * 8, data, 8); - } - Storage.Flush(); - var readerStream = Storage.OpenRead(); - - // assert - Assert.AreEqual(size, Storage.Length); - for (int i = 0; i < size / 8; i++) - { - var data = new byte[8]; // zero bytes - Array.Fill(data, (byte)i); - var buffer = new byte[8]; - Assert.AreEqual(8, readerStream.Read(buffer, 0, 8)); - Assert.IsTrue(buffer.SequenceEqual(data)); - } - - Assert.AreEqual(-1, readerStream.ReadByte()); // end of stream + var data = new byte[10]; // zero bytes + Array.Fill(data, (byte)i); + await Storage.WriteAsync(i * 8, data, 8); } + Storage.Flush(); + var readerStream = Storage.OpenRead(); - [TestMethod] - public async Task TestSerialization() + // assert + Assert.Equal(size, Storage.Length); + for (int i = 0; i < size / 8; i++) { - // arrange - var size = 256; - var data = DummyData.GenerateOrderedBytes(size); - - // act - await Storage.WriteAsync(0, data, size); - var serializedStream = JsonConvert.SerializeObject(Storage); - Storage.Dispose(); - var newStream = JsonConvert.DeserializeObject(serializedStream); - var readerStream = newStream.OpenRead(); - - // assert - Assert.AreEqual(size, readerStream.Length); - for (int i = 0; i < size; i++) - Assert.AreEqual(i, readerStream.ReadByte()); + var data = new byte[8]; // zero bytes + Array.Fill(data, (byte)i); + var buffer = new byte[8]; + Assert.Equal(8, readerStream.Read(buffer, 0, 8)); + Assert.True(buffer.SequenceEqual(data)); } + + Assert.Equal(-1, readerStream.ReadByte()); // end of stream + } + + [Fact] + public async Task TestSerialization() + { + // arrange + var size = 256; + var data = DummyData.GenerateOrderedBytes(size); + + // act + await Storage.WriteAsync(0, data, size); + var serializedStream = JsonConvert.SerializeObject(Storage); + Storage.Dispose(); + var newStream = JsonConvert.DeserializeObject(serializedStream); + var readerStream = newStream.OpenRead(); + + // assert + Assert.Equal(size, readerStream.Length); + for (int i = 0; i < size; i++) + Assert.Equal(i, readerStream.ReadByte()); } } \ No newline at end of file diff --git a/src/Downloader.Test/UnitTests/StorageTestOnFile.cs b/src/Downloader.Test/UnitTests/StorageTestOnFile.cs index 11449c1..7ab4246 100644 --- a/src/Downloader.Test/UnitTests/StorageTestOnFile.cs +++ b/src/Downloader.Test/UnitTests/StorageTestOnFile.cs @@ -1,102 +1,99 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.IO; +using System.IO; using System.Threading.Tasks; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class StorageTestOnFile : StorageTest { - public class StorageTestOnFile : StorageTest + private string path; + private int size; + private ConcurrentStream _storage; + protected override ConcurrentStream Storage => _storage ??= new ConcurrentStream(path, size); + + public StorageTestOnFile() + { + size = 1024 * 1024; // 1MB + path = Path.GetTempFileName(); + } + + public override void Dispose() + { + base.Dispose(); + File.Delete(path); + } + + [Fact] + public void TestInitialSizeOnFileStream() + { + // act + var Storage = new ConcurrentStream(path, size); + + // assert + Assert.Equal(size, new FileInfo(path).Length); + Assert.Equal(size, Storage.Length); + } + + [Fact] + public void TestInitialSizeWithNegativeNumberOnFileStream() + { + // arrange + size = -1; + + // act + Storage.Flush(); // create lazy stream + + // assert + Assert.Equal(0, new FileInfo(path).Length); + Assert.Equal(0, Storage.Length); + } + + [Fact] + public async Task TestWriteSizeOverflowOnFileStream() + { + // arrange + size = 512; + var actualSize = size * 2; + var data = new byte[] { 1 }; + + // act + for (int i = 0; i < actualSize; i++) + await Storage.WriteAsync(i, data, 1); + + Storage.Flush(); + var readerStream = Storage.OpenRead(); + + // assert + Assert.Equal(actualSize, new FileInfo(path).Length); + Assert.Equal(actualSize, Storage.Length); + for (int i = 0; i < actualSize; i++) + Assert.Equal(1, readerStream.ReadByte()); + } + + [Fact] + public async Task TestAccessMoreThanSizeOnFileStream() { - private string path; - private int size; - private ConcurrentStream _storage; - protected override ConcurrentStream Storage => _storage ??= new ConcurrentStream(path, size); - - [TestInitialize] - public override void Initial() - { - size = 1024 * 1024; // 1MB - path = Path.GetTempFileName(); - } - - [TestCleanup] - public override void Cleanup() - { - base.Cleanup(); - File.Delete(path); - } - - [TestMethod] - public void TestInitialSizeOnFileStream() - { - // act - var Storage = new ConcurrentStream(path, size); - - // assert - Assert.AreEqual(size, new FileInfo(path).Length); - Assert.AreEqual(size, Storage.Length); - } - - [TestMethod] - public void TestInitialSizeWithNegativeNumberOnFileStream() - { - // arrange - size = -1; - - // act - Storage.Flush(); // create lazy stream - - // assert - Assert.AreEqual(0, new FileInfo(path).Length); - Assert.AreEqual(0, Storage.Length); - } - - [TestMethod] - public async Task TestWriteSizeOverflowOnFileStream() - { - // arrange - size = 512; - var actualSize = size * 2; - var data = new byte[] { 1 }; - - // act - for (int i = 0; i < actualSize; i++) - await Storage.WriteAsync(i, data, 1); - - Storage.Flush(); - var readerStream = Storage.OpenRead(); - - // assert - Assert.AreEqual(actualSize, new FileInfo(path).Length); - Assert.AreEqual(actualSize, Storage.Length); - for (int i = 0; i < actualSize; i++) - Assert.AreEqual(1, readerStream.ReadByte()); - } - - [TestMethod] - public async Task TestAccessMoreThanSizeOnFileStream() - { - // arrange - size = 10; - var jumpStepCount = 1024; // 1KB - var data = new byte[] { 1, 1, 1, 1, 1 }; - var selectedDataLen = 3; - var actualSize = size + jumpStepCount + selectedDataLen; - - // act - await Storage.WriteAsync(size + jumpStepCount, data, selectedDataLen); - Storage.Flush(); - var readerStream = Storage.OpenRead(); - - // assert - Assert.AreEqual(actualSize, new FileInfo(path).Length); - Assert.AreEqual(actualSize, Storage.Length); - for (int i = 0; i < size + jumpStepCount; i++) - Assert.AreEqual(0, readerStream.ReadByte()); // empty spaces - - for (int i = 0; i < selectedDataLen; i++) - Assert.AreEqual(1, readerStream.ReadByte()); // wrote data spaces - - Assert.AreEqual(-1, readerStream.ReadByte()); // end of stream - } + // arrange + size = 10; + var jumpStepCount = 1024; // 1KB + var data = new byte[] { 1, 1, 1, 1, 1 }; + var selectedDataLen = 3; + var actualSize = size + jumpStepCount + selectedDataLen; + + // act + await Storage.WriteAsync(size + jumpStepCount, data, selectedDataLen); + Storage.Flush(); + var readerStream = Storage.OpenRead(); + + // assert + Assert.Equal(actualSize, new FileInfo(path).Length); + Assert.Equal(actualSize, Storage.Length); + for (int i = 0; i < size + jumpStepCount; i++) + Assert.Equal(0, readerStream.ReadByte()); // empty spaces + + for (int i = 0; i < selectedDataLen; i++) + Assert.Equal(1, readerStream.ReadByte()); // wrote data spaces + + Assert.Equal(-1, readerStream.ReadByte()); // end of stream } } diff --git a/src/Downloader.Test/UnitTests/StorageTestOnMemory.cs b/src/Downloader.Test/UnitTests/StorageTestOnMemory.cs index 14137c4..9c6f032 100644 --- a/src/Downloader.Test/UnitTests/StorageTestOnMemory.cs +++ b/src/Downloader.Test/UnitTests/StorageTestOnMemory.cs @@ -1,18 +1,17 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.IO; +using System.IO; +using Xunit; -namespace Downloader.Test.UnitTests +namespace Downloader.Test.UnitTests; + +public class StorageTestOnMemory : StorageTest { - public class StorageTestOnMemory : StorageTest - { - private ConcurrentStream _storage; - protected override ConcurrentStream Storage => _storage ??= new ConcurrentStream(); + private ConcurrentStream _storage; + protected override ConcurrentStream Storage => _storage ??= new ConcurrentStream(); - [TestMethod] - public void TestInitialSizeOnMemoryStream() - { - // assert - Assert.IsInstanceOfType(Storage.OpenRead(), typeof(MemoryStream)); - } + [Fact] + public void TestInitialSizeOnMemoryStream() + { + // assert + Assert.IsType(Storage.OpenRead()); } } diff --git a/src/Downloader/DownloadPackage.cs b/src/Downloader/DownloadPackage.cs index b272511..43d2e24 100644 --- a/src/Downloader/DownloadPackage.cs +++ b/src/Downloader/DownloadPackage.cs @@ -1,8 +1,9 @@ -using System.Linq; +using System; +using System.Linq; namespace Downloader { - public class DownloadPackage + public class DownloadPackage : IDisposable { public bool IsSaving { get; set; } public bool IsSaveComplete { get; set; } @@ -23,13 +24,14 @@ public void Clear() { foreach (Chunk chunk in Chunks) chunk.Clear(); - } + } Chunks = null; } public void Flush() { - Storage?.Flush(); + if (Storage?.CanWrite == true) + Storage?.Flush(); } public void Validate() @@ -57,5 +59,12 @@ public void BuildStorage(bool reserveFileSize, long maxMemoryBufferBytes = 0) else Storage = new ConcurrentStream(FileName, reserveFileSize ? TotalFileSize : 0, maxMemoryBufferBytes); } + + public void Dispose() + { + Flush(); + Clear(); + Storage?.Dispose(); + } } } \ No newline at end of file