diff --git a/dotnet-tests/.editorconfig b/dotnet-tests/.editorconfig new file mode 100644 index 0000000..95dfeba --- /dev/null +++ b/dotnet-tests/.editorconfig @@ -0,0 +1,21 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] + +# License header +file_header_template = This Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/. + +# CSharpier: https://csharpier.com/docs/Configuration +## Non-configurable behaviors +charset = utf-8 +insert_final_newline = true +trim_trailing_whitespace = true + +## Configurable behaviors +end_of_line = lf +indent_style = space +indent_size = 4 +max_line_length = 120 diff --git a/dotnet-tests/UniffiCS.binding_tests/TestArithmetic.cs b/dotnet-tests/UniffiCS.BindingTests/TestArithmetic.cs similarity index 71% rename from dotnet-tests/UniffiCS.binding_tests/TestArithmetic.cs rename to dotnet-tests/UniffiCS.BindingTests/TestArithmetic.cs index 8b215ef..eb26289 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestArithmetic.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestArithmetic.cs @@ -1,17 +1,17 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -using System.Diagnostics; -using System.IO; -using System; using uniffi.arithmetic; - using ArithmeticException = uniffi.arithmetic.ArithmeticException; -public class TestArithmetic { +namespace UniffiCS.BindingTests; + +public class TestArithmetic +{ [Fact] - public void ArithmeticWorks() { + public void ArithmeticWorks() + { Assert.Equal(6ul, ArithmeticMethods.Add(2, 4)); Assert.Equal(12ul, ArithmeticMethods.Add(4, 8)); diff --git a/dotnet-tests/UniffiCS.binding_tests/TestCallbacks.cs b/dotnet-tests/UniffiCS.BindingTests/TestCallbacks.cs similarity index 62% rename from dotnet-tests/UniffiCS.binding_tests/TestCallbacks.cs rename to dotnet-tests/UniffiCS.BindingTests/TestCallbacks.cs index 9bf5463..f7777a9 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestCallbacks.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestCallbacks.cs @@ -1,43 +1,60 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. using System; using uniffi.callbacks; -class SomeOtherError: Exception {} +namespace UniffiCS.BindingTests; -class CallAnswererImpl: CallAnswerer { +class SomeOtherError : Exception { } + +class CallAnswererImpl : CallAnswerer +{ public String mode; - public CallAnswererImpl(String mode) { + + public CallAnswererImpl(String mode) + { this.mode = mode; } - public String Answer() { - if (mode == "normal") { + public String Answer() + { + if (mode == "normal") + { return "Bonjour"; - } else if (mode == "busy") { + } + else if (mode == "busy") + { throw new TelephoneException.Busy("I'm busy"); - } else { + } + else + { throw new SomeOtherError(); } } } -public class TestCallbacks { +public class TestCallbacks +{ [Fact] - public void CallbackWorks() { - using (var telephone = new Telephone()) { + public void CallbackWorks() + { + using (var telephone = new Telephone()) + { Assert.Equal("Bonjour", telephone.Call(new CallAnswererImpl("normal"))); Assert.Throws(() => telephone.Call(new CallAnswererImpl("busy"))); - Assert.Throws(() => telephone.Call(new CallAnswererImpl("something-else"))); + Assert.Throws( + () => telephone.Call(new CallAnswererImpl("something-else")) + ); } } [Fact] - public void CallbackRegistrationIsNotAffectedByGC() { + public void CallbackRegistrationIsNotAffectedByGC() + { // See `static ForeignCallback INSTANCE` at `templates/CallbackInterfaceTemplate.cs` var callback = new CallAnswererImpl("normal"); @@ -50,12 +67,13 @@ public void CallbackRegistrationIsNotAffectedByGC() { telephone.Call(callback); } - [Fact] - public void CallbackReferenceIsDropped() { + public void CallbackReferenceIsDropped() + { var telephone = new Telephone(); - var weak_callback = CallInItsOwnScope(() => { + var weak_callback = CallInItsOwnScope(() => + { var callback = new CallAnswererImpl("normal"); telephone.Call(callback); return new WeakReference(callback); @@ -71,4 +89,3 @@ private T CallInItsOwnScope(Func getter) return getter(); } } - diff --git a/dotnet-tests/UniffiCS.binding_tests/TestCallbacksFixture.cs b/dotnet-tests/UniffiCS.BindingTests/TestCallbacksFixture.cs similarity index 50% rename from dotnet-tests/UniffiCS.binding_tests/TestCallbacksFixture.cs rename to dotnet-tests/UniffiCS.BindingTests/TestCallbacksFixture.cs index 7be9b4f..2ae7d9c 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestCallbacksFixture.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestCallbacksFixture.cs @@ -1,61 +1,82 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +using System; using System.Collections.Generic; using System.Linq; -using System; using uniffi.fixture_callbacks; -class CsharpGetters: ForeignGetters { - public Boolean GetBool(Boolean v, Boolean argumentTwo) { +namespace UniffiCS.BindingTests; + +class CsharpGetters : ForeignGetters +{ + public Boolean GetBool(Boolean v, Boolean argumentTwo) + { return v ^ argumentTwo; } - public String GetString(String v, Boolean arg2) { - if (v == "bad-argument") { + public String GetString(String v, Boolean arg2) + { + if (v == "bad-argument") + { throw new SimpleException.BadArgument("bad argument"); } - if (v == "unexpected-error") { + if (v == "unexpected-error") + { throw new Exception("something failed"); } return arg2 ? "1234567890123" : v; } - public String? GetOption(String? v, Boolean arg2) { - if (v == "bad-argument") { + public String? GetOption(String? v, Boolean arg2) + { + if (v == "bad-argument") + { throw new ComplexException.ReallyBadArgument(20); } - if (v == "unexpected-error") { + if (v == "unexpected-error") + { throw new Exception("something failed"); } return arg2 && v != null ? v.ToUpper() : v; } - public List GetList(List v, Boolean arg2) { + public List GetList(List v, Boolean arg2) + { return arg2 ? v : new List(); } - public void GetNothing(String v) { - if (v == "bad-argument") { + public void GetNothing(String v) + { + if (v == "bad-argument") + { throw new SimpleException.BadArgument("bad argument"); } - if (v == "unexpected-error") { + if (v == "unexpected-error") + { throw new Exception("something failed"); } } } -class CsharpStringifier: StoredForeignStringifier { - public String FromSimpleType(Int32 value) { +class CsharpStringifier : StoredForeignStringifier +{ + public String FromSimpleType(Int32 value) + { return "C#: " + value.ToString(); } - public String FromComplexType(List? values) { - if (values == null) { - return "C#: null"; - } else { - var stringValues = values.Select(number => { + public String FromComplexType(List? values) + { + if (values == null) + { + return "C#: null"; + } + else + { + var stringValues = values.Select(number => + { return number == null ? "null" : number.ToString(); }); return "C#: " + string.Join(" ", stringValues); @@ -63,27 +84,40 @@ public String FromComplexType(List? values) { } } -public class TestCallbacksFixture { +public class TestCallbacksFixture +{ [Fact] - public void CallbackRoundTripValues() { + public void CallbackRoundTripValues() + { var callback = new CsharpGetters(); - using (var rustGetters = new RustGetters()) { - foreach (var v in new List{true, false}) { + using (var rustGetters = new RustGetters()) + { + foreach (var v in new List { true, false }) + { var flag = true; Assert.Equal(callback.GetBool(v, flag), rustGetters.GetBool(callback, v, flag)); } - foreach (var v in new List>{new List{1, 2}, new List{0, 1}}) { + foreach ( + var v in new List> + { + new List { 1, 2 }, + new List { 0, 1 } + } + ) + { var flag = true; Assert.Equal(callback.GetList(v, flag), rustGetters.GetList(callback, v, flag)); } - foreach (var v in new List{"Hello", "world"}) { + foreach (var v in new List { "Hello", "world" }) + { var flag = true; Assert.Equal(callback.GetString(v, flag), rustGetters.GetString(callback, v, flag)); } - foreach (var v in new List{"Some", null}) { + foreach (var v in new List { "Some", null }) + { var flag = true; Assert.Equal(callback.GetOption(v, flag), rustGetters.GetOption(callback, v, flag)); } @@ -94,43 +128,65 @@ public void CallbackRoundTripValues() { } [Fact] - public void CallbackRoundTripErrors() { + public void CallbackRoundTripErrors() + { var callback = new CsharpGetters(); - using (var rustGetters = new RustGetters()) { + using (var rustGetters = new RustGetters()) + { Assert.Throws(() => rustGetters.GetString(callback, "bad-argument", true)); - Assert.Throws(() => rustGetters.GetString(callback, "unexpected-error", true)); + Assert.Throws( + () => rustGetters.GetString(callback, "unexpected-error", true) + ); - var reallyBadArgument = Assert.Throws(() => rustGetters.GetOption(callback, "bad-argument", true)); + var reallyBadArgument = Assert.Throws( + () => rustGetters.GetOption(callback, "bad-argument", true) + ); Assert.Equal(20, reallyBadArgument.code); - var unexpectedException = Assert.Throws(() => rustGetters.GetOption(callback, "unexpected-error", true)); + var unexpectedException = Assert.Throws( + () => rustGetters.GetOption(callback, "unexpected-error", true) + ); Assert.Equal(new Exception("something failed").Message, unexpectedException.reason); } } [Fact] - public void CallbackMayBeStoredInObject() { + public void CallbackMayBeStoredInObject() + { var stringifier = new CsharpStringifier(); - using (var rustStringifier = new RustStringifier(stringifier)) { - foreach (var v in new List{1, 2}) { + using (var rustStringifier = new RustStringifier(stringifier)) + { + foreach (var v in new List { 1, 2 }) + { Assert.Equal(stringifier.FromSimpleType(v), rustStringifier.FromSimpleType(v)); } - foreach (var v in new List?>{null, new List{null, 3.14}}) { + foreach ( + var v in new List?> + { + null, + new List { null, 3.14 } + } + ) + { Assert.Equal(stringifier.FromComplexType(v), rustStringifier.FromComplexType(v)); } } } [Fact] - public void VoidCallbackExceptions() { + public void VoidCallbackExceptions() + { var callback = new CsharpGetters(); - using (var rustGetters = new RustGetters()) { + using (var rustGetters = new RustGetters()) + { // no exception rustGetters.GetNothing(callback, "foo"); Assert.Throws(() => rustGetters.GetNothing(callback, "bad-argument")); - Assert.Throws(() => rustGetters.GetNothing(callback, "unexpected-error")); + Assert.Throws( + () => rustGetters.GetNothing(callback, "unexpected-error") + ); } } } diff --git a/dotnet-tests/UniffiCS.binding_tests/TestChronological.cs b/dotnet-tests/UniffiCS.BindingTests/TestChronological.cs similarity index 56% rename from dotnet-tests/UniffiCS.binding_tests/TestChronological.cs rename to dotnet-tests/UniffiCS.BindingTests/TestChronological.cs index 58a5e1e..0bc3903 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestChronological.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestChronological.cs @@ -1,67 +1,68 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -using System.Threading; using System; +using System.Threading; using uniffi.chronological; -public class TestChronological { - static DateTime EpochSecond(int seconds, int nanoseconds) { +namespace UniffiCS.BindingTests; + +public class TestChronological +{ + static DateTime EpochSecond(int seconds, int nanoseconds) + { return DateTime.UnixEpoch.AddSeconds(seconds).AddTicks(nanoseconds / 100); } - static TimeSpan TimeSpanSecond(int seconds, int nanoseconds) { + static TimeSpan TimeSpanSecond(int seconds, int nanoseconds) + { return new TimeSpan(seconds * TimeSpan.TicksPerSecond + nanoseconds / 100); } [Fact] - public void ChronologicalWorks() { + public void ChronologicalWorks() + { // Test passing timestamp and duration while returning timestamp - Assert.Equal( - EpochSecond(101, 200), - ChronologicalMethods.Add(EpochSecond(100, 100), TimeSpanSecond(1, 100))); + Assert.Equal(EpochSecond(101, 200), ChronologicalMethods.Add(EpochSecond(100, 100), TimeSpanSecond(1, 100))); // Test passing timestamp while returning duration - Assert.Equal( - TimeSpanSecond(1, 100), - ChronologicalMethods.Diff(EpochSecond(101, 200), EpochSecond(100, 100))); + Assert.Equal(TimeSpanSecond(1, 100), ChronologicalMethods.Diff(EpochSecond(101, 200), EpochSecond(100, 100))); - Assert.Throws(() => { + Assert.Throws(() => + { ChronologicalMethods.Diff(EpochSecond(100, 0), EpochSecond(101, 0)); }); - Assert.Throws(() => { + Assert.Throws(() => + { ChronologicalMethods.Add(DateTime.MaxValue, TimeSpan.MaxValue); }); } [Fact] - public void DateTimeMinMax() { - Assert.Equal( - DateTime.MinValue, - ChronologicalMethods.ReturnTimestamp(DateTime.MinValue)); + public void DateTimeMinMax() + { + Assert.Equal(DateTime.MinValue, ChronologicalMethods.ReturnTimestamp(DateTime.MinValue)); - Assert.Equal( - DateTime.MaxValue, - ChronologicalMethods.ReturnTimestamp(DateTime.MaxValue)); + Assert.Equal(DateTime.MaxValue, ChronologicalMethods.ReturnTimestamp(DateTime.MaxValue)); } [Fact] - public void TimeSpanMax() { + public void TimeSpanMax() + { // Rust does not allow negative timespan, so only maximum value is tested. - Assert.Equal( - TimeSpan.MaxValue, - ChronologicalMethods.ReturnDuration(TimeSpan.MaxValue)); + Assert.Equal(TimeSpan.MaxValue, ChronologicalMethods.ReturnDuration(TimeSpan.MaxValue)); } [Fact] - public void PreEpochTimestampsSerializeCorrectly() { + public void PreEpochTimestampsSerializeCorrectly() + { Assert.Equal( "1969-12-12T00:00:00.000000000Z", - ChronologicalMethods.ToStringTimestamp( - DateTime.Parse("1969-12-12T00:00:00.000000000Z"))); + ChronologicalMethods.ToStringTimestamp(DateTime.Parse("1969-12-12T00:00:00.000000000Z")) + ); // [-999_999_999; 0) is unrepresentable // https://github.com/mozilla/uniffi-rs/issues/1433 @@ -72,16 +73,18 @@ public void PreEpochTimestampsSerializeCorrectly() { Assert.Equal( "1969-12-31T23:59:58.999999900Z", - ChronologicalMethods.ToStringTimestamp( - DateTime.Parse("1969-12-31T23:59:58.999999900Z"))); + ChronologicalMethods.ToStringTimestamp(DateTime.Parse("1969-12-31T23:59:58.999999900Z")) + ); Assert.Equal( DateTime.Parse("1955-11-05T00:06:01.283000200Z"), - ChronologicalMethods.Add(DateTime.Parse("1955-11-05T00:06:00.283000100Z"), TimeSpanSecond(1, 100))); + ChronologicalMethods.Add(DateTime.Parse("1955-11-05T00:06:00.283000100Z"), TimeSpanSecond(1, 100)) + ); } [Fact] - public void TestDateTimeWorksLikeRustSystemTime() { + public void TestDateTimeWorksLikeRustSystemTime() + { // Sleep inbetween to make sure that the clock has enough resolution var before = DateTime.Now; Thread.Sleep(1); @@ -93,7 +96,8 @@ public void TestDateTimeWorksLikeRustSystemTime() { } [Fact] - public void DateTimeAndTimeSpanOptionals() { + public void DateTimeAndTimeSpanOptionals() + { Assert.True(ChronologicalMethods.Optional(DateTime.MaxValue, TimeSpanSecond(0, 0))); Assert.False(ChronologicalMethods.Optional(null, TimeSpanSecond(0, 0))); Assert.False(ChronologicalMethods.Optional(DateTime.MaxValue, null)); diff --git a/dotnet-tests/UniffiCS.binding_tests/TestCoverall.cs b/dotnet-tests/UniffiCS.BindingTests/TestCoverall.cs similarity index 72% rename from dotnet-tests/UniffiCS.binding_tests/TestCoverall.cs rename to dotnet-tests/UniffiCS.BindingTests/TestCoverall.cs index c614ab7..9d0e96e 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestCoverall.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestCoverall.cs @@ -1,17 +1,21 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -using System.Collections.Generic; -using System.Threading; using System; +using System.Threading; using uniffi.coverall; -public class TestCoverall { +namespace UniffiCS.BindingTests; + +public class TestCoverall +{ [Fact] - public void FFIObjectSafeHandleDropsNativeReferenceOutsideOfUsingBlock() { + public void FFIObjectSafeHandleDropsNativeReferenceOutsideOfUsingBlock() + { Assert.Equal(0UL, CoverallMethods.GetNumAlive()); - var closure = () => { + var closure = () => + { var coveralls = new Coveralls("safe_handle_drops_native_reference"); Assert.Equal(1UL, CoverallMethods.GetNumAlive()); }; @@ -22,8 +26,10 @@ public void FFIObjectSafeHandleDropsNativeReferenceOutsideOfUsingBlock() { } [Fact] - public void TestCreateSomeDict() { - using (var d = CoverallMethods.CreateSomeDict()) { + public void TestCreateSomeDict() + { + using (var d = CoverallMethods.CreateSomeDict()) + { Assert.Equal("text", d.text); Assert.Equal("maybe_text", d.maybeText); Assert.True(d.aBool); @@ -49,8 +55,10 @@ public void TestCreateSomeDict() { } [Fact] - public void TestArcs() { - using (var coveralls = new Coveralls("test_arcs")) { + public void TestArcs() + { + using (var coveralls = new Coveralls("test_arcs")) + { Assert.Equal(1UL, CoverallMethods.GetNumAlive()); // One ref held by the foreign-language code, one created for this method call. Assert.Equal(2UL, coveralls.StrongCount()); @@ -60,7 +68,8 @@ public void TestArcs() { Assert.Equal(3UL, coveralls.StrongCount()); Assert.Equal(1UL, CoverallMethods.GetNumAlive()); // Careful, this makes a new C# object which must be separately destroyed. - using (var other = coveralls.GetOther()) { + using (var other = coveralls.GetOther()) + { Assert.Equal("test_arcs", other!.GetName()); } @@ -71,18 +80,21 @@ public void TestArcs() { Assert.Throws(() => coveralls.FalliblePanic("Expected panic in a fallible function!")); coveralls.TakeOther(null); - Assert.Equal(2UL, coveralls.StrongCount()); + Assert.Equal(2UL, coveralls.StrongCount()); } Assert.Equal(0UL, CoverallMethods.GetNumAlive()); } [Fact] - public void TestReturnObjects() { - using (var coveralls = new Coveralls("test_return_objects")) { + public void TestReturnObjects() + { + using (var coveralls = new Coveralls("test_return_objects")) + { Assert.Equal(1UL, CoverallMethods.GetNumAlive()); Assert.Equal(2UL, coveralls.StrongCount()); - using (var c2 = coveralls.CloneMe()) { + using (var c2 = coveralls.CloneMe()) + { Assert.Equal(coveralls.GetName(), c2.GetName()); Assert.Equal(2UL, CoverallMethods.GetNumAlive()); Assert.Equal(2UL, c2.StrongCount()); @@ -103,8 +115,10 @@ public void TestReturnObjects() { } [Fact] - public void TestSimpleErrors() { - using (var coveralls = new Coveralls("test_simple_errors")) { + public void TestSimpleErrors() + { + using (var coveralls = new Coveralls("test_simple_errors")) + { Assert.Throws(() => coveralls.MaybeThrow(true)); Assert.Throws(() => coveralls.MaybeThrowInto(true)); Assert.Throws(() => coveralls.Panic("oops")); @@ -112,17 +126,19 @@ public void TestSimpleErrors() { } [Fact] - public void TestComplexErrors() { - using (var coveralls = new Coveralls("test_complex_errors")) { + public void TestComplexErrors() + { + using (var coveralls = new Coveralls("test_complex_errors")) + { Assert.True(coveralls.MaybeThrowComplex(0)); - var os_exception = Assert.Throws( - () => coveralls.MaybeThrowComplex(1)); + var os_exception = Assert.Throws(() => coveralls.MaybeThrowComplex(1)); Assert.Equal(10, os_exception.code); Assert.Equal(20, os_exception.extendedCode); var permission_denied = Assert.Throws( - () => coveralls.MaybeThrowComplex(2)); + () => coveralls.MaybeThrowComplex(2) + ); Assert.Equal("Forbidden", permission_denied.reason); Assert.Throws(() => coveralls.MaybeThrowComplex(3)); @@ -132,8 +148,10 @@ public void TestComplexErrors() { } [Fact] - public void TestInterfacesInDicts() { - using (var coveralls = new Coveralls("test_interface_in_dicts")) { + public void TestInterfacesInDicts() + { + using (var coveralls = new Coveralls("test_interface_in_dicts")) + { coveralls.AddPatch(new Patch(Color.Red)); coveralls.AddRepair(new Repair(DateTime.Now, new Patch(Color.Blue))); Assert.Equal(2, coveralls.GetRepairs().Count); @@ -141,25 +159,34 @@ public void TestInterfacesInDicts() { } [Fact] - public void MultiThreadedCallsWork() { + public void MultiThreadedCallsWork() + { // Make sure that there is no blocking during concurrent FFI calls. - using (var counter = new ThreadsafeCounter()) { + using (var counter = new ThreadsafeCounter()) + { const int WAIT_MILLIS = 20; - Thread blockingThread = new Thread(new ThreadStart(() => { - counter.BusyWait(WAIT_MILLIS); - })); + Thread blockingThread = new Thread( + new ThreadStart(() => + { + counter.BusyWait(WAIT_MILLIS); + }) + ); var count = 0; - Thread countingThread = new Thread(new ThreadStart(() => { - for (int i = 0; i < WAIT_MILLIS; i++) { - // `count` is only incremented if another thread is blocking the counter. - // This ensures that both calls are running concurrently. - count = counter.IncrementIfBusy(); - Thread.Sleep(1); - } - })); + Thread countingThread = new Thread( + new ThreadStart(() => + { + for (int i = 0; i < WAIT_MILLIS; i++) + { + // `count` is only incremented if another thread is blocking the counter. + // This ensures that both calls are running concurrently. + count = counter.IncrementIfBusy(); + Thread.Sleep(1); + } + }) + ); blockingThread.Start(); countingThread.Start(); @@ -170,9 +197,11 @@ public void MultiThreadedCallsWork() { } [Fact] - public void TestBytes() { - using (var coveralls = new Coveralls("test_bytes")) { - Assert.Equal(new byte[] { 3, 2, 1 }, coveralls.Reverse(new byte[] { 1, 2, 3})); + public void TestBytes() + { + using (var coveralls = new Coveralls("test_bytes")) + { + Assert.Equal(new byte[] { 3, 2, 1 }, coveralls.Reverse(new byte[] { 1, 2, 3 })); } } } diff --git a/dotnet-tests/UniffiCS.BindingTests/TestCustomTypes.cs b/dotnet-tests/UniffiCS.BindingTests/TestCustomTypes.cs new file mode 100644 index 0000000..af43991 --- /dev/null +++ b/dotnet-tests/UniffiCS.BindingTests/TestCustomTypes.cs @@ -0,0 +1,28 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +using System; +using uniffi.custom_types; + +namespace UniffiCS.BindingTests; + +public class TestCustomTypes +{ + [Fact] + public void CustomTypesWork() + { + var demo = CustomTypesMethods.GetCustomTypesDemo(null); + + Assert.Equal(new Uri("http://example.com/"), demo.url); + Assert.Equal(123, demo.handle); + + // Change some data and ensure that the round-trip works + demo = demo with + { + url = new Uri("http://new.example.com/") + }; + demo = demo with { handle = 456 }; + Assert.Equal(demo, CustomTypesMethods.GetCustomTypesDemo(demo)); + } +} diff --git a/dotnet-tests/UniffiCS.binding_tests/TestCustomTypesBuiltin.cs b/dotnet-tests/UniffiCS.BindingTests/TestCustomTypesBuiltin.cs similarity index 69% rename from dotnet-tests/UniffiCS.binding_tests/TestCustomTypesBuiltin.cs rename to dotnet-tests/UniffiCS.BindingTests/TestCustomTypesBuiltin.cs index 17f71c3..4e86e94 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestCustomTypesBuiltin.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestCustomTypesBuiltin.cs @@ -1,14 +1,18 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -using System.Collections.Generic; using System; +using System.Collections.Generic; using uniffi.custom_types_builtin; -public class TestCustomTypesBuiltin { +namespace UniffiCS.BindingTests; + +public class TestCustomTypesBuiltin +{ [Fact] - public void CustomTypesWork() { + public void CustomTypesWork() + { var demo = CustomTypesBuiltinMethods.GetCustomTypesBuiltin(); AssertDemo(demo); @@ -16,10 +20,11 @@ public void CustomTypesWork() { AssertDemo(demo); } - void AssertDemo(CustomTypesBuiltin demo) { + void AssertDemo(CustomTypesBuiltin demo) + { Assert.Equal("Hello, world!", demo.@string); Assert.Equal(new List { "Hello, world!" }, demo.array); - Assert.Equal(new Dictionary { {"hello", "world"} }, demo.table); + Assert.Equal(new Dictionary { { "hello", "world" } }, demo.table); Assert.True(demo.boolean); Assert.Equal(SByte.MaxValue, demo.int8); Assert.Equal(Int16.MaxValue, demo.int16); diff --git a/dotnet-tests/UniffiCS.binding_tests/TestDisposable.cs b/dotnet-tests/UniffiCS.BindingTests/TestDisposable.cs similarity index 61% rename from dotnet-tests/UniffiCS.binding_tests/TestDisposable.cs rename to dotnet-tests/UniffiCS.BindingTests/TestDisposable.cs index 1ca76a8..8115e03 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestDisposable.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestDisposable.cs @@ -1,46 +1,58 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -using System; using uniffi.disposable; -public class TestDisposable { +namespace UniffiCS.BindingTests; + +public class TestDisposable +{ [Fact] - public void ObjectDecrementsLiveCount() { - using (var resource = DisposableMethods.GetResource()) { + public void ObjectDecrementsLiveCount() + { + using (var resource = DisposableMethods.GetResource()) + { Assert.Equal(1, DisposableMethods.GetLiveCount()); } Assert.Equal(0, DisposableMethods.GetLiveCount()); } [Fact] - public void MapDecrementsLiveCount() { - using (var journal = DisposableMethods.GetResourceJournalMap()) { + public void MapDecrementsLiveCount() + { + using (var journal = DisposableMethods.GetResourceJournalMap()) + { Assert.Equal(2, DisposableMethods.GetLiveCount()); } Assert.Equal(0, DisposableMethods.GetLiveCount()); } [Fact] - public void ListDecrementsLiveCount() { - using (var journal = DisposableMethods.GetResourceJournalList()) { + public void ListDecrementsLiveCount() + { + using (var journal = DisposableMethods.GetResourceJournalList()) + { Assert.Equal(2, DisposableMethods.GetLiveCount()); } Assert.Equal(0, DisposableMethods.GetLiveCount()); } [Fact] - public void MapListDecrementsLiveCount() { - using (var journal = DisposableMethods.GetResourceJournalMapList()) { + public void MapListDecrementsLiveCount() + { + using (var journal = DisposableMethods.GetResourceJournalMapList()) + { Assert.Equal(2, DisposableMethods.GetLiveCount()); } Assert.Equal(0, DisposableMethods.GetLiveCount()); } [Fact] - public void EnumDecrementsLiveCount() { - using (var maybe_journal = DisposableMethods.GetMaybeResourceJournal()) { + public void EnumDecrementsLiveCount() + { + using (var maybe_journal = DisposableMethods.GetMaybeResourceJournal()) + { Assert.Equal(2, DisposableMethods.GetLiveCount()); } Assert.Equal(0, DisposableMethods.GetLiveCount()); diff --git a/dotnet-tests/UniffiCS.binding_tests/TestDocstring.cs b/dotnet-tests/UniffiCS.BindingTests/TestDocstring.cs similarity index 72% rename from dotnet-tests/UniffiCS.binding_tests/TestDocstring.cs rename to dotnet-tests/UniffiCS.BindingTests/TestDocstring.cs index bf1ab6c..679ee1d 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestDocstring.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestDocstring.cs @@ -1,6 +1,6 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. using System.Collections.Generic; using System.IO; @@ -8,13 +8,18 @@ using System.Text.RegularExpressions; using uniffi.uniffi_docstring; -public class TestDocstring { - class CallbackImpls : CallbackTest { - public void Test() {} +namespace UniffiCS.BindingTests; + +public class TestDocstring +{ + class CallbackImpls : CallbackTest + { + public void Test() { } } [Fact] - public void DocstringWorks() { + public void DocstringWorks() + { // Checking to make sure the symbols are reachable, // not accidentally commented out by docstrings @@ -44,11 +49,14 @@ public void DocstringWorks() { } [Fact] - public void DocstringsAppearInBindings() { + public void DocstringsAppearInBindings() + { // Hacky way to find project directory based on working directory.. string rootDirectory = Directory.GetCurrentDirectory() + "../../../../../../"; - string uniffiTestSource = File.ReadAllText(rootDirectory + "3rd-party/uniffi-rs/fixtures/docstring/tests/test_generated_bindings.rs"); + string uniffiTestSource = File.ReadAllText( + rootDirectory + "3rd-party/uniffi-rs/fixtures/docstring/tests/test_generated_bindings.rs" + ); MatchCollection matches = Regex.Matches(uniffiTestSource, @""); Assert.NotEmpty(matches); diff --git a/dotnet-tests/UniffiCS.binding_tests/TestGeometry.cs b/dotnet-tests/UniffiCS.BindingTests/TestGeometry.cs similarity index 60% rename from dotnet-tests/UniffiCS.binding_tests/TestGeometry.cs rename to dotnet-tests/UniffiCS.BindingTests/TestGeometry.cs index 3c64177..f749a24 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestGeometry.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestGeometry.cs @@ -1,13 +1,16 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -using System; using uniffi.geometry; -public class TestGeometry { +namespace UniffiCS.BindingTests; + +public class TestGeometry +{ [Fact] - public void GeometryWorks() { + public void GeometryWorks() + { var ln1 = new Line(new Point(0, 0), new Point(1, 2)); var ln2 = new Line(new Point(1, 1), new Point(2, 2)); diff --git a/dotnet-tests/UniffiCS.BindingTests/TestGlobalMethodsClassName.cs b/dotnet-tests/UniffiCS.BindingTests/TestGlobalMethodsClassName.cs new file mode 100644 index 0000000..0ec714f --- /dev/null +++ b/dotnet-tests/UniffiCS.BindingTests/TestGlobalMethodsClassName.cs @@ -0,0 +1,16 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +using uniffi.global_methods_class_name; + +namespace UniffiCS.BindingTests; + +public class TestGlobalMethodsClassName +{ + [Fact] + public void GlobalMethodsClassNameWorks() + { + Assert.Equal("Hello, world!", LibGreeter.HelloWorld()); + } +} diff --git a/dotnet-tests/UniffiCS.binding_tests/TestRondpoint.cs b/dotnet-tests/UniffiCS.BindingTests/TestRondpoint.cs similarity index 86% rename from dotnet-tests/UniffiCS.binding_tests/TestRondpoint.cs rename to dotnet-tests/UniffiCS.BindingTests/TestRondpoint.cs index b91966d..b1ca53c 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestRondpoint.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestRondpoint.cs @@ -1,15 +1,18 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -using System.Collections.Generic; -using System.Globalization; using System; +using System.Collections.Generic; using uniffi.rondpoint; -public class TestRondpoint { +namespace UniffiCS.BindingTests; + +public class TestRondpoint +{ [Fact] - public void CopyWorks() { + public void CopyWorks() + { var dico = new Dictionnaire(Enumeration.Deux, true, (byte)0, 123456789u); var copyDico = RondpointMethods.CopieDictionnaire(dico); Assert.Equal(dico, copyDico); @@ -19,7 +22,8 @@ public void CopyWorks() { var list = new List() { Enumeration.Un, Enumeration.Deux }; Assert.Equal(list, RondpointMethods.CopieEnumerations(list)); - var dict = new Dictionary() { + var dict = new Dictionary() + { { "0", new EnumerationAvecDonnees.Zero() }, { "1", new EnumerationAvecDonnees.Un(1u) }, { "2", new EnumerationAvecDonnees.Deux(2u, "deux") }, @@ -30,18 +34,23 @@ public void CopyWorks() { } [Fact] - public void EnumComparisonOperatorWorks() { + public void EnumComparisonOperatorWorks() + { Assert.Equal(new EnumerationAvecDonnees.Zero(), new EnumerationAvecDonnees.Zero()); Assert.Equal(new EnumerationAvecDonnees.Un(1u), new EnumerationAvecDonnees.Un(1u)); Assert.Equal(new EnumerationAvecDonnees.Deux(2u, "deux"), new EnumerationAvecDonnees.Deux(2u, "deux")); - Assert.NotEqual((EnumerationAvecDonnees)new EnumerationAvecDonnees.Zero(), (EnumerationAvecDonnees)new EnumerationAvecDonnees.Un(1u)); + Assert.NotEqual( + (EnumerationAvecDonnees)new EnumerationAvecDonnees.Zero(), + (EnumerationAvecDonnees)new EnumerationAvecDonnees.Un(1u) + ); Assert.NotEqual(new EnumerationAvecDonnees.Un(1u), new EnumerationAvecDonnees.Un(2u)); Assert.NotEqual(new EnumerationAvecDonnees.Deux(2u, "un"), new EnumerationAvecDonnees.Deux(2u, "deux")); } [Fact] - public void TestRoundTrip() { + public void TestRoundTrip() + { var rt = new Retourneur(); var meanValue = 0x1234_5678_9123_4567; @@ -79,7 +88,8 @@ public void TestRoundTrip() { "null\u0000byte", "été", "ښي لاس ته لوستلو لوستل", - "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama"); + "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama" + ); // signed record var nombresSignes = (int v) => new DictionnaireNombresSignes((sbyte)v, (short)v, (int)v, (long)v); @@ -93,13 +103,14 @@ public void TestRoundTrip() { } [Fact] - public void TestStringifier() { + public void TestStringifier() + { var st = new Stringifier(); var meanValue = 0x1234_5678_9123_4567; var wellKnown = st.WellKnownString("c#"); - Assert.Equal("uniffi 💚 c#!", st.WellKnownString("c#")) ; + Assert.Equal("uniffi 💚 c#!", st.WellKnownString("c#")); // booleans AffirmEnchaine(st.ToStringBoolean, true, false); @@ -125,20 +136,23 @@ public void TestStringifier() { (v) => float.Parse(st.ToStringFloat(v)).ToString(), Single.MinValue, Single.MaxValue, - Single.Epsilon); + Single.Epsilon + ); // doubles AffirmEnchaine( (v) => double.Parse(st.ToStringDouble(v)).ToString(), Double.MinValue, Double.MaxValue, - Double.Epsilon); + Double.Epsilon + ); st.Dispose(); } [Fact] - void TestDefaultParameterLiterals() { + void TestDefaultParameterLiterals() + { var op = new Optionneur(); Assert.Equal("default", op.SinonString()); @@ -183,7 +197,8 @@ void TestDefaultParameterLiterals() { } [Fact] - void ArgumentsOverwriteDefaultParameterLiterals() { + void ArgumentsOverwriteDefaultParameterLiterals() + { var op = new Optionneur(); AffirmAllerRetour(op.SinonString, "foo", "bar"); @@ -191,9 +206,9 @@ void ArgumentsOverwriteDefaultParameterLiterals() { AffirmAllerRetour(op.SinonSequence, new List() { "foo", "bar" }, new List()); // Optionals - #pragma warning disable 8621 +#pragma warning disable 8621 AffirmAllerRetour(op.SinonNull, "foo", "bar"); - #pragma warning restore 8621 +#pragma warning restore 8621 AffirmAllerRetour(op.SinonZero, (int?)0, (int?)1); // Decimals @@ -230,10 +245,12 @@ void ArgumentsOverwriteDefaultParameterLiterals() { } [Fact] - void TestDefaultParameterLiteralsInRecord() { + void TestDefaultParameterLiteralsInRecord() + { // Testing defaulting properties in record types. var defaultes = new OptionneurDictionnaire(); - var explicite = new OptionneurDictionnaire() { + var explicite = new OptionneurDictionnaire() + { i8Var = (sbyte)-8, u8Var = (byte)8, i16Var = (short)-16, @@ -246,17 +263,21 @@ void TestDefaultParameterLiteralsInRecord() { doubleVar = 8.0, booleanVar = true, stringVar = "default", - #pragma warning disable 8625 +#pragma warning disable 8625 listVar = null, - #pragma warning restore 8625 +#pragma warning restore 8625 enumerationVar = Enumeration.Deux, dictionnaireVar = null, }; Assert.Equal(defaultes, explicite); - using (var rt = new Retourneur()) { + using (var rt = new Retourneur()) + { // a default list value (null) is transformed into an empty list after a roundtrip - defaultes = defaultes with {listVar = new List()}; + defaultes = defaultes with + { + listVar = new List() + }; // TODO(CS): C# record comparison doesn't work if the record contains lists/maps. // Rewrite records to use custom struct type. @@ -264,19 +285,22 @@ void TestDefaultParameterLiteralsInRecord() { } } - static void AffirmAllerRetour(Func callback, params T[] list) { - foreach (var value in list) { + static void AffirmAllerRetour(Func callback, params T[] list) + { + foreach (var value in list) + { Assert.Equal(value, callback(value)); } } static void AffirmEnchaine(Func callback, params T[] list) - where T: notnull + where T : notnull { - foreach (var value in list) { - #pragma warning disable 8602 + foreach (var value in list) + { +#pragma warning disable 8602 Assert.Equal(value.ToString().ToLower(), callback(value).ToLower()); - #pragma warning restore 8602 +#pragma warning restore 8602 } } } diff --git a/dotnet-tests/UniffiCS.binding_tests/TestSprites.cs b/dotnet-tests/UniffiCS.BindingTests/TestSprites.cs similarity index 63% rename from dotnet-tests/UniffiCS.binding_tests/TestSprites.cs rename to dotnet-tests/UniffiCS.BindingTests/TestSprites.cs index 2f1ba65..22272e1 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestSprites.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestSprites.cs @@ -1,14 +1,18 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -using System; using uniffi.sprites; -public class TestSprites { +namespace UniffiCS.BindingTests; + +public class TestSprites +{ [Fact] - public void SpritesWork() { - using (var sempty = new Sprite((Point?)null)) { + public void SpritesWork() + { + using (var sempty = new Sprite((Point?)null)) + { Assert.Equal(new Point(0, 0), sempty.GetPosition()); } @@ -24,7 +28,8 @@ public void SpritesWork() { s.Dispose(); Assert.Throws(() => s.MoveBy(new Vector(0, 0))); - using (var srel = Sprite.NewRelativeTo(new Point(0, 1), new Vector(1, 1.5))) { + using (var srel = Sprite.NewRelativeTo(new Point(0, 1), new Vector(1, 1.5))) + { Assert.Equal(new Point(1, 2.5), srel.GetPosition()); } } diff --git a/dotnet-tests/UniffiCS.binding_tests/TestTodoList.cs b/dotnet-tests/UniffiCS.BindingTests/TestTodoList.cs similarity index 82% rename from dotnet-tests/UniffiCS.binding_tests/TestTodoList.cs rename to dotnet-tests/UniffiCS.BindingTests/TestTodoList.cs index 046cd29..2f27b08 100644 --- a/dotnet-tests/UniffiCS.binding_tests/TestTodoList.cs +++ b/dotnet-tests/UniffiCS.BindingTests/TestTodoList.cs @@ -1,14 +1,17 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. using System.Collections.Generic; -using System; using uniffi.todolist; -public class TestTodoList { +namespace UniffiCS.BindingTests; + +public class TestTodoList +{ [Fact] - public void TodoListWorks() { + public void TodoListWorks() + { var todo = new TodoList(); Assert.Throws(() => todo.GetLast()); @@ -35,32 +38,35 @@ public void TodoListWorks() { Assert.Equal(5, todo.GetEntries().Count); - todo.AddEntries(new List() {new TodoEntry("foo"), new TodoEntry("bar")}); + todo.AddEntries(new List() { new TodoEntry("foo"), new TodoEntry("bar") }); Assert.Equal(7, todo.GetEntries().Count); Assert.Equal("bar", todo.GetLastEntry().text); - todo.AddItems(new List() {"bobo", "fofo"}); + todo.AddItems(new List() { "bobo", "fofo" }); Assert.Equal(9, todo.GetItems().Count); Assert.Equal("bobo", todo.GetItems()[7]); Assert.Null(TodolistMethods.GetDefaultList()); // https://github.com/xunit/xunit/issues/2027 - #pragma warning disable CS8602 +#pragma warning disable CS8602 // Note that each individual object instance needs to be explicitly destroyed, // either by using the `.use` helper or explicitly calling its `.destroy` method. // Failure to do so will leak the underlying Rust object. - using (var todo2 = new TodoList()) { + using (var todo2 = new TodoList()) + { TodolistMethods.SetDefaultList(todo); - using (var defaultList = TodolistMethods.GetDefaultList()) { + using (var defaultList = TodolistMethods.GetDefaultList()) + { Assert.NotNull(defaultList); Assert.Equal(todo.GetEntries(), defaultList.GetEntries()); Assert.NotEqual(todo2.GetEntries(), defaultList.GetEntries()); } todo2.MakeDefault(); - using (var defaultList = TodolistMethods.GetDefaultList()) { + using (var defaultList = TodolistMethods.GetDefaultList()) + { Assert.NotEqual(todo.GetEntries(), defaultList.GetEntries()); Assert.Equal(todo2.GetEntries(), defaultList.GetEntries()); } @@ -69,12 +75,13 @@ public void TodoListWorks() { Assert.Equal("Test liveness after being demoted from default", todo.GetLast()); todo2.AddItem("Test shared state through local vs default reference"); - using (var defaultList = TodolistMethods.GetDefaultList()) { + using (var defaultList = TodolistMethods.GetDefaultList()) + { Assert.Equal("Test shared state through local vs default reference", defaultList.GetLast()); } } - #pragma warning restore CS8602 +#pragma warning restore CS8602 // Ensure the kotlin version of deinit doesn't crash, and is idempotent. todo.Dispose(); diff --git a/dotnet-tests/UniffiCS.BindingTests/TestTraitMethod.cs b/dotnet-tests/UniffiCS.BindingTests/TestTraitMethod.cs new file mode 100644 index 0000000..b26638f --- /dev/null +++ b/dotnet-tests/UniffiCS.BindingTests/TestTraitMethod.cs @@ -0,0 +1,28 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +using uniffi.trait_methods; + +namespace UniffiCS.BindingTests; + +public class TestTraitMethods +{ + [Fact] + public void TraitMethodsWork() + { + using (var methods = new TraitMethods("yo")) + { + Assert.Equal("TraitMethods(yo)", methods.ToString()); + } + } + + [Fact] + public void TraitMethodsProcMacro() + { + using (var methods = new ProcTraitMethods("yo")) + { + Assert.Equal("ProcTraitMethods(yo)", methods.ToString()); + } + } +} diff --git a/dotnet-tests/UniffiCS.binding_tests/UniffiCS.binding_tests.csproj b/dotnet-tests/UniffiCS.BindingTests/UniffiCS.BindingTests.csproj similarity index 97% rename from dotnet-tests/UniffiCS.binding_tests/UniffiCS.binding_tests.csproj rename to dotnet-tests/UniffiCS.BindingTests/UniffiCS.BindingTests.csproj index 0094776..957d3f2 100644 --- a/dotnet-tests/UniffiCS.binding_tests/UniffiCS.binding_tests.csproj +++ b/dotnet-tests/UniffiCS.BindingTests/UniffiCS.BindingTests.csproj @@ -1,26 +1,26 @@ - - - - net6.0 - enable - - false - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - + + + + net6.0 + enable + + false + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + diff --git a/dotnet-tests/UniffiCS.BindingTests/Usings.cs b/dotnet-tests/UniffiCS.BindingTests/Usings.cs new file mode 100644 index 0000000..2d703f1 --- /dev/null +++ b/dotnet-tests/UniffiCS.BindingTests/Usings.cs @@ -0,0 +1,5 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +global using Xunit; diff --git a/dotnet-tests/UniffiCS.tests/TestBigEndianStream.cs b/dotnet-tests/UniffiCS.Tests/TestBigEndianStream.cs similarity index 76% rename from dotnet-tests/UniffiCS.tests/TestBigEndianStream.cs rename to dotnet-tests/UniffiCS.Tests/TestBigEndianStream.cs index 3890e8a..8ce9bca 100644 --- a/dotnet-tests/UniffiCS.tests/TestBigEndianStream.cs +++ b/dotnet-tests/UniffiCS.Tests/TestBigEndianStream.cs @@ -1,15 +1,21 @@ -namespace UniffiCS.tests; +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +namespace UniffiCS.Tests; + +using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; -using System; using System.Text; -public class TestBigEndianStream { +public class TestBigEndianStream +{ [Fact] - public void TestBytes() { + public void TestBytes() + { byte[] bytes = System.Text.Encoding.UTF8.GetBytes("Hello, world!"); var stream = new BigEndianStream(new MemoryStream(new byte[bytes.Length])); stream.WriteBytes(bytes); @@ -20,53 +26,49 @@ public void TestBytes() { } [Fact] - public void TestEndianness() { - var endianessTest = (Action write, byte[] expected_bytes) => { + public void TestEndianness() + { + var endianessTest = (Action write, byte[] expected_bytes) => + { var stream = new BigEndianStream(new MemoryStream(new byte[expected_bytes.Length])); write(stream); stream.Position = 0; Assert.Equal(expected_bytes, stream.ReadBytes(expected_bytes.Length)); }; - endianessTest( - (stream) => stream.WriteUShort(0x1122), - new byte[] { 0x11, 0x22 }); + endianessTest((stream) => stream.WriteUShort(0x1122), new byte[] { 0x11, 0x22 }); - endianessTest( - (stream) => stream.WriteUInt(0x11223344), - new byte[] { 0x11, 0x22, 0x33, 0x44}); + endianessTest((stream) => stream.WriteUInt(0x11223344), new byte[] { 0x11, 0x22, 0x33, 0x44 }); endianessTest( (stream) => stream.WriteULong(0x1122334455667788), - new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }); + new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 } + ); - endianessTest( - (stream) => stream.WriteShort(0x1122), - new byte[] { 0x11, 0x22 }); + endianessTest((stream) => stream.WriteShort(0x1122), new byte[] { 0x11, 0x22 }); - endianessTest( - (stream) => stream.WriteInt(0x11223344), - new byte[] { 0x11, 0x22, 0x33, 0x44}); + endianessTest((stream) => stream.WriteInt(0x11223344), new byte[] { 0x11, 0x22, 0x33, 0x44 }); endianessTest( (stream) => stream.WriteLong(0x1122334455667788), - new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }); + new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 } + ); // https://docs.rs/bytes/latest/bytes/trait.BufMut.html#method.put_f32 // https://www.h-schmidt.net/FloatConverter/IEEE754.html - endianessTest( - (stream) => stream.WriteFloat(1.2f), - new byte[] { 0x3F, 0x99, 0x99, 0x9A }); + endianessTest((stream) => stream.WriteFloat(1.2f), new byte[] { 0x3F, 0x99, 0x99, 0x9A }); // https://docs.rs/bytes/latest/bytes/trait.BufMut.html#method.put_f64 // https://www.h-schmidt.net/FloatConverter/IEEE754.html endianessTest( (stream) => stream.WriteDouble(1.2d), - new byte[] { 0x3F, 0xF3, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33 }); + new byte[] { 0x3F, 0xF3, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33 } + ); } [Fact] - void TestReadWrite() { + void TestReadWrite() + { var meanValue = 0x1234_5678_9123_4567; ReadWriteTest( @@ -74,74 +76,85 @@ void TestReadWrite() { (stream) => stream.ReadByte, Byte.MinValue, Byte.MaxValue, - (byte)meanValue); + (byte)meanValue + ); ReadWriteTest( (stream) => stream.WriteUShort, (stream) => stream.ReadUShort, UInt16.MinValue, UInt16.MaxValue, - (ushort)meanValue); + (ushort)meanValue + ); ReadWriteTest( (stream) => stream.WriteUInt, (stream) => stream.ReadUInt, UInt32.MinValue, UInt32.MaxValue, - (uint)meanValue); + (uint)meanValue + ); ReadWriteTest( (stream) => stream.WriteULong, (stream) => stream.ReadULong, UInt64.MinValue, UInt64.MaxValue, - (ulong)meanValue); + (ulong)meanValue + ); ReadWriteTest( (stream) => stream.WriteSByte, (stream) => stream.ReadSByte, SByte.MinValue, SByte.MaxValue, - (sbyte)meanValue); + (sbyte)meanValue + ); ReadWriteTest( (stream) => stream.WriteShort, (stream) => stream.ReadShort, Int16.MinValue, Int16.MaxValue, - (short)meanValue); + (short)meanValue + ); ReadWriteTest( (stream) => stream.WriteInt, (stream) => stream.ReadInt, Int32.MinValue, Int32.MaxValue, - (int)meanValue); + (int)meanValue + ); ReadWriteTest( (stream) => stream.WriteLong, (stream) => stream.ReadLong, Int64.MinValue, Int64.MaxValue, - (long)meanValue); + (long)meanValue + ); ReadWriteTest( (stream) => stream.WriteFloat, (stream) => stream.ReadFloat, Single.MinValue, Single.MaxValue, - Single.Epsilon); + Single.Epsilon + ); ReadWriteTest( (stream) => stream.WriteDouble, (stream) => stream.ReadDouble, Double.MinValue, Double.MaxValue, - Double.Epsilon); + Double.Epsilon + ); } [Fact] - public void TestUnderflowReadThrows() { + public void TestUnderflowReadThrows() + { var newStream = (int length) => new BigEndianStream(new MemoryStream(new byte[length])); Assert.Throws(() => newStream(10).ReadBytes(11)); @@ -161,12 +174,14 @@ public void TestUnderflowReadThrows() { } static void ReadWriteTest( - Func> write, - Func> read, - T minValue, - T maxValue, - T meanValue) - where T: IComparable { + Func> write, + Func> read, + T minValue, + T maxValue, + T meanValue + ) + where T : IComparable + { var memoryStream = new MemoryStream(new byte[Marshal.SizeOf(minValue)]); var stream = new BigEndianStream(memoryStream); @@ -186,4 +201,3 @@ static void ReadWriteTest( Assert.Equal(read(stream)(), meanValue); } } - diff --git a/dotnet-tests/UniffiCS.tests/UniffiCS.tests.csproj b/dotnet-tests/UniffiCS.Tests/UniffiCS.Tests.csproj similarity index 97% rename from dotnet-tests/UniffiCS.tests/UniffiCS.tests.csproj rename to dotnet-tests/UniffiCS.Tests/UniffiCS.Tests.csproj index 7324c00..08e45d3 100644 --- a/dotnet-tests/UniffiCS.tests/UniffiCS.tests.csproj +++ b/dotnet-tests/UniffiCS.Tests/UniffiCS.Tests.csproj @@ -1,23 +1,23 @@ - - - - net6.0 - enable - enable - - false - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - + + + + net6.0 + enable + enable + + false + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + diff --git a/dotnet-tests/UniffiCS.Tests/Usings.cs b/dotnet-tests/UniffiCS.Tests/Usings.cs new file mode 100644 index 0000000..2d703f1 --- /dev/null +++ b/dotnet-tests/UniffiCS.Tests/Usings.cs @@ -0,0 +1,5 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +global using Xunit; diff --git a/dotnet-tests/UniffiCS.binding_tests/TestCustomTypes.cs b/dotnet-tests/UniffiCS.binding_tests/TestCustomTypes.cs deleted file mode 100644 index 3340482..0000000 --- a/dotnet-tests/UniffiCS.binding_tests/TestCustomTypes.cs +++ /dev/null @@ -1,21 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -using System; -using uniffi.custom_types; - -public class TestCustomTypes { - [Fact] - public void CustomTypesWork() { - var demo = CustomTypesMethods.GetCustomTypesDemo(null); - - Assert.Equal(new Uri("http://example.com/"), demo.url); - Assert.Equal(123, demo.handle); - - // Change some data and ensure that the round-trip works - demo = demo with {url = new Uri("http://new.example.com/") }; - demo = demo with {handle = 456}; - Assert.Equal(demo, CustomTypesMethods.GetCustomTypesDemo(demo)); - } -} diff --git a/dotnet-tests/UniffiCS.binding_tests/TestGlobalMethodsClassName.cs b/dotnet-tests/UniffiCS.binding_tests/TestGlobalMethodsClassName.cs deleted file mode 100644 index 57d40f7..0000000 --- a/dotnet-tests/UniffiCS.binding_tests/TestGlobalMethodsClassName.cs +++ /dev/null @@ -1,15 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -using System.Diagnostics; -using System.IO; -using System; -using uniffi.global_methods_class_name; - -public class TestGlobalMethodsClassName { - [Fact] - public void GlobalMethodsClassNameWorks() { - Assert.Equal("Hello, world!", LibGreeter.HelloWorld()); - } -} diff --git a/dotnet-tests/UniffiCS.binding_tests/TestTraitMethod.cs b/dotnet-tests/UniffiCS.binding_tests/TestTraitMethod.cs deleted file mode 100644 index 0f6af4e..0000000 --- a/dotnet-tests/UniffiCS.binding_tests/TestTraitMethod.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -using uniffi.trait_methods; - -public class TestTraitMethods { - [Fact] - public void TraitMethodsWork() { - using (var methods = new TraitMethods("yo")) { - Assert.Equal("TraitMethods(yo)", methods.ToString()); - } - } - - [Fact] - public void TraitMethodsProcMacro() { - using (var methods = new ProcTraitMethods("yo")) { - Assert.Equal("ProcTraitMethods(yo)", methods.ToString()); - } - } -} - diff --git a/dotnet-tests/UniffiCS.binding_tests/Usings.cs b/dotnet-tests/UniffiCS.binding_tests/Usings.cs deleted file mode 100644 index ca0bcca..0000000 --- a/dotnet-tests/UniffiCS.binding_tests/Usings.cs +++ /dev/null @@ -1,5 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -global using Xunit; diff --git a/dotnet-tests/dotnet-tests.sln b/dotnet-tests/UniffiCS.sln similarity index 83% rename from dotnet-tests/dotnet-tests.sln rename to dotnet-tests/UniffiCS.sln index aa1cd24..acd3441 100644 --- a/dotnet-tests/dotnet-tests.sln +++ b/dotnet-tests/UniffiCS.sln @@ -1,34 +1,34 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniffiCS", "UniffiCS.binding_tests\UniffiCS.binding_tests.csproj", "{405D55E2-67ED-4842-8D44-8270641C1BF8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniffiCS.tests", "UniffiCS.tests\UniffiCS.tests.csproj", "{5CBAE51D-2BAD-4C80-836E-DC82E0274851}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniffiCS", "UniffiCS\UniffiCS.csproj", "{84FB93AF-E788-4D31-9FC7-0FFCD3864054}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {405D55E2-67ED-4842-8D44-8270641C1BF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {405D55E2-67ED-4842-8D44-8270641C1BF8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {405D55E2-67ED-4842-8D44-8270641C1BF8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {405D55E2-67ED-4842-8D44-8270641C1BF8}.Release|Any CPU.Build.0 = Release|Any CPU - {5CBAE51D-2BAD-4C80-836E-DC82E0274851}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5CBAE51D-2BAD-4C80-836E-DC82E0274851}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5CBAE51D-2BAD-4C80-836E-DC82E0274851}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5CBAE51D-2BAD-4C80-836E-DC82E0274851}.Release|Any CPU.Build.0 = Release|Any CPU - {84FB93AF-E788-4D31-9FC7-0FFCD3864054}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {84FB93AF-E788-4D31-9FC7-0FFCD3864054}.Debug|Any CPU.Build.0 = Debug|Any CPU - {84FB93AF-E788-4D31-9FC7-0FFCD3864054}.Release|Any CPU.ActiveCfg = Release|Any CPU - {84FB93AF-E788-4D31-9FC7-0FFCD3864054}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniffiCS.BindingTests", "UniffiCS.BindingTests\UniffiCS.BindingTests.csproj", "{405D55E2-67ED-4842-8D44-8270641C1BF8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniffiCS.Tests", "UniffiCS.Tests\UniffiCS.Tests.csproj", "{5CBAE51D-2BAD-4C80-836E-DC82E0274851}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniffiCS", "UniffiCS\UniffiCS.csproj", "{84FB93AF-E788-4D31-9FC7-0FFCD3864054}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {405D55E2-67ED-4842-8D44-8270641C1BF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {405D55E2-67ED-4842-8D44-8270641C1BF8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {405D55E2-67ED-4842-8D44-8270641C1BF8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {405D55E2-67ED-4842-8D44-8270641C1BF8}.Release|Any CPU.Build.0 = Release|Any CPU + {5CBAE51D-2BAD-4C80-836E-DC82E0274851}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5CBAE51D-2BAD-4C80-836E-DC82E0274851}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5CBAE51D-2BAD-4C80-836E-DC82E0274851}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5CBAE51D-2BAD-4C80-836E-DC82E0274851}.Release|Any CPU.Build.0 = Release|Any CPU + {84FB93AF-E788-4D31-9FC7-0FFCD3864054}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {84FB93AF-E788-4D31-9FC7-0FFCD3864054}.Debug|Any CPU.Build.0 = Debug|Any CPU + {84FB93AF-E788-4D31-9FC7-0FFCD3864054}.Release|Any CPU.ActiveCfg = Release|Any CPU + {84FB93AF-E788-4D31-9FC7-0FFCD3864054}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/dotnet-tests/UniffiCS.tests/Usings.cs b/dotnet-tests/UniffiCS.tests/Usings.cs deleted file mode 100644 index c802f44..0000000 --- a/dotnet-tests/UniffiCS.tests/Usings.cs +++ /dev/null @@ -1 +0,0 @@ -global using Xunit; diff --git a/dotnet-tests/UniffiCS/UniffiCS.csproj b/dotnet-tests/UniffiCS/UniffiCS.csproj index 5713882..d558178 100644 --- a/dotnet-tests/UniffiCS/UniffiCS.csproj +++ b/dotnet-tests/UniffiCS/UniffiCS.csproj @@ -8,6 +8,6 @@ - + diff --git a/run_unit_tests.sh b/run_unit_tests.sh index 4dc73c2..f204182 100755 --- a/run_unit_tests.sh +++ b/run_unit_tests.sh @@ -4,7 +4,7 @@ set -euxo pipefail # "Using" statements musn't appear in generated code, but they are required # when compiling the file for tests. To get around this, simply prepend "Using" # statements to the actual file content. -TMP_STREAM_FILE="dotnet-tests/UniffiCS.tests/gen/tmp_BigEndianStream.cs" +TMP_STREAM_FILE="dotnet-tests/UniffiCS.Tests/gen/tmp_BigEndianStream.cs" mkdir -p $(dirname "$TMP_STREAM_FILE") echo "using System;" > $TMP_STREAM_FILE @@ -13,5 +13,5 @@ cat bindgen/templates/BigEndianStream.cs >> $TMP_STREAM_FILE sed -i 's/{#//g' $TMP_STREAM_FILE sed -i 's/#}//g' $TMP_STREAM_FILE -cd dotnet-tests/UniffiCS.tests +cd dotnet-tests/UniffiCS.Tests dotnet test -l "console;verbosity=normal" diff --git a/test_bindings.sh b/test_bindings.sh index 55add73..61a9ca1 100755 --- a/test_bindings.sh +++ b/test_bindings.sh @@ -3,7 +3,7 @@ set -euxo pipefail SCRIPT_DIR="${SCRIPT_DIR:-$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )}" -CSPROJ_DIR="dotnet-tests/UniffiCS.binding_tests" +CSPROJ_DIR="dotnet-tests/UniffiCS.BindingTests" export LD_LIBRARY_PATH="$SCRIPT_DIR/target/debug/:${LD_LIBRARY_PATH:-}" cd $CSPROJ_DIR