http://git-wip-us.apache.org/repos/asf/incubator-reef/blob/c1b5200f/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestMultipleInterface.cs ---------------------------------------------------------------------- diff --git a/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestMultipleInterface.cs b/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestMultipleInterface.cs new file mode 100644 index 0000000..e687ef8 --- /dev/null +++ b/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestMultipleInterface.cs @@ -0,0 +1,104 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using Org.Apache.REEF.Tang.Annotations; +using Org.Apache.REEF.Tang.Implementations; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Org.Apache.REEF.Tang.Implementations.Tang; + +namespace Org.Apache.REEF.Tang.Tests.ClassHierarchy +{ + [TestClass] + public class TestMultipleInterface + { + [TestMethod] + public void TestFoo() + { + var ch = TangFactory.GetTang().GetDefaultClassHierarchy(); + var fNode = ch.GetNode(typeof(Org.Apache.REEF.Tang.Tests.ClassHierarchy.Foo)); + var bNode = ch.GetNode(typeof(Org.Apache.REEF.Tang.Tests.ClassHierarchy.Bar)); + var fbNode = ch.GetNode(typeof(Org.Apache.REEF.Tang.Tests.ClassHierarchy.BarFoo)); + } + } + + public class Foo : IObserver<int> + { + [Inject] + public Foo() + { + } + + public void OnCompleted() + { + throw new NotImplementedException(); + } + + public void OnError(Exception error) + { + throw new NotImplementedException(); + } + + public void OnNext(int value) + { + throw new NotImplementedException(); + } + } + + public class Bar : IObserver<string> + { + public void OnCompleted() + { + throw new NotImplementedException(); + } + + public void OnError(Exception error) + { + throw new NotImplementedException(); + } + + public void OnNext(string value) + { + throw new NotImplementedException(); + } + } + + public class BarFoo : IObserver<string>, IObserver<int> + { + public void OnCompleted() + { + throw new NotImplementedException(); + } + + public void OnError(Exception error) + { + throw new NotImplementedException(); + } + + public void OnNext(string value) + { + throw new NotImplementedException(); + } + + public void OnNext(int value) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-reef/blob/c1b5200f/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestParameterParser.cs ---------------------------------------------------------------------- diff --git a/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestParameterParser.cs b/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestParameterParser.cs new file mode 100644 index 0000000..3a335ef --- /dev/null +++ b/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestParameterParser.cs @@ -0,0 +1,325 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +using System; +using Org.Apache.REEF.Tang.Annotations; +using Org.Apache.REEF.Tang.Implementations.ClassHierarchy; +using Org.Apache.REEF.Tang.Interface; +using Org.Apache.REEF.Tang.Util; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Org.Apache.REEF.Tang.Implementations; +using Org.Apache.REEF.Tang.Implementations.Tang; + +namespace Org.Apache.REEF.Tang.Tests.ClassHierarchy +{ + [TestClass] + public class TestParameterParser + { + [TestMethod] + public void ParseIntTest() + { + var parser = new ParameterParser(); + Int32 o = (Int32)parser.Parse(typeof(Int32), "4"); + + } + + [TestMethod] + public void ParseBoolTest() + { + var parser = new ParameterParser(); + Boolean o = (Boolean)parser.Parse(typeof(Boolean), "false"); + } + + [TestMethod] + public void ParseLongTest() + { + var parser = new ParameterParser(); + long o = (long)parser.Parse(typeof(long), "8675309"); + } + + [TestMethod] + public void ParseStringTest() + { + var parser = new ParameterParser(); + string o = (string)parser.Parse(typeof(string), "hello"); + } + + [TestMethod] + public void ParseDoubleTest() + { + var parser = new ParameterParser(); + Double o = (Double)parser.Parse(typeof(double), "12.6"); + } + + [TestMethod] + public void ParseCharTest() + { + var parser = new ParameterParser(); + Char o = (Char)parser.Parse(typeof(char), "c"); + } + + [TestMethod] + public void ParseByteTest() + { + var parser = new ParameterParser(); + Byte o = (Byte)parser.Parse(typeof(byte), "8"); + } + + [TestMethod] + public void ParseShortTest() + { + var parser = new ParameterParser(); + Int16 o = (Int16)parser.Parse(typeof(short), "8"); + } + + [TestMethod] + public void ParseFloatTest() + { + var parser = new ParameterParser(); + Single o = (Single)parser.Parse(typeof(float), "8.567"); + } + + [TestMethod] + public void ParseByteArrayTest() + { + var parser = new ParameterParser(); + byte[] o = (byte[])parser.Parse(typeof(byte[]), "hello"); + } + + [TestMethod] + public void ParameterParserTest() + { + ParameterParser p = new ParameterParser(); + p.AddParser(typeof(FooParser)); + Foo f = (Foo)p.Parse(typeof(Foo), "woot"); + Assert.AreEqual(f.s, "woot"); + } + + [TestMethod] + public void TestUnregisteredParameterParser() + { + ParameterParser p = new ParameterParser(); + + //p.AddParser(typeof(FooParser)); + Foo f = null; + try + { + f = (Foo) p.Parse(typeof (Foo), "woot"); + } + catch (NotSupportedException) + { + } + Assert.IsNull(f); + } + + [TestMethod] + public void TestReturnSubclass() + { + ParameterParser p = new ParameterParser(); + p.AddParser(typeof(BarParser)); + Bar f = (Bar)p.Parse(typeof(Foo), "woot"); + Assert.AreEqual(f.s, "woot"); + } + + [TestMethod] + public void TestGoodMerge() + { + ParameterParser old = new ParameterParser(); + old.AddParser(typeof(BarParser)); + ParameterParser nw = new ParameterParser(); + nw.MergeIn(old); + Bar f = (Bar)nw.Parse(typeof(Foo), "woot"); + Assert.AreEqual(f.s, "woot"); + } + + [TestMethod] + public void TestGoodMerge2() + { + ParameterParser old = new ParameterParser(); + old.AddParser(typeof(BarParser)); + ParameterParser nw = new ParameterParser(); + nw.AddParser(typeof(BarParser)); + nw.MergeIn(old); + Bar f = (Bar)nw.Parse(typeof(Foo), "woot"); + Assert.AreEqual(f.s, "woot"); + } + + [TestMethod] + public void TestBadMerge() + { + string msg = null; + try + { + ParameterParser old = new ParameterParser(); + old.AddParser(typeof(BarParser)); + ParameterParser nw = new ParameterParser(); + nw.AddParser(typeof(FooParser)); + nw.MergeIn(old); + msg = "Conflict detected when merging parameter parsers! To parse org.apache.reef.tang.implementation.java.TestParameterParser$Foo I have a: TestParameterParser$FooParser the other instance has a: TestParameterParser$BarParser"; + } + catch (ArgumentException) + { + } + Assert.IsNull(msg); + } + + [TestMethod] + public void testEndToEnd() + { + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new Type[] {typeof(BarParser) }); + cb.BindNamedParameter<SomeNamedFoo, Foo>(GenericType<SomeNamedFoo>.Class, "hdfs://woot"); + ILikeBars ilb = tang.NewInjector(cb.Build()).GetInstance<ILikeBars>(); + Assert.IsNotNull(ilb); + } + + [TestMethod] + public void TestDelegatingParser() + { + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { }, new IConfiguration[] { }, new Type[] { typeof(TypeParser) }); + + ICsConfigurationBuilder cb2 = tang.NewConfigurationBuilder(new IConfiguration[] { cb.Build() }); + + cb2.BindNamedParameter<ParseName, ParseableType>(GenericType<ParseName>.Class, "a"); //ParseName : Name<ParseableType> + + ParseableType t = (ParseableType)tang.NewInjector(cb2.Build()).GetNamedInstance(typeof(ParseName)); + Assert.IsTrue(t is ParseTypeA); + + cb2 = tang.NewConfigurationBuilder(cb.Build()); + cb2.BindNamedParameter<ParseNameB, ParseTypeB>(GenericType<ParseNameB>.Class, "b"); //ParseNameB : Name<ParseTypeB : ParseableType> + cb2.BindNamedParameter<ParseNameA, ParseableType>(GenericType<ParseNameA>.Class, "a"); //ParseNameA : Name<ParseableType> + + tang.NewInjector(cb2.Build()).GetInstance(typeof(NeedsA)); + tang.NewInjector(cb2.Build()).GetInstance(typeof(NeedsB)); + } + + class FooParser : IExternalConstructor<Foo> + { + private Foo foo; + [Inject] + public FooParser(string s) + { + this.foo = new Foo(s); + } + + public Foo NewInstance() + { + return foo; + } + } + + class BarParser : IExternalConstructor<Foo> + { + private Bar bar; + [Inject] + public BarParser(String s) + { + this.bar = new Bar(s); + } + public Foo NewInstance() + { + return bar; + } + } + + class Foo + { + public readonly string s; + public Foo(string s) { this.s = s; } + } + class Bar : Foo + { + public Bar(string s) : base(s) { } + } + + [NamedParameter] + class SomeNamedFoo : Name<Foo> { } + + class ILikeBars + { + [Inject] + ILikeBars([Parameter(typeof(SomeNamedFoo))] Foo bar) + { + Bar b = (Bar)bar; + Assert.AreEqual(b.s, "hdfs://woot"); + } + } + + class ParseableType + { + } + + class ParseTypeA : ParseableType + { + } + + class ParseTypeB : ParseableType + { + } + + class TypeParser : IExternalConstructor<ParseableType> + { + ParseableType instance; + [Inject] + public TypeParser(String s) + { + if (s.Equals("a")) { instance = new ParseTypeA(); } + if (s.Equals("b")) { instance = new ParseTypeB(); } + } + + public ParseableType NewInstance() + { + return instance; + } + } + + [NamedParameter] + class ParseName : Name<ParseableType> + { + } + + [NamedParameter] + class ParseNameA : Name<ParseableType> + { + } + + [NamedParameter] + class ParseNameB : Name<ParseTypeB> + { + } + + class NeedsA + { + [Inject] + public NeedsA([Parameter(typeof(ParseNameA))] ParseableType a) + { + Assert.IsTrue(a is ParseTypeA); + } + } + + class NeedsB + { + [Inject] + public NeedsB([Parameter(typeof(ParseNameB))] ParseTypeB b) + { + Assert.IsTrue(b is ParseTypeB); + } + } + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-reef/blob/c1b5200f/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestSerilization.cs ---------------------------------------------------------------------- diff --git a/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestSerilization.cs b/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestSerilization.cs new file mode 100644 index 0000000..ee13cb3 --- /dev/null +++ b/lang/cs/Org.Apache.REEF.Tang.Tests/ClassHierarchy/TestSerilization.cs @@ -0,0 +1,236 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +using System; +using System.Collections.Generic; +using System.Reflection; +using Org.Apache.REEF.Tasks; +using Org.Apache.REEF.Tang.Implementations; +using Org.Apache.REEF.Tang.Interface; +using Org.Apache.REEF.Tang.Protobuf; +using Org.Apache.REEF.Tang.Types; +using Org.Apache.REEF.Tang.Util; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Org.Apache.REEF.Tang.Examples; +using Org.Apache.REEF.Tang.Implementations.InjectionPlan; +using Org.Apache.REEF.Tang.Implementations.Tang; + +namespace Org.Apache.REEF.Tang.Tests.ClassHierarchy +{ + [TestClass] + public class TestSerilization + { + static Assembly asm = null; + + [ClassInitialize] + public static void ClassSetup(TestContext context) + { + asm = Assembly.Load(FileNames.Examples); + Assembly.Load(FileNames.Examples); + } + + [ClassCleanup] + public static void ClassCleanup() + { + } + + [TestInitialize()] + public void TestSetup() + { + } + + [TestCleanup()] + public void TestCleanup() + { + } + + [TestMethod] + public void TestSerializeClassHierarchy() + { + IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(Timer).Assembly.GetName().Name }); + ProtocolBufferClassHierarchy.Serialize("node.bin", ns); + } + + [TestMethod] + public void TestDeSerializeClassHierarchy() + { + Type timerType = typeof (Timer); + Type SecondType = typeof (Timer.Seconds); + Type simpleCOnstuctorType = typeof (SimpleConstructors); + + IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(Timer).Assembly.GetName().Name }); + IClassNode timerClassNode = (IClassNode)ns.GetNode(timerType.AssemblyQualifiedName); + INode secondNode = (INode)ns.GetNode(SecondType.AssemblyQualifiedName); + IClassNode SimpleConstructorsClassNode = (IClassNode)ns.GetNode(simpleCOnstuctorType.AssemblyQualifiedName); + + ProtocolBufferClassHierarchy.Serialize("node.bin", ns); + IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("node.bin"); + + IClassNode timerClassNode2 = (IClassNode)ch.GetNode(timerType.AssemblyQualifiedName); + INode secondNode2 = ch.GetNode(SecondType.AssemblyQualifiedName); + IClassNode SimpleConstructorsClassNode2 = (IClassNode)ch.GetNode(simpleCOnstuctorType.AssemblyQualifiedName); + + Assert.AreEqual(timerClassNode.GetFullName(), timerClassNode2.GetFullName()); + Assert.AreEqual(secondNode.GetFullName(), secondNode2.GetFullName()); + Assert.AreEqual(SimpleConstructorsClassNode.GetFullName(), SimpleConstructorsClassNode2.GetFullName()); + + Assert.IsTrue(SimpleConstructorsClassNode2.GetChildren().Count == 0); + IList<IConstructorDef> def = SimpleConstructorsClassNode2.GetInjectableConstructors(); + Assert.AreEqual(3, def.Count); + } + + [TestMethod] + public void TestDeSerializeClassHierarchyForTask() + { + Type streamTask1Type = typeof (Org.Apache.REEF.Tasks.StreamTask1); + Type helloTaskType = typeof (Org.Apache.REEF.Tasks.HelloTask); + + IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(Org.Apache.REEF.Tasks.HelloTask).Assembly.GetName().Name }); + IClassNode StreamTask1ClassNode = (IClassNode)ns.GetNode(streamTask1Type.AssemblyQualifiedName); + IClassNode HelloTaskClassNode = (IClassNode)ns.GetNode(helloTaskType.AssemblyQualifiedName); + + ProtocolBufferClassHierarchy.Serialize("task.bin", ns); + IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("task.bin"); + IClassNode StreamTask1ClassNode2 = (IClassNode)ch.GetNode(streamTask1Type.AssemblyQualifiedName); + IClassNode HelloTaskClassNode2 = (IClassNode)ch.GetNode(helloTaskType.AssemblyQualifiedName); + + Assert.AreEqual(StreamTask1ClassNode.GetFullName(), StreamTask1ClassNode2.GetFullName()); + Assert.AreEqual(HelloTaskClassNode.GetFullName(), HelloTaskClassNode2.GetFullName()); + } + + [TestMethod] + [DeploymentItem(@".")] + public void TestDeSerializeClassHierarchyFromJava() + { + //the file comes from Java TestClassHierarchyRoundTrip SetUp3 testSimpleConstructors + IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("simpleConstructorJavaProto.bin"); + IClassNode simpleConstructorNode = (IClassNode)ch.GetNode("org.apache.reef.tang.implementation.SimpleConstructors"); + Assert.AreEqual(simpleConstructorNode.GetChildren().Count, 0); + Assert.AreEqual(simpleConstructorNode.GetInjectableConstructors().Count, 3); + } + + [TestMethod] + public void TestSerializeClassHierarchyForAvro() + { + IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(Microsoft.Hadoop.Avro.AvroSerializer).Assembly.GetName().Name }); + Assert.IsNotNull(ns); + ProtocolBufferClassHierarchy.Serialize("avro.bin", ns); + IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("avro.bin"); + Assert.IsNotNull(ch); + } + + [TestMethod] + public void TestDeSerializeClassHierarchyAndBind() + { + Type streamTask1Type = typeof(Org.Apache.REEF.Tasks.StreamTask1); + Type helloTaskType = typeof(Org.Apache.REEF.Tasks.HelloTask); + + IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(Org.Apache.REEF.Tasks.HelloTask).Assembly.GetName().Name }); + IClassNode StreamTask1ClassNode = (IClassNode)ns.GetNode(streamTask1Type.AssemblyQualifiedName); + IClassNode HelloTaskClassNode = (IClassNode)ns.GetNode(helloTaskType.AssemblyQualifiedName); + + ProtocolBufferClassHierarchy.Serialize("task.bin", ns); + IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("task.bin"); + IClassNode StreamTask1ClassNode2 = (IClassNode)ch.GetNode(streamTask1Type.AssemblyQualifiedName); + IClassNode HelloTaskClassNode2 = (IClassNode)ch.GetNode(helloTaskType.AssemblyQualifiedName); + + Assert.AreEqual(StreamTask1ClassNode.GetName(), StreamTask1ClassNode2.GetName()); + Assert.AreEqual(HelloTaskClassNode.GetName(), HelloTaskClassNode2.GetName()); + + //have to use original class hierarchy for the merge. ClassHierarchy from ProtoBuffer doesn't support merge. + IConfigurationBuilder cb = TangFactory.GetTang() + .NewConfigurationBuilder(ns); + cb.AddConfiguration(TaskConfiguration.ConfigurationModule + .Set(TaskConfiguration.Identifier, "Hello_From_Streaming1") + .Set(TaskConfiguration.Task, GenericType<Org.Apache.REEF.Tasks.StreamTask1>.Class) + .Build()); + + IConfiguration taskConfiguration = cb.Build(); + StreamTask1 st = TangFactory.GetTang().NewInjector(taskConfiguration).GetInstance<StreamTask1>(); + Assert.IsNotNull(st); + } + + [TestMethod] + public void TestSerirializeInjectionPlanForTimer() + { + Type timerType = typeof(Timer); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); + cb.BindNamedParameter<Timer.Seconds, Int32>(GenericType < Timer.Seconds>.Class, "2"); + IConfiguration conf = cb.Build(); + IInjector injector = tang.NewInjector(conf); + InjectionPlan ip = injector.GetInjectionPlan(timerType); + ProtocolBufferInjectionPlan.Serialize("timerplan.bin", ip); + var ch = conf.GetClassHierarchy(); + var ip1 = ProtocolBufferInjectionPlan.DeSerialize("timerplan.bin", ch); + Assert.IsNotNull(ip1); + } + + [TestMethod] + public void TestSerirializeInjectionPlanForSimpleConstructor() + { + Type simpleConstructorType = typeof(SimpleConstructors); + + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); + IConfiguration conf = cb.Build(); + IInjector injector = tang.NewInjector(conf); + InjectionPlan ip = injector.GetInjectionPlan(simpleConstructorType); + + ProtocolBufferInjectionPlan.Serialize("plan.bin", ip); + var ch = conf.GetClassHierarchy(); + var ipRecovered = ProtocolBufferInjectionPlan.DeSerialize("plan.bin", ch); + Assert.IsNotNull(ipRecovered); + } + + [TestMethod] + public void TestGenericClass() + { + IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(Timer).Assembly.GetName().Name }); + + Type t = typeof(Timer); + IClassNode EventClassNode = (IClassNode)ns.GetNode(t.AssemblyQualifiedName); + ProtocolBufferClassHierarchy.Serialize("event.bin", ns); + IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("event.bin"); + IClassNode EventClassNode1 = (IClassNode)ns.GetNode(t.AssemblyQualifiedName); + Assert.AreEqual(EventClassNode.GetName(), EventClassNode1.GetName()); + } + + [TestMethod] + public void TestGenericArgument() + { + IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(ClassWithGenericArgument<>).Assembly.GetName().Name }); + + Type t = typeof(ClassWithGenericArgument<>); + IClassNode classNode = (IClassNode)ns.GetNode(t.AssemblyQualifiedName); + var cons = classNode.GetAllConstructors(); + foreach (var c in cons) + { + var args = c.GetArgs(); + foreach (var a in args) + { + Assert.IsNotNull(a.GetName()); + } + } + ProtocolBufferClassHierarchy.Serialize("generic.bin", ns); + IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("generic.bin"); + IClassNode classNode1 = (IClassNode)ns.GetNode(t.AssemblyQualifiedName); + Assert.AreEqual(classNode.GetName(), classNode1.GetName()); + } + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-reef/blob/c1b5200f/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestAvroConfiguration.cs ---------------------------------------------------------------------- diff --git a/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestAvroConfiguration.cs b/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestAvroConfiguration.cs new file mode 100644 index 0000000..4d2fbd3 --- /dev/null +++ b/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestAvroConfiguration.cs @@ -0,0 +1,69 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using Org.Apache.REEF.Tasks; +using Org.Apache.REEF.Tang.Formats; +using Org.Apache.REEF.Tang.Implementations; +using Org.Apache.REEF.Tang.Interface; +using Org.Apache.REEF.Tang.Util; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Org.Apache.REEF.Tang.Implementations.Tang; + +namespace Org.Apache.REEF.Tang.Tests.Configuration +{ + [TestClass] + public class TestAvroConfiguration + { + [TestMethod] + public void TestFromJsonString() + { + IConfigurationSerializer serializerImpl = (IConfigurationSerializer)TangFactory.GetTang().NewInjector().GetInstance(typeof(IConfigurationSerializer)); + + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); + IConfiguration conf = cb.Build(); + string jsonStr = serializerImpl.ToString(conf); + + IConfiguration c = serializerImpl.FromString(jsonStr); + Assert.IsNotNull(c); + + string jsonStr2 = serializerImpl.ToString(c); + + IConfiguration c1 = serializerImpl.FromString(jsonStr2); + Assert.IsNotNull(c1); + } + + private AvroConfiguration ToAvroConfiguration() + { + var a = new AvroConfiguration(); + HashSet<ConfigurationEntry> b = new HashSet<ConfigurationEntry>(); + ConfigurationEntry e1 = new ConfigurationEntry(); + e1.key = "a"; + e1.value = "a1"; + ConfigurationEntry e2 = new ConfigurationEntry(); + e2.key = "b"; + e2.value = "b1=b2"; + b.Add(e1); + b.Add(e2); + a.Bindings = b; + return a; + } + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-reef/blob/c1b5200f/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestAvroSerializerRoundTrip.cs ---------------------------------------------------------------------- diff --git a/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestAvroSerializerRoundTrip.cs b/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestAvroSerializerRoundTrip.cs new file mode 100644 index 0000000..4551a52 --- /dev/null +++ b/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestAvroSerializerRoundTrip.cs @@ -0,0 +1,71 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using Org.Apache.REEF.Tang.Formats; +using Org.Apache.REEF.Tang.Interface; +using Org.Apache.REEF.Tang.Tests.SmokeTest; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Org.Apache.REEF.Tang.Tests.Configuration +{ + internal class TestAvroSerializerRoundTrip + { + [TestClass] + public class AvroConfigurationTest : RoundTripTest + { + public override IConfiguration RoundTrip(IConfiguration configuration) + { + AvroConfiguration aConf = new AvroConfigurationSerializer().ToAvroConfiguration(configuration); + return new AvroConfigurationSerializer().FromAvro(aConf); + } + } + + [TestClass] + public class ByteArrayTest : RoundTripTest + { + public override IConfiguration RoundTrip(IConfiguration configuration) + { + AvroConfigurationSerializer serializer = new AvroConfigurationSerializer(); + byte[] theBytes = serializer.ToByteArray(configuration); + return serializer.FromByteArray(theBytes); + } + } + + [TestClass] + public class FileTest : RoundTripTest + { + public override IConfiguration RoundTrip(IConfiguration configuration) + { + AvroConfigurationSerializer serializer = new AvroConfigurationSerializer(); + serializer.ToFile(configuration, "TangTest.avroconf"); + return serializer.FromFile("TangTest.avroconf"); + } + } + + [TestClass] + public class StringTest : RoundTripTest + { + public override IConfiguration RoundTrip(IConfiguration configuration) + { + AvroConfigurationSerializer serializer = new AvroConfigurationSerializer(); + return serializer.FromString(serializer.ToString(configuration)); + } + } + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-reef/blob/c1b5200f/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestConfiguration.cs ---------------------------------------------------------------------- diff --git a/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestConfiguration.cs b/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestConfiguration.cs new file mode 100644 index 0000000..654c132 --- /dev/null +++ b/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestConfiguration.cs @@ -0,0 +1,568 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +using System; +using System.Collections.Generic; +using System.Reflection; +using Org.Apache.REEF.Tasks; +using Org.Apache.REEF.Tang.Annotations; +using Org.Apache.REEF.Tang.Examples; +using Org.Apache.REEF.Tang.Exceptions; +using Org.Apache.REEF.Tang.Formats; +using Org.Apache.REEF.Tang.Implementations; +using Org.Apache.REEF.Tang.Implementations.Configuration; +using Org.Apache.REEF.Tang.Interface; +using Org.Apache.REEF.Tang.Protobuf; +using Org.Apache.REEF.Tang.Util; +using Org.Apache.REEF.Tang.Tests.ScenarioTest; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Org.Apache.REEF.Tang.Implementations.ClassHierarchy; +using Org.Apache.REEF.Tang.Implementations.Tang; + +namespace Org.Apache.REEF.Tang.Tests.Configuration +{ + [TestClass] + public class TestConfiguration + { + [ClassInitialize] + public static void ClassSetup(TestContext context) + { + } + + [TestMethod] + public void TestDeserializedConfigMerge() + { + Type activityInterfaceType = typeof(ITask); + ITang tang = TangFactory.GetTang(); + + ICsConfigurationBuilder cb1 = tang.NewConfigurationBuilder(); + cb1.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); + cb1.BindNamedParameter<TaskConfigurationOptions.Identifier, string>( + GenericType<TaskConfigurationOptions.Identifier>.Class, "Hello Task"); + IConfiguration conf1 = cb1.Build(); + var serializer = new AvroConfigurationSerializer(); + serializer.ToFile(conf1, "task.config"); + + ICsConfigurationBuilder cb2 = tang.NewConfigurationBuilder(); + cb2.BindNamedParameter<Timer.Seconds, Int32>(GenericType<Timer.Seconds>.Class, "2"); + IConfiguration conf2 = cb2.Build(); + serializer.ToFile(conf2, "timer.config"); + + ProtocolBufferClassHierarchy.Serialize("TaskTimer.bin", conf1.GetClassHierarchy()); + IClassHierarchy ns = ProtocolBufferClassHierarchy.DeSerialize("TaskTimer.bin"); + + AvroConfiguration taskAvroconfiguration = serializer.AvroDeseriaizeFromFile("task.config"); + IConfiguration taskConfiguration = serializer.FromAvro(taskAvroconfiguration, ns); + + AvroConfiguration timerAvroconfiguration = serializer.AvroDeseriaizeFromFile("timer.config"); + IConfiguration timerConfiguration = serializer.FromAvro(timerAvroconfiguration, ns); + + IConfiguration merged = Configurations.MergeDeserializedConfs(taskConfiguration, timerConfiguration); + + var b = merged.newBuilder().Build(); + } + + [TestMethod] + public void TestActivityConfiguration() + { + Type activityInterfaceType = typeof (ITask); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Common, FileNames.Tasks }); + cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); + cb.BindNamedParameter<TaskConfigurationOptions.Identifier, string>( + GenericType<TaskConfigurationOptions.Identifier>.Class, "Hello Task"); + IConfiguration conf = cb.Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "TaskConf.txt"); + IDictionary<string, string> p = ConfigurationFile.FromFile("TaskConf.txt"); + + ITang tang1 = TangFactory.GetTang(); + ICsConfigurationBuilder cb1 = tang1.NewConfigurationBuilder(new string[] { FileNames.Common, FileNames.Tasks }); + ConfigurationFile.AddConfigurationFromFile(cb1, "TaskConf.txt"); + IConfiguration conf1 = cb1.Build(); + + IInjector injector = tang1.NewInjector(conf1); + var activityRef = (ITask) injector.GetInstance(activityInterfaceType); + Assert.IsNotNull(activityRef); + } + + [TestMethod] + public void TestMultipleConfiguration() + { + Type activityInterfaceType = typeof (ITask); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Common, FileNames.Tasks }); + cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); + cb.BindNamedParameter<TaskConfigurationOptions.Identifier, string>( + GenericType<TaskConfigurationOptions.Identifier>.Class, "Hello Task"); + IConfiguration conf = cb.Build(); + + IConfiguration httpConfiguraiton = HttpHandlerConfiguration.CONF + .Set(HttpHandlerConfiguration.P, GenericType<HttpServerReefEventHandler>.Class) + .Set(HttpHandlerConfiguration.P, GenericType<HttpServerNrtEventHandler>.Class) + .Build(); + + IInjector injector = TangFactory.GetTang().NewInjector(new IConfiguration[] {conf, httpConfiguraiton}); + var activityRef = (ITask) injector.GetInstance(activityInterfaceType); + Assert.IsNotNull(activityRef); + + RuntimeClock clock = injector.GetInstance<RuntimeClock>(); + var rh = clock.ClockRuntimeStartHandler.Get(); + Assert.AreEqual(rh.Count, 1); + } + + [TestMethod] + public void TestActivityConfigWithSeperateAssembly() + { + Type activityInterfaceType = typeof (ITask); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Common, FileNames.Tasks }); + cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); + IConfiguration conf = cb.Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "TaskConf1.txt"); + IDictionary<string, string> p = ConfigurationFile.FromFile("TaskConf1.txt"); + + IInjector injector = tang.NewInjector(new string[] { FileNames.Common, FileNames.Tasks }, "TaskConf1.txt"); + var activityRef = (ITask) injector.GetInstance(activityInterfaceType); + + //combined line sample + var o = (ITask) TangFactory.GetTang() + .NewInjector(new string[] { FileNames.Common, FileNames.Tasks }, "TaskConf1.txt") + .GetInstance(typeof (ITask)); + + Assert.IsNotNull(activityRef); + } + + [TestMethod] + public void TestGetConfgiFromProtoBufClassHierarchy() + { + Type iTaskType = typeof(Org.Apache.REEF.Tasks.ITask); + Type helloTaskType = typeof(Org.Apache.REEF.Tasks.HelloTask); + Type identifierType = typeof (TaskConfigurationOptions.Identifier); + + IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { FileNames.Common, FileNames.Tasks }); + ProtocolBufferClassHierarchy.Serialize("Task.bin", ns); + IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("Task.bin"); + ITang tang = TangFactory.GetTang(); + IConfigurationBuilder cb = tang.NewConfigurationBuilder(ch); + cb.Bind(iTaskType.AssemblyQualifiedName, helloTaskType.AssemblyQualifiedName); + cb.Bind(identifierType.AssemblyQualifiedName, "Hello Task"); + IConfiguration conf = cb.Build(); + ConfigurationFile.WriteConfigurationFile(conf, "taskConf2.txt"); + } + + [TestMethod] + public void TestActivityConfig() + { + Type activityInterfaceType = typeof (ITask); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks }); + cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); + IConfiguration conf = cb.Build(); + ConfigurationFile.WriteConfigurationFile(conf, "TaskConf.txt"); + IDictionary<string, string> p = ConfigurationFile.FromFile("TaskConf.txt"); + + IInjector injector = tang.NewInjector(new string[] { FileNames.Common, FileNames.Tasks }, "TaskConf.txt"); + var activityRef = (ITask) injector.GetInstance(activityInterfaceType); + + Assert.IsNotNull(activityRef); + } + + [TestMethod] + public void TestActivityConfigWithString() + { + Type activityInterfaceType = typeof (ITask); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks }); + cb.BindImplementation(GenericType<ITask>.Class, GenericType<HelloTask>.Class); + IConfiguration conf = cb.Build(); + + string s = ConfigurationFile.ToConfigurationString(conf); + ICsConfigurationBuilder cb2 = tang.NewConfigurationBuilder(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks }); + ConfigurationFile.AddConfigurationFromString(cb2, s); + IConfiguration conf2 = cb2.Build(); + + IInjector injector = tang.NewInjector(conf2); + var activityRef = (ITask) injector.GetInstance(activityInterfaceType); + + Assert.IsNotNull(activityRef); + } + + [TestMethod] + public void TestTweetConfiguration() + { + Type tweeterType = typeof (Tweeter); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); + cb.BindImplementation(GenericType<ITweetFactory>.Class, GenericType<MockTweetFactory>.Class); + cb.BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class); + cb.BindNamedParameter<Tweeter.PhoneNumber, long>(GenericType<Tweeter.PhoneNumber>.Class, "8675309"); + IConfiguration conf = cb.Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "tweeterConf.txt"); + IDictionary<string, string> p = ConfigurationFile.FromFile("tweeterConf.txt"); + ITang tang1 = TangFactory.GetTang(); + ICsConfigurationBuilder cb1 = tang1.NewConfigurationBuilder(new string[] { FileNames.Examples }); + ConfigurationFile.AddConfigurationFromFile(cb1, "tweeterConf.txt"); + IConfiguration conf1 = cb1.Build(); + + IInjector injector = tang1.NewInjector(conf1); + var tweeter = (Tweeter) injector.GetInstance(tweeterType); + tweeter.sendMessage(); + } + + [TestMethod] + public void TestTweetConfig() + { + Type tweeterType = typeof (Tweeter); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); + cb.BindImplementation(GenericType<ITweetFactory>.Class, GenericType<MockTweetFactory>.Class); + cb.BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class); + cb.BindNamedParameter<Tweeter.PhoneNumber, long>(GenericType<Tweeter.PhoneNumber>.Class, "8675309"); + IConfiguration conf = cb.Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "tweeterConf.txt"); + IDictionary<string, string> p = ConfigurationFile.FromFile("tweeterConf.txt"); + + IInjector injector = tang.NewInjector(new string[] { FileNames.Examples }, "tweeterConf.txt"); + var tweeter = (Tweeter) injector.GetInstance(tweeterType); + tweeter.sendMessage(); + } + + + [TestMethod] + public void TestTweetConfigWithAvroThroughFile() + { + Type tweeterType = typeof (Tweeter); + ITang tang = TangFactory.GetTang(); + IConfiguration conf = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }) + .BindImplementation(GenericType<ITweetFactory>.Class, + GenericType<MockTweetFactory>.Class) + .BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class) + .BindNamedParameter<Tweeter.PhoneNumber, long>( + GenericType<Tweeter.PhoneNumber>.Class, "8675309") + .Build(); + + var serializer = new AvroConfigurationSerializer(); + serializer.ToFileStream(conf, "tweeterConfAvro.bin"); + IConfiguration conf2 = serializer.FromFileStream("tweeterConfAvro.bin"); + + IInjector injector = tang.NewInjector(conf2); + var tweeter = (Tweeter) injector.GetInstance(tweeterType); + tweeter.sendMessage(); + } + + [TestMethod] + public void TestTweetConfigAddConfigurationFromString() + { + Type tweeterType = typeof (Tweeter); + ITang tang = TangFactory.GetTang(); + IConfiguration conf = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }) + .BindImplementation(GenericType<ITweetFactory>.Class, + GenericType<MockTweetFactory>.Class) + .BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class) + .BindNamedParameter<Tweeter.PhoneNumber, long>( + GenericType<Tweeter.PhoneNumber>.Class, "8675309") + .Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "tweeterConf.txt"); + string s = ConfigurationFile.ToConfigurationString(conf); + ICsConfigurationBuilder cb2 = tang.NewConfigurationBuilder(); + ConfigurationFile.AddConfigurationFromString(cb2, s); + IConfiguration conf2 = cb2.Build(); + + IInjector injector = tang.NewInjector(conf2); + var tweeter = (Tweeter) injector.GetInstance(tweeterType); + tweeter.sendMessage(); + } + + [TestMethod] + public void TestTweetConfigWithAvroSerialization() + { + Type tweeterType = typeof (Tweeter); + ITang tang = TangFactory.GetTang(); + IConfiguration conf = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }) + .BindImplementation(GenericType<ITweetFactory>.Class, + GenericType<MockTweetFactory>.Class) + .BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class) + .BindNamedParameter<Tweeter.PhoneNumber, long>( + GenericType<Tweeter.PhoneNumber>.Class, "8675309") + .Build(); + + var serializer = new AvroConfigurationSerializer(); + byte[] bytes = serializer.ToByteArray(conf); + IConfiguration conf2 = serializer.FromByteArray(bytes); + + IInjector injector = tang.NewInjector(conf2); + var tweeter = (Tweeter) injector.GetInstance(tweeterType); + tweeter.sendMessage(); + } + + [TestMethod] + public void TestTweetConfigGetConfigurationFromString() + { + Type tweeterType = typeof (Tweeter); + ITang tang = TangFactory.GetTang(); + IConfiguration conf = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }) + .BindImplementation(GenericType<ITweetFactory>.Class, + GenericType<MockTweetFactory>.Class) + .BindImplementation(GenericType<ISMS>.Class, GenericType<MockSMS>.Class) + .BindNamedParameter<Tweeter.PhoneNumber, long>( + GenericType<Tweeter.PhoneNumber>.Class, "8675309") + .Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "tweeterConf.txt"); + string s = ConfigurationFile.ToConfigurationString(conf); + IConfiguration conf2 = ConfigurationFile.GetConfiguration(s); + + IInjector injector = tang.NewInjector(conf2); + var tweeter = (Tweeter) injector.GetInstance(tweeterType); + tweeter.sendMessage(); + } + + [TestMethod] + public void TestTweetInvalidBinding() + { + string msg = null; + try + { + TangFactory.GetTang().NewConfigurationBuilder(new string[] { FileNames.Examples }) + .BindImplementation(typeof (ITweetFactory), typeof (MockSMS)) + .Build(); + } + catch (ArgumentException e) + { + msg = e.Message; + } + Assert.IsNotNull(msg); + } + + [TestMethod] + public void TestTimerConfiguration() + { + Type timerType = typeof (Timer); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); + cb.BindNamedParameter<Timer.Seconds, Int32>(GenericType<Timer.Seconds>.Class, "2"); + IConfiguration conf = cb.Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "timerConf.txt"); + IDictionary<string, string> p = ConfigurationFile.FromFile("timerConf.txt"); + + ITang tang1 = TangFactory.GetTang(); + ICsConfigurationBuilder cb1 = tang1.NewConfigurationBuilder(new string[] { FileNames.Examples }); + ConfigurationFile.AddConfigurationFromFile(cb1, "timerConf.txt"); + IConfiguration conf1 = cb1.Build(); + + IInjector injector = tang.NewInjector(conf1); + var timer = (Timer) injector.GetInstance(timerType); + + Assert.IsNotNull(timer); + + timer.sleep(); + } + + [TestMethod] + public void TestDocumentLoadNamedParameterConfiguration() + { + Type documentedLocalNamedParameterType = typeof (DocumentedLocalNamedParameter); + ITang tang = TangFactory.GetTang(); + ICsConfigurationBuilder cb = tang.NewConfigurationBuilder(new string[] { FileNames.Examples }); + cb.BindNamedParameter<DocumentedLocalNamedParameter.Foo, string>( + GenericType<DocumentedLocalNamedParameter.Foo>.Class, "Hello"); + IConfiguration conf = cb.Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "docLoadConf.txt"); + IDictionary<string, string> p = ConfigurationFile.FromFile("docLoadConf.txt"); + + ITang tang1 = TangFactory.GetTang(); + ICsConfigurationBuilder cb1 = tang1.NewConfigurationBuilder(new string[] { FileNames.Examples }); + ConfigurationFile.AddConfigurationFromFile(cb1, "docLoadConf.txt"); + IConfiguration conf1 = cb1.Build(); + + IInjector injector = tang1.NewInjector(conf1); + var doc = (DocumentedLocalNamedParameter) injector.GetInstance(documentedLocalNamedParameterType); + + Assert.IsNotNull(doc); + var s = doc.ToString(); + } + + [TestMethod] + public void TestTimerConfigurationWithClassHierarchy() + { + Type timerType = typeof (Timer); + ClassHierarchyImpl classHierarchyImpl = new ClassHierarchyImpl(FileNames.Examples); + + ITang tang = TangFactory.GetTang(); + IConfiguration conf = tang.NewConfigurationBuilder(classHierarchyImpl) + .BindNamedParameter<Timer.Seconds, Int32>(GenericType<Timer.Seconds>.Class, "1") + .Build(); + + ConfigurationFile.WriteConfigurationFile(conf, "timerConfH.txt"); + IDictionary<string, string> p = ConfigurationFile.FromFile("timerConfH.txt"); + + ITang tang1 = TangFactory.GetTang(); + ICsConfigurationBuilder cb1 = tang1.NewConfigurationBuilder(new string[] { FileNames.Examples }); + ConfigurationFile.AddConfigurationFromFile(cb1, "timerConfH.txt"); + IConfiguration conf1 = cb1.Build(); + + IInjector injector = tang1.NewInjector(conf1); + var timer = (Timer) injector.GetInstance(timerType); + + Assert.IsNotNull(timer); + timer.sleep(); + } + + [TestMethod] + public void TestSetConfig() + { + IConfiguration conf = TangFactory.GetTang().NewConfigurationBuilder() + .BindSetEntry<SetOfNumbers, string>(GenericType<SetOfNumbers>.Class, "four") + .BindSetEntry<SetOfNumbers, string>(GenericType<SetOfNumbers>.Class, "five") + .BindSetEntry<SetOfNumbers, string>(GenericType<SetOfNumbers>.Class, "six") + .Build(); + + Box b = (Box) TangFactory.GetTang().NewInjector(conf).GetInstance(typeof (Box)); + ConfigurationFile.WriteConfigurationFile(conf, "SetOfNumbersConf.txt"); + + string s = ConfigurationFile.ToConfigurationString(conf); + IConfiguration conf2 = ConfigurationFile.GetConfiguration(s); + + Box b2 = (Box) TangFactory.GetTang().NewInjector(conf2).GetInstance(typeof (Box)); + ISet<string> actual = b2.Numbers; + + Assert.IsTrue(actual.Contains("four")); + Assert.IsTrue(actual.Contains("five")); + Assert.IsTrue(actual.Contains("six")); + } + + [TestMethod] + public void TestSetConfigWithAvroSerialization() + { + IConfiguration conf = TangFactory.GetTang().NewConfigurationBuilder() + .BindSetEntry<SetOfNumbers, string>(GenericType<SetOfNumbers>.Class, "four") + .BindSetEntry<SetOfNumbers, string>(GenericType<SetOfNumbers>.Class, "five") + .BindSetEntry<SetOfNumbers, string>(GenericType<SetOfNumbers>.Class, "six") + .Build(); + + Box b = (Box) TangFactory.GetTang().NewInjector(conf).GetInstance(typeof (Box)); + + var serializer = new AvroConfigurationSerializer(); + byte[] bytes = serializer.ToByteArray(conf); + IConfiguration conf2 = serializer.FromByteArray(bytes); + + Box b2 = (Box) TangFactory.GetTang().NewInjector(conf2).GetInstance(typeof (Box)); + ISet<string> actual = b2.Numbers; + + Assert.IsTrue(actual.Contains("four")); + Assert.IsTrue(actual.Contains("five")); + Assert.IsTrue(actual.Contains("six")); + } + + [TestMethod] + public void TestNullStringVaue() + { + string msg = null; + try + { + TangFactory.GetTang().NewConfigurationBuilder() + .BindNamedParameter<NamedParamterNoDefault.NamedString, string>(GenericType<NamedParamterNoDefault.NamedString>.Class, null) + .Build(); + } + catch (IllegalStateException e) + { + msg = e.Message; + } + Assert.IsNotNull(msg); + } + + [TestMethod] + public void TestSetConfigNullValue() + { + string msg = null; + try + { + TangFactory.GetTang().NewConfigurationBuilder() + .BindSetEntry<SetOfNumbersNoDefault, string>(GenericType<SetOfNumbersNoDefault>.Class, null) + .BindSetEntry<SetOfNumbersNoDefault, string>(GenericType<SetOfNumbersNoDefault>.Class, "five") + .BindSetEntry<SetOfNumbersNoDefault, string>(GenericType<SetOfNumbersNoDefault>.Class, "six") + .Build(); + } + catch (IllegalStateException e) + { + msg = e.Message; + } + Assert.IsNotNull(msg); + } + } + + [NamedParameter(DefaultValues = new string[] {"one", "two", "three"})] + class SetOfNumbers : Name<ISet<string>> + { + } + + class Box + { + public ISet<string> Numbers; + + [Inject] + Box([Parameter(typeof (SetOfNumbers))] ISet<string> numbers) + { + this.Numbers = numbers; + } + } + + [NamedParameter] + class SetOfNumbersNoDefault : Name<ISet<string>> + { + } + + class BoxNoDefault + { + public ISet<string> Numbers; + + [Inject] + BoxNoDefault([Parameter(typeof(SetOfNumbersNoDefault))] ISet<string> numbers) + { + this.Numbers = numbers; + } + } + + class NamedParamterNoDefault + { + private string str; + + [NamedParameter] + public class NamedString : Name<string> + { + } + + [Inject] + NamedParamterNoDefault([Parameter(typeof (NamedString))] string str) + { + this.str = str; + } + + public string GetString() + { + return str; + } + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-reef/blob/c1b5200f/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestCsConfigurationBuilderExtension.cs ---------------------------------------------------------------------- diff --git a/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestCsConfigurationBuilderExtension.cs b/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestCsConfigurationBuilderExtension.cs new file mode 100644 index 0000000..0f01208 --- /dev/null +++ b/lang/cs/Org.Apache.REEF.Tang.Tests/Configuration/TestCsConfigurationBuilderExtension.cs @@ -0,0 +1,179 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using Org.Apache.REEF.Tang.Implementations; +using Org.Apache.REEF.Tang.Interface; +using Org.Apache.REEF.Tang.Util; +using Org.Apache.REEF.Tang.Tests.Injection; +using Org.Apache.REEF.Tang.Tests.Tang; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Org.Apache.REEF.Tang.Implementations.Tang; + +namespace Org.Apache.REEF.Tang.Tests.Configuration +{ + /// <summary> + /// This class is to test extension API defined in ICsConfigurationBuilder + /// </summary> + [TestClass] + public class TestCsConfigurationBuilderExtension + { + [TestMethod] + public void TestBindNamedParameter1() + { + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindNamedParameter<AImplName, Aimpl, INamedImplA>(); + cb.BindNamedParameter<BImplName, Bimpl, INamedImplA>(); + + IInjector i = TangFactory.GetTang().NewInjector(cb.Build()); + Aimpl a1 = (Aimpl)i.GetNamedInstance<AImplName, INamedImplA>(GenericType<AImplName>.Class); + Aimpl a2 = (Aimpl)i.GetNamedInstance<AImplName, INamedImplA>(GenericType<AImplName>.Class); + Bimpl b1 = (Bimpl)i.GetNamedInstance<BImplName, INamedImplA>(GenericType<BImplName>.Class); + Bimpl b2 = (Bimpl)i.GetNamedInstance<BImplName, INamedImplA>(GenericType<BImplName>.Class); + Assert.AreSame(a1, a2); + Assert.AreSame(b1, b2); + } + + [TestMethod] + public void TestBindStringNamedParam() + { + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindStringNamedParam<StringTest.NamedString>("foo"); + IInjector i = TangFactory.GetTang().NewInjector(cb.Build()); + var o = i.GetInstance<StringTest>(); + o.Verify("foo"); + } + + [TestMethod] + public void TestBindIntNamedParam() + { + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindIntNamedParam<Int32Test.NamedInt>("8"); + IInjector i = TangFactory.GetTang().NewInjector(cb.Build()); + var o = i.GetInstance<Int32Test>(); + o.Verify(8); + } + + [TestMethod] + public void TestBindNamedParam() + { + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindNamedParam<BooleanTest.NamedBool, bool>("true"); + IInjector i = TangFactory.GetTang().NewInjector(cb.Build()); + var o = i.GetInstance<BooleanTest>(); + o.Verify(true); + } + + [TestMethod] + public void TestBindSetEntryImplValue() + { + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindSetEntry<TestSetInjection.SetOfClasses, TestSetInjection.Integer1, INumber>() //bind an impl to the interface of the set + .BindIntNamedParam<TestSetInjection.Integer1.NamedInt>("4"); //bind parameter for the impl + + IInjector i = TangFactory.GetTang().NewInjector(cb.Build()); + + ISet<INumber> actual = i.GetInstance<TestSetInjection.Pool>().Numbers; + ISet<INumber> expected = new HashSet<INumber>(); + expected.Add(new TestSetInjection.Integer1(4)); + + Assert.IsTrue(Utilities.Utilities.Equals<INumber>(actual, expected)); + } + + [TestMethod] + public void TestBindSetEntryStringValue() + { + IConfiguration conf = TangFactory.GetTang().NewConfigurationBuilder() + .BindSetEntry<SetOfNumbers, string>("four") + .BindSetEntry<SetOfNumbers, string>("five") + .BindSetEntry<SetOfNumbers, string>("six") + .Build(); + + Box b = (Box)TangFactory.GetTang().NewInjector(conf).GetInstance(typeof(Box)); + ISet<string> actual = b.Numbers; + + Assert.IsTrue(actual.Contains("four")); + Assert.IsTrue(actual.Contains("five")); + Assert.IsTrue(actual.Contains("six")); + } + + [TestMethod] + public void TestBindImplementation() + { + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindImplementation<Interf, Impl>(); + Interf o = TangFactory.GetTang().NewInjector(cb.Build()).GetInstance<Interf>(); + Assert.IsTrue(o is Impl); + } + + [TestMethod] + public void TestBindList() + { + IList<string> injected = new List<string>(); + injected.Add("hi"); + injected.Add("hello"); + injected.Add("bye"); + + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindList<StringList, string>(injected); + + IInjector i = TangFactory.GetTang().NewInjector(cb.Build()); + IList<string> actual = ((StringClass)i.GetInstance(typeof(StringClass))).StringList; + + Assert.IsTrue(actual.Contains("hi")); + Assert.IsTrue(actual.Contains("hello")); + Assert.IsTrue(actual.Contains("bye")); + Assert.AreEqual(actual.Count, 3); + } + + [TestMethod] + public void TestObjectInjectWithInjectableSubclassesMultipleInstances() + { + IList<string> injected = new List<string>(); + injected.Add(typeof(TestSetInjection.Integer1).AssemblyQualifiedName); + injected.Add(typeof(TestSetInjection.Integer1).AssemblyQualifiedName); + injected.Add(typeof(TestSetInjection.Float1).AssemblyQualifiedName); + + ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); + cb.BindIntNamedParam<TestSetInjection.Integer1.NamedInt>("5"); + cb.BindNamedParam<TestSetInjection.Float1.NamedFloat, float>("12.5"); + cb.BindList<ListOfClasses, INumber>(injected); + + IInjector i = TangFactory.GetTang().NewInjector(cb.Build()); + + IList<INumber> actual = ((PoolListClass)i.GetInstance(typeof(PoolListClass))).Numbers; + + Assert.IsTrue(actual.Count == 3); + Assert.IsTrue(actual.Contains(new TestSetInjection.Integer1(5))); + Assert.IsTrue(actual.Contains(new TestSetInjection.Integer1(5))); + Assert.IsTrue(actual.Contains(new TestSetInjection.Float1(12.5f))); + } + + [TestMethod] + public void TestBindConstructor() + { + ICsConfigurationBuilder b = TangFactory.GetTang().NewConfigurationBuilder(); + b.BindConstructor<TestExternalConstructors.A, TestExternalConstructors.ACons>(); + b.BindConstructor<TestExternalConstructors.B, TestExternalConstructors.BCons>(); + + TangFactory.GetTang().NewInjector(b.Build()).GetInstance(typeof(TestExternalConstructors.B)); + TangFactory.GetTang().NewInjector(b.Build()).GetInstance(typeof(TestExternalConstructors.A)); + } + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-reef/blob/c1b5200f/lang/cs/Org.Apache.REEF.Tang.Tests/Format/TestConfigurationModule.cs ---------------------------------------------------------------------- diff --git a/lang/cs/Org.Apache.REEF.Tang.Tests/Format/TestConfigurationModule.cs b/lang/cs/Org.Apache.REEF.Tang.Tests/Format/TestConfigurationModule.cs new file mode 100644 index 0000000..5c56b96 --- /dev/null +++ b/lang/cs/Org.Apache.REEF.Tang.Tests/Format/TestConfigurationModule.cs @@ -0,0 +1,523 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using Org.Apache.REEF.Tang.Annotations; +using Org.Apache.REEF.Tang.Exceptions; +using Org.Apache.REEF.Tang.Formats; +using Org.Apache.REEF.Tang.Implementations; +using Org.Apache.REEF.Tang.Interface; +using Org.Apache.REEF.Tang.Util; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Org.Apache.REEF.Tang.Implementations.Tang; + +namespace Org.Apache.REEF.Tang.Tests.Format +{ + public interface IFoo + { + int getFooness(); + } + + interface ISuper + { + } + + [TestClass] + public class TestConfigurationModule + { + [ClassInitialize] + public static void ClassSetup(TestContext context) + { + } + + [ClassCleanup] + public static void ClassCleanup() + { + } + + [TestInitialize()] + public void TestSetup() + { + } + + [TestCleanup()] + public void TestCleanup() + { + } + + [TestMethod] + public void SmokeTest() + { + // Here we set some configuration values. In true tang style, + // you won't be able to set them more than once ConfigurationModule's + // implementation is complete. + Type fooType = typeof(Org.Apache.REEF.Tang.Tests.Format.IFoo); + + IConfiguration c = MyConfigurationModule.Conf + .Set(MyConfigurationModule.TheFoo, GenericType<FooImpl>.Class) + .Set(MyConfigurationModule.FooNess, "12") + .Build(); + IFoo f = (IFoo)TangFactory.GetTang().NewInjector(c).GetInstance(fooType); + Assert.AreEqual(f.getFooness(), 12); + } + + [TestMethod] + public void SmokeTestConfig() + { + // Here we set some configuration values. In true tang style, + // you won't be able to set them more than once ConfigurationModule's + // implementation is complete. + Type fooType = typeof(Org.Apache.REEF.Tang.Tests.Format.IFoo); + + IConfiguration c = MyConfigurationModule.Conf + .Set(MyConfigurationModule.TheFoo, GenericType<FooImpl>.Class) + .Set(MyConfigurationModule.FooNess, "12") + .Build(); + IFoo f = (IFoo)TangFactory.GetTang().NewInjector(c).GetInstance(fooType); + Assert.AreEqual(f.getFooness(), 12); + AvroConfigurationSerializer serializerCs = new AvroConfigurationSerializer(); + + serializerCs.ToFileStream(c, "TangTestCs.avroconf"); + var c3 = serializerCs.FromFileStream("TangTestCs.avroconf"); + IFoo f3 = (IFoo)TangFactory.GetTang().NewInjector(c3).GetInstance(fooType); + Assert.AreEqual(f3.getFooness(), 12); + + serializerCs.ToFile(c, "TangTestCs1.avro"); + var c4 = serializerCs.FromFile("TangTestCs1.avro"); + IFoo f4 = (IFoo)TangFactory.GetTang().NewInjector(c4).GetInstance(fooType); + Assert.AreEqual(f4.getFooness(), 12); + + IConfigurationSerializer serializerImpl = (IConfigurationSerializer)TangFactory.GetTang().NewInjector().GetInstance(typeof(IConfigurationSerializer)); + serializerImpl.ToFile(c, "TangTestCs1.avro"); + var c5 = serializerImpl.FromFile("TangTestCs1.avro"); + IFoo f5 = (IFoo)TangFactory.GetTang().NewInjector(c5).GetInstance(fooType); + Assert.AreEqual(f5.getFooness(), 12); + + //this is to test the file generated from Java. name,value b=must be recognized by C# class hierarchy + AvroConfigurationSerializer serializer = new AvroConfigurationSerializer(); + var avroConfig = serializer.AvroDeseriaizeFromFile("Evaluator.conf"); + Assert.IsNotNull(avroConfig); + } + + [TestMethod] + public void OmitOptionalTest() + { + Type fooType = typeof(Org.Apache.REEF.Tang.Tests.Format.IFoo); + + IConfiguration c = MyConfigurationModule.Conf + .Set(MyConfigurationModule.TheFoo, GenericType<FooImpl>.Class) + .Build(); + IFoo f = (IFoo)TangFactory.GetTang().NewInjector(c).GetInstance(fooType); + Assert.AreEqual(f.getFooness(), 42); + } + + [TestMethod] + public void OmitRequiredTest() + { + string msg = null; + try + { + MyConfigurationModule.Conf + .Set(MyConfigurationModule.FooNess, "12") + .Build(); + msg = "Attempt to build configuration before setting required option(s): { THE_FOO }"; + } + catch (Exception) + { + } + Assert.IsNull(msg); + } + + [TestMethod] + public void BadConfTest() + { + string msg = null; + try + { + object obj = MyMissingBindConfigurationModule.BadConf; + msg = "Found declared options that were not used in binds: { FOO_NESS }" + obj; + } + catch (Exception) + { + } + Assert.IsNull(msg); + } + + [TestMethod] + public void NonExistentStringBindOK() + { + new MyBadConfigurationModule().BindImplementation(GenericType<IFoo>.Class, "i.do.not.exist"); + } + + [TestMethod] + public void NonExistentStringBindNotOK() + { + string msg = null; + try + { + new MyBadConfigurationModule().BindImplementation(GenericType<IFoo>.Class, "i.do.not.exist").Build(); + msg = "ConfigurationModule refers to unknown class: i.do.not.exist"; + } + catch (Exception) + { + } + Assert.IsNull(msg); + } + + [TestMethod] + public void MultiBindTest() + { + // Here we set some configuration values. In true tang style, + // you won't be able to set them more than once ConfigurationModule's + // implementation is complete. + IConfiguration c = MultiBindConfigurationModule.Conf + .Set(MultiBindConfigurationModule.TheFoo, GenericType<FooImpl>.Class) + .Set(MultiBindConfigurationModule.FOONESS, "12") + .Build(); + IFoo f = (IFoo)TangFactory.GetTang().NewInjector(c).GetInstance(typeof(IFoo)); + IFoo g = (IFoo)TangFactory.GetTang().NewInjector(c).GetInstance(typeof(object)); + Assert.AreEqual(f.getFooness(), 12); + Assert.AreEqual(g.getFooness(), 12); + Assert.IsFalse(f == g); + } + + [TestMethod] + public void ForeignSetTest() + { + string msg = null; + try + { + MultiBindConfigurationModule.Conf.Set(MyConfigurationModule.TheFoo, GenericType<FooImpl>.Class); + msg = "Unknown Impl/Param when setting RequiredImpl. Did you pass in a field from some other module?"; + } + catch (Exception) + { + } + Assert.IsNull(msg); + } + + [TestMethod] + public void ForeignBindTest() + { + string msg = null; + try + { + new MyConfigurationModule().BindImplementation(GenericType<object>.Class, MultiBindConfigurationModule.TheFoo); + msg = "Unknown Impl/Param when binding RequiredImpl. Did you pass in a field from some other module?"; + } + catch (Exception) + { + } + Assert.IsNull(msg); + } + + [TestMethod] + public void SingletonTest() + { + IConfiguration c = new MyConfigurationModule() + .BindImplementation(GenericType<IFoo>.Class, MyConfigurationModule.TheFoo) + .BindNamedParameter(GenericType<Fooness>.Class, MyConfigurationModule.FooNess) + .Build() + .Set(MyConfigurationModule.TheFoo, GenericType<FooImpl>.Class) + .Build(); + IInjector i = TangFactory.GetTang().NewInjector(c); + Assert.IsTrue(i.GetInstance(typeof(IFoo)) == i.GetInstance(typeof(IFoo))); + } + + [TestMethod] + public void ImmutablilityTest() + { + // builder methods return copies; the original module is immutable + ConfigurationModule builder1 = MyConfigurationModule.Conf + .Set(MyConfigurationModule.TheFoo, GenericType<FooImpl>.Class); + + Assert.IsFalse(builder1 == MyConfigurationModule.Conf); + + IConfiguration config1 = builder1.Build(); + + // reusable + IConfiguration config2 = MyConfigurationModule.Conf + .Set(MyConfigurationModule.TheFoo, GenericType<FooAltImpl>.Class) + .Build(); + + // instantiation of each just to be sure everything is fine in this situation + IInjector i1 = TangFactory.GetTang().NewInjector(config1); + IInjector i2 = TangFactory.GetTang().NewInjector(config2); + Assert.AreEqual(42, ((IFoo)i1.GetInstance(typeof(IFoo))).getFooness()); + Assert.AreEqual(7, ((IFoo)i2.GetInstance(typeof(IFoo))).getFooness()); + } + + [TestMethod] + public void SetParamTest() + { + IConfiguration c = SetConfigurationModule.CONF + .Set(SetConfigurationModule.P, "a") + .Set(SetConfigurationModule.P, "b") + .Build(); + + ISet<string> s = (ISet<string>)TangFactory.GetTang().NewInjector(c).GetNamedInstance(typeof(SetName)); + Assert.AreEqual(s.Count, 2); + Assert.IsTrue(s.Contains("a")); + Assert.IsTrue(s.Contains("b")); + } + + [TestMethod] + public void SetClassTest() + { + IConfiguration c = SetClassConfigurationModule.CONF + .Set(SetClassConfigurationModule.P, GenericType<SubA>.Class) + .Set(SetClassConfigurationModule.P, GenericType<SubB>.Class) + .Build(); + ISet<ISuper> s = (ISet<ISuper>)TangFactory.GetTang().NewInjector(c).GetNamedInstance(typeof(SetClass)); + Assert.AreEqual(2, s.Count); + + bool sawA = false, sawB = false; + foreach (ISuper sup in s) + { + if (sup is SubA) + { + sawA = true; + } + else if (sup is SubB) + { + sawB = true; + } + else + { + Assert.Fail(); + } + } + Assert.IsTrue(sawA && sawB); + } + + [TestMethod] + public void SetClassRoundTripTest() + { + IConfiguration c = SetClassConfigurationModule.CONF + .Set(SetClassConfigurationModule.P, GenericType<SubA>.Class) + .Set(SetClassConfigurationModule.P, GenericType<SubB>.Class) + .Build(); + IConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(c); + + AvroConfigurationSerializer serializer = new AvroConfigurationSerializer(); + IConfiguration c2 = serializer.FromString(serializer.ToString(cb.Build())); + + //ConfigurationFile.AddConfiguration(cb, ConfigurationFile.ToConfigurationString(c)); + ISet<ISuper> s = (ISet<ISuper>)TangFactory.GetTang().NewInjector(c2).GetNamedInstance(typeof(SetClass)); + Assert.AreEqual(2, s.Count); + bool sawA = false, sawB = false; + foreach (ISuper sup in s) + { + if (sup is SubA) + { + sawA = true; + } + else if (sup is SubB) + { + sawB = true; + } + else + { + Assert.Fail(); + } + } + Assert.IsTrue(sawA && sawB); + } + + [TestMethod] + public void ErrorOnStaticTimeSet() + { + string msg = null; + try + { + StaticTimeSet.CONF.AssertStaticClean(); + msg = + " Detected statically set ConfigurationModule Parameter / Implementation. set() should only be used dynamically. Use bind...() instead."; + } + catch (ClassHierarchyException) + { + } + Assert.IsNull(msg); + } + + [TestMethod] + public void ErrorOnSetMerge() + { + ConfigurationModuleBuilder cb = null; + try + { + ConfigurationModuleBuilder b = new ConfigurationModuleBuilder(); + cb = b.Merge(StaticTimeSet.CONF); + } + catch (ClassHierarchyException e) + { + System.Diagnostics.Debug.WriteLine(e); + } + Assert.IsNull(cb); + } + } + + [NamedParameter("Fooness", "Fooness", "42")] + public class Fooness : Name<int> + { + } + + public class FooImpl : IFoo + { + private readonly int fooness; + + [Inject] + FooImpl([Parameter(typeof(Fooness))] int fooness) + { + this.fooness = fooness; + } + + public int getFooness() + { + return this.fooness; + } + } + + public class FooAltImpl : IFoo + { + private readonly int fooness; + + [Inject] + FooAltImpl([Parameter(Value = typeof(Fooness))] int fooness) + { + this.fooness = fooness; + } + + public int getFooness() + { + return 7; + } + } + + public sealed class MyConfigurationModule : ConfigurationModuleBuilder + { + // Tell us what implementation you want, or else!! + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly RequiredImpl<IFoo> TheFoo = new RequiredImpl<IFoo>(); + + // If you want, you can change the fooness. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly OptionalParameter<int> FooNess = new OptionalParameter<int>(); + + // This binds the above to tang configuration stuff. You can use parameters more than + // once, but you'd better use them all at least once, or I'll throw exceptions at you. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly ConfigurationModule Conf = new MyConfigurationModule() + .BindImplementation(GenericType<IFoo>.Class, MyConfigurationModule.TheFoo) + .BindNamedParameter(GenericType<Fooness>.Class, MyConfigurationModule.FooNess) + .Build(); + } + + public class MyMissingBindConfigurationModule : ConfigurationModuleBuilder + { + // Tell us what implementation you want, or else!! + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly RequiredImpl<IFoo> TheFoo = new RequiredImpl<IFoo>(); + + // If you want, you can change the fooness. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly OptionalParameter<int> FooNess = new OptionalParameter<int>(); + + // This conf doesn't use FOO_NESS. Expect trouble below + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly ConfigurationModule BadConf = new MyMissingBindConfigurationModule() + .BindImplementation(GenericType<IFoo>.Class, MyMissingBindConfigurationModule.TheFoo) + .Build(); + } + + public class MyBadConfigurationModule : ConfigurationModuleBuilder + { + } + + public class MultiBindConfigurationModule : ConfigurationModuleBuilder + { + // Tell us what implementation you want, or else!! + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly RequiredImpl<IFoo> TheFoo = new RequiredImpl<IFoo>(); + + // If you want, you can change the fooness. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly OptionalParameter<int> FOONESS = new OptionalParameter<int>(); + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Required by Tang")] + public static readonly ConfigurationModule Conf = new MultiBindConfigurationModule() + .BindImplementation(GenericType<IFoo>.Class, MultiBindConfigurationModule.TheFoo) + .BindImplementation(GenericType<object>.Class, MultiBindConfigurationModule.TheFoo) + .BindNamedParameter(GenericType<Fooness>.Class, MultiBindConfigurationModule.FOONESS) + .Build(); + } + + [NamedParameter] + class SetName : Name<ISet<string>> + { + } + + class SetConfigurationModule : ConfigurationModuleBuilder + { + public static readonly RequiredParameter<string> P = new RequiredParameter<string>(); + + public static readonly ConfigurationModule CONF = new SetConfigurationModule() + .BindSetEntry(GenericType<SetName>.Class, SetConfigurationModule.P) + .Build(); + } + + [NamedParameter] + class SetClass : Name<ISet<ISuper>> + { + } + + class SetClassConfigurationModule : ConfigurationModuleBuilder + { + public static readonly RequiredParameter<ISuper> P = new RequiredParameter<ISuper>(); + public static readonly ConfigurationModule CONF = new SetClassConfigurationModule() + .BindSetEntry(GenericType<SetClass>.Class, SetClassConfigurationModule.P) + .Build(); + } + + class SubA : ISuper + { + [Inject] + public SubA() + { + } + } + + class SubB : ISuper + { + [Inject] + public SubB() + { + } + } + + class StaticTimeSet : ConfigurationModuleBuilder + { + public static readonly OptionalImpl<ISuper> X = new OptionalImpl<ISuper>(); + public static readonly ConfigurationModule CONF = new StaticTimeSet() + .BindImplementation(GenericType<ISuper>.Class, X) + .Build() + .Set(X, GenericType<SubA>.Class); + } +} \ No newline at end of file
