Beispiel #1
0
 public void CanReadShouldBeFalseIfAbilityIsNotDefined()
 {
     new MockAbility().Initialize( new MockUser() );
     var resource = new MockResource();
     var result = Can.Read( resource );
     Assert.True( result );
 }
Beispiel #2
0
        public void LastTokenReleasesResource()
        {
            var resource = new MockResource();
            var handle   = new SharedHandle <MockResource>(resource);

            var token = handle.Access();

            token.Dispose();

            Assert.Multiple(() =>
            {
                Assert.AreEqual(1, resource.ReleaseCalls);

                Assert.AreEqual(0, handle.Tokens);
            });
        }
        public void GenerateCommonParameterPropertyTest()
        {
            var method = new MockMethod()
            {
                Name       = "Method",
                Parameters = new Dictionary <string, IDiscoveryParameter>()
            };
            var resource = new MockResource();

            resource.Methods.Add("Method", method);
            var resourceDecl = new CodeTypeDeclaration();
            var requestDecl  = new CodeTypeDeclaration();

            #region Create common Parameters
            IDictionary <string, IDiscoveryParameter> commonParameters = new Dictionary <string, IDiscoveryParameter>();
            var dict = new JsonDictionary {
                { "name", "alt" }, { "location", "query" }, { "type", "string" }, { "default", "json" }
            };
            var p = ServiceFactory.Default.CreateParameter("alt", dict);
            commonParameters["alt"] = p;
            #endregion

            // Confirm that two properties and two fields are generated.
            var decorator = new CommonParameterRequestDecorator(commonParameters);
            decorator.DecorateClass(resource, method, requestDecl, resourceDecl);

            Assert.AreEqual(2, requestDecl.Members.Count); // Property  + field.
            Assert.AreEqual(0, resourceDecl.Members.Count);

            CodeTypeMemberCollection newMembers = requestDecl.Members;

            // Check the generated field.
            Assert.IsInstanceOf <CodeMemberField>(newMembers[0]);
            Assert.AreEqual("_alt", newMembers[0].Name);

            // Check the generated property.
            Assert.IsInstanceOf <CodeMemberProperty>(newMembers[1]);
            CodeMemberProperty property = (CodeMemberProperty)newMembers[1];
            Assert.AreEqual("Alt", property.Name);

            // Check that the property has a Key attribute.
            Assert.AreEqual(1, property.CustomAttributes.Count);
            Assert.AreEqual(
                typeof(RequestParameterAttribute).FullName, property.CustomAttributes[0].AttributeType.BaseType);
            Assert.AreEqual(
                "alt", ((CodePrimitiveExpression)property.CustomAttributes[0].Arguments[0].Value).Value);
        }
Beispiel #4
0
            private void DoWork(object arg)
            {
                _isRunning = true;
                while (_isRunning)
                {
                    if (_mockResource.LastException != null)
                    {
                        Debug.WriteLine("DoWork is now shutdown by Resource LastException is not null.");
                        break;
                    }

                    if (_shutdownEvent.WaitOne(0))
                    {
                        Debug.WriteLine("DoWork is now shutdown by shutDownEvent.");
                        break;
                    }

                    try
                    {
                        _mockResource.DoMethod(arg);

                        if (arg.ToString() == "RiseLoopException")
                        {
                            throw new Exception("Loop Exception.");
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("DoWork is now shutdown by Loop Exception. Message:" + ex.Message);
                        break;
                    }
                }
                /*Itt kezdődik a vége*/
                if (_mockResource != null)
                {
                    /*Erőforrás felszabadítása, itt a szabályos.*/
                    _mockResource.Dispose();
                    _mockResource = null;
                }
                /*Leáll és a Stop-nak jelzem, hogy mehet tovább.*/
                _isRunning = false;
                _readyToDisposeEvent.Set();

                Debug.WriteLine("Loop is colsed...");
            }
        public void GivenARunningApiWhenSearchingForACompany()
        {
            var name   = "GG";
            var apiKey = Guid.NewGuid().ToString();

            _resource = new MockResource(new ResourceIdentifier("GET", CreateCompaniesPath(), $"?api_key={apiKey}&filters={{\"name\":\"{name}\"}}"));
            _resource.ReturnsBody(JsonSearchResponse);

            _api = new Api();
            _api.RegisterResource(_resource);
            _api.Start();

            var client = new DueDilClientFactory(new DueDilSettings(_api.Uri, apiKey, _sandboxMode)).CreateClient();

            _actual = client.SearchCompaniesAsync(new Terms()
            {
                Name = name
            }).Result;
        }
Beispiel #6
0
        public void AddRequiredParametersTest()
        {
            var parameterA = new MockParameter()
            {
                Name = "ParamA", IsRequired = false
            };
            var parameterB = new MockParameter()
            {
                Name = "ParamB", IsRequired = true
            };
            var method = new MockMethod()
            {
                Name       = "Method",
                Parameters = new Dictionary <string, IDiscoveryParameter>()
            };

            method.Parameters.Add("ParamA", parameterA);
            method.Parameters.Add("ParamB", parameterB);
            var resource = new MockResource();

            resource.Methods.Add("Method", method);
            var resourceDecl = new CodeTypeDeclaration();
            var typeProvider = new DefaultObjectTypeProvider("Schema");

            // Confirm that the "service" parameter is added.
            var             decorator   = new RequestConstructorDecorator(typeProvider);
            CodeConstructor constructor = new CodeConstructor();

            decorator.AddRequestParameters(resourceDecl, method, constructor, false);

            Assert.AreEqual(1, constructor.Parameters.Count);
            Assert.AreEqual("paramB", constructor.Parameters[0].Name);
            Assert.AreEqual(1, constructor.Statements.Count);

            // Check that optional parameters are added when the appropriate flag is set.
            constructor = new CodeConstructor();
            decorator.AddRequestParameters(resourceDecl, method, constructor, true);

            Assert.AreEqual(2, constructor.Parameters.Count);
            Assert.AreEqual("paramB", constructor.Parameters[0].Name);
            Assert.AreEqual("paramA", constructor.Parameters[1].Name);
            Assert.AreEqual(2, constructor.Statements.Count);
        }
        public void DecorateClassTest()
        {
            var decorator = new ServiceRequestInheritanceDecorator(
                new DefaultObjectTypeProvider("Schema"));
            var resource = new MockResource();
            var method   = new MockMethod()
            {
                ResponseType = "MySchema"
            };
            var decl         = new CodeTypeDeclaration();
            var resourceDecl = new CodeTypeDeclaration();

            // Check for ": ServiceRequest<Schema.MySchema>".
            decorator.DecorateClass(resource, method, decl, resourceDecl);
            Assert.AreEqual(1, decl.BaseTypes.Count);
            Assert.AreEqual(typeof(ServiceRequest <>).FullName, decl.BaseTypes[0].BaseType);
            Assert.AreEqual(1, decl.BaseTypes[0].TypeArguments.Count);
            Assert.AreEqual("Schema.MySchema", decl.BaseTypes[0].TypeArguments[0].BaseType);
        }
        public void DecorateClassTest()
        {
            var decorator = new BodyPropertyDecorator(new DefaultObjectTypeProvider("Schema"));
            var resource  = new MockResource();
            var method    = new MockMethod()
            {
                Name = "Test", RequestType = "SomeSchema", HasBody = true
            };
            var decl         = new CodeTypeDeclaration();
            var resourceDecl = new CodeTypeDeclaration();

            decorator.DecorateClass(resource, method, decl, resourceDecl);

            Assert.AreEqual(3, decl.Members.Count);
            Assert.IsInstanceOf <CodeMemberField>(decl.Members[0]);
            Assert.IsInstanceOf <CodeMemberProperty>(decl.Members[1]);
            Assert.AreEqual("Body", decl.Members[1].Name);
            Assert.IsInstanceOf <CodeMemberMethod>(decl.Members[2]);
            Assert.AreEqual("GetBody", decl.Members[2].Name);
        }
Beispiel #9
0
        public void GenerateSubresourceTest()
        {
            var          dec         = new SubresourceClassDecorator();
            const string serviceName = "TestService";
            var          decorators  = new IResourceDecorator[0];

            // Create generators.
            var resourceGen = new ResourceContainerGenerator(new IResourceContainerDecorator[0]);
            var requestGen  = new RequestClassGenerator(new IRequestDecorator[0]);

            // Test generation of the nested class
            var subresource = new MockResource {
                Name = "Sub"
            };
            CodeTypeDeclaration decl = dec.GenerateSubresource(
                subresource, serviceName, decorators, requestGen, resourceGen, new string[0]);

            Assert.IsNotNull(decl);
            Assert.AreEqual(decl.Name, "SubResource");
        }
        public void AddIsMethodResultRecursionTest()
        {
            var dic    = new Dictionary <JsonSchema, SchemaImplementationDetails>();
            var schema = new JsonSchema();

            var method = new MockMethod()
            {
                ResponseType = "TestSchema"
            };

            var subresource = new MockResource();

            subresource.Methods.Add("TestMethod", method);

            var resource = new MockResource();

            resource.Resources.Add("Subresource", subresource);

            var service = new MockService();

            service.Schemas.Add("TestSchema", new MockSchema {
                SchemaDetails = schema
            });
            service.Resources.Add("TestResource", resource);

            // Test parameter validation:
            Assert.Throws <ArgumentNullException>(
                () => ImplementationDetailsGenerator.AddIsMethodResult(null, service, service.Resources.Values));
            Assert.Throws <ArgumentNullException>(
                () => ImplementationDetailsGenerator.AddIsMethodResult(dic, null, service.Resources.Values));
            Assert.Throws <ArgumentNullException>(
                () => ImplementationDetailsGenerator.AddIsMethodResult(dic, service, (IEnumerable <IResource>)null));

            // Test recursive add:
            ImplementationDetailsGenerator.AddIsMethodResult(dic, service, service.Resources.Values);
            Assert.AreEqual(dic.Count, 1);

            var implDetails = dic[schema];

            Assert.IsTrue(implDetails.IsMethodResult);
        }
        public void GenerationTest()
        {
            var resource = new MockResource();

            resource.Name = "Test";
            resource.Methods.Add(
                "TestMethod", new MockMethod {
                Name = "TestMethod", HttpMethod = "GET", ResponseType = "int"
            });

            // Run the generator.
            var counter              = new CountingDecorator();
            var generator            = ConstructGenerator(resource, counter, new SubresourceClassDecorator());
            CodeTypeDeclaration clss = generator.CreateClass();

            Assert.IsNotNull(clss);
            Assert.AreEqual("TestResource", clss.Name);

            // Confirm that decorators have run.
            Assert.AreEqual(1, counter.Count);
        }
        public void GenerateRequestClassDecoratorOrderTest()
        {
            var generator =
                new RequestClassGenerator(
                    new IRequestDecorator[]
            {
                new MockRequestDecorator("One"), new MockRequestDecorator("Two"),
                new MockRequestDecorator("Three")
            });
            var decl     = new CodeTypeDeclaration();
            var resource = new MockResource();
            var method   = new MockMethod();

            // Check the order of the generated members.
            var genClass = generator.GenerateRequestClass(resource, method, decl, Enumerable.Empty <string>());

            Assert.AreEqual(3, genClass.Members.Count);
            Assert.AreEqual("One", genClass.Members[0].Name);
            Assert.AreEqual("Two", genClass.Members[1].Name);
            Assert.AreEqual("Three", genClass.Members[2].Name);
        }
        public void GenerateParameterPropertyTest()
        {
            var parameter = new MockParameter()
            {
                Name = "Param"
            };
            var method = new MockMethod()
            {
                Name       = "Method",
                Parameters = new Dictionary <string, IDiscoveryParameter>()
            };

            method.Parameters.Add("Param", parameter);
            var resource = new MockResource();

            resource.Methods.Add("Method", method);
            var resourceDecl = new CodeTypeDeclaration();

            // Confirm that two properties and two fields are generated.
            var decorator = new ParameterPropertyDecorator();
            CodeTypeMemberCollection newMembers = decorator.GenerateParameterProperty(
                parameter, method, resourceDecl, Enumerable.Empty <string>());

            Assert.AreEqual(2, newMembers.Count); // Property  + field.
            Assert.AreEqual(0, resourceDecl.Members.Count);

            // Check the generated property.
            Assert.IsInstanceOf <CodeMemberField>(newMembers[0]);

            CodeMemberProperty property = (CodeMemberProperty)newMembers[1];

            Assert.AreEqual("Param", property.Name);

            // Check that the property has a Key attribute.
            Assert.AreEqual(1, property.CustomAttributes.Count);
            Assert.AreEqual(
                typeof(RequestParameterAttribute).FullName, property.CustomAttributes[0].AttributeType.BaseType);
            Assert.AreEqual(
                "Param", ((CodePrimitiveExpression)property.CustomAttributes[0].Arguments[0].Value).Value);
        }
Beispiel #14
0
        public async Task DeployAsync_InOrder()
        {
            // Arrange
            var resourceA = new MockResource("A")
            {
                Delay = TimeSpan.FromMilliseconds(40)
            };
            var resourceB = new MockResource("B")
            {
                Delay = TimeSpan.FromMilliseconds(60)
            };
            var resourceC = new MockResource("C")
            {
                Delay = TimeSpan.FromMilliseconds(80)
            };

            resourceA.AddAntecedent(resourceB);
            resourceB.AddAntecedent(resourceC);

            var resources = new List <IDeploymentResource>
            {
                resourceA,
                resourceB,
                resourceC
            };
            var resourceProvider       = new MockDeploymentResourceProvider();
            IDeploymentContext context = new MockDeploymentContext(resourceProvider)
            {
                Parallel = false
            };
            IDeploymentManager target = new DeploymentManager();

            // Act
            await target.DeployAsync(context, resources, CancellationToken.None);

            // Assert
            Assert.AreEqual(3, resourceA.CompletedIndex);
            Assert.AreEqual(2, resourceB.CompletedIndex);
            Assert.AreEqual(1, resourceC.CompletedIndex);
        }
        public void GenerateRequestClassTest()
        {
            var decorator = new CountingRequestDecorator();
            var generator = new RequestClassGenerator(new IRequestDecorator[] { decorator });
            var decl      = new CodeTypeDeclaration();

            // Create a test resource.
            var        resource = new MockResource();
            MockMethod method   = new MockMethod()
            {
                Name = "MethodA"
            };

            resource.Methods.Add("MethodA", method);

            // Run the generator
            CodeTypeDeclaration newClass = generator.GenerateRequestClass(resource, method, decl, new string[0]);

            Assert.IsNotNull(newClass);
            Assert.AreEqual(1, decorator.TimesCalled);
            Assert.AreEqual(0, newClass.Members.Count);
        }
Beispiel #16
0
        public void DecorateClassTest()
        {
            var method = new MockMethod()
            {
                Name       = "Method",
                Parameters = new Dictionary <string, IDiscoveryParameter>()
            };

            method.Parameters.Add("Param", new MockParameter()
            {
                Name = "Param"
            });
            var resource = new MockResource();

            resource.Methods.Add("Method", method);
            var resourceDecl = new CodeTypeDeclaration();
            var requestDecl  = new CodeTypeDeclaration();
            var typeProvider = new DefaultObjectTypeProvider("Schema");

            // Confirm that the decorator has run correctly.
            var decorator = new RequestConstructorDecorator(typeProvider)
            {
                CreateOptionalConstructor = true
            };

            decorator.DecorateClass(resource, method, requestDecl, resourceDecl);
            Assert.AreEqual(2, requestDecl.Members.Count); // 2 Constructors.
            Assert.IsInstanceOf <CodeConstructor>(requestDecl.Members[0]);
            Assert.AreEqual(0, resourceDecl.Members.Count);

            // Test the decorator without optional parameters.
            requestDecl = new CodeTypeDeclaration();
            decorator.CreateOptionalConstructor = false;
            decorator.DecorateClass(resource, method, requestDecl, resourceDecl);
            Assert.AreEqual(1, requestDecl.Members.Count); // 1 Constructor.
            Assert.IsInstanceOf <CodeConstructor>(requestDecl.Members[0]);
            Assert.AreEqual(0, resourceDecl.Members.Count);
        }
Beispiel #17
0
 public void ShouldBeAbleToCheckIfAUserHasAnAbility()
 {
     var resource = new MockResource();
     var result = Can.Read( resource );
     Assert.False( result );
 }
Beispiel #18
0
        public async Task DeployAsync([Values(true, false)] bool parallel)
        {
            // Arrange
            TestContext.WriteLine();
            var resourceA = new MockResource("A")
            {
                Delay = TimeSpan.FromMilliseconds(10)
            };
            var resourceB = new MockResource("B")
            {
                Delay = TimeSpan.FromMilliseconds(10)
            };
            var resourceC = new MockResource("C")
            {
                Delay = TimeSpan.FromMilliseconds(10)
            };
            var resourceD = new MockResource("D")
            {
                Delay = TimeSpan.FromMilliseconds(70)
            };
            var resourceE = new MockResource("E")
            {
                Delay = TimeSpan.FromMilliseconds(10)
            };

            resourceE.AddAntecedent(resourceC);
            resourceC.AddAntecedent(resourceB);
            resourceB.AddAntecedent(resourceA);
            resourceD.AddAntecedent(resourceA);

            var resources = new List <IDeploymentResource>
            {
                resourceA,
                resourceB,
                resourceC,
                resourceD,
                resourceE
            };
            var resourceProvider = new MockDeploymentResourceProvider();

            resourceProvider.Reset();
            IDeploymentContext context = new MockDeploymentContext(resourceProvider)
            {
                Parallel = parallel
            };
            IDeploymentManager target = new DeploymentManager();

            // Act
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            await target.DeployAsync(context, resources, CancellationToken.None);

            stopwatch.Stop();

            // Assert
            TestContext.WriteLine("Elapsed Time: " + stopwatch.Elapsed);
            if (parallel)
            {
                Assert.AreEqual(1, resourceA.CompletedIndex);
                Assert.AreEqual(2, resourceB.CompletedIndex);
                Assert.AreEqual(3, resourceC.CompletedIndex);
                Assert.AreEqual(5, resourceD.CompletedIndex);
                Assert.AreEqual(4, resourceE.CompletedIndex);
            }
            else
            {
                Assert.AreEqual(3, resourceA.CompletedIndex);
                Assert.AreEqual(4, resourceB.CompletedIndex);
                Assert.AreEqual(5, resourceC.CompletedIndex);
                Assert.AreEqual(2, resourceD.CompletedIndex);
                Assert.AreEqual(6, resourceE.CompletedIndex);
            }
        }