예제 #1
0
        public void HttpResponseDataInResult()
        {
            MockServiceTracer tracer = new MockServiceTracer();

            System.Net.Http.HttpResponseMessage httpResponse = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
            httpResponse.Headers.Add("x-ms-header", "value");
            tracer.HttpResponses.Add(httpResponse);

            LiveTestRequest request = new LiveTestRequest();

            request.Id           = "12345";
            request.JsonRpc      = "2.0";
            request.HttpResponse = true;

            CommandExecutionResult result   = new CommandExecutionResult(null, null, false);
            LiveTestResponse       response = request.MakeResponse(result, tracer, this.logger);

            Assert.NotNull(response.Result.Headers);
            Assert.True(response.Result.Headers is Dictionary <string, object>);
            Dictionary <string, object> headers = (Dictionary <string, object>)response.Result.Headers;

            Assert.Equal(1, headers.Count);
            Assert.True(headers.ContainsKey("x-ms-header"));
            Assert.Equal(new string[] { "value" }, headers["x-ms-header"]);

            Assert.Equal((long)System.Net.HttpStatusCode.Accepted, response.Result.StatusCode);
        }
예제 #2
0
        public void SingleErrorResponse()
        {
            MockServiceTracer tracer      = new MockServiceTracer();
            object            errorResult = 5;
            List <object>     errors      = new List <object>();

            errors.Add(errorResult);
            CommandExecutionResult result  = new CommandExecutionResult(null, errors, true);
            LiveTestRequest        request = new LiveTestRequest();

            request.Id      = "12345";
            request.JsonRpc = "2.0";
            LiveTestResponse response = request.MakeResponse(result, tracer, this.logger);

            Assert.Equal(request.Id, response.Id);
            Assert.Equal(request.JsonRpc, response.JsonRpc);

            Assert.NotNull(response.Error);
            Assert.Equal(-32600, response.Error.Code); // Invalid Request error code defined by LSP

            Assert.NotNull(response.Error.Data);
            Assert.Null(response.Error.Data.Headers);
            Assert.Equal(default(long), response.Error.Data.StatusCode);
            Assert.NotNull(response.Error.Data.Response);
            Assert.Equal(errorResult, response.Error.Data.Response);
        }
        public void ReservedParameterStaysJObject()
        {
            GeneratedModule module = new GeneratedModule(null);
            OperationData   test   = new OperationData("testoperationid", "Get-Test");

            module.Operations["testoperationid"] = test;
            test.Parameters["__reserved"]        = new ParameterData()
            {
                Name = "__reserved",
                Type = new RuntimeTypeData()
                {
                    Type = typeof(string)
                }
            };

            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);
            JsonSerializerSettings   settings  = new JsonSerializerSettings();

            settings.Converters.Add(converter);

            string          json    = "{\"method\":\"A.testOperationId\",\"jsonrpc\":\"2.0\",\"id\":\"0\",\"params\":{\"__reserved\":{}}}";
            LiveTestRequest request = JsonConvert.DeserializeObject <LiveTestRequest>(json, settings);

            Assert.NotNull(request);
            Assert.Equal("0", request.Id);
            Assert.Equal("2.0", request.JsonRpc);
            Assert.Equal("A.testOperationId", request.Method);
            Assert.Equal("testoperationid", request.OperationId);
            Assert.True(request.Params.ContainsKey("__reserved"));
            Assert.Equal(typeof(JObject), request.Params["__reserved"].GetType());
        }
예제 #4
0
        public async Task RunAsync()
        {
            if (this.IsRunning)
            {
                throw new InvalidOperationException("Server is already running.");
            }

            // Retrieve all module information using the current runspace manager
            this.currentModule = this.parameters.RunspaceManager.GetModuleInfo(this.parameters.ModulePath);

            // Force load the module
            this.currentModule.Load(force: true);
            this.IsRunning = true;

            // Start message read thread
            this.messageReadThread = new Thread(async() =>
            {
                while (this.IsRunning)
                {
                    LiveTestRequest msg = await this.Input.ReadBlockAsync <LiveTestRequest>();
                    if (this.IsRunning)
                    {
                        this.parameters.Logger?.LogAsync("Processing message: {0}", Newtonsoft.Json.JsonConvert.SerializeObject(msg));
                        Task.Run(() => this.currentModule.ProcessRequest(msg));
                    }
                }
            })
            {
                IsBackground = true
            };
            this.messageReadThread.Start();
        }
예제 #5
0
        public void ProcessOperationFromJsonFull()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing")
            {
                Parameters = new Dictionary <string, ParameterData>()
                {
                    { "parameter", new ParameterData()
                      {
                          Name = "Parameter", Type = new RuntimeTypeData(typeof(GeneratedModuleTestsObject))
                      } }
                }
            };

            string json = "{\"method\":\"Things.Thing_Get\",\"params\":{\"__reserved\":{\"credentials\":[{\"x-ps-credtype\":\"commandBased\",\"tenantId\":\"testTenantId\",\"clientId\":\"testClientId\",\"secret\":\"testSecret\"},{\"x-ps-credtype\":\"parameterBased\",\"tenantId\":\"testTenantId\",\"clientId\":\"testClientId\",\"secret\":\"testSecret\"}]},\"parameter\":{\"string\":\"testValue\",\"number\":500,\"object\":{\"decimal\":1.2,\"boolean\":true}}}}";
            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);

            Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
            converter.RegisterSelf(settings);

            MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory();

            credentialsFactory.RegisterProvider("commandbased", new CommandBasedCredentialProvider());
            credentialsFactory.RegisterProvider("parameterbased", new ParameterBasedCredentialProvider());

            LiveTestRequest        request = Newtonsoft.Json.JsonConvert.DeserializeObject <LiveTestRequest>(json, settings);
            CommandExecutionResult result  = module.ProcessRequest(request, credentialsFactory);

            Assert.Equal("Login-Account [parameter {[String testValue] [Number 500] [Object [Decimal 1.2] [Boolean True]]}]", (string)runspace.InvokeHistory[0]);
            Assert.Equal("Login-Account [parameter {[String testValue] [Number 500] [Object [Decimal 1.2] [Boolean True]]}] [CredentialKey testCredentials]", (string)runspace.InvokeHistory[1]);
        }
        /// <summary>
        /// Create all credential providers specified by the given request, assuming the __reserved parameter has alreayd been converted by TranslateCredentialsObjects.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        public virtual IEnumerable <ICredentialProvider> Create(LiveTestRequest request, Logger logger)
        {
            if (request.Params != null && request.Params.ContainsKey("__reserved"))
            {
                Dictionary <string, object> reservedParams = (Dictionary <string, object>)request.Params["__reserved"];
                LiveTestCredentials[]       arr            = (LiveTestCredentials[])reservedParams["credentials"];
                foreach (LiveTestCredentials credentials in arr)
                {
                    ICredentialProvider provider = null;
                    string credType = String.IsNullOrEmpty(credentials.Type) ? "azure" : credentials.Type.ToLowerInvariant();
                    if (this.providers.ContainsKey(credType))
                    {
                        provider = this.providers[credType](logger);
                    }

                    if (provider != null)
                    {
                        foreach (string property in credentials.Properties.Keys)
                        {
                            provider.Set(property, credentials.Properties[property]);
                        }

                        yield return(provider);
                    }
                }
            }
        }
예제 #7
0
        public void UnknownProvider()
        {
            LiveTestRequest request = new LiveTestRequest();

            request.Params = new Dictionary <string, object>()
            {
                { "__reserved", new Dictionary <string, object>()
                  {
                      { "credentials", new LiveTestCredentials[] { new LiveTestCredentials()
                                                                   {
                                                                       Type       = Path.GetRandomFileName(),
                                                                       Properties = new Dictionary <string, object>()
                                                                       {
                                                                           { "tenantId", "testTenantId" },
                                                                           { "clientId", "testClientId" },
                                                                           { "secret", "testSecret" }
                                                                       }
                                                                   } } }
                  } }
            };

            LiveTestCredentialFactory         test   = new LiveTestCredentialFactory();
            IEnumerable <ICredentialProvider> result = test.Create(request, this.logger);

            Assert.Equal(0, result.Count());
        }
예제 #8
0
        public void TranslateMultipleCredentials()
        {
            string          requestJson = "{ \"params\": { \"__reserved\": { \"credentials\": [{ \"tenantId\": \"testTenantId\", \"clientId\": \"testClientId\", \"secret\": \"testSecret\", \"x-ps-credtype\": \"random\" },{ \"tenantId\": \"testTenantId\", \"clientId\": \"testClientId\", \"secret\": \"testSecret\" }] } } }";
            LiveTestRequest request     = Newtonsoft.Json.JsonConvert.DeserializeObject <LiveTestRequest>(requestJson);

            LiveTestCredentialFactory test = new LiveTestCredentialFactory();

            test.TranslateCredentialsObjects(request);

            request.Params.ContainsKey("__reserved");
            Assert.True(request.Params["__reserved"] is Dictionary <string, object>);
            Dictionary <string, object> reservedParams = (Dictionary <string, object>)request.Params["__reserved"];

            Assert.True(reservedParams.ContainsKey("credentials"));
            Assert.True(((Dictionary <string, object>)request.Params["__reserved"])["credentials"] is LiveTestCredentials[]);
            LiveTestCredentials[] credsArray = (LiveTestCredentials[])reservedParams["credentials"];

            Assert.Equal(2, credsArray.Length);
            LiveTestCredentials result = credsArray[0];

            Assert.Equal("random", result.Type);
            Assert.Equal("testTenantId", result.Properties["tenantId"].ToString());
            Assert.Equal("testClientId", result.Properties["clientId"].ToString());
            Assert.Equal("testSecret", result.Properties["secret"].ToString());

            result = credsArray[1];
            Assert.Equal("azure", result.Type);
            Assert.Equal("testTenantId", result.Properties["tenantId"].ToString());
            Assert.Equal("testClientId", result.Properties["clientId"].ToString());
            Assert.Equal("testSecret", result.Properties["secret"].ToString());
        }
예제 #9
0
        public void MultipleResultResponse()
        {
            MockServiceTracer tracer    = new MockServiceTracer();
            object            psResult1 = 5;
            object            psResult2 = "test";
            List <object>     psResults = new List <object>();

            psResults.Add(psResult1);
            psResults.Add(psResult2);
            CommandExecutionResult result  = new CommandExecutionResult(psResults, null, false);
            LiveTestRequest        request = new LiveTestRequest();

            request.Id      = "12345";
            request.JsonRpc = "2.0";
            LiveTestResponse response = request.MakeResponse(result, tracer, this.logger);

            Assert.Equal(request.Id, response.Id);
            Assert.Equal(request.JsonRpc, response.JsonRpc);

            Assert.NotNull(response.Result);
            Assert.Null(response.Result.Headers);
            Assert.Equal(default(long), response.Result.StatusCode);
            Assert.NotNull(response.Result.Response);
            Assert.Collection <object>((object[])response.Result.Response, new Action <object>[]
            {
                (obj) =>
                {
                    Assert.Equal(psResult1, obj);
                },
                (obj) =>
                {
                    Assert.Equal(psResult2, obj);
                }
            });
        }
예제 #10
0
        public void AzureCredType()
        {
            LiveTestRequest request = new LiveTestRequest();

            request.Params = new Dictionary <string, object>()
            {
                { "__reserved", new Dictionary <string, object>()
                  {
                      { "credentials", new LiveTestCredentials[] { new LiveTestCredentials()
                                                                   {
                                                                       Type       = "azure",
                                                                       Properties = new Dictionary <string, object>()
                                                                       {
                                                                           { "tenantId", "testTenantId" },
                                                                           { "clientId", "testClientId" },
                                                                           { "secret", "testSecret" }
                                                                       }
                                                                   } } }
                  } }
            };

            LiveTestCredentialFactory         test   = new LiveTestCredentialFactory();
            IEnumerable <ICredentialProvider> result = test.Create(request, this.logger);

            Assert.Equal(1, result.Count());
            ICredentialProvider first = result.First();

            Assert.NotNull(first);
            Assert.IsType <AzureCredentialProvider>(first);
            AzureCredentialProvider provider = (AzureCredentialProvider)first;

            Assert.Equal("testTenantId", provider.TenantId);
            Assert.Equal("testClientId", provider.ClientId);
            Assert.Equal("testSecret", provider.Secret);
        }
예제 #11
0
        public void ProcessOperationWithCredentials()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing");

            MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory();

            credentialsFactory.RegisterProvider("commandbased", new CommandBasedCredentialProvider());
            credentialsFactory.RegisterProvider("parameterbased", new ParameterBasedCredentialProvider());
            LiveTestRequest request = new LiveTestRequest();

            request.Method      = "Things.Thing_Get";
            request.OperationId = "Thing_Get";
            request.Params      = new Dictionary <string, object>()
            {
                { "__reserved", new Dictionary <string, object>()
                  {
                      { "credentials", new LiveTestCredentials[] { new LiveTestCredentials()
                                                                   {
                                                                       Type       = "commandBased",
                                                                       Properties = new Dictionary <string, object>()
                                                                       {
                                                                           { "tenantId", "testTenantId" },
                                                                           { "clientId", "testClientId" },
                                                                           { "secret", "testSecret" }
                                                                       }
                                                                   }, new LiveTestCredentials()
                                                                   {
                                                                       Type       = "parameterBased",
                                                                       Properties = new Dictionary <string, object>()
                                                                       {
                                                                           { "tenantId", "testTenantId" },
                                                                           { "clientId", "testClientId" },
                                                                           { "secret", "testSecret" }
                                                                       }
                                                                   } } }
                  } }
            };
            request.Params["parameter"] = new GeneratedModuleTestsObject()
            {
                String = "testValue",
                Number = 500,
                Object = new GeneratedModuleTestsSubObject()
                {
                    Decimal = 1.2,
                    Boolean = true
                }
            };

            CommandExecutionResult result = module.ProcessRequest(request, credentialsFactory);

            Assert.Equal(2, runspace.InvokeHistory.Count);
            Assert.Equal("Login-Account", (string)runspace.InvokeHistory[0]);
            Assert.Equal("Login-Account [CredentialKey testCredentials]", (string)runspace.InvokeHistory[1]);
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteRawValue("null");
                return;
            }

            LiveTestRequest             request = (LiveTestRequest)value;
            Dictionary <string, object> dict    = new Dictionary <string, object>();

            foreach (PropertyInfo pi in value.GetType().GetProperties())
            {
                if (!pi.Name.Equals("params", StringComparison.OrdinalIgnoreCase) && pi.GetCustomAttribute(typeof(JsonIgnoreAttribute)) == null)
                {
                    object val = pi.GetValue(value);
                    if ((val != null) || serializer.NullValueHandling == NullValueHandling.Include)
                    {
                        dict[pi.Name.ToLowerInvariant()] = val;
                    }
                }
            }

            dict["params"] = request.Params;
            if (module.Operations.ContainsKey(request.OperationId))
            {
                OperationData op = module.Operations[request.OperationId];
                Dictionary <string, object> newParams = new Dictionary <string, object>();
                foreach (string key in request.Params.Keys)
                {
                    if (key.Equals("__reserved", StringComparison.OrdinalIgnoreCase))
                    {
                        newParams[key] = request.Params;
                    }
                    else if (op.Parameters.ContainsKey(key))
                    {
                        // Decide if the JSON name or the PowerShell name should be used
                        if (!String.IsNullOrEmpty(op.Parameters[key].JsonName))
                        {
                            newParams[op.Parameters[key].JsonName.ToLowerInvariant()] = request.Params[key];
                        }
                        else
                        {
                            newParams[op.Parameters[key].Name.ToLowerInvariant()] = request.Params[key];
                        }
                    }
                }

                dict["params"] = newParams;
            }

            serializer.Serialize(writer, dict);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JsonSerializer  cleanSerializer = new JsonSerializer();
            LiveTestRequest request         = cleanSerializer.Deserialize(reader, objectType) as LiveTestRequest;
            // Current test protocol states that the method is given as A.B_C, so ignore anything without a '.'.
            int dotIndex = request.Method.IndexOf('.');

            if (dotIndex != -1)
            {
                request.OperationId = request.Method.Substring(dotIndex + 1).ToLowerInvariant();
                if (module.Operations.ContainsKey(request.OperationId))
                {
                    OperationData op = module.Operations[request.OperationId];
                    if (request.Params != null)
                    {
                        Dictionary <string, object> newParams = new Dictionary <string, object>();
                        foreach (string key in request.Params.Keys)
                        {
                            // Reserved parameter will be converted later.
                            if (key.Equals("__reserved", StringComparison.OrdinalIgnoreCase))
                            {
                                newParams[key] = request.Params[key];
                            }
                            else
                            {
                                ParameterData match = op.Parameters.Where((kvp) => !String.IsNullOrEmpty(kvp.Value.JsonName) &&
                                                                          kvp.Value.JsonName.Equals(key, StringComparison.OrdinalIgnoreCase)).Select((kvp) => kvp.Value).FirstOrDefault();
                                if (match == null && op.Parameters.ContainsKey(key.ToLowerInvariant()))
                                {
                                    match = op.Parameters[key.ToLowerInvariant()];
                                }
                                if (match != null)
                                {
                                    // This means that the parameter has been renamed from the spec name.
                                    object converted;
                                    if (ConvertObject(request.Params[key], match.Type.Type, serializer, out converted))
                                    {
                                        newParams[match.Name.ToLowerInvariant()] = converted;
                                    }
                                }
                            }
                        }

                        request.Params = newParams;
                    }
                }
            }

            return(request);
        }
        public void ConvertsMappedPropertyOfParameter()
        {
            GeneratedModule module = new GeneratedModule(null);
            OperationData   test   = new OperationData("testoperationid", "Get-Test");

            module.Operations["testoperationid"] = test;
            RuntimeTypeData jsonParmData = new RuntimeTypeData()
            {
                Type = typeof(LiveTestRequestConverterTestsObject)
            };

            jsonParmData.Properties["property"] = new ParameterData()
            {
                Name     = "property",
                JsonName = "prop",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(string)
                }
            };
            test.Parameters["jsonparm"] = new ParameterData()
            {
                Name = "jsonParm",
                Type = jsonParmData
            };

            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);
            JsonSerializerSettings   settings  = new JsonSerializerSettings();

            settings.Converters.Add(converter);
            settings.Converters.Add(new DynamicTypedObjectConverter(jsonParmData));

            string          json    = "{\"method\":\"A.testOperationId\",\"jsonrpc\":\"2.0\",\"id\":\"0\",\"params\":{\"jsonparm\":{\"prop\":\"testValue\"}}}";
            LiveTestRequest request = JsonConvert.DeserializeObject <LiveTestRequest>(json, settings);

            Assert.NotNull(request);
            Assert.Equal("0", request.Id);
            Assert.Equal("2.0", request.JsonRpc);
            Assert.Equal("A.testOperationId", request.Method);
            Assert.Equal("testoperationid", request.OperationId);
            Assert.True(request.Params.ContainsKey("jsonparm"));
            Assert.Equal(typeof(LiveTestRequestConverterTestsObject), request.Params["jsonparm"].GetType());
            Assert.Equal("testValue", ((LiveTestRequestConverterTestsObject)request.Params["jsonparm"]).Property);

            string reserialized = JsonConvert.SerializeObject(request, settings);

            Assert.Equal(json, reserialized);
        }
예제 #15
0
        public void TranslateHttpResponseProperty()
        {
            string          requestJson = "{ \"params\": { \"__reserved\": { \"httpResponse\": true } } }";
            LiveTestRequest request     = Newtonsoft.Json.JsonConvert.DeserializeObject <LiveTestRequest>(requestJson);

            LiveTestCredentialFactory test = new LiveTestCredentialFactory();

            test.TranslateCredentialsObjects(request);

            request.Params.ContainsKey("__reserved");
            Assert.True(request.Params["__reserved"] is Dictionary <string, object>);
            Dictionary <string, object> reservedParams = (Dictionary <string, object>)request.Params["__reserved"];

            Assert.False(reservedParams.ContainsKey("httpResponse"));
            Assert.True(request.HttpResponse);
        }
예제 #16
0
        public void NullResultResponse()
        {
            MockServiceTracer      tracer  = new MockServiceTracer();
            CommandExecutionResult result  = new CommandExecutionResult(null, null, false);
            LiveTestRequest        request = new LiveTestRequest();

            request.Id      = "12345";
            request.JsonRpc = "2.0";
            LiveTestResponse response = request.MakeResponse(result, tracer, this.logger);

            Assert.Equal(request.Id, response.Id);
            Assert.Equal(request.JsonRpc, response.JsonRpc);

            Assert.NotNull(response.Result);
            Assert.Null(response.Result.Headers);
            Assert.Equal(default(long), response.Result.StatusCode);
            Assert.Null(response.Result.Response);
        }
예제 #17
0
        public void ProcessOperationSimpleParameters()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing")
            {
                Parameters = new Dictionary <string, ParameterData>()
                {
                    { "Integer", new ParameterData()
                      {
                          Name = "Integer", Type = new RuntimeTypeData(typeof(int))
                      } },
                    { "Boolean", new ParameterData()
                      {
                          Name = "Boolean", Type = new RuntimeTypeData(typeof(bool))
                      } },
                    { "Decimal", new ParameterData()
                      {
                          Name = "Decimal", Type = new RuntimeTypeData(typeof(double))
                      } },
                    { "String", new ParameterData()
                      {
                          Name = "String", Type = new RuntimeTypeData(typeof(string))
                      } }
                }
            };

            MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory();
            LiveTestRequest           request            = new LiveTestRequest();

            request.Method            = "Things.Thing_Get";
            request.OperationId       = "Thing_Get";
            request.Params            = new Dictionary <string, object>();
            request.Params["integer"] = 5;
            request.Params["boolean"] = true;
            request.Params["decimal"] = 1.2;
            request.Params["string"]  = "testValue";

            CommandExecutionResult result = module.ProcessRequest(request, credentialsFactory);

            Assert.Equal(1, runspace.InvokeHistory.Count);
            Assert.Equal("Get-Thing [Integer 5] [Boolean True] [Decimal 1.2] [String testValue]", ((string)runspace.InvokeHistory[0]));
        }
예제 #18
0
        public void HttpResponseDataInErrorNoHttpResponseEnabled()
        {
            MockServiceTracer tracer = new MockServiceTracer();

            System.Net.Http.HttpResponseMessage httpResponse = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.BadGateway);
            httpResponse.Headers.Add("x-ms-header", "value");
            tracer.HttpResponses.Add(httpResponse);

            LiveTestRequest request = new LiveTestRequest();

            request.Id      = "12345";
            request.JsonRpc = "2.0";

            CommandExecutionResult result   = new CommandExecutionResult(null, null, true);
            LiveTestResponse       response = request.MakeResponse(result, tracer, this.logger);

            Assert.Null(response.Error.Data.Headers);
            Assert.Equal(default(long), response.Error.Data.StatusCode);
        }
        /// <summary>
        /// On first read, <paramref name="request"/> may contain a __reserved property with a generic JSON object. That object should have a credentials property.
        /// This method exists to convert the generic object of the credentials property into a strongly typed array of LiveTestCredentials objects.
        ///
        /// After processing, the __reserved property will be transformed into a Dictionary&lt;string, object&gt; object. The credentials key will point to an array of LiveTestCredentials objects.
        /// </summary>
        /// <param name="request">Request object to transform.</param>
        public virtual void TranslateCredentialsObjects(LiveTestRequest request)
        {
            // Check if request requires conversion
            if (request.Params != null && request.Params.ContainsKey("__reserved") && request.Params["__reserved"] is JObject)
            {
                JObject reservedParams = (JObject)request.Params["__reserved"];
                Dictionary <string, object> reservedParamsDict = new Dictionary <string, object>();
                foreach (JProperty property in reservedParams.Properties())
                {
                    if (property.Name.Equals("credentials", StringComparison.OrdinalIgnoreCase))
                    {
                        List <LiveTestCredentials> credsList = new List <LiveTestCredentials>();
                        if (property.Value is JObject)
                        {
                            // Single credentials object
                            credsList.Add(GetCredentials((JObject)property.Value));
                        }
                        else if (property.Value is JArray)
                        {
                            // Array of credentials objects
                            foreach (JToken obj in (JArray)property.Value)
                            {
                                credsList.Add(GetCredentials((JObject)obj));
                            }
                        }

                        reservedParamsDict[property.Name] = credsList.ToArray();
                    }
                    else if (property.Name.Equals("httpResponse", StringComparison.OrdinalIgnoreCase))
                    {
                        request.HttpResponse = property.Value.Value <bool>();
                    }
                    else
                    {
                        reservedParamsDict[property.Name] = property.Value;
                    }
                }

                request.Params["__reserved"] = reservedParamsDict;
            }
        }
예제 #20
0
        public void ExceptionResponse()
        {
            int             errorCode = 1;
            Exception       ex        = new NotImplementedException();
            LiveTestRequest request   = new LiveTestRequest();

            request.Id      = "12345";
            request.JsonRpc = "2.0";
            LiveTestResponse response = request.MakeResponse(ex, errorCode);

            Assert.Equal(request.Id, response.Id);
            Assert.Equal(request.JsonRpc, response.JsonRpc);

            Assert.NotNull(response.Error);
            Assert.Equal(errorCode, response.Error.Code);

            Assert.NotNull(response.Error.Data);
            Assert.Null(response.Error.Data.Headers);
            Assert.Equal(default(long), response.Error.Data.StatusCode);
            Assert.Equal(ex, response.Error.Data.Response);
        }
예제 #21
0
        public void MultipleErrorResponse()
        {
            MockServiceTracer tracer       = new MockServiceTracer();
            object            errorResult1 = 5;
            object            errorResult2 = "test";
            List <object>     errors       = new List <object>();

            errors.Add(errorResult1);
            errors.Add(errorResult2);
            CommandExecutionResult result  = new CommandExecutionResult(null, errors, true);
            LiveTestRequest        request = new LiveTestRequest();

            request.Id      = "12345";
            request.JsonRpc = "2.0";
            LiveTestResponse response = request.MakeResponse(result, tracer, this.logger);

            Assert.Equal(request.Id, response.Id);
            Assert.Equal(request.JsonRpc, response.JsonRpc);

            Assert.NotNull(response.Error);
            Assert.Equal(-32600, response.Error.Code); // Invalid Request error code defined by LSP

            Assert.NotNull(response.Error.Data);
            Assert.Null(response.Error.Data.Headers);
            Assert.Equal(default(long), response.Error.Data.StatusCode);
            Assert.NotNull(response.Error.Data.Response);
            Assert.True(response.Error.Data.Response is object[]);
            Assert.Collection <object>((object[])response.Error.Data.Response, new Action <object>[]
            {
                (obj) =>
                {
                    Assert.Equal(errorResult1, obj);
                },
                (obj) =>
                {
                    Assert.Equal(errorResult2, obj);
                }
            });
        }
예제 #22
0
        public void ProcessOperationComplexParameters()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing")
            {
                Parameters = new Dictionary <string, ParameterData>()
                {
                    { "Parameter", new ParameterData()
                      {
                          Name = "Parameter", Type = new RuntimeTypeData(typeof(GeneratedModuleTestsObject))
                      } }
                }
            };

            MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory();
            LiveTestRequest           request            = new LiveTestRequest();

            request.Method              = "Things.Thing_Get";
            request.OperationId         = "Thing_Get";
            request.Params              = new Dictionary <string, object>();
            request.Params["parameter"] = new GeneratedModuleTestsObject()
            {
                String = "testValue",
                Number = 500,
                Object = new GeneratedModuleTestsSubObject()
                {
                    Decimal = 1.2,
                    Boolean = true
                }
            };

            CommandExecutionResult result = module.ProcessRequest(request, credentialsFactory);

            Assert.Equal(1, runspace.InvokeHistory.Count);
            Assert.Equal("Get-Thing [Parameter {[String testValue] [Number 500] [Object [Decimal 1.2] [Boolean True]]}]", (string)runspace.InvokeHistory[0]);
        }
예제 #23
0
 public override IEnumerable ProcessRequest(LiveTestRequest request)
 {
     this.ProcessRequestCalled = true;
     return(null);
 }
예제 #24
0
 public virtual IEnumerable ProcessRequest(LiveTestRequest request)
 {
     return(null);
 }
        public void ConvertsPrimitiveParameters()
        {
            GeneratedModule module = new GeneratedModule(null);
            OperationData   test   = new OperationData("testoperationid", "Get-Test");

            module.Operations["testoperationid"] = test;
            test.Parameters["string"]            = new ParameterData()
            {
                Name     = "string",
                JsonName = "stringparm",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(string)
                }
            };
            test.Parameters["bool"] = new ParameterData()
            {
                Name     = "bool",
                JsonName = "boolparm",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(bool)
                }
            };
            test.Parameters["array"] = new ParameterData()
            {
                Name     = "array",
                JsonName = "arrayparm",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(bool[])
                }
            };

            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);
            JsonSerializerSettings   settings  = new JsonSerializerSettings();

            converter.RegisterSelf(settings);

            string          json    = "{\"method\":\"A.testOperationId\",\"jsonrpc\":\"2.0\",\"id\":\"0\",\"params\":{\"stringparm\":\"testValue\",\"boolparm\":true,\"arrayparm\":[true,false]}}";
            LiveTestRequest request = JsonConvert.DeserializeObject <LiveTestRequest>(json, settings);

            Assert.NotNull(request);
            Assert.Equal("0", request.Id);
            Assert.Equal("2.0", request.JsonRpc);
            Assert.Equal("A.testOperationId", request.Method);
            Assert.Equal("testoperationid", request.OperationId);
            Assert.True(request.Params.ContainsKey("string"));
            Assert.Equal(typeof(string), request.Params["string"].GetType());
            Assert.Equal("testValue", (string)request.Params["string"]);
            Assert.True(request.Params.ContainsKey("bool"));
            Assert.Equal(typeof(bool), request.Params["bool"].GetType());
            Assert.True((bool)request.Params["bool"]);
            Assert.True(request.Params.ContainsKey("array"));
            Assert.Equal(typeof(bool[]), request.Params["array"].GetType());
            Assert.Equal(2, ((bool[])request.Params["array"]).Length);
            Assert.True(((bool[])request.Params["array"])[0]);
            Assert.False(((bool[])request.Params["array"])[1]);

            string reserialized = JsonConvert.SerializeObject(request, settings);

            Assert.Equal(json, reserialized);
        }
예제 #26
0
        static void Main(string[] args)
        {
            //PARAMS
            LiveTestRequest request = new LiveTestRequest
            {
                TradingPairs = new List <string> {
                    "ethbtc",
                    "ltcbtc",
                    "bnbbtc",
                    "neobtc",
                    "bccbtc",
                    "gasbtc",
                    "wtcbtc",
                    "qtumbtc",
                    "yoyobtc",
                    "zrxbtc",
                    "funbtc",
                    "snmbtc",
                    "iotabtc",
                    "xvgbtc",
                    "eosbtc",
                    "sntbtc",
                    "etcbtc",
                    "engbtc",
                    "zecbtc",
                    "dashbtc",
                    "icnbtc",
                    "btgbtc",
                    "trxbtc",
                    "xrpbtc",
                    "enjbtc",
                    "storjbtc",
                    "venbtc",
                    "kmdbtc",
                    "nulsbtc",
                    "rdnbtc",
                    "xmrbtc",
                    "batbtc",
                    "arnbtc",
                    "gvtbtc",
                    "cdtbtc",
                    "gxsbtc",
                    "poebtc",
                    "fuelbtc",
                    "manabtc",
                    "dgdbtc",
                    "adxbtc",
                    "cmtbtc",
                    "xlmbtc",
                    "tnbbtc",
                    "gtobtc",
                    "icxbtc",
                    "ostbtc",
                    "elfbtc",
                    "aionbtc",
                    "edobtc",
                    "navbtc",
                    "lunbtc",
                    "trigbtc",
                    "vibebtc",
                    "iostbtc",
                    "chatbtc",
                    "steembtc",
                    "nanobtc",
                    "viabtc",
                    "blzbtc",
                    "aebtc",
                    "rpxbtc",
                    "ncashbtc",
                    "poabtc",
                    "zilbtc",
                    "ontbtc",
                    "stormbtc",
                    "xembtc",
                    "wanbtc",
                    "wprbtc",
                    "qlcbtc",
                    "sysbtc",
                    "grsbtc",
                    "cloakbtc",
                    "gntbtc",
                    "loombtc",
                    "bcnbtc",
                    "repbtc",
                    "tusdbtc",
                    "zenbtc",
                    "skybtc",
                    "cvcbtc",
                    "thetabtc",
                    "iotxbtc",
                    "qkcbtc",
                    "agibtc",
                    "nxsbtc",
                    "databtc",
                    "scbtc",
                    "npxsbtc",
                    "keybtc",
                    "nasbtc",
                    "mftbtc",
                    "dentbtc",
                    "ardrbtc",
                    "hotbtc",
                    "vetbtc",
                    "dockbtc",
                    "polybtc",
                },


                From          = new DateTime(2018, 08, 30),
                To            = new DateTime(2018, 08, 30),
                Interval      = TimeInterval.Minutes_15,
                Algorthm      = TradingAlgorthm.Macd,
                StartAmount   = 1m,
                TradingAmount = 0.1m,
                OrderType     = OrderType.LIMIT
            };

            //to start back testing, load the first 100 candles to build the relavent indicators
            //then loop though the remianing candles to simulate live trade streaming.
            //the system can then make decisions at which points to buy and sell (simple SMA strategy to start with).
            //once the processing has been completed the result are displayed, each trade with buy price and sell price and percentage profit.
            var backTest = new LiveTest(request);

            backTest.Log += LogTrade;
            //TODO make this process ASYNC.
            Console.WriteLine($"Starting Amount: {request.StartAmount}btc");
            backTest.StartTrading();
            backTest.FinishTrading();
            Console.WriteLine($"StartTime: {backTest.StartTime} FinishTime: {backTest.FinishTime}");

            DisplayTrades(request.TradingResults);

            Console.WriteLine($"BTC Finishing Amount: {request.FinalAmount}btc");
            Console.WriteLine($"Total PNL - {request.TradingResults.Sum(x => x.Pnl)}");
            Console.WriteLine($"Total % profit - {CalculatePercent(request)}");

            Console.ReadKey();
        }
예제 #27
0
        public async Task RunAsync()
        {
            if (this.IsRunning)
            {
                throw new InvalidOperationException("Server is already running.");
            }

            // Retrieve all module information using the current runspace manager
            this.currentModule        = this.parameters.RunspaceManager.GetModuleInfo(this.parameters.ModulePath);
            this.currentModule.Logger = this.parameters.Logger;

            // Parse specifications/metadata files for extra information, e.g. parameter renaming
            if (this.parameters.SpecificationPaths != null)
            {
                foreach (string specificationPath in this.parameters.SpecificationPaths)
                {
                    if (this.parameters.Logger != null)
                    {
                        this.parameters.Logger.LogAsync("Loading specification file: " + specificationPath);
                    }
                    Json.JsonPathFinder jsonFinder = new Json.JsonPathFinder(File.ReadAllText(specificationPath));
                    if (this.parameters.Logger != null)
                    {
                        this.parameters.Logger.LogAsync("Parsing specification file: " + specificationPath);
                    }
                    this.currentModule.LoadMetadataFromSpecification(jsonFinder);
                }
            }

            this.currentModule.CompleteMetadataLoad();

            // For JSON-RPC pipe input/output, add Newtonsoft.Json converters
            Newtonsoft.Json.JsonSerializerSettings inputSerializerSettings = null;
            if (this.Input is JsonRpcPipe)
            {
                JsonRpcPipe jsonRpcPipe = (JsonRpcPipe)this.Input;
                inputSerializerSettings = jsonRpcPipe.JsonSerializerSettings;
                new LiveTestRequestConverter(this.currentModule).RegisterSelf(jsonRpcPipe.JsonSerializerSettings);
                if (this.parameters.Logger != null)
                {
                    this.parameters.Logger.JsonSerializerSettings = jsonRpcPipe.JsonSerializerSettings;
                }
            }

            if (this.Output is JsonRpcPipe)
            {
                JsonRpcPipe jsonRpcPipe = (JsonRpcPipe)this.Output;
                // Double check this is a different object than the input pipe, if any.
                if (inputSerializerSettings == null || inputSerializerSettings != jsonRpcPipe.JsonSerializerSettings)
                {
                    new LiveTestRequestConverter(this.currentModule).RegisterSelf(jsonRpcPipe.JsonSerializerSettings);
                    if (this.parameters.Logger != null)
                    {
                        this.parameters.Logger.JsonSerializerSettings = jsonRpcPipe.JsonSerializerSettings;
                    }
                }
            }

            this.IsRunning = true;

            // Start message read thread
            this.messageReadThread = new Thread(async() =>
            {
                while (this.IsRunning)
                {
                    try
                    {
                        // Block and wait for the next request
                        LiveTestRequest msg = await this.Input.ReadBlock <LiveTestRequest>();
                        if (this.IsRunning)
                        {
                            if (msg == null)
                            {
                                if (this.parameters.Logger != null)
                                {
                                    this.parameters.Logger.LogAsync("Input stream has been closed, stopping server.", msg);
                                }

                                this.IsRunning = false;
                            }
                            else
                            {
                                if (this.parameters.Logger != null)
                                {
                                    this.parameters.Logger.LogAsync("Processing message: {0}", msg);
                                }
                                Task.Run(() =>
                                {
                                    LiveTestResponse response    = null;
                                    IServiceTracer serviceTracer = null;
                                    try
                                    {
                                        // Enable service tracing so that we can get service layer information required by test protocol
                                        long invocationId = this.parameters.TracingManager.GetNextInvocationId();
                                        serviceTracer     = this.parameters.TracingManager.CreateTracer(invocationId, this.parameters.Logger);
                                        this.parameters.TracingManager.EnableTracing();
                                        // Process teh request
                                        CommandExecutionResult commandResult = this.currentModule.ProcessRequest(msg, this.parameters.CredentialFactory);
                                        if (commandResult == null)
                                        {
                                            if (this.parameters.Logger != null)
                                            {
                                                this.parameters.Logger.LogAsync("Command not found.");
                                            }

                                            response = msg.MakeResponse(null, MethodNotFound);
                                        }
                                        else
                                        {
                                            response = msg.MakeResponse(commandResult, serviceTracer, parameters.ObjectTransforms, this.parameters.Logger);
                                        }
                                    }
                                    catch (Exception exRequest)
                                    {
                                        if (this.parameters.Logger != null)
                                        {
                                            this.parameters.Logger.LogError("Exception processing request: " + exRequest.ToString());
                                        }

                                        response = msg.MakeResponse(exRequest, InternalError);
                                    }
                                    finally
                                    {
                                        if (response != null)
                                        {
                                            this.Output.WriteBlock(response);
                                        }

                                        if (serviceTracer != null)
                                        {
                                            this.parameters.TracingManager.RemoveTracer(serviceTracer);
                                        }
                                    }
                                });
                            }
                        }
                    }
                    catch (Exception eRead)
                    {
                        if (this.parameters.Logger != null)
                        {
                            this.parameters.Logger.LogError("Exception during test server message loop: " + eRead.ToString());
                        }

                        this.IsRunning = false;
                    }
                }
            })
            {
                IsBackground = true
            };
            this.messageReadThread.Start();
            if (this.parameters.Logger != null)
            {
                this.parameters.Logger.LogAsync("PowerShell live test server has started.");
            }
        }
예제 #28
0
        public virtual CommandExecutionResult ProcessRequest(LiveTestRequest request, LiveTestCredentialFactory credentialsFactory)
        {
            if (this.Logger != null)
            {
                this.Logger.LogAsync("Translating credentials...");
            }
            credentialsFactory.TranslateCredentialsObjects(request);
            CommandExecutionResult result = null;
            string operationId            = request.OperationId == null ? null : request.OperationId.ToLowerInvariant();

            if (this.Logger != null)
            {
                this.Logger.LogAsync("Operation ID of message: " + operationId);
            }
            if (!String.IsNullOrEmpty(operationId) && this.Operations.ContainsKey(operationId))
            {
                if (this.Logger != null)
                {
                    this.Logger.LogAsync("Processing operation...");
                }
                OperationData op = this.Operations[operationId];
                // Create the command
                ICommandBuilder command = this.runspace.CreateCommand();
                command.Command = op.Command;
                foreach (string parameterName in op.Parameters.Keys)
                {
                    if (request.Params != null && request.Params.ContainsKey(parameterName.ToLowerInvariant()))
                    {
                        command.AddParameter(parameterName, request.Params[parameterName.ToLowerInvariant()]);
                    }
                    else
                    {
                        this.Logger.LogAsync("Request missing parameter: " + parameterName);
                    }
                }

                // Process credentials
                IEnumerable <ICredentialProvider> credProviders = credentialsFactory.Create(request, this.Logger);
                foreach (ICredentialProvider credProvider in credProviders)
                {
                    credProvider.Process(command);
                }

                // Run the command
                result = command.Invoke();

                // Run post processors, if any
                foreach (ICommandPostProcessor postProcessor in op.PostProcessors)
                {
                    result = postProcessor.Process(result);
                }
            }
            else
            {
                // error
                if (this.Logger != null)
                {
                    this.Logger.LogError("Operation ID was not found in module under test.");
                }
            }

            return(result);
        }
예제 #29
0
 public override CommandExecutionResult ProcessRequest(LiveTestRequest request, LiveTestCredentialFactory credentialsFactory)
 {
     this.ProcessRequestCalled = true;
     return(null);
 }