private void ShouldNotifyGatewayAboutFailureInDataTransfer() { const string id = "ConsentManagerId"; var dataFlowNotificationClient = new Mock <DataFlowNotificationClient>(MockBehavior.Strict, null); var configuration = new GatewayConfiguration { ClientId = id }; var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClient = new HttpClient(handlerMock.Object); var dataRequest = TestBuilder.DataRequest(TestBuilder.Faker().Random.Hash()); var entries = new List <Entry>().AsEnumerable(); var dataFlowClient = new DataFlowClient(httpClient, dataFlowNotificationClient.Object, configuration); handlerMock .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Throws(new Exception("Unknown exception")) .Verifiable(); dataFlowNotificationClient.Setup(client => client.NotifyGateway(id, It.IsAny <DataNotificationRequest>())) .Returns(Task.CompletedTask); dataFlowClient.SendDataToHiu(dataRequest, entries, null); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); }
public RegisterGatewayResult(GatewayConfiguration configuration) { Contract.Requires(configuration != null); Configuration = configuration; Status = RegisterGatewayResultStatus.Success; }
public TcpClientHandler(ILogger <TcpClientHandler> logger, ITcpClientManager tcpClientManager, IServerSessionManager serverSessionManager, IOptions <GatewayConfiguration> options) { this.logger = logger; this.tcpClientManager = tcpClientManager; this.serverSessionManager = serverSessionManager; configuration = options.Value; }
public AuthHubClient( GatewayConfiguration gatewayConfiguration, StateService stateService) { this.stateService = stateService; hubConnection = new HubConnectionBuilder() .WithAutomaticReconnect() .WithUrl(gatewayConfiguration.Endpoint + "/hub/auth", opts => { opts.AccessTokenProvider = () => { return(Task.FromResult(stateService.State.UserId.ToString())); }; opts.SkipNegotiation = true; opts.Transports = HttpTransportType.WebSockets; }) .Build(); hubConnection.Closed += _ => { connected = false; return(Task.CompletedTask); }; hubConnection.Reconnected += (e) => { connected = true; return(Task.CompletedTask); }; _ = Task.Run(async() => { await hubConnection.StartAsync(); connected = true; }); }
private void ShouldReturnDataComponent() { const string gatewayUrl = "https://root/central-registry"; var dataFlowNotificationClient = new Mock <DataFlowNotificationClient>(MockBehavior.Strict, null); var configuration = new GatewayConfiguration { Url = gatewayUrl, ClientId = "IN0410000183", ClientSecret = TestBuilder.RandomString() }; const string transactionId = "transactionId"; var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClient = new HttpClient(handlerMock.Object); var dataRequest = TestBuilder.TraceableDataRequest(transactionId); var content = TestBuilder.Faker().Random.String(); var checksum = TestBuilder.Faker().Random.Hash(); var dataNotificationRequest = TestBuilder.DataNotificationRequest(transactionId); var correlationId = Uuid.Generate().ToString(); var entries = new List <Entry> { new Entry(content, MediaTypeNames.Application.Json, checksum, null, "careContextReference") }.AsEnumerable(); var expectedUri = new Uri("http://callback/data/notification"); var dataFlowClient = new DataFlowClient(httpClient, dataFlowNotificationClient.Object, configuration); handlerMock .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK }) .Verifiable(); dataFlowNotificationClient.Setup(client => client.NotifyGateway(dataRequest.CmSuffix, It.IsAny <DataNotificationRequest>(), correlationId)) .Returns(Task.CompletedTask) .Callback((string cmSuffix, DataNotificationRequest request, string correlationId) => { dataNotificationRequest.Should().NotBeNull(); dataNotificationRequest.Notifier.Id.Should().Be(request.Notifier.Id); dataNotificationRequest.Notifier.Type.Should().Be(request.Notifier.Type); dataNotificationRequest.TransactionId.Should().Be(request.TransactionId); dataNotificationRequest.StatusNotification.HipId.Should().Be(request.StatusNotification.HipId); dataNotificationRequest.StatusNotification.SessionStatus.Should().Be( request.StatusNotification.SessionStatus); }); dataFlowClient.SendDataToHiu(dataRequest, entries, null); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post && message.RequestUri == expectedUri), ItExpr.IsAny <CancellationToken>()); }
public DataFlowClient(HttpClient httpClient, DataFlowNotificationClient dataFlowNotificationClient, GatewayConfiguration gatewayConfiguration) { this.httpClient = httpClient; this.dataFlowNotificationClient = dataFlowNotificationClient; this.gatewayConfiguration = gatewayConfiguration; }
public BranchTcpServerHandler(ILogger <BranchTcpServerHandler> logger, IServerSessionManager serverSessionManager, ITcpClientFactory tcpClientFactory, ITcpClientManager tcpClientManager, IOptions <GatewayConfiguration> options) { this.logger = logger; this.tcpClientManager = tcpClientManager; this.serverSessionManager = serverSessionManager; configuration = options.Value; Parallel.ForEach(configuration.BrabchServer, x => tcpClientFactory.CreateTcpClient(x.MatchId)); }
public GatewayHelper(GatewayConfiguration config) { this.GatewayConfig = config; Operators = (from o in config.Operators select(OperatorType) Enum.Parse(typeof(OperatorType), o)).ToList(); SendMQHelper = new MQHelper.RabbitMQHelper(AppConfig.MQHost, AppConfig.MQVHost, AppConfig.MQUserName, AppConfig.MQPassword); SendMQHelper.BindQueue(config.Gateway, AppConfig.MaxPriority, config.Gateway); }
private void ShouldReturnDataToGateway() { var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClient = new HttpClient(handlerMock.Object); var gatewayConfiguration = new GatewayConfiguration { Url = "http://someUrl" }; var authenticationUri = new Uri($"{gatewayConfiguration.Url}/{PATH_SESSIONS}"); var expectedUri = new Uri($"{gatewayConfiguration.Url}{PATH_ON_DISCOVER}"); var patientEnquiryRepresentation = new PatientEnquiryRepresentation( "123", "Jack", new List <CareContextRepresentation>(), new List <string>()); var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation( patientEnquiryRepresentation, Guid.NewGuid(), DateTime.Now, "transactionId", null, new Resp("requestId")); var gatewayClient = new GatewayClient(httpClient, gatewayConfiguration); var definition = new { accessToken = "Whatever", tokenType = "Bearer" }; var result = JsonConvert.SerializeObject(definition); var correlationId = Uuid.Generate().ToString(); handlerMock .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsInOrder(() => Task.FromResult(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(result) }), () => Task.FromResult(new HttpResponseMessage { StatusCode = HttpStatusCode.OK })); gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, "ncg", correlationId); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post && message.RequestUri == expectedUri), ItExpr.IsAny <CancellationToken>()); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post && message.RequestUri == authenticationUri), ItExpr.IsAny <CancellationToken>()); }
public ApiController( LatestDataProvider latestDataProvider, GatewayConfiguration gatewayConfiguration, AprsConfig aprsConfig ) { _latestDataProvider = latestDataProvider; _gatewayConfiguration = gatewayConfiguration; _aprsConfig = aprsConfig; }
public static void AddFirstPartyServices( this IServiceCollection services, IHostingEnvironment env, IConfigurationRoot rawConfig, GatewayConfiguration config) => services .RegisterConfig(config) .AddAuth(config) .AddDatabase(env, config) .AddTicketingConnector(env, rawConfig, config?.Connector?.Ticket) .AddMicroserviceProxies(config);
public InstantMessageProcessActor( ActorSystem actorSystem, GatewayConfiguration gatewayConfiguration ) { _actorSystem = actorSystem; _gatewayConfiguration = gatewayConfiguration; _latestAircraftMessages = new Dictionary <string, FlightDataDto>(); SetUpReceiver(); }
public ActorControlService( StreamProvider streamProvider, ActorPropsFactory actorPropsFactory, ActorSystem actorSystem, GatewayConfiguration gatewayConfiguration ) { _streamProvider = streamProvider; _actorPropsFactory = actorPropsFactory; _actorSystem = actorSystem; _gatewayConfiguration = gatewayConfiguration; }
/// <summary> /// Called by the service fabric when the listener is to be started /// </summary> /// <param name="cancellationToken">A token to monitor for abort requests</param> /// <returns>A task that completes when the service is openned</returns> public async Task <string> OpenAsync(CancellationToken cancellationToken) { string publishAddress = null; Guid traceId = Guid.NewGuid(); int threadCount = Environment.ProcessorCount; this.serverControl = new CancellationTokenSource(); GatewayConfiguration configuration = this.configurationProvider.Config; this.logger.Informational(traceId, this.componentName, "OpenAsync() invoked."); var iotHubConfigurationProvider = new ConfigurationProvider <IoTHubConfiguration>(traceId, this.serviceContext.ServiceName, this.serviceContext.CodePackageActivationContext, this.logger, "IoTHubClient"); iotHubConfigurationProvider.ConfigurationChangedEvent += (sender, args) => this.unsupportedConfigurationChangeCallback?.Invoke(); iotHubConfigurationProvider.ConfigurationPropertyChangedEvent += (sender, args) => this.unsupportedConfigurationChangeCallback?.Invoke(); IoTHubConfiguration iotHubConfiguration = iotHubConfigurationProvider.Config; X509Certificate2 certificate = this.GetServerCertificate(configuration); this.logger.Informational(traceId, this.componentName, "Certificate retrieved."); var mqttConfigurationProvider = new ConfigurationProvider <MqttServiceConfiguration>(traceId, this.serviceContext.ServiceName, this.serviceContext.CodePackageActivationContext, this.logger, "Mqtt"); mqttConfigurationProvider.ConfigurationChangedEvent += (sender, args) => this.unsupportedConfigurationChangeCallback?.Invoke(); mqttConfigurationProvider.ConfigurationPropertyChangedEvent += (sender, args) => this.unsupportedConfigurationChangeCallback?.Invoke(); MqttServiceConfiguration mqttConfiguration = mqttConfigurationProvider.Config; if (mqttConfiguration != null) { var mqttInboundTemplates = new List <string>(mqttConfiguration.MqttInboundTemplates); var mqttOutboundTemplates = new List <string>(mqttConfiguration.MqttOutboundTemplates); ISessionStatePersistenceProvider qosSessionProvider = await this.GetSessionStateProviderAsync(traceId, mqttConfiguration).ConfigureAwait(false); IQos2StatePersistenceProvider qos2SessionProvider = await this.GetQos2StateProvider(traceId, mqttConfiguration).ConfigureAwait(false); this.logger.Informational(traceId, this.componentName, "QOS Providers instantiated."); var settingsProvider = new ServiceFabricConfigurationProvider(traceId, this.componentName, this.logger, configuration, iotHubConfiguration, mqttConfiguration); this.bootStrapper = new Bootstrapper(settingsProvider, qosSessionProvider, qos2SessionProvider, mqttInboundTemplates, mqttOutboundTemplates); this.runTask = this.bootStrapper.RunAsync(certificate, threadCount, this.serverControl.Token); publishAddress = this.BuildPublishAddress(configuration); this.logger.Informational(traceId, this.componentName, "Bootstrapper instantiated."); } else { this.logger.Critical(traceId, this.componentName, "Failed to start endpoint because Mqtt service configuration is missing."); } return(publishAddress); }
public DBConfigurationPoller(IOcelotLoggerFactory ocelotLoggerFactory, IFileConfigurationRepository fileConfigurationRepository, IInternalConfigurationRepository internalConfigurationRepository, IInternalConfigurationCreator internalConfigurationCreator, GatewayConfiguration gatewayConfiguration) { _internalConfigRepo = internalConfigurationRepository; _internalConfigCreator = internalConfigurationCreator; _logger = ocelotLoggerFactory.CreateLogger <DBConfigurationPoller>(); _repo = fileConfigurationRepository; _option = gatewayConfiguration; }
internal static string ToConnectionString(this GatewayConfiguration gatewayConfiguration) { const string hostPattern = "{0}:{1}"; const string connectionStringPattern = "host={0};username={1};password={2};prefetchcount={3}"; var hostStringArray = gatewayConfiguration.Hosts .Select(x => string.Format(hostPattern, x.HostName, x.Port)) .ToArray(); var hosts = string.Join(",", hostStringArray); return(string.Format(connectionStringPattern, hosts, gatewayConfiguration.UserCrenedtial.UserName, gatewayConfiguration.UserCrenedtial.Password, gatewayConfiguration.PrefetchCount)); }
public RPCResult <GatewayConfiguration> GetGatewayConfig(string gateway) { try { GatewayConfiguration config = GatewayConfigDB.GetConfig(gateway); return(new RPCResult <GatewayConfiguration>(true, config, "")); } catch (Exception ex) { LogHelper.LogError("SMSService", "SMSService.GetGatewayConfig", ex.ToString()); return(new RPCResult <GatewayConfiguration>(false, null, "获取网关出现错误")); } }
protected override async Task <GatewayConfiguration> GetGatewayConfigurationCore() { var gatewayConfiguration = new GatewayConfiguration { AuthenticationUrl = await GetAppSettingValue("lyftAuthorizationUrl"), ApiUrl = await GetAppSettingValue("lyftApiUrl"), ClientID = await GetAppSettingValue("lyftClientID"), ClientSecret = await GetAppSettingValue("lyftClientSecret") }; return(gatewayConfiguration); }
public OgnConvertActor( IActorRefFactory actorSystem, AircraftProvider aircraftProvider, GatewayConfiguration gatewayConfiguration ) { // When receiving the raw string from the listener, convert it to FlightData and pass it to the next Actor Receive <string>(message => { var convertedMessage = StreamConversionService.ConvertData(message); if (convertedMessage == null) { // Ignore non-parseable messages return; } // The next step also happens on this Actor so tell another "Self" to handle the FlightData actorSystem.ActorSelection(Self.Path).Tell(convertedMessage, Self); }); // When receiving FlightData, convert it into FlightDataDto and pass it to the next actor Receive <FlightData>(message => { var aircraft = aircraftProvider.Load(message.AircraftId); if (!aircraft.Visible) { // The aircraft should not be visible, therefore drop the message. return; } var flying = message.Altitude >= gatewayConfiguration.MinimalAltitude && message.Speed >= gatewayConfiguration.MinimalSpeed; var convertedMessage = new FlightDataDto( message.Speed, message.Altitude, message.VerticalSpeed, message.TurnRate, message.Course, message.Position, message.DateTime, new AircraftDto(aircraft), flying ); // Pass the convertedMessage to the IMessageProcessActor so it can be further processed. actorSystem .ActorSelection($"user/{ActorControlService.MessageProcessActorName}") .Tell(convertedMessage, Self); }); }
public static IHandlerBuilder Build(Environment environment, GatewayConfiguration config) { var hosts = VirtualHosts.Create(); if (config.Hosts != null) { foreach (var host in config.Hosts) { hosts.Add(host.Key, GetHandler(environment, host.Value)); } } return(hosts); }
public ActorPropsFactory( GatewayConfiguration gatewayConfiguration, ActorSystem actorSystem, AircraftProvider aircraftProvider, IHubContext <DefaultHub> hubContext, LatestDataProvider latestDataProvider ) { _gatewayConfiguration = gatewayConfiguration; _actorSystem = actorSystem; _aircraftProvider = aircraftProvider; _hubContext = hubContext; _latestDataProvider = latestDataProvider; }
public RPCResult UpdateGatewayConfig(GatewayConfiguration config) { try { if (GatewayConfigDB.Update(config)) { return(new RPCResult(true, "")); } LogHelper.LogWarn("SMSService", "SMSService.UpdateGatewayConfig", "网关更新数据库失败"); return(new RPCResult(false, "更新网关失败")); } catch (Exception ex) { LogHelper.LogError("SMSService", "SMSService.UpdateGatewayConfig", ex.ToString()); return(new RPCResult(false, "更新网关出现错误")); } }
/// <summary> /// 添加网关配置信息 /// </summary> /// <param name="gatewayConfig"></param> /// <returns></returns> public static bool Add(GatewayConfiguration gatewayConfig) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into GatewayConfig("); strSql.Append("Gateway,Operators,HandlingAbility,MaxPackageSize)"); strSql.Append(" values ("); strSql.Append("@Gateway,@Operators,@HandlingAbility,@MaxPackageSize)"); DBHelper.Instance.Execute(strSql.ToString(), new { Gateway = gatewayConfig.Gateway, Operators = string.Join(";", gatewayConfig.Operators), HandlingAbility = gatewayConfig.HandlingAbility, MaxPackageSize = gatewayConfig.MaxPackageSize }); return(true); }
private void ShouldNotPostDataIfAuthenticationWithGatewayFailed() { var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClient = new HttpClient(handlerMock.Object); var gatewayConfiguration = new GatewayConfiguration { Url = "http://someUrl" }; var authenticationUri = new Uri($"{gatewayConfiguration.Url}/{PATH_SESSIONS}"); var patientEnquiryRepresentation = new PatientEnquiryRepresentation( "123", "Jack", new List <CareContextRepresentation>(), new List <string>()); var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation( patientEnquiryRepresentation, Guid.NewGuid(), DateTime.Now, "transactionId", null, new Resp("requestId")); var gatewayClient = new GatewayClient(httpClient, gatewayConfiguration); var correlationId = Uuid.Generate().ToString(); handlerMock .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway }) .Verifiable(); gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, "ncg", correlationId); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post && message.RequestUri == authenticationUri), ItExpr.IsAny <CancellationToken>()); }
/// <summary> /// 更新一条数据 /// </summary> public static bool Update(GatewayConfiguration gatewayConfig) { StringBuilder strSql = new StringBuilder(); strSql.Append("update GatewayConfig set "); strSql.Append("Operators=@Operators,"); strSql.Append("MaxPackageSize=@MaxPackageSize,"); strSql.Append("HandlingAbility=@HandlingAbility"); strSql.Append(" where Gateway=@Gateway"); DBHelper.Instance.Execute(strSql.ToString(), new { Gateway = gatewayConfig.Gateway, Operators = string.Join(";", gatewayConfig.Operators), HandlingAbility = gatewayConfig.HandlingAbility, MaxPackageSize = gatewayConfig.MaxPackageSize }); return(true); }
/// <summary> /// Configures all services & providers that are based on the appsettings.json /// </summary> /// <param name="services">The systems' IServiceCollection</param> private void ConfigureConfigBasedServices(IServiceCollection services) { var gatewayConfiguration = new GatewayConfiguration(); Configuration.GetSection("GatewayOptions").Bind(gatewayConfiguration); services.AddSingleton(gatewayConfiguration); var aprsConfig = new AprsConfig(); Configuration.GetSection("AprsConfig").Bind(aprsConfig); services.AddSingleton(aprsConfig); services.AddSingleton(_ => { var provider = new AircraftProvider(aprsConfig); provider.Initialize().GetAwaiter().GetResult(); return(provider); }); }
public void ConfigureServices(IServiceCollection services) { Mock <IDiscoveryRequestRepository> discoveryRequestRepository = new Mock <IDiscoveryRequestRepository>(); Mock <ILinkPatientRepository> linkPatientRepository = new Mock <ILinkPatientRepository>(); Mock <IMatchingRepository> matchingRepository = new Mock <IMatchingRepository>(); Mock <IPatientRepository> patientRepository = new Mock <IPatientRepository>(); Mock <ICareContextRepository> careContextRepository = new Mock <ICareContextRepository>(); Mock <IBackgroundJobClient> backgroundJobClient = new Mock <IBackgroundJobClient>(); Mock <ILogger <PatientDiscovery> > logger = new Mock <ILogger <PatientDiscovery> >(); var patientDiscovery = new PatientDiscovery( matchingRepository.Object, discoveryRequestRepository.Object, linkPatientRepository.Object, patientRepository.Object, careContextRepository.Object, logger.Object); var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClient = new HttpClient(handlerMock.Object); var gatewayConfiguration = new GatewayConfiguration { Url = "http://someUrl" }; var gatewayClient = new GatewayClient(httpClient, gatewayConfiguration); services .AddScoped <IPatientDiscovery, PatientDiscovery>(provider => patientDiscovery) .AddScoped <IGatewayClient, GatewayClient>(provider => gatewayClient) .AddScoped(provider => backgroundJobClient.Object) .AddRouting(options => options.LowercaseUrls = true) .AddControllers() .AddNewtonsoftJson( options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }) .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; options.JsonSerializerOptions.IgnoreNullValues = true; }) .Services .AddAuthentication("Test") .AddScheme <AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { }); }
public TcpClient(IServiceProvider serviceProvider, ITcpClientSessionManager sessionManager, ILogger <TcpClient> logger, IOptions <GatewayConfiguration> configuration) { this.logger = logger; this.sessionManager = sessionManager; this.configuration = configuration.Value; eventLoopGroup = new MultithreadEventLoopGroup(); bootstrap = new Bootstrap().Group(eventLoopGroup) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.ConnectTimeout, TimeSpan.FromSeconds(30)) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { var scope = serviceProvider.CreateScope().ServiceProvider; IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new IdleStateHandler(this.configuration.BrabchServerReaderIdleTimeSeconds, this.configuration.BrabchServerWriterIdleTimeSeconds, this.configuration.BrabchServerAllIdleTimeSeconds)); pipeline.AddLast(scope.GetRequiredService <TcpMetadataDecoder>()); pipeline.AddLast(scope.GetRequiredService <TcpMetadataEncoder>()); pipeline.AddLast(scope.GetRequiredService <TcpClientHandler>()); })); }
private async void ShouldReturnAccessToken() { var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClient = new HttpClient(handlerMock.Object); const string rootRul = "http://someUrl"; var expectedUri = new Uri($"{rootRul}/{PATH_SESSIONS}"); var correlationId = Uuid.Generate().ToString(); var configuration = new GatewayConfiguration { Url = rootRul, ClientId = TestBuilder.RandomString(), ClientSecret = TestBuilder.RandomString() }; var response = JsonConvert.SerializeObject(new { tokenType = "bearer", accessToken = "token" }); handlerMock .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(response, Encoding.UTF8, MediaTypeNames.Application.Json) }) .Verifiable(); var client = new GatewayClient(httpClient, configuration); var result = await client.Authenticate(correlationId); result.HasValue.Should().BeTrue(); result.MatchSome(token => token.Should().BeEquivalentTo("bearer token")); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post && message.RequestUri == expectedUri), ItExpr.IsAny <CancellationToken>()); }
public RPCResult AddGatewayConfig(GatewayConfiguration config) { try { if (GatewayConfigDB.Exist(config.Gateway)) { return(new RPCResult(false, "已存在此网关")); } if (GatewayConfigDB.Add(config)) { return(new RPCResult(true, "")); } LogHelper.LogWarn("SMSService", "SMSService.AddGatewayConfig", "网关添加数据库失败"); return(new RPCResult(false, "添加网关失败")); } catch (Exception ex) { LogHelper.LogError("SMSService", "SMSService.AddGatewayConfig", ex.ToString()); return(new RPCResult(false, "添加网关出现错误")); } }