コード例 #1
0
ファイル: HubControllerTests.cs プロジェクト: ndrmc/cats-hub
        public void Init()
        {
            var hubs = new List <Hub>
            {
                new Hub {
                    HubID = 1, Name = "Adama", HubOwnerID = 1
                },
                new Hub {
                    HubID = 2, Name = "Kombolcha", HubOwnerID = 2
                },
            };
            var hubServices = new Mock <IHubService>();

            hubServices.Setup(t => t.GetAllHub()).Returns(hubs);

            var hubOwners = new List <HubOwner>
            {
                new HubOwner {
                    HubOwnerID = 1, Name = "DRMFSS"
                },
                new HubOwner {
                    HubOwnerID = 2, Name = "EFSRA"
                }
            };
            var hubOwnerService = new Mock <HubOwnerService>();

            hubOwnerService.Setup(t => t.GetAllHubOwner()).Returns(hubOwners);

            _hubController = new HubController(hubOwnerService.Object, hubServices.Object);
        }
コード例 #2
0
ファイル: HubControllerTest.cs プロジェクト: nathnael/cats
      public void Init()
      {
          var hub = new List <Hub>
          {
              new Hub {
                  HubID = 1, Name = "One", HubOwnerID = 1
              },
              new Hub {
                  HubID = 2, Name = "Two", HubOwnerID = 2
              },
          };
          var hubService = new Mock <IHubService>();

          hubService.Setup(m => m.GetAllHub()).Returns(hub);

          var hubOwner = new List <HubOwner>
          {
              new HubOwner {
                  HubOwnerID = 1, Name = "Owner1", LongName = "Hub Owner 1"
              },
              new HubOwner {
                  HubOwnerID = 2, Name = "Owner2", LongName = "Hub Owner 2"
              }
          };
          var hubOwnerService = new Mock <IHubOwnerService>();

          hubOwnerService.Setup(m => m.GetAllHubOwner()).Returns(hubOwner);

          _hubController = new HubController(hubService.Object, hubOwnerService.Object);
      }
コード例 #3
0
            private static string WriteConnection(HubController controller)
            {
                return($@"
{SharedWriter.GetObsolete(controller)}
public class {controller.Name}HubConnection : HubConnection
{{

	public {controller.Name}HubConnection(IConnectionFactory connectionFactory,
		IHubProtocol protocol,
		IServiceProvider serviceProvider,
		ILoggerFactory loggerFactory)
		: base(connectionFactory, protocol, serviceProvider, loggerFactory) {{ }}


	public {controller.Name}HubConnection(IConnectionFactory connectionFactory,
		IHubProtocol protocol,
		ILoggerFactory loggerFactory)
		: base(connectionFactory, protocol, loggerFactory) {{ }}


	{string.Join(Environment.NewLine, controller.GetEndpoints().Select(WriteEndpoint))}
	{string.Join(Environment.NewLine, controller.GetMessages().Select(WriteMessage))}
}}
");
            }
コード例 #4
0
            private static string WriteConnectionBuilder(HubController controller)
            {
                return
                    ($@"
{SharedWriter.GetObsolete(controller)}
public class {controller.Name}HubConnectionBuilder : HubConnectionBuilder
{{
	private bool _hubConnectionBuilt;

	public {controller.Name}HubConnectionBuilder(Uri host, HttpTransportType? transports = null, Action<HttpConnectionOptions> configureHttpConnection = null) : base()
	{{
		//Remove default HubConnection to use custom one
		Services.Remove(Services.Where(x => x.ServiceType == typeof(HubConnection)).Single());
		Services.AddSingleton<{controller.Name}HubConnection>();

		Services.Configure<HttpConnectionOptions>(o =>
		{{
			o.Url = new Uri(host,""{controller.Route}"");
			if (transports != null)
			{{
				o.Transports = transports.Value;
			}}
		}});

		if (configureHttpConnection != null)
		{{
			Services.Configure(configureHttpConnection);
		}}

		Services.AddSingleton<IConnectionFactory, HttpConnectionFactory>();
	}}


	public new {controller.Name}HubConnection Build()
	{{
		// Build can only be used once
		if (_hubConnectionBuilt)
		{{
			throw new InvalidOperationException(""HubConnectionBuilder allows creation only of a single instance of HubConnection."");
		}}

		_hubConnectionBuilt = true;

		// The service provider is disposed by the HubConnection
		var serviceProvider = Services.BuildServiceProvider();

		var connectionFactory = serviceProvider.GetService<IConnectionFactory>();
		if (connectionFactory == null)
		{{
			throw new InvalidOperationException($""Cannot create {{nameof(HubConnection)}} instance.An {{nameof(IConnectionFactory)}} was not configured."");
		}}

		return serviceProvider.GetService<{controller.Name}HubConnection>();
	}}
}}
");
            }
コード例 #5
0
        public void ToString_CleansBleDeviceId()
        {
            _mockLegoHub.SetupGet(h => h.HubType).Returns(Models.Enums.HubType.BoostMoveHub);
            _hubController = new HubController(_mockLegoHub.Object, "BluetoothLE#BluetoothLE34:34:23");

            var result = _hubController.ToString();

            VerifyMocks();
            Assert.Equal("BoostMoveHub (34:34:23)", result);
        }
コード例 #6
0
 public static string WriteErrorMessage(HubController controller)
 {
     if (controller.Failed)
     {
         return($@"{(controller.UnexpectedFailure ? "#error PLEASE MAKE A GITHUB REPO ISSUE" : "#warning")} {controller.Name}Hub {(controller.UnexpectedFailure ? "has failed generation with unexpected error" : "is misconfigured for generation")} :: {controller.Error.Replace('\r', ' ').Replace('\n', ' ')}");
     }
     else
     {
         return(null);
     }
 }
コード例 #7
0
        public async Task And_Given_An_Invalid_Hub_Then_The_Not_Found_Page_Is_Returned(
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] HubController controller)
        {
            SetupMediator(new GetHubQueryResult <Domain.Content.Hub>(), mockMediator, false);

            var controllerResult = await InstantiateController <ViewResult>(controller);

            controllerResult.AssertThatTheObjectResultIsValid();
            controllerResult.AssertThatTheReturnedViewIsCorrect("~/Views/Error/PageNotFound.cshtml");
            mockMediator.Verify(o => o.Send(It.IsAny <GetSiteMapQuery>(), It.IsAny <CancellationToken>()), Times.Once);
        }
コード例 #8
0
        public async Task And_Given_Valid_Hub_Then_The_Page_Is_Returned(
            GetHubQueryResult <Domain.Content.Hub> mediatorResult, [Frozen] Mock <IMediator> mockMediator,
            [Greedy] HubController controller)
        {
            SetupMediator(mediatorResult, mockMediator, false);

            var controllerResult = await InstantiateController <ViewResult>(controller);

            controllerResult.AssertThatTheObjectResultIsValid();
            controllerResult.AssertThatTheObjectValueIsValid <Page <Domain.Content.Hub> >();
            controllerResult.AssertThatTheReturnedViewIsCorrect("~/Views/Hubs/" + HubName + "Hub.cshtml");
        }
コード例 #9
0
        public async Task And_Is_Preview_Then_Given_Valid_Hub_Then_The_Page_Is_Returned(
            GetHubQueryResult <Domain.Content.Hub> mediatorResult, [Frozen] Mock <IMediator> mockMediator,
            [Greedy] HubController controller)
        {
            SetupMediator(mediatorResult, mockMediator, true);

            var controllerResult = await InstantiateController <ViewResult>(controller, true);

            controllerResult.AssertThatTheObjectResultIsValid();
            controllerResult.AssertThatTheObjectValueIsValid <Page <Domain.Content.Hub> >();
            controllerResult.AssertThatTheReturnedViewIsCorrect("~/Views/Hubs/" + HubName + "Hub.cshtml");
            mockMediator.Verify(o => o.Send(It.IsAny <GetSiteMapQuery>(), It.IsAny <CancellationToken>()), Times.Never);
        }
コード例 #10
0
            public static string WriteHub(HubController controller)
            {
                return
                    ($@"
{(controller.NamespaceSuffix != null ? $@"namespace {controller.NamespaceSuffix}
{{" : string.Empty)}

	{WriteConnectionBuilder(controller)}

	{WriteConnection(controller)}

{(controller.NamespaceSuffix != null ? $@"}}" : string.Empty)}
");
            }
コード例 #11
0
        public async Task And_Given_A_Valid_Hub_Then_The_Hub_Is_Returned(
            string hubName,
            GetHubQueryResult mediatorResult,
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] HubController controller)
        {
            SetupMediator(mediatorResult, mockMediator, hubName);

            var controllerResult = await InstantiateController <OkObjectResult>(controller, hubName);

            var actualResult = controllerResult.Value as GetHubResponse;

            Assert.IsNotNull(actualResult);
            actualResult.Hub.Should().BeEquivalentTo(mediatorResult.PageModel);
        }
コード例 #12
0
        public async Task And_Given_Invalid_Hub_And_A_Slug_Then_The_Article_Is_Not_Returned(
            string hubName,
            GetHubQueryResult mediatorResult,
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] HubController controller)
        {
            mediatorResult.PageModel = null;

            SetupMediator(new GetHubQueryResult(), mockMediator, hubName);

            var controllerResult = await InstantiateController <NotFoundObjectResult>(controller, hubName);

            var actualResult = controllerResult.Value as NotFoundResponse;

            Assert.IsNotNull(actualResult);
            actualResult.Message.Should().Be($"Hub not found for {hubName}");
        }
        public async Task Then_The_Article_Is_Returned_From_The_Mediator_Query(
            string hubName,
            GetPreviewHubQueryResult mediatorResult,
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] HubController controller)
        {
            mockMediator
            .Setup(x => x.Send(
                       It.Is <GetPreviewHubQuery>(c => c.Hub.Equals(hubName)), It.IsAny <CancellationToken>()))
            .ReturnsAsync(mediatorResult);

            var actual = await controller.GetPreviewHub(hubName) as OkObjectResult;

            Assert.IsNotNull(actual);
            var actualResult = actual.Value as GetHubResponse;

            Assert.IsNotNull(actualResult);
            actualResult.Hub.Should().BeEquivalentTo(mediatorResult.PageModel);
        }
コード例 #14
0
    private void OnMouseDown()
    {
        HubController HC = hubController.GetComponent <HubController>();

        //if (HC.rotating != true)
        //{
        //    HC.hubCorrectAngle += amountToRotate;
        //    HC.rotating = true;
        //}

        if (rotatingLeft)
        {
            HC.TriggerRotationLeft();
        }
        else
        {
            HC.TriggerRotationRight();
        }
    }
        public async Task Then_The_NotFound_Is_Returned_If_No_Result(
            string hubName,
            GetPreviewHubQueryResult mediatorResult,
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] HubController controller)
        {
            mockMediator
            .Setup(x => x.Send(
                       It.Is <GetPreviewHubQuery>(c => c.Hub.Equals(hubName)), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new GetPreviewHubQueryResult
            {
                PageModel = null
            });

            var actual = await controller.GetPreviewHub(hubName) as NotFoundObjectResult;

            Assert.IsNotNull(actual);
            var actualResult = actual.Value as NotFoundResponse;

            Assert.IsNotNull(actualResult);
            actualResult.Message.Should().Be($"Preview hub not found for {hubName}");
        }
コード例 #16
0
        private static async Task <T> InstantiateController <T>(HubController controller, string hubName)
        {
            var controllerResult = (T)await controller.GetHubAsync(hubName, CancellationToken.None);

            return(controllerResult);
        }
コード例 #17
0
        private static async Task <T> InstantiateController <T>(HubController controller, bool preview = false)
        {
            var controllerResult = (T)await controller.GetHubAsync(HubName, preview, CancellationToken.None);

            return(controllerResult);
        }
コード例 #18
0
        private static HubEndpoint ReadMethodAsHubEndpoint(HubController parent, MethodDeclarationSyntax syntax)
        {
            var attributes = syntax.DescendantNodes().OfType <AttributeListSyntax>().SelectMany(x => x.Attributes).ToList();

            var endpoint = new HubEndpoint(parent);

            endpoint.Name = syntax.Identifier.ValueText.CleanMethodName();


            endpoint.Virtual  = syntax.Modifiers.Any(x => x.Text == "virtual");
            endpoint.Override = syntax.Modifiers.Any(x => x.Text == "override");
            endpoint.New      = syntax.Modifiers.Any(x => x.Text == "new");


            //Ignore generator attribute
            endpoint.Ignored = attributes.HasAttribute <NotGeneratedAttribute>();

            //Obsolete Attribute
            var obsoleteAttribute = attributes.GetAttribute <ObsoleteAttribute>();

            if (obsoleteAttribute != null)
            {
                endpoint.Obsolete        = true;
                endpoint.ObsoleteMessage = obsoleteAttribute.GetAttributeValue();
            }

            //Response types
            var messageAttributes = attributes.GetAttributes <ProducesMessageAttribute>();
            var messages          = messageAttributes.Select(x => new MessageDefinition(x)).ToList();

            endpoint.Messages = messages.Select(x => new Message(x.Name, x.Types)).ToList();

            var duplicateMessages = endpoint.Messages.GroupBy(x => x.Name).Where(x => x.Count() > 1 && !x.All(y => y.Types.SequenceEqual(x.First().Types))).ToList();

            if (duplicateMessages.Any())
            {
                throw new NotSupportedException($"Hub has the same message with different parameters defined on different endpoints. {string.Join(", ", duplicateMessages.Select(x => x.Key?.ToString()))}");
            }



            var parameters = syntax.ParameterList.Parameters.Select(x => new HubParameterDefinition(x)).ToList();
            var hubParams  = parameters.Select(x => new HubParameter(x.Name, x.Type, x.Default)).ToList();

            endpoint.Parameters = hubParams.Cast <IParameter>().NotNull().ToList();

            var duplicateParameters = endpoint.GetParameters().GroupBy(x => x.Name).Where(x => x.Count() > 1).ToList();

            if (duplicateParameters.Any())
            {
                throw new NotSupportedException($"Endpoint has multiple parameters of the same name defined. {string.Join(", ", duplicateParameters.Select(x => x.Key?.ToString()))}");
            }

            var invalidParameters = endpoint.GetParameters().Where(x => !Microsoft.CodeAnalysis.CSharp.SyntaxFacts.IsValidIdentifier(x.Name)).ToList();

            if (invalidParameters.Any())
            {
                throw new NotSupportedException($"Endpoint {parent.Name}.{endpoint.Name} has parameters that are invalid variable names. {string.Join(", ", invalidParameters.Select(x => x.Name))}");
            }


            var rawReturnType = syntax.ReturnType?.ToFullString();

            var returnType = Helpers.GetTypeFromString(rawReturnType.Trim());

            while (returnType.IsContainerReturnType())
            {
                returnType = returnType.Arguments.SingleOrDefault();
            }

            if (Helpers.IsType(typeof(ChannelReader <>).FullName.CleanGenericTypeDefinition(), returnType?.Name))
            {
                endpoint.Channel     = true;
                endpoint.ChannelType = returnType.Arguments.SingleOrDefault().ToString();
            }


            return(endpoint);
        }
コード例 #19
0
        public static HubController ReadClassAsHubController(ClassDeclarationSyntax syntax)
        {
            var attributes = syntax.AttributeLists.SelectMany(x => x.Attributes).ToList();

            var controller = new HubController();

            try
            {
                controller.Name = $@"{syntax.Identifier.ValueText.Trim().Replace("Hub", "")}";

                controller.Abstract = syntax.Modifiers.Any(x => x.Text == "abstract");

                if (syntax.BaseList == null)
                {
                    controller.Ignored = true;
                    return(controller);
                }

                var generatedAttribute = attributes.GetAttribute <GenerateHubAttribute>();
                if (generatedAttribute == null)
                {
                    controller.Ignored = true;
                    return(controller);
                }

                controller.BaseClass = syntax.BaseList.Types.Where(x => x.ToFullString().Trim().EndsWith("Hub")).SingleOrDefault()?.ToFullString().Trim().Replace("Hub", "");

                controller.Ignored = attributes.HasAttribute <NotGeneratedAttribute>();


                var namespaceAttribute = attributes.GetAttribute <NamespaceSuffixAttribute>();
                if (namespaceAttribute != null)
                {
                    controller.NamespaceSuffix = namespaceAttribute.ArgumentList.Arguments.ToFullString().Replace("\"", "");
                }

                var routeAttribute = attributes.GetAttribute <RouteAttribute>();
                if (routeAttribute != null)                //Fetch route from RouteAttribute
                {
                    controller.Route = routeAttribute.ArgumentList.Arguments.ToFullString().Replace("\"", "");
                }

                if (controller.Route == null && !controller.Abstract && !controller.Ignored)                //No Route, invalid controller
                {
                    controller.Ignored = true;
                    throw new NotSupportedException("Controller must have a route to be valid for generation.");
                }

                if (controller.Route != null)
                {
                    var match = RouteVersionRegex.Match(controller.Route);
                    if (match.Success)
                    {
                        var group = match.Groups[1];
                        controller.NamespaceVersion = group.Value.ToUpper();
                    }
                }

                //Obsolete Attribute
                var obsoleteAttribute = attributes.GetAttribute <ObsoleteAttribute>();
                if (obsoleteAttribute != null)
                {
                    controller.Obsolete        = true;
                    controller.ObsoleteMessage = obsoleteAttribute.GetAttributeValue();
                }

                //Only public endpoints can be hit anyways
                var methods = syntax.DescendantNodes().OfType <MethodDeclarationSyntax>()
                              .Where(x => x.Modifiers.Any(y => y.Text == "public"))
                              .ToList();
                controller.Endpoints = methods.Select(x => ReadMethodAsHubEndpoint(controller, x)).ToList();

                if (!controller.Endpoints.Any(x => !x.Ignored))
                {
                    controller.Ignored = true;
                }
            }
            catch (NotSupportedException nse)
            {
                if (controller.Ignored)
                {
                    return(controller);
                }

                controller.Failed = true;
                controller.Error  = nse.Message;
            }
#if !DEBUG
            catch (Exception ex)
            {
                controller.Failed            = true;
                controller.UnexpectedFailure = true;
                controller.Error             = ex.ToString();
            }
#endif
            return(controller);
        }
コード例 #20
0
 public HubControllerTests()
 {
     _mockGattCharacteristicWrapper = new Mock <IGattCharacteristicWrapper>();
     _mockLegoHub   = new Mock <ILegoHub>();
     _hubController = new HubController(_mockLegoHub.Object, "");
 }