コード例 #1
0
        public ExampleSimpleListTest()
        {
            _mockData = new List <Employee>()
            {
                new Employee {
                    Id = 1, FirstName = "John", LastName = "Doe "
                },
                new Employee {
                    Id = 2, FirstName = "Jane", LastName = "Doe "
                }
            };

            var employeeRepositoryStub = Stubber.Create <IEmployeeRepository>()
                                         .Setup(x => x.GetAll(It.IsAny <int>())).Returns(_mockData)
                                         .Setup(x => x.Get(It.IsAny <int>())).Returns((int id) => _mockData.FirstOrDefault(x => x.Id == id))
                                         .Setup(x => x.Update(It.IsAny <Employee>())).Calls((Employee update) =>
            {
                var data       = _mockData.First(x => x.Id == update.Id);
                data.FirstName = update.FirstName;
                data.LastName  = update.LastName;
            })
                                         .Setup(x => x.Remove(It.IsAny <int>())).Calls((int id) => _mockData.Remove(_mockData.First(x => x.Id == id)))
                                         .Object;

            _hubEmulator = new HubEmulatorBuilder()
                           .AddServices(services => services.AddTransient(x => employeeRepositoryStub))
                           .Register <SimpleListVM>()
                           .Build();
        }
コード例 #2
0
ファイル: MinimalApiTest.cs プロジェクト: dsuryd/dotNetify
        public void MinimalApiTest_WithAuthorizeOnAuthenticatedClient_AccessGranted()
        {
            var vmName  = "HelloWorldAccessGranted";
            var builder = WebApplication.CreateBuilder();

            builder.Services.AddDotNetify().AddSignalR();
            var app = builder.Build();

            app.MapVM(vmName, [Authorize]() => new { FirstName = "Hello", LastName = "World" });

            var vm = VMController.CreateVMInstance(vmName);

            var hubEmulator = new HubEmulatorBuilder()
                              .Register(vmName, vm)
                              .UseFilter <AuthorizeFilter>()
                              .Build();

            var identity = Stubber.Create <IIdentity>().Setup(x => x.AuthenticationType).Returns("CustomAuth").Object;
            var client   = hubEmulator.CreateClient(user: new ClaimsPrincipal(identity));

            var response = client.Connect(vmName).As <HelloWorldState>();

            Assert.AreEqual("Hello", response.FirstName);
            Assert.AreEqual("World", response.LastName);
        }
コード例 #3
0
        public async Task ShouldBeAbleToCreateACandidate()
        {
            var requestCandidate = Stubber.StubCandidateDto();

            var responseCandidate = await ApiClient.PostCandidate(requestCandidate)
                                    .AwaitGetSuccessfulResponse <CandidateDto>();

            responseCandidate.ToLikeness().ShouldEqual(requestCandidate);
        }
コード例 #4
0
        public async Task ShouldBeAbleToCreateAQuestion()
        {
            var requestQuestion = Stubber.StubQuestionDto();

            var responseQuestion = await ApiClient.PostQuestion(requestQuestion)
                                   .AwaitGetSuccessfulResponse <QuestionDto>();

            responseQuestion.ToLikeness().ShouldEqual(requestQuestion);
        }
コード例 #5
0
        public async Task ShouldBeAbleToCreateAnInterviewTemplateWithoutQuestions()
        {
            var requestInterviewTemplate = Stubber.StubInterviewTemplateDto();

            var responseInterviewTemplate = await ApiClient.PostInterviewTemplate(requestInterviewTemplate)
                                            .AwaitGetSuccessfulResponse <InterviewTemplateDto>();

            responseInterviewTemplate.ToLikeness().ShouldEqual(requestInterviewTemplate);
        }
コード例 #6
0
        public async Task ShouldBeAbleToCreateAnEmptyInterview()
        {
            var requestInterview = Stubber.StubInterviewDto();

            var responseInterview = await ApiClient.PostInterview(requestInterview)
                                    .AwaitGetSuccessfulResponse <InterviewDto>();

            Assert.IsNotNull(responseInterview.Id);
        }
コード例 #7
0
        public async Task ShouldBeAbleToCreateInterviewFromTemplate()
        {
            var dbInterviewTemplate = await Arranger.CreateInterviewTemplate();

            var requestInterview = Stubber.StubInterviewDto();

            var responseInterview = await ApiClient.PostInterview(requestInterview, dbInterviewTemplate.Id)
                                    .AwaitGetSuccessfulResponse <InterviewDto>();

            var dbInterviewTemplateDto = Mapper.Map <IEnumerable <QuestionDto> >(dbInterviewTemplate.Questions);

            Assert.IsTrue(responseInterview.Questions.CompareCollectionsUsingLikeness <QuestionDto, QuestionDto>(dbInterviewTemplateDto));
        }
コード例 #8
0
        public async Task ShouldBeABleToUpdateQuestion()
        {
            var questionDto = Mapper.Map <QuestionDto>(await Arranger.CreateQuestion());

            var questionPatchRequest = Stubber.StubQuestionPatchRequest();

            questionPatchRequest.ApplyTo(questionDto);

            await ApiClient.PatchQuestion(questionDto.Id, questionPatchRequest);

            var updatedQuestionDto = Mapper.Map <QuestionDto>(await Arranger.GetQuestion(questionDto.Id));

            SemanticComparisonExtensions.ToLikeness <QuestionDto>(questionDto, true).ShouldEqual(updatedQuestionDto);
        }
コード例 #9
0
        public async Task ShouldBeAbleToUpdateCandidate()
        {
            var candidateDto = Mapper.Map <CandidateDto>(await Arranger.CreateCandidate());

            var patchRequest = Stubber.StubCandidatePatchRequest();

            patchRequest.ApplyTo(candidateDto);

            (await ApiClient.PatchCandidate(candidateDto.Id, patchRequest))
            .EnsureSuccessStatusCode();

            var updatedCandidateDto = Mapper.Map <CandidateDto>(await Arranger.GetCandidate(candidateDto.Id));

            SemanticComparisonExtensions.ToLikeness <CandidateDto>(candidateDto, true)
            .ShouldEqual(updatedCandidateDto);
        }
コード例 #10
0
        public async Task ShouldBeAbleToCreateAnInterviewTemplateWithQuestions()
        {
            var requestInterviewTemplate = Stubber.StubInterviewTemplateDto();

            var questions = await Arranger.CreateQuestions();

            requestInterviewTemplate.QuestionIds = questions.Select(q => q.Id);

            var responseInterviewTemplate = await ApiClient.PostInterviewTemplate(requestInterviewTemplate)
                                            .AwaitGetSuccessfulResponse <InterviewTemplateDto>();

            responseInterviewTemplate
            .ToLikeness()
            .WithCollectionSequenceEquals(o => o.QuestionIds)
            .ShouldEqual(requestInterviewTemplate);
        }
コード例 #11
0
        public async Task ShouldBeAbleToCreateInterviewWithCandidate()
        {
            var requestInterviewDto = Stubber.StubInterviewDto();

            var dbCandidate = await Arranger.CreateCandidate();

            requestInterviewDto.Candidate = Mapper.Map <CandidateDto>(dbCandidate);

            var responseInterviewDto = await ApiClient.PostInterview(requestInterviewDto, candidateId : dbCandidate.Id)
                                       .AwaitGetSuccessfulResponse <InterviewDto>();

            responseInterviewDto
            .ToLikeness()
            .WithInnerLikeness(o => o.Candidate, o => o.Candidate)
            .ShouldEqual(requestInterviewDto);
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: Reinms/Stubber-Publicizer
        public static void Main(String[] args)
        {
            if (args is null || args.Length != 1)
            {
                Console.WriteLine("Bad args, press any key to close");
                _ = Console.ReadKey();
                return;
            }

            String path = args[0];

            StubbingOptions options = GetOptionsFromConsole(path);

            Console.WriteLine(Stubber.StubAssembly(options) ? "Success" : "Failed");
            Console.WriteLine("Press any key to close");
            _ = Console.ReadKey();
        }
コード例 #13
0
        public async Task ShouldBeAbleToPatchAnInterviewTemplate()
        {
            var interviewTemplateDto = Mapper.Map <InterviewTemplateDto>(await Arranger.CreateInterviewTemplate());

            var patchRequest = Stubber.StubInterviewTemplatePatchRequest();

            patchRequest.ApplyTo(interviewTemplateDto);

            (await ApiClient.PatchInterviewTemplate(interviewTemplateDto.Id, patchRequest))
            .EnsureSuccessStatusCode();

            var updatedInterviewTemplateDto = Mapper.Map <InterviewTemplateDto>(
                await Arranger.GetInterviewTemplate(interviewTemplateDto.Id));

            SemanticComparisonExtensions.ToLikeness <InterviewTemplateDto>(interviewTemplateDto)
            .Without(o => o.QuestionIds)
            .ShouldEqual(updatedInterviewTemplateDto);
        }
コード例 #14
0
        public void Setup()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appSettings.json");

            var configuration = builder.Build();

            ServiceProvider = new ServiceCollection()
                              .AddOptions()
                              .Configure <AppSettings>(configuration)
                              .AddSingleton <IQuestionRepository, QuestionRepository>()
                              .AddSingleton <IInterviewRepository, InterviewRepository>()
                              .AddSingleton <IInterviewTemplateRepository, InterviewTemplateRepository>()
                              .AddSingleton <ICandidateRepository, CandidateRepository>()
                              .AddSingleton <IMapper>(new Mapper(new MapperConfiguration(c => c.AddProfile(new MappingProfile()))))
                              .AddSingleton <Arranger, Arranger>()
                              .AddSingleton <Stubber, Stubber>()
                              .AddSingleton <ApiClient, ApiClient>()
                              .BuildServiceProvider();

            var appSettings = ServiceProvider.GetService <IOptions <AppSettings> >().Value;

            HttpClient             = new HttpClient();
            HttpClient.BaseAddress = new Uri(appSettings.ApiUri);

            Arranger  = ServiceProvider.GetService <Arranger>();
            Stubber   = ServiceProvider.GetService <Stubber>();
            ApiClient = ServiceProvider.GetService <ApiClient>();

            _Fixture = new Fixture();

            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <MappingProfile>();
            });

            Mapper = config.CreateMapper();
        }
コード例 #15
0
ファイル: MinimalApiTest.cs プロジェクト: dsuryd/dotNetify
        public void MinimalApiTest_WithAuthorizeOnUnauthenticatedClient_AccessDenied()
        {
            var vmName  = "HelloWorldAccessDenied";
            var builder = WebApplication.CreateBuilder();

            builder.Services.AddDotNetify().AddSignalR();
            var app = builder.Build();

            app.MapVM(vmName, [Authorize]() => new { FirstName = "Hello", LastName = "World" });

            var vm = VMController.CreateVMInstance(vmName);

            var hubEmulator = new HubEmulatorBuilder()
                              .Register(vmName, vm)
                              .UseFilter <AuthorizeFilter>()
                              .Build();

            var identity = Stubber.Create <IIdentity>().Setup(x => x.AuthenticationType).Returns(string.Empty).Object;
            var client   = hubEmulator.CreateClient(user: null);

            var response = client.Connect(vmName);

            Assert.IsTrue(response.First().ToString().Contains(nameof(UnauthorizedAccessException)));
        }
コード例 #16
0
        private void Setup(IClientEmulator forwardingClient, IDotNetifyHubForwarderFactory hubForwarderFactory, IClientEmulator[] clients, Action <string, string> callback = null)
        {
            // Build a mock hub proxy that will be used to forward messages.  This proxy will be set to communicate to another hub emulator.
            var hubProxy = Substitute.For <IDotNetifyHubProxy>();

            hubProxy.StartAsync().Returns(Task.CompletedTask);
            hubProxy.ConnectionState.Returns(HubConnectionState.Connected);

            // When the hub proxy's Invoke method is called, call the other hub emulator's Invoke method,
            // then get the response through the client emulator connecting with that hub, and finally
            // raise the hub proxy's own Response_VM event with the response.
            hubProxy.Invoke(Arg.Any <string>(), Arg.Any <object[]>(), Arg.Any <IDictionary <string, object> >())
            .Returns(arg =>
            {
                var callType   = arg[0].ToString();
                var methodArgs = (arg[1] as object[]).Select(x =>
                {
                    if (x is string)
                    {
                        return(x);
                    }
                    if (x != null)
                    {
                        return(JObject.FromObject(x));
                    }
                    return(null);
                }).ToArray();

                var metadataString = JsonSerializer.Serialize((IDictionary <string, object>)arg[2]);
                var metadata       = Newtonsoft.Json.JsonConvert.DeserializeObject <IDictionary <string, object> >(metadataString);
                foreach (var kvp in metadata.ToList())
                {
                    metadata[kvp.Key] = kvp.Value is string?kvp.Value: JObject.FromObject(kvp.Value);
                }

                forwardingClient.Hub.InvokeAsync(callType, methodArgs, metadata).GetAwaiter().GetResult();

                var responses = forwardingClient.ResponseHistory.Select(x => x.Payload).ToArray();
                forwardingClient.ResponseHistory.Clear();
                foreach (var response in responses)
                {
                    hubProxy.Response_VM += Raise.EventWith(this,
                                                            (ResponseVMEventArgs) new InvokeResponseEventArgs
                    {
                        MethodName = response[0].ToString(),
                        MethodArgs = (response[1] as object[]).Select(x => x.ToString()).ToArray(),
                        Metadata   = (response[2] as Dictionary <string, object>).ToDictionary(x => x.Key, x => x.Value.ToString())
                    });
                }
                callback?.Invoke(callType, methodArgs[0].ToString());

                return(Task.CompletedTask);
            });

            // Build a mock hub response that will receive response back to the above hub proxy.
            var hubResponse = Stubber.Create <IDotNetifyHubResponse>()
                              .Setup(x => x.SendAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
                              .Returns((string connectionId, string vmId, string data) =>
            {
                var client = clients.First(x => x.ConnectionId == connectionId);
                return((client as IClientProxy).SendCoreAsync(nameof(IDotNetifyHubMethod.Response_VM), new object[] { new object[] { vmId, data } }));
            })
                              .Setup(x => x.SendToManyAsync(It.IsAny <IReadOnlyList <string> >(), It.IsAny <string>(), It.IsAny <string>()))
                              .Returns((IReadOnlyList <string> connectionIds, string vmId, string data) =>
            {
                foreach (var connectionId in connectionIds)
                {
                    var client = clients.First(x => x.ConnectionId == connectionId);
                    (client as IClientProxy).SendCoreAsync(nameof(IDotNetifyHubMethod.Response_VM), new object[] { new object[] { vmId, data } });
                }
                return(Task.CompletedTask);
            })
                              .Object;

            var hubForwarder = new DotNetifyHubForwarder(hubProxy, hubResponse);

            hubForwarderFactory.InvokeInstanceAsync(Arg.Any <string>(), Arg.Any <ForwardingOptions>(), Arg.Any <Func <DotNetifyHubForwarder, Task> >())
            .Returns((callInfo) => callInfo.Arg <Func <DotNetifyHubForwarder, Task> >().Invoke(hubForwarder));
        }