コード例 #1
0
        public void SpecTest(TestCase testCase)
        {
            Assume.That(!testCase.IsInvalid);

            var uriTemplate = new UriTemplate(testCase.Template);
            var uri = uriTemplate.Resolve(testCase.Suite.Variables);
            Assert.Contains(uri, testCase.Expecteds);
        }
コード例 #2
0
        public void TestResolving()
        {
            var template = new UriTemplate("http://store2.io/api/v2/catalogs/{pin}/products/scroll{?pageToken,pretty}");

            var uri = template.Resolve(new Dictionary<string, object>
            {
                {"pin", "13"}, // int here fails!
                {"pageToken", null}
            });

            Assert.AreEqual("http://store2.io/api/v2/catalogs/13/products/scroll", uri);
        }
コード例 #3
0
        public void MultiplePathSegmentTest()
        {
            var template = new UriTemplate("http://example.com/{path1}/{path2}");

            var actual = template.Resolve(new Dictionary<string, object>
            {
                { "path1", "foo" },
                { "path2", "bar" }
            });

            Assert.AreEqual("http://example.com/foo/bar", actual);
        }
コード例 #4
0
        public void ExampleTest()
        {
            var template = new UriTemplate("http://example.org/{area}/last-news{?type,count}");

            var uri = template.Resolve(new Dictionary<string, object>
            {
                { "area", "world" },
                { "type", "actual" },
                { "count", "10" }
            });

            Assert.AreEqual("http://example.org/world/last-news?type=actual&count=10", uri);
        }
コード例 #5
0
        public void ComplexTest()
        {
            var template = new UriTemplate("http://example.com{/paths*}{?q1,q2}{#f*}");

            var actual = template.Resolve(new Dictionary<string, object>
            {
                { "paths", new string[] { "foo", "bar" } },
                { "q1", "abc" },
                { "f", new Dictionary<string, string> { { "key1", "val1" }, { "key2", null } } }
            });

            Assert.AreEqual("http://example.com/foo/bar?q1=abc#key1=val1,key2=", actual);
        }
コード例 #6
0
        /// <summary>
        ///     Execute runs a HTTP request/response with the API endpoint.
        /// </summary>
        /// <typeparam name="T">Expected result type</typeparam>
        /// <param name="method">HTTP method, e.g. POST or GET</param>
        /// <param name="uriTemplate">URI Template as of RFC 6570</param>
        /// <param name="parameters">Query String Parameters</param>
        /// <param name="headers">Headers key/value pairs</param>
        /// <param name="body">Body</param>
        /// <returns>A <see cref="Task{T}" /> with an <see cref="IResponse" /></returns>
        /// <exception cref="ServiceException">A <see cref="ServiceException" /> is thrown if something goes wrong.</exception>
        public async Task<IResponse> Execute(HttpMethod method, string uriTemplate,
            IDictionary<string, object> parameters,
            IDictionary<string, string> headers, object body)
        {
            var template = new UriTemplate(uriTemplate);
            var url = template.Resolve(parameters);

            using (var client = new HttpClient())
            {
                // Always use application/json
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Always add a User-Agent
                var request = new HttpRequestMessage(method, url);
                request.Headers.Add("User-Agent", UserAgent);
                foreach (var kv in headers)
                {
                    request.Headers.Add(kv.Key, kv.Value);
                }
                if (body != null)
                {
                    var content = body is string ? (string) body : JsonConvert.SerializeObject(body);
                    request.Content = new StringContent(content, Encoding.UTF8, "application/json");
                }

                // Perform HTTP request and wrap response in IResponse
                try
                {
                    var httpResponse = await client.SendAsync(request);
                    var response = new Response(httpResponse);

                    if (httpResponse.IsSuccessStatusCode)
                    {
                        return response;
                    }

                    throw ServiceException.FromResponse(response);
                }
                catch (ServiceException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    throw new ServiceException("Request failed", null, e);
                }
            }
        }
コード例 #7
0
        public void SpecInvalidTest(TestCase testCase)
        {
            Assume.That(testCase.IsInvalid);

            try
            {
                var uriTemplate = new UriTemplate(testCase.Template);
                var uri = uriTemplate.Resolve(testCase.Suite.Variables);
            }
            catch (Exception exception)
            {
                if (exception is UriTemplateException)
                {
                    return;
                }
            }

            Assert.Fail("Template must be invalid");
        }
コード例 #8
0
ファイル: ComposerViewModel.cs プロジェクト: paulswartz/Mason
    private void Execute(FrameworkElement sender)
    {
      string url = Url;
      if (IsHRefTemplate)
      {
        try
        {
          JObject json = JsonConvert.DeserializeObject(Body) as JObject;
          if (json != null)
          {
            Resta.UriTemplates.UriTemplate t = new Resta.UriTemplates.UriTemplate(Url);
            IDictionary<string, object> parameters = new JsonObjectDictionary(json);
            url = t.Resolve(parameters);
          }
        }
        catch (Exception)
        {
          MessageBox.Show(GetOwnerWindow(), "Invalid URL template or template values");
          return;
        }
      }

      try
      {
        Uri tmp = new Uri(Url);
      }
      catch (Exception)
      {
        MessageBox.Show(GetOwnerWindow(), "Invalid URL");
        return;
      }

      if (string.IsNullOrEmpty(Method))
      {
        MessageBox.Show(GetOwnerWindow(), "Missing HTTP method");
        return;
      }

      ISession session = RamoneServiceManager.Session;

      Request req = session.Bind(url).Method(Method);

      if (Headers != null)
      {
        foreach (string line in Headers.Split('\n'))
        {
          int colonPos = line.IndexOf(':');
          if (colonPos > 0)
          {
            string header = line.Substring(0, colonPos).Trim();
            string value = line.Substring(colonPos + 1).Trim();
            if (!string.IsNullOrEmpty(header) && !string.IsNullOrEmpty(value))
            {
              if (header.Equals("accept", StringComparison.InvariantCultureIgnoreCase))
                req.Accept(value);
              else if (!header.Equals("content-type", StringComparison.InvariantCultureIgnoreCase))
                req.Header(header, value);
            }
          }
        }
      }

      if (SelectedType == MasonProperties.EncodingTypes.JSON && Body != null)
      {
        req.AsJson();
        req.Body(Body);
      }
      else if (SelectedType == MasonProperties.EncodingTypes.JSONFiles)
      {
        req.AsMultipartFormData();
        Hashtable files = new Hashtable();
        if (Body != null && !string.IsNullOrEmpty(JsonPartName))
          files[JsonPartName] = new Ramone.IO.StringFile { Filename = JsonPartName, ContentType = "application/json", Data = Body };
        foreach (ComposerFileViewModel file in Files)
        {
          if (!string.IsNullOrEmpty(file.Name) && !string.IsNullOrEmpty(file.Filename) && System.IO.File.Exists(file.Filename))
            files[file.Name] = new Ramone.IO.File(file.Filename);
        }
        req.Body(files);
      }

      Window w = Window.GetWindow(sender as DependencyObject);

      Publish(new ExecuteWebRequestEventArgs(session, req) { OnSuccess = (r => HandleSuccess(r, w)) });
    }
コード例 #9
0
        public void PathSegmentTest()
        {
            var template = new UriTemplate("http://example.com/{path}");

            var actual = template.Resolve(new Dictionary<string, object>
            {
                { "path", "foo" }
            });

            Assert.AreEqual("http://example.com/foo", actual);
        }
コード例 #10
0
        public void QueryParamsWithoutValuesTest()
        {
            var template = new UriTemplate("http://example.com/foo{?q1,q2}");

            var actual = template.Resolve(new Dictionary<string, object>());

            Assert.AreEqual("http://example.com/foo", actual);
        }
コード例 #11
0
        public void QueryParamsWithOneValueTest()
        {
            var template = new UriTemplate("http://example.com/foo{?q1,q2}");

            var actual = template.Resolve(new Dictionary<string, object>()
            {
                { "q1", "abc" }
            });

            Assert.AreEqual("http://example.com/foo?q1=abc", actual);
        }
コード例 #12
0
        public void QueryParamsWithMultipleValuesTest()
        {
            var template = new UriTemplate("http://example.com/foo{?q1,q2}");

            var actual = template.Resolve(new Dictionary<string, object>
            {
                { "q1", new string[] { "abc", "def", "ghi" } },
                { "q2", "10" }
            });

            Assert.AreEqual("http://example.com/foo?q1=abc,def,ghi&q2=10", actual);
        }
コード例 #13
0
        public void QueryParamsExpandedTest()
        {
            var template = new UriTemplate("http://example.com/foo{?q*}");

            var actual = template.Resolve(new Dictionary<string, object>
            {
                { "q", new Dictionary<string, string> { { "q1", "abc" }, { "q2", "def" } } }
            });

            Assert.AreEqual("http://example.com/foo?q1=abc&q2=def", actual);
        }
コード例 #14
0
 public string Resolve()
 {
     return(template.Resolve(variables));
 }
コード例 #15
0
        private void Execute(FrameworkElement sender)
        {
            string url = Url;

            if (IsHRefTemplate)
            {
                try
                {
                    JObject json = JsonConvert.DeserializeObject(Body) as JObject;
                    if (json != null)
                    {
                        Resta.UriTemplates.UriTemplate t          = new Resta.UriTemplates.UriTemplate(Url);
                        IDictionary <string, object>   parameters = new JsonObjectDictionary(json);
                        url = t.Resolve(parameters);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show(GetOwnerWindow(), "Invalid URL template or template values");
                    return;
                }
            }

            try
            {
                Uri tmp = new Uri(Url);
            }
            catch (Exception)
            {
                MessageBox.Show(GetOwnerWindow(), "Invalid URL");
                return;
            }

            if (string.IsNullOrEmpty(Method))
            {
                MessageBox.Show(GetOwnerWindow(), "Missing HTTP method");
                return;
            }

            ISession session = RamoneServiceManager.Session;

            Request req = session.Bind(url).Method(Method);

            if (Headers != null)
            {
                foreach (string line in Headers.Split('\n'))
                {
                    int colonPos = line.IndexOf(':');
                    if (colonPos > 0)
                    {
                        string header = line.Substring(0, colonPos).Trim();
                        string value  = line.Substring(colonPos + 1).Trim();
                        if (!string.IsNullOrEmpty(header) && !string.IsNullOrEmpty(value))
                        {
                            if (header.Equals("accept", StringComparison.InvariantCultureIgnoreCase))
                            {
                                req.Accept(value);
                            }
                            else if (!header.Equals("content-type", StringComparison.InvariantCultureIgnoreCase))
                            {
                                req.Header(header, value);
                            }
                        }
                    }
                }
            }

            if (SelectedType == MasonProperties.EncodingTypes.JSON && Body != null)
            {
                req.AsJson();
                req.Body(Body);
            }
            else if (SelectedType == MasonProperties.EncodingTypes.JSONFiles)
            {
                req.AsMultipartFormData();
                Hashtable files = new Hashtable();
                if (Body != null && !string.IsNullOrEmpty(JsonPartName))
                {
                    files[JsonPartName] = new Ramone.IO.StringFile {
                        Filename = JsonPartName, ContentType = "application/json", Data = Body
                    }
                }
                ;
                foreach (ComposerFileViewModel file in Files)
                {
                    if (!string.IsNullOrEmpty(file.Name) && !string.IsNullOrEmpty(file.Filename) && System.IO.File.Exists(file.Filename))
                    {
                        files[file.Name] = new Ramone.IO.File(file.Filename);
                    }
                }
                req.Body(files);
            }

            Window w = Window.GetWindow(sender as DependencyObject);

            Publish(new ExecuteWebRequestEventArgs(session, req)
            {
                OnSuccess = (r => HandleSuccess(r, w))
            });
        }