using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using UnitTestSharp; namespace Amphora.UnitTests { public class FlagRegistryTests : TestFixture { public static FlagRegistry Sample() { return FlagRegistry.ScanTypes(new[] { typeof(SampleFlags) }); } public static Flags Read(params string[] arguments) { return Sample().Parse(arguments).Value; } public static string ProblemsWith(params string[] arguments) { StatusOr result = Sample().Parse(arguments); if (result.IsOk) { throw new InvalidOperationException("The arguments were fine."); } return result.Status.Describe(); } public static Type EmittedTypeWith(string name, bool generic) { var assembly = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName("FlagRegistryTests." + name), AssemblyBuilderAccess.Run); TypeBuilder type = assembly.DefineDynamicModule(name).DefineType(name, TypeAttributes.Public); if (generic) { type.DefineGenericParameters("Stuff"); } type.DefineField("Flag", typeof(Flag), FieldAttributes.Public | FieldAttributes.Static); return type.CreateType(); } public class RegisterTests : TestFixture { public void NoName_Throws() { CheckThrow(typeof(ArgumentNullException)); new FlagRegistry().Register(null, "owner", new Flag("")); } public void NoOwner_Throws() { CheckThrow(typeof(ArgumentNullException)); new FlagRegistry().Register("name", null, new Flag("")); } public void NoFlag_Throws() { CheckThrow(typeof(ArgumentNullException)); new FlagRegistry().Register("name", "owner", null); } public void AnEmptyName_Throws() { CheckThrow(typeof(ArgumentException)); new FlagRegistry().Register("", "owner", new Flag("")); } public void AnUppercaseName_Throws() { CheckThrow(typeof(ArgumentException)); new FlagRegistry().Register("Name", "owner", new Flag("")); } public void ANameWithADash_Throws() { CheckThrow(typeof(ArgumentException)); new FlagRegistry().Register("no-vsync", "owner", new Flag("")); } public void ANameWithDigits_IsAllowed() { var registry = new FlagRegistry(); registry.Register("x2", "owner", new Flag("")); CheckEqual(1, registry.Count); } public void TwoFlagsWithOneName_ThrowsNamingBothOwners() { var registry = new FlagRegistry(); registry.Register("level", "First.Level", new Flag("")); var thrown = Throws(() => registry.Register("level", "Second.Level", new Flag(""))); CheckEqual("--level is claimed by Second.Level and by First.Level. Rename one of them.", thrown.Message); } public void ABooleansOffFormClashingWithAName_Throws() { var registry = new FlagRegistry(); registry.Register("novsync", "First.Novsync", new Flag("")); var thrown = Throws(() => registry.Register("vsync", "Second.Vsync", new Flag(""))); CheckEqual("--novsync is claimed by Second.Vsync and by First.Novsync. Rename one of them.", thrown.Message); } public void ANameClashingWithABooleansOffForm_Throws() { var registry = new FlagRegistry(); registry.Register("vsync", "First.Vsync", new Flag("")); var thrown = Throws(() => registry.Register("novsync", "Second.Novsync", new Flag(""))); CheckEqual("--novsync is claimed by Second.Novsync and by First.Vsync. Rename one of them.", thrown.Message); } public void ANonBooleanNamedNoSomething_IsAllowedBesideAFlagCalledSomething() { var registry = new FlagRegistry(); registry.Register("vsync", "First.Vsync", new Flag("")); registry.Register("novsync", "Second.Novsync", new Flag("")); CheckEqual(2, registry.Count); } public void AClash_LeavesTheRegistryAsItWas() { var registry = new FlagRegistry(); registry.Register("novsync", "First.Novsync", new Flag("")); Throws(() => registry.Register("vsync", "Second.Vsync", new Flag(""))); registry.Register("vsync", "Third.Vsync", new Flag("")); CheckEqual(2, registry.Count); } public void HelpIsTaken() { var thrown = Throws(() => new FlagRegistry().Register("help", "Mine.Help", new Flag(""))); CheckEqual("--help is claimed by Mine.Help and by the built-in help request. Rename one of them.", thrown.Message); } public void OneFlagUnderTwoNames_Throws() { var registry = new FlagRegistry(); var flag = new Flag(""); registry.Register("level", "First.Level", flag); var thrown = Throws(() => registry.Register("depth", "Second.Depth", flag)); CheckEqual("Second.Depth is the same flag as First.Level. A flag has one name.", thrown.Message); } public void OneFlagUnderTheSameNameTwice_AddsItOnce() { var registry = new FlagRegistry(); var flag = new Flag(""); registry.Register("level", "First.Level", flag); registry.Register("level", "First.Level", flag); CheckEqual(1, registry.Count); } public void KeepsTheFlagsInTheOrderTheyCame() { var registry = new FlagRegistry(); var first = new Flag(""); var second = new Flag(""); registry.Register("b", "owner.B", first); registry.Register("a", "owner.A", second); CheckEqual("b", registry.Registered[0].Name); CheckEqual("owner.A", registry.Registered[1].Owner); CheckTrue(ReferenceEquals(second, registry.Registered[1].Flag)); } private static InvalidOperationException Throws(System.Action action) { try { action(); } catch (InvalidOperationException exception) { return exception; } throw new InvalidOperationException("Nothing was thrown."); } } public class IndexOfTests : TestFixture { public void ARegisteredFlag_IsItsPosition() { CheckEqual(3, Sample().IndexOf(SampleFlags.Level)); } public void AFlagNotRegistered_IsMinusOne() { CheckEqual(-1, Sample().IndexOf(new Flag(""))); } public void NoFlag_IsMinusOne() { CheckEqual(-1, Sample().IndexOf(null)); } } public class ScanTypesTests : TestFixture { public void FindsEveryFlagInAStaticField() { CheckEqual(11, Sample().Count); } public void NamesEachForItsFieldInLowercase() { CheckEqual(0, Sample().IndexOf(SampleFlags.Vsync)); CheckEqual("vsync", Sample().Registered[0].Name); } public void NamesTheOwnerByTypeAndField() { CheckEqual("Amphora.UnitTests.SampleFlags.Vsync", Sample().Registered[0].Owner); } public void FindsAFlagInAPrivateField() { CheckEqual(9, Sample().IndexOf(SampleFlags.PrivateFlag)); } public void LeavesOutFieldsThatAreNotFlags() { foreach (RegisteredFlag registered in Sample().Registered) { CheckFalse(registered.Name == "notaflag" || registered.Name == "onaninstance"); } } public void ATypeWithNoFlags_AddsNothing() { CheckEqual(0, FlagRegistry.ScanTypes(new[] { typeof(string) }).Count); } public void AFieldHoldingNothing_Throws() { Type type = EmittedTypeWith("NullFlag", generic: false); CheckThrow(typeof(InvalidOperationException)); FlagRegistry.ScanTypes(new[] { type }); } public void AFlagOnAGenericType_Throws() { Type type = EmittedTypeWith("GenericFlag", generic: true); CheckThrow(typeof(InvalidOperationException)); FlagRegistry.ScanTypes(new[] { type }); } } public class ScanAssembliesTests : TestFixture { public void FindsTheFlagsOfEachAssembly() { FlagRegistry registry = FlagRegistry.ScanAssemblies(new[] { typeof(SampleFlags).Assembly }); CheckEqual(11, registry.Count); CheckEqual(0, registry.IndexOf(SampleFlags.Vsync)); } public void TheAmphoraAssemblyHasNoFlagsToClash() { CheckEqual(0, FlagRegistry.ScanAssemblies(new[] { typeof(Flag<>).Assembly }).Count); } } public class ScanLoadedAssembliesTests : TestFixture { public void FindsTheFlagsOfTheLoadedAssemblies() { CheckGreater(FlagRegistry.ScanLoadedAssemblies().IndexOf(SampleFlags.Level), -1); } public void LeavesOutDynamicAssemblies() { EmittedTypeWith("LoadedNullFlag", generic: false); CheckGreater(FlagRegistry.ScanLoadedAssemblies().Count, 0); } } public class ParseTests : TestFixture { public void NoNull_Throws() { CheckThrow(typeof(ArgumentNullException)); Sample().Parse(null); } public void NoArguments_GivesEveryDefault() { Flags flags = Read(); CheckEqual(true, flags.Get(SampleFlags.Vsync)); CheckEqual(7UL, flags.Get(SampleFlags.Seed)); CheckEqual(1.5, flags.Get(SampleFlags.Scale)); CheckEqual("none", flags.Get(SampleFlags.Title)); CheckEqual(SampleMode.Slow, flags.Get(SampleFlags.Mode)); CheckNull(flags.Get(SampleFlags.Nameless)); CheckFalse(flags.HelpRequested); } public void ABareBooleanName_TurnsItOn() { CheckTrue(Read("--quiet").Get(SampleFlags.Quiet)); } public void ANoPrefixedBooleanName_TurnsItOff() { CheckFalse(Read("--novsync").Get(SampleFlags.Vsync)); } public void ABooleanWithAValue_TakesIt() { CheckFalse(Read("--vsync=false").Get(SampleFlags.Vsync)); } public void AFailure_IsOfTheInvalidArgumentsKind() { StatusOr result = Sample().Parse(new[] { "--wibble" }); CheckEqual(FlagRegistry.InvalidArguments, result.Status.Kind); } public void ABooleanWithABadValue_Fails() { CheckEqual("--vsync needs true or false, not 'maybe'.", ProblemsWith("--vsync=maybe")); } public void TheOffFormWithAValue_Fails() { CheckEqual("--novsync takes no value.", ProblemsWith("--novsync=true")); } public void AValueAfterEquals_IsReadAsTheFlagsType() { Flags flags = Read("--seed=42", "--level=-4", "--offset=3000000000", "--scale=2.5", "--title=A=b", "--mode=fast"); CheckEqual(42UL, flags.Get(SampleFlags.Seed)); CheckEqual(-4, flags.Get(SampleFlags.Level)); CheckEqual(3000000000L, flags.Get(SampleFlags.Offset)); CheckEqual(2.5, flags.Get(SampleFlags.Scale)); CheckEqual("A=b", flags.Get(SampleFlags.Title)); CheckEqual(SampleMode.Fast, flags.Get(SampleFlags.Mode)); } public void ACustomFlag_IsReadByItsParser() { CheckEqual('z', Read("--letter=z").Get(SampleFlags.Letter)); } public void ACustomFlagTheParserRejects_Fails() { CheckEqual("--letter needs one letter, not '12'.", ProblemsWith("--letter=12")); } public void ANonBooleanWithNoValue_Fails() { CheckEqual("--seed needs a value, as in =value.", ProblemsWith("--seed")); } public void AnEmptyValue_IsAnEmptyString() { CheckEqual("", Read("--title=").Get(SampleFlags.Title)); } public void ABadNumber_Fails() { CheckEqual("--level needs a whole number, not 'x'.", ProblemsWith("--level=x")); } public void AnUnknownFlag_Fails() { CheckEqual("There's no flag --wibble.", ProblemsWith("--wibble")); } public void AnUnknownFlagWithAValue_NamesJustTheFlag() { CheckEqual("There's no flag --wibble.", ProblemsWith("--wibble=3")); } public void ANameOnItsOwn_Fails() { CheckEqual("There's no flag --.", ProblemsWith("--")); } public void ACapitalizedName_Fails() { CheckEqual("There's no flag --Seed.", ProblemsWith("--Seed=3")); } public void HelpWithAValue_Fails() { CheckEqual("There's no flag --help.", ProblemsWith("--help=1")); } public void ASingleDashArgument_Fails() { CheckEqual("'-debug' isn't a flag. Flags start with --.", ProblemsWith("-debug")); } public void AnArgumentWithNoDashes_Fails() { CheckEqual("'level=3' isn't a flag. Flags start with --.", ProblemsWith("level=3")); } public void ANullArgument_Fails() { CheckEqual("There's a null argument.", ProblemsWith(new string[] { null })); } public void ANamedTwice_Fails() { CheckEqual("--seed is given more than once.", ProblemsWith("--seed=1", "--seed=2")); } public void ABooleanAndItsOffForm_Fails() { CheckEqual("--vsync is given more than once.", ProblemsWith("--vsync", "--novsync")); } public void EveryProblem_IsReportedALineEach() { CheckEqual("There's no flag --a." + Environment.NewLine + "--level needs a whole number, not 'x'.", ProblemsWith("--a", "--level=x", "--seed=3")); } public void AFailedFlag_DoesNotCountAsGiven() { CheckEqual("--seed needs a value, as in =value." + Environment.NewLine + "--seed needs a value, as in =value.", ProblemsWith("--seed", "--seed")); } public void LongHelp_AsksForHelp() { CheckTrue(Read("--help").HelpRequested); } public void ShortHelp_AsksForHelp() { CheckTrue(Read("-h").HelpRequested); } public void QuestionMark_AsksForHelp() { CheckTrue(Read("-?").HelpRequested); } public void HelpBesideAProblem_StillAsksForHelp() { Flags flags = Read("--wibble", "--help"); CheckTrue(flags.HelpRequested); } public void Flags_AreReadAgainstTheRegistryThatParsedThem() { FlagRegistry registry = Sample(); Flags flags = registry.Parse(new[] { "--level=9" }).Value; CheckEqual(9, flags.Get(SampleFlags.Level)); } } public class ParseWhatItCanTests : TestFixture { public void NoArguments_Throws() { CheckThrow(typeof(ArgumentNullException)); Sample().ParseWhatItCan(null, new List()); } public void NowhereForProblems_Throws() { CheckThrow(typeof(ArgumentNullException)); Sample().ParseWhatItCan(new string[0], null); } public void GoodArguments_AreReadWithNoProblems() { var problems = new List(); Flags flags = Sample().ParseWhatItCan(new[] { "--level=9" }, problems); CheckEqual(9, flags.Get(SampleFlags.Level)); CheckEqual(0, problems.Count); } public void TheArgumentsAfterAWrongOne_AreStillRead() { Flags flags = Sample().ParseWhatItCan(new[] { "--wibble", "--level=9" }, new List()); CheckEqual(9, flags.Get(SampleFlags.Level)); } public void ABadValue_LeavesTheDefaultAndCountsAsNotGiven() { Flags flags = Sample().ParseWhatItCan(new[] { "--level=x" }, new List()); CheckEqual((int)SampleFlags.Level.DefaultValue, flags.Get(SampleFlags.Level)); CheckFalse(flags.WasGiven(SampleFlags.Level)); } public void AFlagNamedTwice_KeepsTheFirst() { Flags flags = Sample().ParseWhatItCan(new[] { "--level=1", "--level=2" }, new List()); CheckEqual(1, flags.Get(SampleFlags.Level)); } public void EachProblem_IsAddedAfterThoseAlreadyThere() { var problems = new List { "Before." }; Sample().ParseWhatItCan(new[] { "--a", "--level=x" }, problems); CheckEqual(3, problems.Count); CheckEqual("Before.", problems[0]); CheckEqual("There's no flag --a.", problems[1]); CheckEqual("--level needs a whole number, not 'x'.", problems[2]); } } public class UsageTests : TestFixture { public void ListsEachFlagOnALineByName() { var registry = new FlagRegistry(); registry.Register("vsync", "A.Vsync", SampleFlags.Vsync); registry.Register("level", "A.Level", SampleFlags.Level); registry.Register("nameless", "A.Nameless", SampleFlags.Nameless); CheckEqual(string.Join(Environment.NewLine, new[] { "Flags:", " --level= Sets the level. (default: 3)", " --nameless= Has no default.", " --vsync, --novsync Turns vertical sync on. (default: true)", " --help, -h, -? Lists these flags and exits.", "", }), registry.Usage()); } public void ABooleanThatStartsOff_ShowsOnlyItsNameAndNoDefault() { var registry = new FlagRegistry(); registry.Register("quiet", "A.Quiet", SampleFlags.Quiet); CheckEqual(string.Join(Environment.NewLine, new[] { "Flags:", " --quiet Mutes the sound.", " --help, -h, -? Lists these flags and exits.", "", }), registry.Usage()); } public void WithNoFlags_ListsOnlyHelp() { CheckEqual("Flags:" + Environment.NewLine + " --help, -h, -? Lists these flags and exits." + Environment.NewLine, new FlagRegistry().Usage()); } } } }