h in response.Headers) {
+ Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
}
+ Console.WriteLine(response.ContentAsJson(pretty: true));
}
- ///
- /// Main is a simple entrypoint for command line calling of the endpoint examples
- ///
- /// Command line args, expects API Key, (optional) alt URL
- static void Main(string[] args) {
- if (args.Length != 0) {
- new Sentences().RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
- }
- else {
- Console.WriteLine("An API Key is required");
- }
+ catch (Exception e) {
+ Console.WriteLine("Exception: " + e.Message);
+ }
+ }
+ ///
+ /// Main is a simple entrypoint for command line calling of the endpoint examples
+ ///
+ /// Command line args, expects API Key, (optional) alt URL
+ static void Main(string[] args) {
+ if (args.Length != 0) {
+ RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
+ }
+ else {
+ Console.WriteLine("An API Key is required");
}
}
}
diff --git a/examples/Sentiment.cs b/examples/Sentiment.cs
index 67a4293..624b486 100644
--- a/examples/Sentiment.cs
+++ b/examples/Sentiment.cs
@@ -1,59 +1,59 @@
-using Rosette.Api;
-using Rosette.Api.Models;
+using Rosette.Api.Client;
+using Rosette.Api.Client.Models;
-namespace examples {
- class Sentiment
- {
- ///
- /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
- /// An optional alternate URL may be provided, i.e. for an on-premise solution.
- ///
- /// Required api key (obtained from Basis Technology)
- /// Optional alternate URL
- private void RunEndpoint(string apiKey, string? altUrl =null) {
- try {
- ApiClient api = new ApiClient(apiKey);
- if (!string.IsNullOrEmpty(altUrl)) {
- api.UseAlternateURL(altUrl);
- }
- // Create a temporary file to demonstrate multi-part file upload of data
- var newFile = Path.GetTempFileName();
- StreamWriter sw = new StreamWriter(newFile);
- string sentiment_file_data = @"New Ghostbusters FilmOriginal Ghostbuster Dan Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new all-female Ghostbusters cast, telling The Hollywood Reporter, “The Aykroyd family is delighted by this inheritance of the Ghostbusters torch by these most magnificent women in comedy.”
";
- sw.WriteLine(sentiment_file_data);
- sw.Flush();
- sw.Close();
+namespace Rosette.Api.Examples;
- using (FileStream fs = File.OpenRead(newFile)) {
- Rosette.Api.Endpoints.Sentiment endpoint = new Rosette.Api.Endpoints.Sentiment(fs)
- .SetFileContentType(@"application/octet-stream")
- .SetLanguage("eng");
- Response response = endpoint.Call(api);
- foreach (KeyValuePair h in response.Headers) {
- Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
- }
- Console.WriteLine(response.ContentAsJson(pretty: true));
- }
+class Sentiment
+{
+ ///
+ /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
+ /// An optional alternate URL may be provided, i.e. for an on-premise solution.
+ ///
+ /// Required api key (obtained from Basis Technology)
+ /// Optional alternate URL
+ private static void RunEndpoint(string apiKey, string? altUrl = null) {
+ try {
+ ApiClient api = new(apiKey);
+ if (!string.IsNullOrEmpty(altUrl)) {
+ api.UseAlternateURL(altUrl);
+ }
+ // Create a temporary file to demonstrate multi-part file upload of data
+ var newFile = Path.GetTempFileName();
+ StreamWriter sw = new(newFile);
+ string sentiment_file_data = @"New Ghostbusters FilmOriginal Ghostbuster Dan Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new all-female Ghostbusters cast, telling The Hollywood Reporter, “The Aykroyd family is delighted by this inheritance of the Ghostbusters torch by these most magnificent women in comedy.”
";
+ sw.WriteLine(sentiment_file_data);
+ sw.Flush();
+ sw.Close();
- if (File.Exists(newFile)) {
- File.Delete(newFile);
+ using (FileStream fs = File.OpenRead(newFile)) {
+ Rosette.Api.Client.Endpoints.Sentiment endpoint = new Rosette.Api.Client.Endpoints.Sentiment(fs)
+ .SetFileContentType(@"application/octet-stream")
+ .SetLanguage("eng");
+ Response response = endpoint.Call(api);
+ foreach (KeyValuePair h in response.Headers) {
+ Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
}
+ Console.WriteLine(response.ContentAsJson(pretty: true));
}
- catch (Exception e) {
- Console.WriteLine("Exception: " + e.Message);
+
+ if (File.Exists(newFile)) {
+ File.Delete(newFile);
}
}
- ///
- /// Main is a simple entrypoint for command line calling of the endpoint examples
- ///
- /// Command line args, expects API Key, (optional) alt URL
- static void Main(string[] args) {
- if (args.Length != 0) {
- new Sentiment().RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
- }
- else {
- Console.WriteLine("An API Key is required");
- }
+ catch (Exception e) {
+ Console.WriteLine("Exception: " + e.Message);
+ }
+ }
+ ///
+ /// Main is a simple entrypoint for command line calling of the endpoint examples
+ ///
+ /// Command line args, expects API Key, (optional) alt URL
+ static void Main(string[] args) {
+ if (args.Length != 0) {
+ RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
+ }
+ else {
+ Console.WriteLine("An API Key is required");
}
}
}
\ No newline at end of file
diff --git a/examples/SimilarTerms.cs b/examples/SimilarTerms.cs
index 91264ab..208e4ab 100644
--- a/examples/SimilarTerms.cs
+++ b/examples/SimilarTerms.cs
@@ -1,60 +1,59 @@
-using Rosette.Api;
-using Rosette.Api.Models;
+using Rosette.Api.Client;
+using Rosette.Api.Client.Models;
-namespace examples
+namespace Rosette.Api.Examples;
+
+class SimilarTerms
{
- class SimilarTerms
+ ///
+ /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
+ /// An optional alternate URL may be provided, i.e. for an on-premise solution.
+ ///
+ /// Required api key (obtained from Basis Technology)
+ /// Optional alternate URL
+ private static void RunEndpoint(string apiKey, string? altUrl = null)
{
- ///
- /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
- /// An optional alternate URL may be provided, i.e. for an on-premise solution.
- ///
- /// Required api key (obtained from Basis Technology)
- /// Optional alternate URL
- private void RunEndpoint(string apiKey, string? altUrl = null)
+ try
{
- try
+ ApiClient api = new(apiKey);
+ if (!string.IsNullOrEmpty(altUrl))
{
- ApiClient api = new ApiClient(apiKey);
- if (!string.IsNullOrEmpty(altUrl))
- {
- api.UseAlternateURL(altUrl);
- }
+ api.UseAlternateURL(altUrl);
+ }
- var similar_terms_data = "spy";
- var resultLanguages = new List() { "spa", "deu", "jpn" };
+ var similar_terms_data = "spy";
+ var resultLanguages = new List() { "spa", "deu", "jpn" };
- Rosette.Api.Endpoints.SimilarTerms endpoint = new(similar_terms_data);
- endpoint.SetOption("resultLanguages", resultLanguages);
- Response response = endpoint.Call(api);
+ Rosette.Api.Client.Endpoints.SimilarTerms endpoint = new(similar_terms_data);
+ endpoint.SetOption("resultLanguages", resultLanguages);
+ Response response = endpoint.Call(api);
- // Print out the response headers
- foreach (KeyValuePair h in response.Headers)
- {
- Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
- }
- // Print out the content in JSON format. The Content property returns an IDictionary.
- Console.WriteLine(response.ContentAsJson(pretty: true));
- }
- catch (Exception e)
+ // Print out the response headers
+ foreach (KeyValuePair h in response.Headers)
{
- Console.WriteLine("Exception: " + e.Message);
+ Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
}
+ // Print out the content in JSON format. The Content property returns an IDictionary.
+ Console.WriteLine(response.ContentAsJson(pretty: true));
}
- ///
- /// Main is a simple entrypoint for command line calling of the endpoint examples
- ///
- /// Command line args, expects API Key, (optional) alt URL
- static void Main(string[] args)
+ catch (Exception e)
{
- if (args.Length != 0)
- {
- new SimilarTerms().RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
- }
- else
- {
- Console.WriteLine("An API Key is required");
- }
+ Console.WriteLine("Exception: " + e.Message);
+ }
+ }
+ ///
+ /// Main is a simple entrypoint for command line calling of the endpoint examples
+ ///
+ /// Command line args, expects API Key, (optional) alt URL
+ static void Main(string[] args)
+ {
+ if (args.Length != 0)
+ {
+ RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
+ }
+ else
+ {
+ Console.WriteLine("An API Key is required");
}
}
}
\ No newline at end of file
diff --git a/examples/SyntaxDependencies.cs b/examples/SyntaxDependencies.cs
index 6cf38aa..32b9ede 100644
--- a/examples/SyntaxDependencies.cs
+++ b/examples/SyntaxDependencies.cs
@@ -1,44 +1,44 @@
-using Rosette.Api;
-using Rosette.Api.Models;
+using Rosette.Api.Client;
+using Rosette.Api.Client.Models;
-namespace examples {
- class SyntaxDependencies
- {
- ///
- /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
- /// An optional alternate URL may be provided, i.e. for an on-premise solution.
- ///
- /// Required api key (obtained from Basis Technology)
- /// Optional alternate URL
- private void RunEndpoint(string apiKey, string? altUrl =null) {
- try {
- ApiClient api = new ApiClient(apiKey);
- if (!string.IsNullOrEmpty(altUrl)) {
- api.UseAlternateURL(altUrl);
- }
- string syntax_dependencies_data = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday.";
- Rosette.Api.Endpoints.SyntaxDependencies endpoint = new(syntax_dependencies_data);
- Response response = endpoint.Call(api);
- foreach (KeyValuePair h in response.Headers) {
- Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
- }
- Console.WriteLine(response.ContentAsJson(pretty: true));
+namespace Rosette.Api.Examples;
+
+class SyntaxDependencies
+{
+ ///
+ /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
+ /// An optional alternate URL may be provided, i.e. for an on-premise solution.
+ ///
+ /// Required api key (obtained from Basis Technology)
+ /// Optional alternate URL
+ private static void RunEndpoint(string apiKey, string? altUrl = null) {
+ try {
+ ApiClient api = new(apiKey);
+ if (!string.IsNullOrEmpty(altUrl)) {
+ api.UseAlternateURL(altUrl);
}
- catch (Exception e) {
- Console.WriteLine("Exception: " + e.Message);
+ string syntax_dependencies_data = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday.";
+ Rosette.Api.Client.Endpoints.SyntaxDependencies endpoint = new(syntax_dependencies_data);
+ Response response = endpoint.Call(api);
+ foreach (KeyValuePair h in response.Headers) {
+ Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
}
+ Console.WriteLine(response.ContentAsJson(pretty: true));
}
- ///
- /// Main is a simple entrypoint for command line calling of the endpoint examples
- ///
- /// Command line args, expects API Key, (optional) alt URL
- static void Main(string[] args) {
- if (args.Length != 0) {
- new SyntaxDependencies().RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
- }
- else {
- Console.WriteLine("An API Key is required");
- }
+ catch (Exception e) {
+ Console.WriteLine("Exception: " + e.Message);
+ }
+ }
+ ///
+ /// Main is a simple entrypoint for command line calling of the endpoint examples
+ ///
+ /// Command line args, expects API Key, (optional) alt URL
+ static void Main(string[] args) {
+ if (args.Length != 0) {
+ RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
+ }
+ else {
+ Console.WriteLine("An API Key is required");
}
}
}
diff --git a/examples/TextEmbedding.cs b/examples/TextEmbedding.cs
index 757f105..144fdd4 100644
--- a/examples/TextEmbedding.cs
+++ b/examples/TextEmbedding.cs
@@ -1,46 +1,46 @@
-using Rosette.Api;
-using Rosette.Api.Models;
+using Rosette.Api.Client;
+using Rosette.Api.Client.Models;
-namespace examples {
- class TextEmbedding
- {
- ///
- /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
- /// An optional alternate URL may be provided, i.e. for an on-premise solution.
- ///
- /// Required api key (obtained from Basis Technology)
- /// Optional alternate URL
- private void RunEndpoint(string apiKey, string? altUrl =null) {
- try {
- ApiClient api = new ApiClient(apiKey);
- if (!string.IsNullOrEmpty(altUrl)) {
- api.UseAlternateURL(altUrl);
- }
- string embedding_data = @"Cambridge, Massachusetts";
- Rosette.Api.Endpoints.TextEmbedding endpoint = new(embedding_data);
- Response response = endpoint.Call(api);
- foreach (KeyValuePair h in response.Headers)
- {
- Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
- }
+namespace Rosette.Api.Examples;
- Console.WriteLine(response.ContentAsJson(pretty: true));
+class TextEmbedding
+{
+ ///
+ /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
+ /// An optional alternate URL may be provided, i.e. for an on-premise solution.
+ ///
+ /// Required api key (obtained from Basis Technology)
+ /// Optional alternate URL
+ private static void RunEndpoint(string apiKey, string? altUrl = null) {
+ try {
+ ApiClient api = new(apiKey);
+ if (!string.IsNullOrEmpty(altUrl)) {
+ api.UseAlternateURL(altUrl);
}
- catch (Exception e) {
- Console.WriteLine(e.Message);
+ string embedding_data = @"Cambridge, Massachusetts";
+ Rosette.Api.Client.Endpoints.TextEmbedding endpoint = new(embedding_data);
+ Response response = endpoint.Call(api);
+ foreach (KeyValuePair h in response.Headers)
+ {
+ Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
}
+
+ Console.WriteLine(response.ContentAsJson(pretty: true));
}
- ///
- /// Main is a simple entrypoint for command line calling of the endpoint examples
- ///
- /// Command line args, expects API Key, (optional) alt URL
- static void Main(string[] args) {
- if (args.Length != 0) {
- new TextEmbedding().RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
- }
- else {
- Console.WriteLine("An API Key is required");
- }
+ catch (Exception e) {
+ Console.WriteLine(e.Message);
+ }
+ }
+ ///
+ /// Main is a simple entrypoint for command line calling of the endpoint examples
+ ///
+ /// Command line args, expects API Key, (optional) alt URL
+ static void Main(string[] args) {
+ if (args.Length != 0) {
+ RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
+ }
+ else {
+ Console.WriteLine("An API Key is required");
}
}
}
diff --git a/examples/Tokens.cs b/examples/Tokens.cs
index bda4202..1676fc3 100644
--- a/examples/Tokens.cs
+++ b/examples/Tokens.cs
@@ -1,44 +1,44 @@
-using Rosette.Api;
-using Rosette.Api.Models;
+using Rosette.Api.Client;
+using Rosette.Api.Client.Models;
-namespace examples {
- class Tokens
- {
- ///
- /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
- /// An optional alternate URL may be provided, i.e. for an on-premise solution.
- ///
- /// Required api key (obtained from Basis Technology)
- /// Optional alternate URL
- private void RunEndpoint(string apiKey, string? altUrl =null) {
- try {
- ApiClient api = new ApiClient(apiKey);
- if (!string.IsNullOrEmpty(altUrl)) {
- api.UseAlternateURL(altUrl);
- }
- string tokens_data = @"北京大学生物系主任办公室内部会议";
- Rosette.Api.Endpoints.Tokens endpoint = new(tokens_data);
- Response response = endpoint.Call(api);
- foreach (KeyValuePair h in response.Headers) {
- Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
- }
- Console.WriteLine(response.ContentAsJson(pretty: true));
+namespace Rosette.Api.Examples;
+
+class Tokens
+{
+ ///
+ /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
+ /// An optional alternate URL may be provided, i.e. for an on-premise solution.
+ ///
+ /// Required api key (obtained from Basis Technology)
+ /// Optional alternate URL
+ private static void RunEndpoint(string apiKey, string? altUrl = null) {
+ try {
+ ApiClient api = new(apiKey);
+ if (!string.IsNullOrEmpty(altUrl)) {
+ api.UseAlternateURL(altUrl);
}
- catch (Exception e) {
- Console.WriteLine("Exception: " + e.Message);
+ string tokens_data = @"北京大学生物系主任办公室内部会议";
+ Rosette.Api.Client.Endpoints.Tokens endpoint = new(tokens_data);
+ Response response = endpoint.Call(api);
+ foreach (KeyValuePair h in response.Headers) {
+ Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
}
+ Console.WriteLine(response.ContentAsJson(pretty: true));
}
- ///
- /// Main is a simple entrypoint for command line calling of the endpoint examples
- ///
- /// Command line args, expects API Key, (optional) alt URL
- static void Main(string[] args) {
- if (args.Length != 0) {
- new Tokens().RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
- }
- else {
- Console.WriteLine("An API Key is required");
- }
+ catch (Exception e) {
+ Console.WriteLine("Exception: " + e.Message);
+ }
+ }
+ ///
+ /// Main is a simple entrypoint for command line calling of the endpoint examples
+ ///
+ /// Command line args, expects API Key, (optional) alt URL
+ static void Main(string[] args) {
+ if (args.Length != 0) {
+ RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
+ }
+ else {
+ Console.WriteLine("An API Key is required");
}
}
}
diff --git a/examples/Topics.cs b/examples/Topics.cs
index 544f735..6d1d7bf 100644
--- a/examples/Topics.cs
+++ b/examples/Topics.cs
@@ -1,44 +1,44 @@
-using Rosette.Api;
-using Rosette.Api.Models;
+using Rosette.Api.Client;
+using Rosette.Api.Client.Models;
-namespace examples {
- class Topics
- {
- ///
- /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
- /// An optional alternate URL may be provided, i.e. for an on-premise solution.
- ///
- /// Required api key (obtained from Basis Technology)
- /// Optional alternate URL
- private void RunEndpoint(string apiKey, string? altUrl =null) {
- try {
- ApiClient api = new ApiClient(apiKey);
- if (!string.IsNullOrEmpty(altUrl)) {
- api.UseAlternateURL(altUrl);
- }
- string topics_data = @"Lily Collins is in talks to join Nicholas Hoult in Chernin Entertainment and Fox Searchlight's J.R.R. Tolkien biopic Tolkien. Anthony Boyle, known for playing Scorpius Malfoy in the British play Harry Potter and the Cursed Child, also has signed on for the film centered on the famed author. In Tolkien, Hoult will play the author of the Hobbit and Lord of the Rings book series that were later adapted into two Hollywood trilogies from Peter Jackson. Dome Karukoski is directing the project.";
- Rosette.Api.Endpoints.Topics endpoint = new(topics_data);
- Response response = endpoint.Call(api);
- foreach (KeyValuePair h in response.Headers) {
- Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
- }
- Console.WriteLine(response.ContentAsJson(pretty: true));
+namespace Rosette.Api.Examples;
+
+class Topics
+{
+ ///
+ /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
+ /// An optional alternate URL may be provided, i.e. for an on-premise solution.
+ ///
+ /// Required api key (obtained from Basis Technology)
+ /// Optional alternate URL
+ private static void RunEndpoint(string apiKey, string? altUrl = null) {
+ try {
+ ApiClient api = new(apiKey);
+ if (!string.IsNullOrEmpty(altUrl)) {
+ api.UseAlternateURL(altUrl);
}
- catch (Exception e) {
- Console.WriteLine("Exception: " + e.Message);
+ string topics_data = @"Lily Collins is in talks to join Nicholas Hoult in Chernin Entertainment and Fox Searchlight's J.R.R. Tolkien biopic Tolkien. Anthony Boyle, known for playing Scorpius Malfoy in the British play Harry Potter and the Cursed Child, also has signed on for the film centered on the famed author. In Tolkien, Hoult will play the author of the Hobbit and Lord of the Rings book series that were later adapted into two Hollywood trilogies from Peter Jackson. Dome Karukoski is directing the project.";
+ Rosette.Api.Client.Endpoints.Topics endpoint = new(topics_data);
+ Response response = endpoint.Call(api);
+ foreach (KeyValuePair h in response.Headers) {
+ Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
}
+ Console.WriteLine(response.ContentAsJson(pretty: true));
}
- ///
- /// Main is a simple entrypoint for command line calling of the endpoint examples
- ///
- /// Command line args, expects API Key, (optional) alt URL
- static void Main(string[] args) {
- if (args.Length != 0) {
- new Topics().RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
- }
- else {
- Console.WriteLine("An API Key is required");
- }
+ catch (Exception e) {
+ Console.WriteLine("Exception: " + e.Message);
+ }
+ }
+ ///
+ /// Main is a simple entrypoint for command line calling of the endpoint examples
+ ///
+ /// Command line args, expects API Key, (optional) alt URL
+ static void Main(string[] args) {
+ if (args.Length != 0) {
+ RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
+ }
+ else {
+ Console.WriteLine("An API Key is required");
}
}
}
\ No newline at end of file
diff --git a/examples/Transliteration.cs b/examples/Transliteration.cs
index dc484c1..894293c 100644
--- a/examples/Transliteration.cs
+++ b/examples/Transliteration.cs
@@ -1,46 +1,46 @@
-using Rosette.Api;
-using Rosette.Api.Models;
+using Rosette.Api.Client;
+using Rosette.Api.Client.Models;
-namespace examples {
- class Transliteration
- {
- ///
- /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
- /// An optional alternate URL may be provided, i.e. for an on-premise solution.
- ///
- /// Required api key (obtained from Basis Technology)
- /// Optional alternate URL
- private void RunEndpoint(string apiKey, string? altUrl =null) {
- try {
- ApiClient api = new ApiClient(apiKey);
- if (!string.IsNullOrEmpty(altUrl)) {
- api.UseAlternateURL(altUrl);
- }
- string transliteration_data = "ana r2ye7 el gam3a el sa3a 3 el 3asr";
+namespace Rosette.Api.Examples;
- Rosette.Api.Endpoints.Transliteration endpoint = new Rosette.Api.Endpoints.Transliteration(transliteration_data).SetLanguage("ara");
- Response response = endpoint.Call(api);
-
- foreach (KeyValuePair h in response.Headers) {
- Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
- }
- Console.WriteLine(response.ContentAsJson(pretty: true));
+class Transliteration
+{
+ ///
+ /// RunEndpoint runs the example. By default the endpoint will be run against the Rosette Cloud Service.
+ /// An optional alternate URL may be provided, i.e. for an on-premise solution.
+ ///
+ /// Required api key (obtained from Basis Technology)
+ /// Optional alternate URL
+ private static void RunEndpoint(string apiKey, string? altUrl = null) {
+ try {
+ ApiClient api = new(apiKey);
+ if (!string.IsNullOrEmpty(altUrl)) {
+ api.UseAlternateURL(altUrl);
}
- catch (Exception e) {
- Console.WriteLine("Exception: " + e.Message);
+ string transliteration_data = "ana r2ye7 el gam3a el sa3a 3 el 3asr";
+
+ Rosette.Api.Client.Endpoints.Transliteration endpoint = new Rosette.Api.Client.Endpoints.Transliteration(transliteration_data).SetLanguage("ara");
+ Response response = endpoint.Call(api);
+
+ foreach (KeyValuePair h in response.Headers) {
+ Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
}
+ Console.WriteLine(response.ContentAsJson(pretty: true));
}
- ///
- /// Main is a simple entrypoint for command line calling of the endpoint examples
- ///
- /// Command line args, expects API Key, (optional) alt URL
- static void Main(string[] args) {
- if (args.Length != 0) {
- new Transliteration().RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
- }
- else {
- Console.WriteLine("An API Key is required");
- }
+ catch (Exception e) {
+ Console.WriteLine("Exception: " + e.Message);
+ }
+ }
+ ///
+ /// Main is a simple entrypoint for command line calling of the endpoint examples
+ ///
+ /// Command line args, expects API Key, (optional) alt URL
+ static void Main(string[] args) {
+ if (args.Length != 0) {
+ RunEndpoint(args[0], args.Length > 1 ? args[1] : null);
+ }
+ else {
+ Console.WriteLine("An API Key is required");
}
}
}
diff --git a/rosette_api/ApiClient.cs b/rosette_api/ApiClient.cs
index 20562fe..1ecc042 100644
--- a/rosette_api/ApiClient.cs
+++ b/rosette_api/ApiClient.cs
@@ -1,6 +1,6 @@
using System.Net;
-namespace Rosette.Api;
+namespace Rosette.Api.Client;
public class ApiClient : IDisposable
{
diff --git a/rosette_api/Endpoints/AddressSimilarity.cs b/rosette_api/Endpoints/AddressSimilarity.cs
index 69a29e6..a6868e5 100644
--- a/rosette_api/Endpoints/AddressSimilarity.cs
+++ b/rosette_api/Endpoints/AddressSimilarity.cs
@@ -1,7 +1,7 @@
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints
{
public class AddressSimilarity : EndpointBase
{
@@ -18,7 +18,12 @@ public AddressSimilarity(AddressField? address1, AddressField? address2) : base(
Params["address2"] = address2;
}
- public Response Call(ApiClient api)
+ public new Task CallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
+ return Funcs.PostCallAsync(api, cancellationToken);
+ }
+
+ public new Response Call(ApiClient api)
{
return Funcs.PostCall(api);
}
diff --git a/rosette_api/Endpoints/Categories.cs b/rosette_api/Endpoints/Categories.cs
index 25768db..83f3a3c 100644
--- a/rosette_api/Endpoints/Categories.cs
+++ b/rosette_api/Endpoints/Categories.cs
@@ -1,6 +1,6 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class Categories : ContentEndpointBase
{
@@ -8,7 +8,6 @@ public class Categories : ContentEndpointBase
/// CategoriesEndpoint returns the categories extracted from the endpoint
///
/// text, Uri object or FileStream
- public Categories(object content) : base("categories", content)
- {
- }
+ public Categories(object content) : base("categories", content) { }
}
+
diff --git a/rosette_api/Endpoints/Core/ContentEndpointBase.cs b/rosette_api/Endpoints/Core/ContentEndpointBase.cs
index 9ce705b..91302cd 100644
--- a/rosette_api/Endpoints/Core/ContentEndpointBase.cs
+++ b/rosette_api/Endpoints/Core/ContentEndpointBase.cs
@@ -1,6 +1,6 @@
-using Rosette.Api.Models;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Endpoints.Core;
+namespace Rosette.Api.Client.Endpoints.Core;
///
/// Abstract base class for Rosette API endpoints that accept content and common parameters
@@ -93,12 +93,23 @@ public T SetFileContentType(string contentType)
///
public string Filename => Funcs.Filename;
+ ///
+ /// CallAsync passes the data to the server and returns the response asynchronously
+ ///
+ /// ApiClient object
+ /// Optional cancellation token
+ /// Response
+ public new Task CallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
+ return Funcs.PostCallAsync(api, cancellationToken);
+ }
+
///
/// Call passes the data to the server and returns the response
///
/// RosetteAPI object
/// RosetteResponse
- public Response Call(ApiClient api)
+ public new Response Call(ApiClient api)
{
return Funcs.PostCall(api);
}
diff --git a/rosette_api/Endpoints/Core/EndpointBase.cs b/rosette_api/Endpoints/Core/EndpointBase.cs
index 49b6b4a..1a7e66e 100644
--- a/rosette_api/Endpoints/Core/EndpointBase.cs
+++ b/rosette_api/Endpoints/Core/EndpointBase.cs
@@ -1,6 +1,7 @@
-using System.Collections.Specialized;
+using Rosette.Api.Client.Models;
+using System.Collections.Specialized;
-namespace Rosette.Api.Endpoints.Core;
+namespace Rosette.Api.Client.Endpoints.Core;
public class EndpointBase where T : EndpointBase
{
@@ -88,4 +89,22 @@ public T RemoveUrlParameter(string parameterKey)
return (T)this;
}
+ ///
+ /// CallAsync passes the data to the server and returns the response asynchronously
+ ///
+ /// ApiClient object
+ /// Optional cancellation token
+ /// Response
+ public Task CallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
+ return Funcs.GetCallAsync(api, cancellationToken);
+ }
+
+ ///
+ /// Call passes the data to the server and returns the response
+ ///
+ /// ApiClient object
+ /// Response
+ public Response Call(ApiClient api) => Funcs.GetCall(api);
+
}
diff --git a/rosette_api/Endpoints/Core/EndpointExecutor.cs b/rosette_api/Endpoints/Core/EndpointExecutor.cs
index 621c9a4..6169d52 100644
--- a/rosette_api/Endpoints/Core/EndpointExecutor.cs
+++ b/rosette_api/Endpoints/Core/EndpointExecutor.cs
@@ -1,10 +1,10 @@
-using Rosette.Api.Models;
+using Rosette.Api.Client.Models;
using System.Collections.Specialized;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
-namespace Rosette.Api.Endpoints.Core;
+namespace Rosette.Api.Client.Endpoints.Core;
///
/// EndpointProcessor provices the compilation and processing of the endpoint
@@ -17,6 +17,7 @@ public class EndpointExecutor {
private const string LANGUAGE = "language";
private const string GENRE = "genre";
private const string OPTIONS = "options";
+ private const string HTTP_MEDIA_TYPE = "application/json";
///
/// _params contains the parameters to be sent to the server
@@ -132,30 +133,39 @@ public string? Genre {
}
///
- /// GetCall executes the endpoint against the server using GetAsync
+ /// GetCallAsync executes the endpoint against the server using GetAsync
///
- /// RosetteAPI object
- /// RosetteResponse
- public Response GetCall(ApiClient api) {
+ /// ApiClient object
+ /// Optional cancellation token
+ /// Response
+ public async Task GetCallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
string url = api.URI + Endpoint;
- Task task = Task.Run(async () => await api.Client.GetAsync(url));
- var response = task.Result;
-
- return new Response(response);
+ var responseMsg = await api.Client.GetAsync(url, cancellationToken).ConfigureAwait(false);
+ return await Response.CreateAsync(responseMsg).ConfigureAwait(false);
}
///
- /// Call calls the server with the provided data using PostAsync
+ /// GetCall executes the endpoint against the server using GetAsync
///
- /// RosetteAPI object
- /// Rosette Response
- public virtual Response PostCall(ApiClient api)
+ /// ApiClient object
+ /// Response
+ public Response GetCall(ApiClient api)
+ {
+ return GetCallAsync(api).GetAwaiter().GetResult();
+ }
+
+ /// PostCallAsync calls the server with the provided data using PostAsync
+ ///
+ /// ApiClient object
+ /// Optional cancellation token
+ /// Response
+ public virtual async Task PostCallAsync(ApiClient api, CancellationToken cancellationToken = default)
{
string url = api.URI + Endpoint + ToQueryString();
if (Filestream == null)
{
- // Use relaxed encoder to send actual Unicode characters
var serializeOptions = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
@@ -164,20 +174,28 @@ public virtual Response PostCall(ApiClient api)
HttpContent content = new StringContent(
JsonSerializer.Serialize(AppendOptions(_params), serializeOptions),
Encoding.UTF8,
- "application/json"
+ HTTP_MEDIA_TYPE
);
- Task task = Task.Run(async () => await api.Client.PostAsync(url, content));
- var response = task.Result;
-
- return new Response(response);
+ var responseMsg = await api.Client.PostAsync(url, content, cancellationToken).ConfigureAwait(false);
+ return await Response.CreateAsync(responseMsg).ConfigureAwait(false);
}
else
{
- return PostAsMultipart(api, url);
+ return await PostAsMultipartAsync(api, url, cancellationToken).ConfigureAwait(false);
}
}
+ ///
+ /// PostCall calls the server with the provided data using PostAsync
+ ///
+ /// ApiClient object
+ /// Response
+ public virtual Response PostCall(ApiClient api)
+ {
+ return PostCallAsync(api).GetAwaiter().GetResult();
+ }
+
///
/// AppendOptions appends any provided options to the parameter dictionary
///
@@ -193,6 +211,43 @@ private Dictionary AppendOptions(Dictionary dict
return dict;
}
+ ///
+ /// PostAsMultipartAsync handles processing of files as a multipart upload
+ ///
+ /// ApiClient object
+ /// Endpoint URL
+ /// Optional cancellation token
+ /// Response object
+ private async Task PostAsMultipartAsync(ApiClient api, string url, CancellationToken cancellationToken = default)
+ {
+ using (var multiPartContent = new MultipartFormDataContent())
+ {
+ var streamContent = new StreamContent(Filestream);
+ streamContent.Headers.Add("Content-Type", FileContentType);
+ streamContent.Headers.Add("Content-Disposition", "mixed; name=\"content\"; filename=\"" + Path.GetFileName(Filestream.Name) + "\"");
+ multiPartContent.Add(streamContent, "content", Path.GetFileName(Filestream.Name));
+
+ if (_options.Count > 0 || _params.Count > 0)
+ {
+ var serializeOptions = new JsonSerializerOptions
+ {
+ Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
+ };
+
+ var stringContent = new StringContent(
+ JsonSerializer.Serialize(AppendOptions(_params), serializeOptions),
+ Encoding.UTF8,
+ HTTP_MEDIA_TYPE
+ );
+ stringContent.Headers.Add("Content-Disposition", "mixed; name=\"request\"");
+ multiPartContent.Add(stringContent, "request");
+ }
+
+ var responseMsg = await api.Client.PostAsync(url, multiPartContent, cancellationToken).ConfigureAwait(false);
+ return await Response.CreateAsync(responseMsg).ConfigureAwait(false);
+ }
+ }
+
///
/// PostAsMultipart handles processing of files as a multipart upload
///
@@ -218,7 +273,7 @@ private Response PostAsMultipart(ApiClient api, string url)
var stringContent = new StringContent(
JsonSerializer.Serialize(AppendOptions(_params), serializeOptions),
Encoding.UTF8,
- "application/json"
+ HTTP_MEDIA_TYPE
);
stringContent.Headers.Add("Content-Disposition", "mixed; name=\"request\"");
_multiPartContent.Add(stringContent, "request");
@@ -260,11 +315,4 @@ private string ToQueryString() {
return sb.ToString();
}
- ///
- /// HasContent checks for content to send
- ///
- /// bool if content, contenturi or filename
- private bool HasContent() {
- return _params.ContainsKey(CONTENT) || _params.ContainsKey(CONTENTURI) || !string.IsNullOrEmpty(Filename);
- }
}
diff --git a/rosette_api/Endpoints/Entities.cs b/rosette_api/Endpoints/Entities.cs
index 9a06295..6a611b6 100644
--- a/rosette_api/Endpoints/Entities.cs
+++ b/rosette_api/Endpoints/Entities.cs
@@ -1,6 +1,6 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class Entities : ContentEndpointBase
{
@@ -8,7 +8,6 @@ public class Entities : ContentEndpointBase
/// EntitiesEndpoint returns the entities extracted from the endpoint
///
/// text, Uri object or FileStream
- public Entities(object content) : base("entities", content)
- {
- }
+ public Entities(object content) : base("entities", content) { }
}
+
diff --git a/rosette_api/Endpoints/Events.cs b/rosette_api/Endpoints/Events.cs
index 9d9c19f..98b787f 100644
--- a/rosette_api/Endpoints/Events.cs
+++ b/rosette_api/Endpoints/Events.cs
@@ -1,6 +1,6 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class Events : ContentEndpointBase
{
@@ -8,7 +8,5 @@ public class Events : ContentEndpointBase
/// EventsEndpoint returns the events extracted from the endpoint
///
/// text, Uri object or FileStream
- public Events(object content) : base("events", content)
- {
- }
-}
\ No newline at end of file
+ public Events(object content) : base("events", content) { }
+}
diff --git a/rosette_api/Endpoints/Info.cs b/rosette_api/Endpoints/Info.cs
index eec493e..8a6196e 100644
--- a/rosette_api/Endpoints/Info.cs
+++ b/rosette_api/Endpoints/Info.cs
@@ -1,12 +1,9 @@
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints
{
public class Info : EndpointBase
{
public Info() : base("info") { }
-
- public Response Call(ApiClient api) => Funcs.GetCall(api);
}
}
diff --git a/rosette_api/Endpoints/Language.cs b/rosette_api/Endpoints/Language.cs
index ec07ee9..e65dc6c 100644
--- a/rosette_api/Endpoints/Language.cs
+++ b/rosette_api/Endpoints/Language.cs
@@ -1,6 +1,6 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class Language : ContentEndpointBase
{
@@ -8,7 +8,6 @@ public class Language : ContentEndpointBase
/// LanguageEndpoint returns the language extracted from the endpoint
///
/// text, Uri object or FileStream
- public Language(object content) : base("language", content)
- {
- }
+ public Language(object content) : base("language", content) { }
}
+
diff --git a/rosette_api/Endpoints/Morphology.cs b/rosette_api/Endpoints/Morphology.cs
index ba98f80..d003f65 100644
--- a/rosette_api/Endpoints/Morphology.cs
+++ b/rosette_api/Endpoints/Morphology.cs
@@ -1,7 +1,7 @@
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints
{
public enum MorphologyFeature {
/// provide complete morphology
@@ -77,14 +77,7 @@ public Morphology SetFileContentType(string contentType) {
}
public string FileContentType => Funcs.FileContentType;
public string Filename => Funcs.Filename;
- ///
- /// Call passes the data to the server and returns the response
- ///
- /// RosetteAPI object
- /// RosetteResponse
- public Response Call(ApiClient api) {
- return Funcs.PostCall(api);
- }
+
///
/// FeatureAsString returns the feature enum in its endpoint string form
///
@@ -102,5 +95,14 @@ public string FeatureAsString(MorphologyFeature feature) {
return _featureEndpoint[feature];
}
+ public new Task CallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
+ return Funcs.PostCallAsync(api, cancellationToken);
+ }
+
+ public new Response Call(ApiClient api)
+ {
+ return Funcs.PostCall(api);
+ }
}
}
diff --git a/rosette_api/Endpoints/NameDeduplication.cs b/rosette_api/Endpoints/NameDeduplication.cs
index 5f96a45..f46a3a9 100644
--- a/rosette_api/Endpoints/NameDeduplication.cs
+++ b/rosette_api/Endpoints/NameDeduplication.cs
@@ -1,7 +1,7 @@
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints
{
public class NameDeduplication : EndpointBase
{
@@ -12,6 +12,7 @@ public class NameDeduplication : EndpointBase
public NameDeduplication(List names) : base("name-deduplication") {
SetNames(names);
}
+
///
/// SetNames assigns a list of RosetteName objects to be processed
///
@@ -24,6 +25,7 @@ public NameDeduplication SetNames(List names) {
Params["names"] = names;
return this;
}
+
///
/// Names returns the list of RosetteName objects
///
@@ -32,6 +34,7 @@ public NameDeduplication SetNames(List names) {
Params["names"] as IList :
null;
}
+
///
/// SetProfileID sets a profile ID to be used during processing
///
@@ -41,6 +44,7 @@ public NameDeduplication SetProfileID(string profileID) {
Params["profileid"] = profileID;
return this;
}
+
///
/// ProfileID returns the profile ID or empty string
///
@@ -49,6 +53,7 @@ public NameDeduplication SetProfileID(string profileID) {
Params["profileid"].ToString() :
string.Empty;
}
+
///
/// SetThreshold sets the threshold to be used for determining deduplication cluster sizing
///
@@ -58,6 +63,7 @@ public NameDeduplication SetThreshold(float threshold) {
Params["threshold"] = threshold;
return this;
}
+
///
/// Threshold returns the threshold or the default, 0.75f
///
@@ -66,14 +72,15 @@ public NameDeduplication SetThreshold(float threshold) {
(float)Params["threshold"] :
0.75f;
}
- ///
- /// Call returns the response from the server
- ///
- /// RosetteAPI object
- /// RosetteResponse
- public Response Call(ApiClient api) {
- return Funcs.PostCall(api);
+
+ public new Task CallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
+ return Funcs.PostCallAsync(api, cancellationToken);
}
+ public new Response Call(ApiClient api)
+ {
+ return Funcs.PostCall(api);
+ }
}
}
diff --git a/rosette_api/Endpoints/NameSimilarity.cs b/rosette_api/Endpoints/NameSimilarity.cs
index 062c677..1647ec1 100644
--- a/rosette_api/Endpoints/NameSimilarity.cs
+++ b/rosette_api/Endpoints/NameSimilarity.cs
@@ -1,7 +1,7 @@
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints
{
public class NameSimilarity : EndpointBase {
///
@@ -16,7 +16,13 @@ public NameSimilarity(Name? name1, Name? name2) : base("name-similarity") {
Params["name2"] = name2;
}
- public Response Call(ApiClient api) {
+ public new Task CallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
+ return Funcs.PostCallAsync(api, cancellationToken);
+ }
+
+ public new Response Call(ApiClient api)
+ {
return Funcs.PostCall(api);
}
}
diff --git a/rosette_api/Endpoints/NameTranslation.cs b/rosette_api/Endpoints/NameTranslation.cs
index 1e8f8da..d0a93a0 100644
--- a/rosette_api/Endpoints/NameTranslation.cs
+++ b/rosette_api/Endpoints/NameTranslation.cs
@@ -1,7 +1,7 @@
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints
{
public class NameTranslation : EndpointBase
{
@@ -19,6 +19,7 @@ public NameTranslation(string name, string targetLanguage="eng") : base("name-tr
SetName(name);
SetTargetLanguage(targetLanguage);
}
+
///
/// SetName defines the name to be translated
///
@@ -29,11 +30,13 @@ public NameTranslation SetName(string name) {
return this;
}
+
public string? Name { get =>
Params.ContainsKey(NAME) ?
Params[NAME].ToString() :
string.Empty;
}
+
///
/// SetEntityType sets the optional entity type, PERSON, LOCATION or ORGANIZATION
///
@@ -44,11 +47,13 @@ public NameTranslation SetEntityType(string entityType) {
return this;
}
+
public string? EntityType { get =>
Params.ContainsKey(ENTITY_TYPE) ?
Params[ENTITY_TYPE].ToString() :
string.Empty;
}
+
///
/// SetSourceLanguageOfOrigin sets the optional ISO 639-3 code for the name's language of origin
///
@@ -59,6 +64,7 @@ public NameTranslation SetSourceLanguageOfOrigin(string sourceLanguageOfOrigin)
return this;
}
+
public string? SourceLanguageOfOrigin { get =>
Params.ContainsKey(SOURCE_LANGUAGE_OF_ORIGIN) ?
Params[SOURCE_LANGUAGE_OF_ORIGIN].ToString() :
@@ -74,11 +80,13 @@ public NameTranslation SetSourceLanguageOfUse(string sourceLanguageOfUse) {
return this;
}
+
public string? SourceLanguageOfUse { get =>
Params.ContainsKey(SOURCE_LANGUAGE_OF_USE) ?
Params[SOURCE_LANGUAGE_OF_USE].ToString() :
String.Empty;
}
+
///
/// SetSourceScript sets the optional ISO 15924 code for the name's script
///
@@ -94,6 +102,7 @@ public NameTranslation SetSourceScript(string sourceScript) {
Params[SOURCE_SCRIPT].ToString() :
string.Empty;
}
+
///
/// SetTargetLanguage sets the ISO 639-3 code for the translation language.
/// Defaults to "eng"
@@ -105,11 +114,13 @@ public NameTranslation SetTargetLanguage(string targetLanguage) {
return this;
}
+
public string? TargetLanguage { get =>
Params.ContainsKey(TARGET_LANGUAGE) ?
Params[TARGET_LANGUAGE].ToString() :
String.Empty;
}
+
///
/// SetTargetScheme sets the optional transliteration scheme for the translation
///
@@ -120,11 +131,13 @@ public NameTranslation SetTargetScheme(string targetScheme) {
return this;
}
+
public string? TargetScheme { get =>
Params.ContainsKey(TARGET_SCHEME) ?
Params[TARGET_SCHEME].ToString() :
string.Empty;
}
+
///
/// SetTargetScript sets the optional ISO 15924 code for the translation script
///
@@ -135,6 +148,7 @@ public NameTranslation SetTargetScript(string targetScript) {
return this;
}
+
public string? TargetScript { get => Params.ContainsKey(TARGET_SCRIPT) ?
Params[TARGET_SCRIPT].ToString() :
string.Empty;
@@ -158,7 +172,13 @@ public NameTranslation SetMaximumResults(int maximumResults)
null;
}
- public Response Call(ApiClient api) {
+ public new Task CallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
+ return Funcs.PostCallAsync(api, cancellationToken);
+ }
+
+ public new Response Call(ApiClient api)
+ {
return Funcs.PostCall(api);
}
}
diff --git a/rosette_api/Endpoints/Ping.cs b/rosette_api/Endpoints/Ping.cs
index 52858af..40245aa 100644
--- a/rosette_api/Endpoints/Ping.cs
+++ b/rosette_api/Endpoints/Ping.cs
@@ -1,12 +1,9 @@
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints
{
public class Ping : EndpointBase
{
public Ping() : base("ping") { }
-
- public Response Call(ApiClient api) => Funcs.GetCall(api);
}
}
diff --git a/rosette_api/Endpoints/RecordSimilarity.cs b/rosette_api/Endpoints/RecordSimilarity.cs
index 29ebb81..5ea759f 100644
--- a/rosette_api/Endpoints/RecordSimilarity.cs
+++ b/rosette_api/Endpoints/RecordSimilarity.cs
@@ -1,7 +1,7 @@
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class RecordSimilarity : EndpointBase
{
@@ -21,7 +21,12 @@ public RecordSimilarity(Dictionary? fields,
Params["records"] = records;
}
- public Response Call(ApiClient api)
+ public new Task CallAsync(ApiClient api, CancellationToken cancellationToken = default)
+ {
+ return Funcs.PostCallAsync(api, cancellationToken);
+ }
+
+ public new Response Call(ApiClient api)
{
return Funcs.PostCall(api);
}
diff --git a/rosette_api/Endpoints/Relationships.cs b/rosette_api/Endpoints/Relationships.cs
index e1a94c9..880a71e 100644
--- a/rosette_api/Endpoints/Relationships.cs
+++ b/rosette_api/Endpoints/Relationships.cs
@@ -1,6 +1,6 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class Relationships : ContentEndpointBase
{
@@ -8,7 +8,5 @@ public class Relationships : ContentEndpointBase
/// RelationshipsEndpoint returns the relationships between entities in the input text
///
/// text, Uri object or FileStream
- public Relationships(object content) : base("relationships", content)
- {
- }
-}
\ No newline at end of file
+ public Relationships(object content) : base("relationships", content) { }
+}
diff --git a/rosette_api/Endpoints/SemanticsVector.cs b/rosette_api/Endpoints/SemanticsVector.cs
index 484b953..2c12e47 100644
--- a/rosette_api/Endpoints/SemanticsVector.cs
+++ b/rosette_api/Endpoints/SemanticsVector.cs
@@ -1,6 +1,6 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class SemanticsVector : ContentEndpointBase
{
@@ -8,7 +8,5 @@ public class SemanticsVector : ContentEndpointBase
/// SemanticVectorsEndpoint returns the relationships between entities in the input text
///
/// text, Uri object or FileStream
- public SemanticsVector(object content) : base("semantics/vector", content)
- {
- }
-}
\ No newline at end of file
+ public SemanticsVector(object content) : base("semantics/vector", content) { }
+}
diff --git a/rosette_api/Endpoints/Sentences.cs b/rosette_api/Endpoints/Sentences.cs
index 577953f..9762dd5 100644
--- a/rosette_api/Endpoints/Sentences.cs
+++ b/rosette_api/Endpoints/Sentences.cs
@@ -1,13 +1,11 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints
-{
- public class Sentences : ContentEndpointBase {
- ///
- /// SentencesEndpoint returns each entity extracted from the input
- ///
- /// text, Uri object or FileStream
- public Sentences(object content) : base("sentences", content) {
- }
- }
+namespace Rosette.Api.Client.Endpoints;
+
+public class Sentences : ContentEndpointBase {
+ ///
+ /// SentencesEndpoint returns each entity extracted from the input
+ ///
+ /// text, Uri object or FileStream
+ public Sentences(object content) : base("sentences", content) { }
}
diff --git a/rosette_api/Endpoints/Sentiment.cs b/rosette_api/Endpoints/Sentiment.cs
index 0bbe478..e3f0174 100644
--- a/rosette_api/Endpoints/Sentiment.cs
+++ b/rosette_api/Endpoints/Sentiment.cs
@@ -1,15 +1,12 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints;
+
+public class Sentiment : ContentEndpointBase
{
- public class Sentiment : ContentEndpointBase
- {
- ///
- /// SentimentEndpoint analyzes the positive and negative sentiment expressed by the input
- ///
- /// text, Uri object or FileStream
- public Sentiment(object content) : base("sentiment", content)
- {
- }
- }
-}
\ No newline at end of file
+ ///
+ /// SentimentEndpoint analyzes the positive and negative sentiment expressed by the input
+ ///
+ /// text, Uri object or FileStream
+ public Sentiment(object content) : base("sentiment", content) { }
+}
diff --git a/rosette_api/Endpoints/SimilarTerms.cs b/rosette_api/Endpoints/SimilarTerms.cs
index a320e8e..5fbb6ef 100644
--- a/rosette_api/Endpoints/SimilarTerms.cs
+++ b/rosette_api/Endpoints/SimilarTerms.cs
@@ -1,6 +1,6 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class SimilarTerms : ContentEndpointBase
{
@@ -8,7 +8,5 @@ public class SimilarTerms : ContentEndpointBase
/// SimilarTerms returns terms that are similar to the input
///
/// text, Uri object or FileStream
- public SimilarTerms(object content) : base("semantics/similar", content)
- {
- }
-}
\ No newline at end of file
+ public SimilarTerms(object content) : base("semantics/similar", content) { }
+}
diff --git a/rosette_api/Endpoints/SyntaxDependencies.cs b/rosette_api/Endpoints/SyntaxDependencies.cs
index 271e364..a10d5fd 100644
--- a/rosette_api/Endpoints/SyntaxDependencies.cs
+++ b/rosette_api/Endpoints/SyntaxDependencies.cs
@@ -1,12 +1,11 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class SyntaxDependencies : ContentEndpointBase {
///
/// SyntaxDependenciesEndpoint returns the parse tree of the input text as a list of labeled directed links between tokens, as well as the list of tokens in the input sentence
///
/// text, Uri object or FileStream
- public SyntaxDependencies(object content) : base("syntax/dependencies", content) {
- }
+ public SyntaxDependencies(object content) : base("syntax/dependencies", content) { }
}
diff --git a/rosette_api/Endpoints/TextEmbedding.cs b/rosette_api/Endpoints/TextEmbedding.cs
index 7b809df..6c62962 100644
--- a/rosette_api/Endpoints/TextEmbedding.cs
+++ b/rosette_api/Endpoints/TextEmbedding.cs
@@ -1,15 +1,12 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints
+namespace Rosette.Api.Client.Endpoints;
+
+public class TextEmbedding : ContentEndpointBase
{
- public class TextEmbedding : ContentEndpointBase
- {
- ///
- /// TextEmbeddingEndpoint returns the embedding for the input text
- ///
- /// text, Uri object or FileStream
- public TextEmbedding(object content) : base("text-embedding", content)
- {
- }
- }
+ ///
+ /// TextEmbeddingEndpoint returns the embedding for the input text
+ ///
+ /// text, Uri object or FileStream
+ public TextEmbedding(object content) : base("text-embedding", content) { }
}
\ No newline at end of file
diff --git a/rosette_api/Endpoints/Tokens.cs b/rosette_api/Endpoints/Tokens.cs
index 257d33c..6261ba1 100644
--- a/rosette_api/Endpoints/Tokens.cs
+++ b/rosette_api/Endpoints/Tokens.cs
@@ -1,12 +1,11 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class Tokens : ContentEndpointBase {
///
/// TokensEndpoint returns each entity extracted from the input
///
/// text, Uri object or FileStream
- public Tokens(object content) : base("tokens", content) {
- }
+ public Tokens(object content) : base("tokens", content) { }
}
diff --git a/rosette_api/Endpoints/Topics.cs b/rosette_api/Endpoints/Topics.cs
index 68bdadb..d81a6ee 100644
--- a/rosette_api/Endpoints/Topics.cs
+++ b/rosette_api/Endpoints/Topics.cs
@@ -1,12 +1,11 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class Topics : ContentEndpointBase {
///
/// TopicsEndpoint returns the topic extracted from the endpoint
///
/// text, Uri object or FileStream
- public Topics(object content) : base("topics", content) {
- }
+ public Topics(object content) : base("topics", content) { }
}
diff --git a/rosette_api/Endpoints/Transliteration.cs b/rosette_api/Endpoints/Transliteration.cs
index 62b2415..c7e236f 100644
--- a/rosette_api/Endpoints/Transliteration.cs
+++ b/rosette_api/Endpoints/Transliteration.cs
@@ -1,12 +1,11 @@
-using Rosette.Api.Endpoints.Core;
+using Rosette.Api.Client.Endpoints.Core;
-namespace Rosette.Api.Endpoints;
+namespace Rosette.Api.Client.Endpoints;
public class Transliteration : ContentEndpointBase {
///
/// TransliterationEndpoint returns the transliteration of the input
///
/// text, Uri object or FileStream
- public Transliteration(object content) : base("transliteration", content) {
- }
+ public Transliteration(object content) : base("transliteration", content) { }
}
diff --git a/rosette_api/Models/AddressField.cs b/rosette_api/Models/AddressField.cs
index 0230af9..79998ff 100644
--- a/rosette_api/Models/AddressField.cs
+++ b/rosette_api/Models/AddressField.cs
@@ -1,4 +1,4 @@
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Abstract parent class for UnfieldedAddress and FieldedAddress
diff --git a/rosette_api/Models/BooleanRecord.cs b/rosette_api/Models/BooleanRecord.cs
index f1e206d..4ec6c84 100644
--- a/rosette_api/Models/BooleanRecord.cs
+++ b/rosette_api/Models/BooleanRecord.cs
@@ -1,7 +1,7 @@
-using rosette_api.Models.JsonConverter;
+using Rosette.Api.Client.Models.JsonConverter;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing a boolean record
diff --git a/rosette_api/Models/DateField.cs b/rosette_api/Models/DateField.cs
index 7fd78ee..12a8ea9 100644
--- a/rosette_api/Models/DateField.cs
+++ b/rosette_api/Models/DateField.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Abstract parent class for UnfieldedDate and FieldedDate
diff --git a/rosette_api/Models/EntityType.cs b/rosette_api/Models/EntityType.cs
index 6c95126..85b91c8 100644
--- a/rosette_api/Models/EntityType.cs
+++ b/rosette_api/Models/EntityType.cs
@@ -1,4 +1,4 @@
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Represents the type of entity for name processing
diff --git a/rosette_api/Models/FieldedAddressRecord.cs b/rosette_api/Models/FieldedAddressRecord.cs
index a6b662a..41cc222 100644
--- a/rosette_api/Models/FieldedAddressRecord.cs
+++ b/rosette_api/Models/FieldedAddressRecord.cs
@@ -1,7 +1,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing a fielded address
diff --git a/rosette_api/Models/FieldedDateRecord.cs b/rosette_api/Models/FieldedDateRecord.cs
index 57d5b1a..cfd84b4 100644
--- a/rosette_api/Models/FieldedDateRecord.cs
+++ b/rosette_api/Models/FieldedDateRecord.cs
@@ -1,7 +1,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing a fielded date
diff --git a/rosette_api/Models/FieldedNameRecord.cs b/rosette_api/Models/FieldedNameRecord.cs
index f1f6778..c130569 100644
--- a/rosette_api/Models/FieldedNameRecord.cs
+++ b/rosette_api/Models/FieldedNameRecord.cs
@@ -1,7 +1,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing a fielded name
diff --git a/rosette_api/Models/GenderType.cs b/rosette_api/Models/GenderType.cs
index de79b01..8d4b592 100644
--- a/rosette_api/Models/GenderType.cs
+++ b/rosette_api/Models/GenderType.cs
@@ -1,9 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Text.Json.Serialization;
-
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Possible gender options for the Name objects
diff --git a/rosette_api/Models/JsonConverter/RecordSimilarityFieldConverter.cs b/rosette_api/Models/JsonConverter/RecordSimilarityFieldConverter.cs
index 9c83035..12a8a8c 100644
--- a/rosette_api/Models/JsonConverter/RecordSimilarityFieldConverter.cs
+++ b/rosette_api/Models/JsonConverter/RecordSimilarityFieldConverter.cs
@@ -1,9 +1,7 @@
-using Rosette.Api.Models;
using System.Text.Json;
-using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
-namespace rosette_api.Models.JsonConverter;
+namespace Rosette.Api.Client.Models.JsonConverter;
///
/// JsonConverter for RecordSimilarityField interface polymorphic serialization
diff --git a/rosette_api/Models/JsonConverter/RecordSimilarityRecordsConverter.cs b/rosette_api/Models/JsonConverter/RecordSimilarityRecordsConverter.cs
index 2dd4e5c..9c32eef 100644
--- a/rosette_api/Models/JsonConverter/RecordSimilarityRecordsConverter.cs
+++ b/rosette_api/Models/JsonConverter/RecordSimilarityRecordsConverter.cs
@@ -1,8 +1,7 @@
-using Rosette.Api.Models;
-using System.Text.Json;
+using System.Text.Json;
using System.Text.Json.Serialization;
-namespace rosette_api.Models.JsonConverter;
+namespace Rosette.Api.Client.Models.JsonConverter;
///
/// JsonConverter for RecordSimilarityRecords to properly serialize RecordSimilarityField values
diff --git a/rosette_api/Models/JsonConverter/UnfieldedRecordSimilarityConverter.cs b/rosette_api/Models/JsonConverter/UnfieldedRecordSimilarityConverter.cs
index 394cf8b..e4ff1e2 100644
--- a/rosette_api/Models/JsonConverter/UnfieldedRecordSimilarityConverter.cs
+++ b/rosette_api/Models/JsonConverter/UnfieldedRecordSimilarityConverter.cs
@@ -1,8 +1,7 @@
-using Rosette.Api.Models;
using System.Text.Json;
using System.Text.Json.Serialization;
-namespace rosette_api.Models.JsonConverter;
+namespace Rosette.Api.Client.Models.JsonConverter;
///
/// JsonConverter for Unfielded Record Similarity objects
diff --git a/rosette_api/Models/Name.cs b/rosette_api/Models/Name.cs
index ae0f578..8e1dabc 100644
--- a/rosette_api/Models/Name.cs
+++ b/rosette_api/Models/Name.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
public class Name
{
diff --git a/rosette_api/Models/NameField.cs b/rosette_api/Models/NameField.cs
index a740b7d..c57a834 100644
--- a/rosette_api/Models/NameField.cs
+++ b/rosette_api/Models/NameField.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Abstract parent class for UnfieldedName and FieldedName
diff --git a/rosette_api/Models/NumberRecord.cs b/rosette_api/Models/NumberRecord.cs
index 5473a69..61f716f 100644
--- a/rosette_api/Models/NumberRecord.cs
+++ b/rosette_api/Models/NumberRecord.cs
@@ -1,7 +1,7 @@
-using rosette_api.Models.JsonConverter;
+using Rosette.Api.Client.Models.JsonConverter;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing a number record
diff --git a/rosette_api/Models/RecordFieldType.cs b/rosette_api/Models/RecordFieldType.cs
index 5732b6c..c8ae7a5 100644
--- a/rosette_api/Models/RecordFieldType.cs
+++ b/rosette_api/Models/RecordFieldType.cs
@@ -1,4 +1,4 @@
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
/// RecordFieldType
///
diff --git a/rosette_api/Models/RecordSimilarityField.cs b/rosette_api/Models/RecordSimilarityField.cs
index 25aa547..2d557a0 100644
--- a/rosette_api/Models/RecordSimilarityField.cs
+++ b/rosette_api/Models/RecordSimilarityField.cs
@@ -1,4 +1,4 @@
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Parent Interface for RecordSimilarityField objects
diff --git a/rosette_api/Models/RecordSimilarityFieldInfo.cs b/rosette_api/Models/RecordSimilarityFieldInfo.cs
index 05a8f72..08a290a 100644
--- a/rosette_api/Models/RecordSimilarityFieldInfo.cs
+++ b/rosette_api/Models/RecordSimilarityFieldInfo.cs
@@ -1,7 +1,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models {
+namespace Rosette.Api.Client.Models {
///
/// Class for representing record similarity field information
diff --git a/rosette_api/Models/RecordSimilarityProperties.cs b/rosette_api/Models/RecordSimilarityProperties.cs
index c14bc82..4e5033c 100644
--- a/rosette_api/Models/RecordSimilarityProperties.cs
+++ b/rosette_api/Models/RecordSimilarityProperties.cs
@@ -1,7 +1,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models
+namespace Rosette.Api.Client.Models
{
public class RecordSimilarityProperties
{
diff --git a/rosette_api/Models/RecordSimilarityRecords.cs b/rosette_api/Models/RecordSimilarityRecords.cs
index 1b8f0e7..b970658 100644
--- a/rosette_api/Models/RecordSimilarityRecords.cs
+++ b/rosette_api/Models/RecordSimilarityRecords.cs
@@ -1,8 +1,8 @@
-using rosette_api.Models.JsonConverter;
+using Rosette.Api.Client.Models.JsonConverter;
using System.Text.Json;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
[JsonConverter(typeof(RecordSimilarityRecordsConverter))]
public class RecordSimilarityRecords
diff --git a/rosette_api/Models/Response.cs b/rosette_api/Models/Response.cs
index 0d52752..c691fdd 100644
--- a/rosette_api/Models/Response.cs
+++ b/rosette_api/Models/Response.cs
@@ -3,96 +3,150 @@
using System.Text.Encodings.Web;
using System.Text.Json;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
public class Response
{
- public Response(HttpResponseMessage responseMsg) {
+ // Private constructor for async factory
+ private Response()
+ {
Content = new Dictionary();
Headers = new Dictionary();
+ }
+ // Keep existing synchronous constructor for backward compatibility
+ public Response(HttpResponseMessage responseMsg) : this()
+ {
StatusCode = (int)responseMsg.StatusCode;
- if (responseMsg.IsSuccessStatusCode) {
- foreach (var header in responseMsg.Headers) {
- Headers.Add(header.Key, string.Join("", header.Value));
- }
- foreach (var header in responseMsg.Content.Headers) {
- Headers.Add(header.Key, string.Join("", header.Value));
- }
+ if (responseMsg.IsSuccessStatusCode)
+ {
+ ProcessHeaders(responseMsg);
byte[] byteArray = responseMsg.Content.ReadAsByteArrayAsync().Result;
- if(byteArray[0] == '\x1f' && byteArray[1] == '\x8b' && byteArray[2] == '\x08') {
- byteArray = Decompress(byteArray);
- }
- string result = string.Empty;
- using (StreamReader reader = new StreamReader(new MemoryStream(byteArray), Encoding.UTF8)) {
- result = reader.ReadToEnd();
- }
-
+ string result = ProcessContent(byteArray);
Content = JsonSerializer.Deserialize>(result)!;
}
- else {
- throw new HttpRequestException(string.Format("{0}: {1}: {2}", (int)responseMsg.StatusCode, responseMsg.ReasonPhrase, ContentToString(responseMsg.Content)));
+ else
+ {
+ throw new HttpRequestException(
+ $"{(int)responseMsg.StatusCode}: {responseMsg.ReasonPhrase}: {ContentToString(responseMsg.Content)}");
}
}
+ ///
+ /// CreateAsync creates a Response asynchronously from an HttpResponseMessage
+ ///
+ /// HTTP response message
+ /// Optional cancellation token
+ /// Response
+ public static async Task CreateAsync(HttpResponseMessage responseMsg, CancellationToken cancellationToken = default)
+ {
+ var response = new Response
+ {
+ StatusCode = (int)responseMsg.StatusCode
+ };
+
+ if (responseMsg.IsSuccessStatusCode)
+ {
+ response.ProcessHeaders(responseMsg);
+ byte[] byteArray = await responseMsg.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
+ string result = response.ProcessContent(byteArray);
+ response.Content = JsonSerializer.Deserialize>(result)!;
+ }
+ else
+ {
+ string errorContent = await ContentToStringAsync(responseMsg.Content, cancellationToken).ConfigureAwait(false);
+ throw new HttpRequestException(
+ $"{(int)responseMsg.StatusCode}: {responseMsg.ReasonPhrase}: {errorContent}");
+ }
+
+ return response;
+ }
+
///
/// Headers provides read access to the Response Headers collection
///
- /// IDictionary of string, string
- public IDictionary Headers {get; private set;}
+ public IDictionary Headers { get; private set; }
///
/// Content provides read access to the Response IDictionary
///
- /// IDictionary of string, object
- public IDictionary Content {get; private set;}
+ public IDictionary Content { get; private set; }
+
+ ///
+ /// StatusCode returns the HTTP status code
+ ///
+ public int StatusCode { get; private set; }
public object ContentAsJson(bool pretty = false)
{
var options = new JsonSerializerOptions
{
WriteIndented = pretty,
- Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // Don't escape Unicode characters
+ Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
return JsonSerializer.Serialize(Content, options);
}
- public int StatusCode {get; private set;}
+ private void ProcessHeaders(HttpResponseMessage responseMsg)
+ {
+ foreach (var header in responseMsg.Headers)
+ {
+ Headers.Add(header.Key, string.Join("", header.Value));
+ }
+ foreach (var header in responseMsg.Content.Headers)
+ {
+ Headers.Add(header.Key, string.Join("", header.Value));
+ }
+ }
+ private string ProcessContent(byte[] byteArray)
+ {
+ if (byteArray.Length >= 3 && byteArray[0] == '\x1f' && byteArray[1] == '\x8b' && byteArray[2] == '\x08')
+ {
+ byteArray = Decompress(byteArray);
+ }
- /// Decompress decompresses GZIP files
- /// Source: http://www.dotnetperls.com/decompress
- ///
- /// (byte[]): Data in byte form to decompress
- /// (byte[]) Decompressed data
- private byte[] Decompress(byte[] gzip) {
- // Create a GZIP stream with decompression mode.
- // ... Then create a buffer and write into while reading from the GZIP stream.
- using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress)) {
+ using (StreamReader reader = new StreamReader(new MemoryStream(byteArray), Encoding.UTF8))
+ {
+ return reader.ReadToEnd();
+ }
+ }
+
+ private byte[] Decompress(byte[] gzip)
+ {
+ using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
+ {
const int size = 4096;
byte[] buffer = new byte[size];
- using (MemoryStream memory = new MemoryStream()) {
- int count = 0;
- do {
+ using (MemoryStream memory = new MemoryStream())
+ {
+ int count;
+ do
+ {
count = stream.Read(buffer, 0, size);
- if (count > 0) {
+ if (count > 0)
+ {
memory.Write(buffer, 0, count);
}
- }
- while (count > 0);
+ } while (count > 0);
return memory.ToArray();
}
}
}
- internal static string ContentToString(HttpContent httpContent) {
- if (httpContent != null) {
- var readAsStringAsync = httpContent.ReadAsStringAsync();
- return readAsStringAsync.Result;
- }
- else {
- return string.Empty;
+
+ internal static string ContentToString(HttpContent httpContent)
+ {
+ return httpContent?.ReadAsStringAsync().Result ?? string.Empty;
+ }
+
+ internal static async Task ContentToStringAsync(HttpContent httpContent, CancellationToken cancellationToken = default)
+ {
+ if (httpContent != null)
+ {
+ return await httpContent.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
}
+ return string.Empty;
}
}
\ No newline at end of file
diff --git a/rosette_api/Models/StringRecord.cs b/rosette_api/Models/StringRecord.cs
index a2a0c3e..f3433fa 100644
--- a/rosette_api/Models/StringRecord.cs
+++ b/rosette_api/Models/StringRecord.cs
@@ -1,7 +1,7 @@
-using rosette_api.Models.JsonConverter;
+using Rosette.Api.Client.Models.JsonConverter;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing a string record
diff --git a/rosette_api/Models/UnfieldedAddressRecord.cs b/rosette_api/Models/UnfieldedAddressRecord.cs
index 2f61ecd..2aae035 100644
--- a/rosette_api/Models/UnfieldedAddressRecord.cs
+++ b/rosette_api/Models/UnfieldedAddressRecord.cs
@@ -1,7 +1,7 @@
-using rosette_api.Models.JsonConverter;
+using Rosette.Api.Client.Models.JsonConverter;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing an unfielded address
diff --git a/rosette_api/Models/UnfieldedDateRecord.cs b/rosette_api/Models/UnfieldedDateRecord.cs
index 03aeda0..ea715cd 100644
--- a/rosette_api/Models/UnfieldedDateRecord.cs
+++ b/rosette_api/Models/UnfieldedDateRecord.cs
@@ -1,7 +1,7 @@
-using rosette_api.Models.JsonConverter;
+using Rosette.Api.Client.Models.JsonConverter;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing an unfielded date
diff --git a/rosette_api/Models/UnfieldedNameRecord.cs b/rosette_api/Models/UnfieldedNameRecord.cs
index f8dfe1d..b5cc5a1 100644
--- a/rosette_api/Models/UnfieldedNameRecord.cs
+++ b/rosette_api/Models/UnfieldedNameRecord.cs
@@ -1,7 +1,7 @@
-using rosette_api.Models.JsonConverter;
+using Rosette.Api.Client.Models.JsonConverter;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing an unfielded name
diff --git a/rosette_api/Models/UnknownFieldRecord.cs b/rosette_api/Models/UnknownFieldRecord.cs
index e359beb..7297719 100644
--- a/rosette_api/Models/UnknownFieldRecord.cs
+++ b/rosette_api/Models/UnknownFieldRecord.cs
@@ -1,8 +1,8 @@
-using rosette_api.Models.JsonConverter;
+using Rosette.Api.Client.Models.JsonConverter;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
-namespace Rosette.Api.Models;
+namespace Rosette.Api.Client.Models;
///
/// Class for representing an unknown field
diff --git a/rosette_api/Utilities.cs b/rosette_api/Utilities.cs
index b4100f9..ff2adc3 100644
--- a/rosette_api/Utilities.cs
+++ b/rosette_api/Utilities.cs
@@ -1,4 +1,4 @@
-namespace Rosette.Api;
+namespace Rosette.Api.Client;
public static class Utilities
{
diff --git a/tests/ApiClientTests.cs b/tests/ApiClientTests.cs
index c1ee05a..19a400e 100644
--- a/tests/ApiClientTests.cs
+++ b/tests/ApiClientTests.cs
@@ -1,96 +1,97 @@
-namespace Rosette.Api.Tests
-{
- public class ApiClientTests
- {
- private static readonly string _defaultUri = "https://api.rosette.com/rest/v1/";
- private static readonly string _testKey = "testKey";
+using Rosette.Api.Client;
- private static ApiClient Init() {
- return new ApiClient(_testKey);
- }
+namespace Rosette.Api.Tests;
- [Fact]
- public void TestKey() {
- ApiClient api = Init();
- Assert.Equal(_testKey, api.APIKey);
- }
+public class ApiClientTests
+{
+ private static readonly string _defaultUri = "https://api.rosette.com/rest/v1/";
+ private static readonly string _testKey = "testKey";
+
+ private static ApiClient Init() {
+ return new ApiClient(_testKey);
+ }
+
+ [Fact]
+ public void ApiKey_ReturnsProvidedKey_WhenInitialized() {
+ ApiClient api = Init();
+ Assert.Equal(_testKey, api.APIKey);
+ }
- [Fact]
- public void TestNullKey() {
+ [Fact]
+ public void Constructor_ThrowsArgumentNullException_WhenApiKeyIsNull() {
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
- string key = null;
+ string key = null;
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
#pragma warning disable CS8604 // Possible null reference argument.
- Exception ex = Assert.Throws(() => new ApiClient(key));
+ Exception ex = Assert.Throws(() => new ApiClient(key));
#pragma warning restore CS8604 // Possible null reference argument.
- Assert.Equal("Value cannot be null. (Parameter 'apiKey')", ex.Message);
- }
+ Assert.Equal("Value cannot be null. (Parameter 'apiKey')", ex.Message);
+ }
- [Fact]
- public void TestURI() {
- ApiClient api = Init();
- Assert.Equal(_defaultUri, api.URI);
+ [Fact]
+ public void URI_ReturnsDefaultAndAppendsTrailingSlash_WhenUsingAlternateUrl() {
+ ApiClient api = Init();
+ Assert.Equal(_defaultUri, api.URI);
- // test alternate url as well as auto append trailing slash
- string alternateUrl = "https://stage.rosette.com/rest/v1";
- api.UseAlternateURL(alternateUrl);
- Assert.Equal(alternateUrl + "/", api.URI);
- }
+ // test alternate url as well as auto append trailing slash
+ string alternateUrl = "https://stage.rosette.com/rest/v1";
+ api.UseAlternateURL(alternateUrl);
+ Assert.Equal(alternateUrl + "/", api.URI);
+ }
- [Fact]
- public void TestConnections() {
- ApiClient api = Init();
- Assert.Equal(2, api.ConcurrentConnections);
+ [Fact]
+ public void ConcurrentConnections_ReturnsCorrectValue_WhenDefaultAndAssigned() {
+ ApiClient api = Init();
+ Assert.Equal(2, api.ConcurrentConnections);
- api.AssignConcurrentConnections(6);
- Assert.Equal(6, api.ConcurrentConnections);
- }
+ api.AssignConcurrentConnections(6);
+ Assert.Equal(6, api.ConcurrentConnections);
+ }
- [Fact]
- public void TestValidCustomHeader() {
- ApiClient api = Init();
- Exception ex = Assert.Throws(() => api.AddCustomHeader("BogusHeader", "BogusValue"));
+ [Fact]
+ public void AddCustomHeader_ThrowsArgumentException_WhenHeaderNameIsInvalid() {
+ ApiClient api = Init();
+ Exception ex = Assert.Throws(() => api.AddCustomHeader("BogusHeader", "BogusValue"));
- Assert.Contains(@"Custom header name must begin with 'X-RosetteAPI-'", ex.Message);
- }
+ Assert.Contains(@"Custom header name must begin with 'X-RosetteAPI-'", ex.Message);
+ }
- [Fact]
- public void TestVersion() {
- Assert.NotEmpty(ApiClient.Version);
- }
+ [Fact]
+ public void Version_IsNotEmpty_Always() {
+ Assert.NotEmpty(ApiClient.Version);
+ }
- [Fact]
- public void TestTimeout() {
- ApiClient api = Init();
- Assert.Equal(300, api.Timeout);
+ [Fact]
+ public void Timeout_ReturnsCorrectValue_WhenDefaultAndAssigned() {
+ ApiClient api = Init();
+ Assert.Equal(300, api.Timeout);
- api.AssignTimeout(15);
- Assert.Equal(15, api.Timeout);
- }
+ api.AssignTimeout(15);
+ Assert.Equal(15, api.Timeout);
+ }
- [Fact]
- public void TestDebug() {
- ApiClient api = Init();
- Assert.False(api.Debug);
+ [Fact]
+ public void Debug_TogglesToTrue_WhenSetDebugCalled() {
+ ApiClient api = Init();
+ Assert.False(api.Debug);
- api.SetDebug();
- Assert.True(api.Debug);
- }
+ api.SetDebug();
+ Assert.True(api.Debug);
+ }
- [Fact]
- public void TestDefaultClient() {
- ApiClient api = Init();
-
- Assert.Equal(_defaultUri, api.Client.BaseAddress.AbsoluteUri);
- var acceptHeader = new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json");
- Assert.Contains(acceptHeader, api.Client.DefaultRequestHeaders.Accept);
- foreach (string encodingType in new List() { "gzip", "deflate" }) {
- var encodingHeader = new System.Net.Http.Headers.StringWithQualityHeaderValue(encodingType);
- Assert.Contains(encodingHeader, api.Client.DefaultRequestHeaders.AcceptEncoding);
- }
- Assert.Equal(api.Timeout, api.Client.Timeout.TotalSeconds);
- }
+ [Fact]
+ public void Client_HasCorrectDefaultConfiguration_WhenInitialized() {
+ ApiClient api = Init();
+ Assert.Equal(_defaultUri, api.Client.BaseAddress.AbsoluteUri);
+ var acceptHeader = new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json");
+ Assert.Contains(acceptHeader, api.Client.DefaultRequestHeaders.Accept);
+ foreach (string encodingType in new List() { "gzip", "deflate" }) {
+ var encodingHeader = new System.Net.Http.Headers.StringWithQualityHeaderValue(encodingType);
+ Assert.Contains(encodingHeader, api.Client.DefaultRequestHeaders.AcceptEncoding);
+ }
+ Assert.Equal(api.Timeout, api.Client.Timeout.TotalSeconds);
}
+
}
diff --git a/tests/CategoriesTests.cs b/tests/CategoriesTests.cs
index 7e0b4c2..9f76b63 100644
--- a/tests/CategoriesTests.cs
+++ b/tests/CategoriesTests.cs
@@ -1,46 +1,45 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class CategoriesTests
{
- public class CategoriesTests
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCalledWithText()
+ {
+ Categories c = new Categories("Sample text for categorization");
+
+ Assert.Equal("categories", c.Endpoint);
+ Assert.Equal("Sample text for categorization", c.Content);
+ }
+
+ [Fact]
+ public void SetLanguage_SetsLanguageProperty_WhenCalled()
+ {
+ Categories c = new Categories("Sample text")
+ .SetLanguage("eng");
+
+ Assert.Equal("eng", c.Language);
+ Assert.Equal("Sample text", c.Content);
+ }
+
+ [Fact]
+ public void SetGenre_SetsGenreProperty_WhenCalled()
{
- [Fact]
- public void CheckBasicUsage()
- {
- Categories c = new Categories("Sample text for categorization");
-
- Assert.Equal("categories", c.Endpoint);
- Assert.Equal("Sample text for categorization", c.Content);
- }
-
- [Fact]
- public void CheckWithLanguage()
- {
- Categories c = new Categories("Sample text")
- .SetLanguage("eng");
-
- Assert.Equal("eng", c.Language);
- Assert.Equal("Sample text", c.Content);
- }
-
- [Fact]
- public void CheckWithGenre()
- {
- Categories c = new Categories("Sample text")
- .SetGenre("social-media");
-
- Assert.Equal("", c.Genre);
- }
-
- [Fact]
- public void CheckFluentAPI()
- {
- Categories c = new Categories("Sample text")
- .SetLanguage("eng")
- .SetOption("customOption", "value");
-
- Assert.Equal("eng", c.Language);
- Assert.Equal("value", c.Options["customOption"]);
- }
+ Categories c = new Categories("Sample text")
+ .SetGenre("social-media");
+
+ Assert.Equal("", c.Genre);
+ }
+
+ [Fact]
+ public void FluentAPI_AllowsMethodChaining_WhenSettingMultipleProperties()
+ {
+ Categories c = new Categories("Sample text")
+ .SetLanguage("eng")
+ .SetOption("customOption", "value");
+
+ Assert.Equal("eng", c.Language);
+ Assert.Equal("value", c.Options["customOption"]);
}
}
\ No newline at end of file
diff --git a/tests/ContentEndpointBaseTests.cs b/tests/ContentEndpointBaseTests.cs
new file mode 100644
index 0000000..63c907f
--- /dev/null
+++ b/tests/ContentEndpointBaseTests.cs
@@ -0,0 +1,408 @@
+using Rosette.Api.Client.Endpoints.Core;
+
+namespace Rosette.Api.Tests;
+
+// Concrete test implementation of ContentEndpointBase for testing
+internal class TestContentEndpoint : ContentEndpointBase
+{
+ public TestContentEndpoint(object content) : base("test-endpoint", content)
+ {
+ }
+}
+
+public class ContentEndpointBaseTests
+{
+ [Fact]
+ public void Constructor_ValidContent_SetsContentAndEndpoint()
+ {
+ // Arrange & Act
+ var endpoint = new TestContentEndpoint("test content");
+
+ // Assert
+ Assert.Equal("test-endpoint", endpoint.Endpoint);
+ Assert.Equal("test content", endpoint.Content);
+ }
+
+ [Fact]
+ public void Constructor_NullContent_ThrowsArgumentNullException()
+ {
+ // Arrange & Act & Assert
+ Assert.Throws(() => new TestContentEndpoint(null!));
+ }
+
+ [Fact]
+ public void Constructor_UriContent_SetsContentAsUriString()
+ {
+ // Arrange
+ var uri = new Uri("http://example.com/document");
+
+ // Act
+ var endpoint = new TestContentEndpoint(uri);
+
+ // Assert
+ Assert.Equal("http://example.com/document", endpoint.Content.ToString());
+ }
+
+ [Fact]
+ public void SetContent_ValidString_UpdatesContent()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("initial content");
+
+ // Act
+ var result = endpoint.SetContent("updated content");
+
+ // Assert
+ Assert.Equal("updated content", endpoint.Content);
+ Assert.Same(endpoint, result); // Verify fluent API
+ }
+
+ [Fact]
+ public void SetContent_NullContent_ThrowsArgumentNullException()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("initial content");
+
+ // Act & Assert
+ Assert.Throws(() => endpoint.SetContent(null!));
+ }
+
+ [Fact]
+ public void SetContent_Uri_UpdatesContentToUriString()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("initial content");
+ var uri = new Uri("http://example.com/new");
+
+ // Act
+ endpoint.SetContent(uri);
+
+ // Assert
+ Assert.Equal("http://example.com/new", endpoint.Content.ToString());
+ }
+
+ [Fact]
+ public void Content_AfterConstruction_ReturnsProvidedContent()
+ {
+ // Arrange & Act
+ var endpoint = new TestContentEndpoint("test content");
+
+ // Assert
+ Assert.Equal("test content", endpoint.Content);
+ }
+
+ [Fact]
+ public void SetLanguage_ValidLanguageCode_SetsLanguage()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ var result = endpoint.SetLanguage("eng");
+
+ // Assert
+ Assert.Equal("eng", endpoint.Language);
+ Assert.Same(endpoint, result); // Verify fluent API
+ }
+
+ [Fact]
+ public void SetLanguage_NullLanguage_ThrowsArgumentNullException()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act & Assert
+ Assert.Throws(() => endpoint.SetLanguage(null!));
+ }
+
+ [Fact]
+ public void SetLanguage_EmptyLanguage_ThrowsArgumentException()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act & Assert
+ Assert.Throws(() => endpoint.SetLanguage(string.Empty));
+ }
+
+ [Fact]
+ public void SetLanguage_WhitespaceLanguage_ThrowsArgumentException()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act & Assert
+ Assert.Throws(() => endpoint.SetLanguage(" "));
+ }
+
+ [Fact]
+ public void Language_WithoutSettingLanguage_ReturnsEmptyString()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ var language = endpoint.Language;
+
+ // Assert
+ Assert.Equal(string.Empty, language);
+ }
+
+ [Fact]
+ public void Language_AfterSettingLanguage_ReturnsSetValue()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+ endpoint.SetLanguage("spa");
+
+ // Act
+ var language = endpoint.Language;
+
+ // Assert
+ Assert.Equal("spa", language);
+ }
+
+ [Fact]
+ public void SetGenre_AnyValue_IsIgnoredAndReturnsInstance()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ var result = endpoint.SetGenre("social-media");
+
+ // Assert
+ Assert.Same(endpoint, result); // Verify fluent API
+ Assert.Equal(string.Empty, endpoint.Genre); // Genre should remain empty
+ }
+
+ [Fact]
+ public void Genre_WithoutSettingGenre_ReturnsEmptyString()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ var genre = endpoint.Genre;
+
+ // Assert
+ Assert.Equal(string.Empty, genre);
+ }
+
+ [Fact]
+ public void Genre_AfterSettingGenre_RemainsEmptyBecauseIgnored()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+ endpoint.SetGenre("news");
+
+ // Act
+ var genre = endpoint.Genre;
+
+ // Assert
+ Assert.Equal(string.Empty, genre); // Genre is ignored in ContentEndpointBase
+ }
+
+ [Fact]
+ public void SetFileContentType_ValidContentType_SetsFileContentType()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ var result = endpoint.SetFileContentType("application/pdf");
+
+ // Assert
+ Assert.Equal("application/pdf", endpoint.FileContentType);
+ Assert.Same(endpoint, result); // Verify fluent API
+ }
+
+ [Fact]
+ public void SetFileContentType_NullContentType_ThrowsArgumentNullException()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act & Assert
+ Assert.Throws(() => endpoint.SetFileContentType(null!));
+ }
+
+ [Fact]
+ public void SetFileContentType_EmptyContentType_ThrowsArgumentException()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act & Assert
+ Assert.Throws(() => endpoint.SetFileContentType(string.Empty));
+ }
+
+ [Fact]
+ public void SetFileContentType_WhitespaceContentType_ThrowsArgumentException()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act & Assert
+ Assert.Throws(() => endpoint.SetFileContentType(" "));
+ }
+
+ [Fact]
+ public void FileContentType_Default_ReturnsTextPlain()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ var contentType = endpoint.FileContentType;
+
+ // Assert
+ Assert.Equal("text/plain", contentType); // Default from EndpointExecutor
+ }
+
+ [Fact]
+ public void FileContentType_AfterSetting_ReturnsSetValue()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+ endpoint.SetFileContentType("application/json");
+
+ // Act
+ var contentType = endpoint.FileContentType;
+
+ // Assert
+ Assert.Equal("application/json", contentType);
+ }
+
+ [Fact]
+ public void Filename_WithoutFileStream_ReturnsEmptyString()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ var filename = endpoint.Filename;
+
+ // Assert
+ Assert.Equal(string.Empty, filename);
+ }
+
+ [Fact]
+ public void FluentAPI_ChainMultipleMethods_AllSettersReturnSameInstance()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("initial content");
+
+ // Act
+ var result = endpoint
+ .SetContent("updated content")
+ .SetLanguage("eng")
+ .SetGenre("news")
+ .SetFileContentType("application/json");
+
+ // Assert
+ Assert.Same(endpoint, result);
+ Assert.Equal("updated content", endpoint.Content);
+ Assert.Equal("eng", endpoint.Language);
+ Assert.Equal(string.Empty, endpoint.Genre); // Genre is ignored
+ Assert.Equal("application/json", endpoint.FileContentType);
+ }
+
+ [Fact]
+ public void FluentAPI_ComplexChaining_MaintainsCorrectState()
+ {
+ // Arrange & Act
+ var endpoint = new TestContentEndpoint("original")
+ .SetLanguage("eng")
+ .SetContent("modified")
+ .SetFileContentType("text/html");
+
+ // Assert
+ Assert.Equal("modified", endpoint.Content);
+ Assert.Equal("eng", endpoint.Language);
+ Assert.Equal("text/html", endpoint.FileContentType);
+ Assert.Equal("test-endpoint", endpoint.Endpoint);
+ }
+
+ [Fact]
+ public void SetContent_MultipleTypes_HandlesAllContentTypes()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("initial");
+
+ // Act & Assert - String
+ endpoint.SetContent("string content");
+ Assert.Equal("string content", endpoint.Content);
+
+ // Act & Assert - Uri
+ var uri = new Uri("http://example.com");
+ endpoint.SetContent(uri);
+ Assert.Equal("http://example.com/", endpoint.Content.ToString());
+ }
+
+ [Fact]
+ public void Constructor_WithFileStream_SetsContentAndFilename()
+ {
+ // Arrange
+ string tempFile = Path.GetTempFileName();
+ try
+ {
+ File.WriteAllText(tempFile, "test data");
+ using var fileStream = new FileStream(tempFile, FileMode.Open, FileAccess.Read);
+
+ // Act
+ var endpoint = new TestContentEndpoint(fileStream);
+
+ // Assert
+ Assert.NotNull(endpoint.Content);
+ Assert.Equal(tempFile, endpoint.Filename);
+ }
+ finally
+ {
+ if (File.Exists(tempFile))
+ {
+ File.Delete(tempFile);
+ }
+ }
+ }
+
+ [Fact]
+ public void SetLanguage_ISO6393Code_AcceptsThreeLetterCode()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ endpoint.SetLanguage("zho"); // Chinese
+
+ // Assert
+ Assert.Equal("zho", endpoint.Language);
+ }
+
+ [Fact]
+ public void Options_SetOption_CanSetCustomOptions()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ endpoint.SetOption("customKey", "customValue");
+
+ // Assert
+ Assert.True(endpoint.Options.ContainsKey("customKey"));
+ Assert.Equal("customValue", endpoint.Options["customKey"]);
+ }
+
+ [Fact]
+ public void UrlParameters_SetUrlParameter_CanSetQueryParameters()
+ {
+ // Arrange
+ var endpoint = new TestContentEndpoint("content");
+
+ // Act
+ endpoint.SetUrlParameter("output", "rosette");
+
+ // Assert
+ Assert.Equal("rosette", endpoint.UrlParameters["output"]);
+ }
+}
\ No newline at end of file
diff --git a/tests/EndpointBaseTests.cs b/tests/EndpointBaseTests.cs
index de099cf..e1531a5 100644
--- a/tests/EndpointBaseTests.cs
+++ b/tests/EndpointBaseTests.cs
@@ -1,54 +1,658 @@
-using Rosette.Api.Endpoints;
-using Rosette.Api.Endpoints.Core;
+using RichardSzalay.MockHttp;
+using Rosette.Api.Client;
+using Rosette.Api.Client.Endpoints;
+using Rosette.Api.Client.Models;
+using System.Net;
-namespace Rosette.Api.Tests {
+namespace Rosette.Api.Tests
+{
public class EndpointBaseTests
{
+ private static readonly string _defaultUri = "https://api.rosette.com/rest/v1/*";
+ [Fact]
+ public void Constructor_ValidEndpoint_SetsEndpointName()
+ {
+ // Arrange & Act
+ var endpoint = new Entities("test content");
- private static ApiClient Init() {
- return new ApiClient("testkey");
+ // Assert
+ Assert.Equal("entities", endpoint.Endpoint);
}
[Fact]
- public void CheckEndpoint() {
- EndpointBase ec = new EndpointBase("foo");
- Assert.Equal("foo", ec.Endpoint);
+ public void Options_InitialState_IsEmpty()
+ {
+ // Arrange & Act
+ var endpoint = new Entities("foo");
+
+ // Assert
+ Assert.Empty(endpoint.Options);
}
+ [Fact]
+ public void Params_InitialState_IsNotEmpty()
+ {
+ // Arrange & Act
+ var endpoint = new Entities("foo");
+ // Assert
+ Assert.NotEmpty(endpoint.Params);
+ }
[Fact]
- public void CheckOptions() {
- Entities e = new Entities("foo").SetOption("test", "value");
+ public void UrlParameters_InitialState_IsEmpty()
+ {
+ // Arrange & Act
+ var endpoint = new Entities("foo");
+
+ // Assert
+ Assert.Empty(endpoint.UrlParameters);
+ }
+ [Fact]
+ public void SetOption_ValidOption_AddsToOptions()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act
+ e.SetOption("test", "value");
+
+ // Assert
Assert.Equal("value", e.Options["test"]);
+ }
+
+ [Fact]
+ public void SetOption_MultipleOptions_AddsAllOptions()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+ // Act
+ e.SetOption("test", "value");
e.SetOption("test2", "value2");
+ // Assert
+ Assert.Equal("value", e.Options["test"]);
Assert.Equal("value2", e.Options["test2"]);
+ }
+
+ [Fact]
+ public void SetOption_NullOptionName_ThrowsArgumentNullException()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act & Assert
+ Assert.Throws(() => e.SetOption(null!, "value"));
+ }
+
+ [Fact]
+ public void SetOption_EmptyOptionName_ThrowsArgumentException()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act & Assert
+ Assert.Throws(() => e.SetOption(string.Empty, "value"));
+ }
- e.RemoveOption("value");
+ [Fact]
+ public void SetOption_NullOptionValue_ThrowsArgumentNullException()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act & Assert
+ Assert.Throws(() => e.SetOption("test", null!));
+ }
+
+ [Fact]
+ public void SetOption_ReturnsInstance_ForFluentAPI()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act
+ var result = e.SetOption("test", "value");
+
+ // Assert
+ Assert.Same(e, result);
+ }
+
+ [Fact]
+ public void RemoveOption_ExistingOption_RemovesOption()
+ {
+ // Arrange
+ Entities e = new Entities("foo")
+ .SetOption("test", "value");
+
+ // Act
+ e.RemoveOption("test");
- Assert.True(!e.Options.ContainsKey("value"));
+ // Assert
+ Assert.False(e.Options.ContainsKey("test"));
+ }
+
+ [Fact]
+ public void RemoveOption_NonExistingOption_DoesNotThrow()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act & Assert
+ var exception = Record.Exception(() => e.RemoveOption("nonexistent"));
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void RemoveOption_NullKey_ThrowsArgumentNullException()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act & Assert
+ Assert.Throws(() => e.RemoveOption(null!));
+ }
+
+ [Fact]
+ public void RemoveOption_ReturnsInstance_ForFluentAPI()
+ {
+ // Arrange
+ Entities e = new Entities("foo")
+ .SetOption("test", "value");
+ // Act
+ var result = e.RemoveOption("test");
+
+ // Assert
+ Assert.Same(e, result);
+ }
+
+ [Fact]
+ public void ClearOptions_WithOptions_RemovesAllOptions()
+ {
+ // Arrange
+ Entities e = new Entities("foo")
+ .SetOption("test1", "value1")
+ .SetOption("test2", "value2");
+
+ // Act
e.ClearOptions();
- Assert.True(e.Options.Count == 0);
+ // Assert
+ Assert.Empty(e.Options);
}
[Fact]
- public void CheckUrlParameters() {
- Entities e = new Entities("foo").SetUrlParameter("test", "value");
+ public void ClearOptions_ReturnsInstance_ForFluentAPI()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act
+ var result = e.ClearOptions();
+
+ // Assert
+ Assert.Same(e, result);
+ }
+
+ [Fact]
+ public void SetUrlParameter_ValidParameter_AddsToUrlParameters()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act
+ e.SetUrlParameter("test", "value");
+ // Assert
Assert.Equal("value", e.UrlParameters["test"]);
+ }
+
+ [Fact]
+ public void SetUrlParameter_NullKey_ThrowsArgumentNullException()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act & Assert
+ Assert.Throws(() => e.SetUrlParameter(null!, "value"));
+ }
+
+ [Fact]
+ public void SetUrlParameter_NullValue_ThrowsArgumentNullException()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act & Assert
+ Assert.Throws(() => e.SetUrlParameter("key", null!));
+ }
+
+ [Fact]
+ public void SetUrlParameter_ReturnsInstance_ForFluentAPI()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+ // Act
+ var result = e.SetUrlParameter("test", "value");
+
+ // Assert
+ Assert.Same(e, result);
+ }
+
+ [Fact]
+ public void RemoveUrlParameter_ExistingParameter_RemovesParameter()
+ {
+ // Arrange
+ Entities e = new Entities("foo")
+ .SetUrlParameter("test", "value");
+
+ // Act
e.RemoveUrlParameter("test");
- Assert.True(e.UrlParameters.Count == 0);
+ // Assert
+ Assert.Empty(e.UrlParameters);
+ }
+
+ [Fact]
+ public void RemoveUrlParameter_NullKey_ThrowsArgumentNullException()
+ {
+ // Arrange
+ Entities e = new Entities("foo");
+
+ // Act & Assert
+ Assert.Throws(() => e.RemoveUrlParameter(null!));
+ }
+
+ [Fact]
+ public void RemoveUrlParameter_ReturnsInstance_ForFluentAPI()
+ {
+ // Arrange
+ Entities e = new Entities("foo")
+ .SetUrlParameter("test", "value");
+
+ // Act
+ var result = e.RemoveUrlParameter("test");
+
+ // Assert
+ Assert.Same(e, result);
+ }
+
+ [Fact]
+ public void FluentAPI_ChainMultipleMethods_AllSettersReturnSameInstance()
+ {
+ // Arrange & Act
+ var endpoint = new Entities("content")
+ .SetOption("opt1", "val1")
+ .SetOption("opt2", "val2")
+ .SetUrlParameter("param", "value")
+ .SetLanguage("eng");
+
+ // Assert
+ Assert.Equal("val1", endpoint.Options["opt1"]);
+ Assert.Equal("val2", endpoint.Options["opt2"]);
+ Assert.Equal("value", endpoint.UrlParameters["param"]);
+ Assert.Equal("eng", endpoint.Language);
+ }
+
+ [Fact]
+ public void Call_ValidEndpoint_ReturnsResponse()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content");
+
+ // Act
+ Response result = endpoint.Call(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.NotNull(result.Content);
+ }
+
+ #region Async Tests
+
+ [Fact]
+ public async Task CallAsync_ValidEndpoint_ReturnsResponse()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content");
+
+ // Act
+ Response result = await endpoint.CallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.NotNull(result.Content);
+ }
+
+ [Fact]
+ public async Task CallAsync_WithCancellationToken_ReturnsResponse()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content");
+ using var cts = new CancellationTokenSource();
+
+ // Act
+ Response result = await endpoint.CallAsync(api, cts.Token);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.NotNull(result.Content);
+ }
+
+ [Fact]
+ public async Task CallAsync_CancelledToken_ThrowsOperationCanceledException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(async () =>
+ {
+ await Task.Delay(100);
+ return new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent("{\"test\": \"OK\"}")
+ };
+ });
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content");
+ var cts = new CancellationTokenSource();
+ cts.Cancel(); // Cancel immediately
+
+ // Act & Assert
+ await Assert.ThrowsAsync(
+ async () => await endpoint.CallAsync(api, cts.Token));
+ }
+
+ [Fact]
+ public async Task CallAsync_WithTimeout_ThrowsOperationCanceledException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(async () =>
+ {
+ await Task.Delay(5000); // 5 second delay
+ return new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent("{\"test\": \"OK\"}")
+ };
+ });
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content");
+ using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); // 100ms timeout
+
+ // Act & Assert
+ await Assert.ThrowsAnyAsync(
+ async () => await endpoint.CallAsync(api, cts.Token));
+ }
+
+ [Fact]
+ public async Task CallAsync_WithOptions_SendsOptionsToServer()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content")
+ .SetOption("linkEntities", true);
+
+ // Act
+ Response result = await endpoint.CallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.True((bool)endpoint.Options["linkEntities"]);
+ }
+
+ [Fact]
+ public async Task CallAsync_WithUrlParameters_AppendsQueryString()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When("https://api.rosette.com/rest/v1/entities?output=rosette")
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content")
+ .SetUrlParameter("output", "rosette");
+
+ // Act
+ Response result = await endpoint.CallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.Equal("rosette", endpoint.UrlParameters["output"]);
}
+ [Fact]
+ public async Task CallAsync_ErrorResponse_ThrowsHttpRequestException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.BadRequest, "application/json", "{\"message\": \"Bad Request\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content");
+
+ // Act & Assert
+ await Assert.ThrowsAsync(
+ async () => await endpoint.CallAsync(api));
+ }
+
+ [Fact]
+ public async Task CallAsync_NotFoundResponse_ThrowsHttpRequestException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.NotFound, "application/json", "{\"message\": \"Not Found\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+ Entities endpoint = new Entities("test content");
+
+ // Act & Assert
+ await Assert.ThrowsAsync(
+ async () => await endpoint.CallAsync(api));
+ }
+
+ [Fact]
+ public async Task CallAsync_UnauthorizedResponse_ThrowsHttpRequestException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.Unauthorized, "application/json", "{\"message\": \"Unauthorized\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content");
+
+ // Act & Assert
+ await Assert.ThrowsAsync(
+ async () => await endpoint.CallAsync(api));
+ }
+
+ [Fact]
+ public async Task CallAsync_WithLanguage_SendsLanguageParameter()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content")
+ .SetLanguage("eng");
+
+ // Act
+ Response result = await endpoint.CallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.Equal("eng", endpoint.Language);
+ }
+
+ [Fact]
+ public async Task CallAsync_MultipleCallsToSameEndpoint_EachReturnsResponse()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content");
+
+ // Act
+ Response result1 = await endpoint.CallAsync(api);
+ Response result2 = await endpoint.CallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result1.StatusCode);
+ Assert.Equal((int)HttpStatusCode.OK, result2.StatusCode);
+ Assert.NotSame(result1, result2); // Different instances
+ }
+
+ [Fact]
+ public async Task CallAsync_WithFluentChaining_AllSettingsApplied()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When("https://api.rosette.com/rest/v1/entities?output=rosette")
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint = new Entities("test content")
+ .SetLanguage("eng")
+ .SetOption("linkEntities", true)
+ .SetUrlParameter("output", "rosette");
+
+ // Act
+ Response result = await endpoint.CallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.Equal("eng", endpoint.Language);
+ Assert.True((bool)endpoint.Options["linkEntities"]);
+ Assert.Equal("rosette", endpoint.UrlParameters["output"]);
+ }
+
+ [Fact]
+ public async Task CallAsync_ConcurrentCalls_BothComplete()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Entities endpoint1 = new Entities("content1");
+ Entities endpoint2 = new Entities("content2");
+
+ // Act
+ var task1 = endpoint1.CallAsync(api);
+ var task2 = endpoint2.CallAsync(api);
+ var results = await Task.WhenAll(task1, task2);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, results[0].StatusCode);
+ Assert.Equal((int)HttpStatusCode.OK, results[1].StatusCode);
+ }
+
+ [Fact]
+ public async Task CallAsync_InfoEndpoint_UsesGetCall()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When("https://api.rosette.com/rest/v1/info")
+ .Respond(HttpStatusCode.OK, "application/json", "{\"name\": \"Rosette API\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Info endpoint = new Info();
+
+ // Act
+ Response result = await endpoint.CallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.NotNull(result.Content);
+ }
+
+ [Fact]
+ public async Task CallAsync_PingEndpoint_UsesGetCall()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When("https://api.rosette.com/rest/v1/ping")
+ .Respond(HttpStatusCode.OK, "application/json", "{\"message\": \"pong\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ Ping endpoint = new Ping();
+
+ // Act
+ Response result = await endpoint.CallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.NotNull(result.Content);
+ }
+ #endregion
}
}
\ No newline at end of file
diff --git a/tests/EndpointExecutorTests.cs b/tests/EndpointExecutorTests.cs
index 466c506..f6c8d03 100644
--- a/tests/EndpointExecutorTests.cs
+++ b/tests/EndpointExecutorTests.cs
@@ -2,139 +2,507 @@
using System.Collections.Specialized;
using System.Net;
using System.Text.Json;
-using Rosette.Api.Endpoints.Core;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints.Core;
+using Rosette.Api.Client.Models;
+using Rosette.Api.Client;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class EndpointExecutorTests
{
- public class EndpointExecutorTests
- {
- private readonly Dictionary _params;
- private readonly Dictionary _options;
- private readonly NameValueCollection _urlParameters;
- private static readonly string _defaultUri = "https://api.rosette.com/rest/v1/*";
-
- public EndpointExecutorTests() {
- _params = new Dictionary();
- _options = new Dictionary();
- _urlParameters = new NameValueCollection();
- }
+ private readonly Dictionary _params;
+ private readonly Dictionary _options;
+ private readonly NameValueCollection _urlParameters;
+ private static readonly string _defaultUri = "https://api.rosette.com/rest/v1/*";
- [Fact]
- public void CheckContent() {
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
- Assert.Empty(f.Content.ToString()!);
- f.Content = "Sample Content";
- Assert.Equal("Sample Content", f.Content);
- Assert.True(_params.ContainsKey("content"));
- Assert.False(_params.ContainsKey("contenturi"));
- }
+ public EndpointExecutorTests() {
+ _params = new Dictionary();
+ _options = new Dictionary();
+ _urlParameters = new NameValueCollection();
+ }
- [Fact]
- public void CheckEndpoint() {
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
- Assert.Equal("test", f.Endpoint);
- }
+ [Fact]
+ public void Content_SetStringAndAddToParams_WhenAssigned() {
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ Assert.Empty(f.Content.ToString()!);
+ f.Content = "Sample Content";
+ Assert.Equal("Sample Content", f.Content);
+ Assert.True(_params.ContainsKey("content"));
+ Assert.False(_params.ContainsKey("contenturi"));
+ }
+
+ [Fact]
+ public void Endpoint_ReturnsProvidedValue_WhenInitialized() {
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ Assert.Equal("test", f.Endpoint);
+ }
- [Fact]
- public void CheckContentUri() {
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ [Fact]
+ public void Content_SetUriAndAddToParams_WhenAssignedUri() {
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ Assert.Empty(f.Content.ToString()!);
+ f.Content = new Uri("http://google.com");
+ Assert.Equal("http://google.com/", f.Content);
+ Assert.True(_params.ContainsKey("contenturi"));
+ Assert.False(_params.ContainsKey("content"));
+ }
+
+ [Fact]
+ public void Content_SetFileStreamAndFilename_WhenAssignedFileStream() {
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ Assert.Empty(f.Content.ToString()!);
+ var newFile = Path.GetTempFileName();
+ using (FileStream fs = File.OpenRead(newFile)) {
+ f.Content = fs;
+ Assert.Equal(newFile, f.Filename);
Assert.Empty(f.Content.ToString()!);
- f.Content = new Uri("http://google.com");
- Assert.Equal("http://google.com/", f.Content);
- Assert.True(_params.ContainsKey("contenturi"));
Assert.False(_params.ContainsKey("content"));
+ Assert.False(_params.ContainsKey("contenturi"));
}
+ }
- [Fact]
- public void CheckFilename() {
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
- Assert.Empty(f.Content.ToString()!);
- var newFile = Path.GetTempFileName();
- using (FileStream fs = File.OpenRead(newFile)) {
- f.Content = fs;
- Assert.Equal(newFile, f.Filename);
- Assert.Empty(f.Content.ToString()!);
- Assert.False(_params.ContainsKey("content"));
- Assert.False(_params.ContainsKey("contenturi"));
+ [Fact]
+ public void Language_SetLanguage_WhenAssigned() {
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ Assert.Empty(f.Language!);
+ f.Language = "eng";
+ Assert.Equal("eng", f.Language);
+ }
+
+ [Fact]
+ public void Genre_SetGenre_WhenAssigned() {
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ Assert.Empty(f.Genre!);
+ f.Genre = "social-media";
+ Assert.Equal("social-media", f.Genre);
+ }
+
+ [Fact]
+ public void FileContentType_SetContentType_WhenAssigned() {
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ Assert.Equal("text/plain", f.FileContentType);
+ f.FileContentType = "octet/stream";
+ Assert.Equal("octet/stream", f.FileContentType);
+ }
+
+ [Fact]
+ public void Parameters_SerializeCorrectly_WhenOptionsSet() {
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+
+ api.AssignClient(client);
+
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+
+ _options["opt"] = true;
+ Dictionary paramTest = new Dictionary();
+ paramTest["content"] = "Test Content";
+ paramTest["options"] = _options;
+
+ f.Content = "Test Content";
+ Response result = f.PostCall(api);
+ Assert.Equal(JsonSerializer.Serialize(paramTest), JsonSerializer.Serialize(f.Parameters));
+ }
+
+ [Fact]
+ public void PostCall_ReturnsOKResponse_WhenCalledWithValidContent() {
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+
+ api.AssignClient(client);
+
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ f.Content = "Test content";
+ Response result = f.PostCall(api);
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ }
+
+ [Fact]
+ public void GetCall_ReturnsOKResponse_WhenCalled() {
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+
+ api.AssignClient(client);
+
+ EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ Response result = f.GetCall(api);
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ }
+
+ #region Async Tests
+
+ [Fact]
+ public async Task GetCallAsync_ValidRequest_ReturnsResponse()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+
+ // Act
+ Response result = await executor.GetCallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.NotNull(result.Content);
+ }
+
+ [Fact]
+ public async Task GetCallAsync_WithCancellationToken_ReturnsResponse()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ using var cts = new CancellationTokenSource();
+
+ // Act
+ Response result = await executor.GetCallAsync(api, cts.Token);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ }
+
+ [Fact]
+ public async Task GetCallAsync_CancelledToken_ThrowsOperationCanceledException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(async () =>
+ {
+ await Task.Delay(100); // Simulate delay
+ return new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent("{\"test\": \"OK\"}")
+ };
+ });
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ var cts = new CancellationTokenSource();
+ cts.Cancel(); // Cancel immediately
+
+ // Act & Assert
+ await Assert.ThrowsAsync(
+ async () => await executor.GetCallAsync(api, cts.Token));
+ }
+
+ [Fact]
+ public async Task PostCallAsync_WithStringContent_ReturnsResponse()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ executor.Content = "Test content";
+
+ // Act
+ Response result = await executor.PostCallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.NotNull(result.Content);
+ }
+
+ [Fact]
+ public async Task PostCallAsync_WithCancellationToken_ReturnsResponse()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ executor.Content = "Test content";
+ using var cts = new CancellationTokenSource();
+
+ // Act
+ Response result = await executor.PostCallAsync(api, cts.Token);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ }
+
+ [Fact]
+ public async Task PostCallAsync_CancelledToken_ThrowsOperationCanceledException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(async () =>
+ {
+ await Task.Delay(100);
+ return new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent("{\"test\": \"OK\"}")
+ };
+ });
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ executor.Content = "Test content";
+ var cts = new CancellationTokenSource();
+ cts.Cancel();
+
+ // Act & Assert
+ await Assert.ThrowsAsync(
+ async () => await executor.PostCallAsync(api, cts.Token));
+ }
+
+ [Fact]
+ public async Task PostCallAsync_WithOptions_SerializesCorrectly()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ _options["opt"] = true;
+ executor.Content = "Test Content";
+
+ Dictionary expectedParams = new Dictionary
+ {
+ ["content"] = "Test Content",
+ ["options"] = _options
+ };
+
+ // Act
+ Response result = await executor.PostCallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.Equal(JsonSerializer.Serialize(expectedParams), JsonSerializer.Serialize(executor.Parameters));
+ }
+
+ [Fact]
+ public async Task PostCallAsync_WithFileContent_SendsMultipart()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ var tempFile = Path.GetTempFileName();
+ File.WriteAllText(tempFile, "test file content");
+
+ try
+ {
+ using (FileStream fs = File.OpenRead(tempFile))
+ {
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ executor.Content = fs;
+
+ // Act
+ Response result = await executor.PostCallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.Equal(tempFile, executor.Filename);
}
}
-
- [Fact]
- public void CheckLanguage() {
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
- Assert.Empty(f.Language!);
- f.Language = "eng";
- Assert.Equal("eng", f.Language);
+ finally
+ {
+ if (File.Exists(tempFile))
+ {
+ File.Delete(tempFile);
+ }
}
+ }
- [Fact]
- public void CheckGenre() {
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
- Assert.Empty(f.Genre!);
- f.Genre = "social-media";
- Assert.Equal("social-media", f.Genre);
- }
+ [Fact]
+ public async Task PostCallAsync_WithFileAndOptions_SendsMultipartWithRequest()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ var tempFile = Path.GetTempFileName();
+ File.WriteAllText(tempFile, "test file content");
+
+ try
+ {
+ using (FileStream fs = File.OpenRead(tempFile))
+ {
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ _options["language"] = "eng";
+ executor.Content = fs;
- [Fact]
- public void CheckFileContentType() {
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
- Assert.Equal("text/plain", f.FileContentType);
- f.FileContentType = "octet/stream";
- Assert.Equal("octet/stream", f.FileContentType);
+ // Act
+ Response result = await executor.PostCallAsync(api);
+
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ Assert.True(_options.ContainsKey("language"));
+ }
+ }
+ finally
+ {
+ if (File.Exists(tempFile))
+ {
+ File.Delete(tempFile);
+ }
}
+ }
- [Fact]
- public void TestParameterSerialization() {
- ApiClient api = new ApiClient("testkey");
- var mockHttp = new MockHttpMessageHandler();
- mockHttp.When(_defaultUri)
- .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
- var client = mockHttp.ToHttpClient();
+ [Fact]
+ public async Task PostCallAsync_WithUrlParameters_AppendsQueryString()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When("https://api.rosette.com/rest/v1/test?output=rosette")
+ .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
- api.AssignClient(client);
+ _urlParameters.Add("output", "rosette");
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ executor.Content = "Test content";
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ // Act
+ Response result = await executor.PostCallAsync(api);
- _options["opt"] = true;
- Dictionary paramTest = new Dictionary();
- paramTest["content"] = "Test Content";
- paramTest["options"] = _options;
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ }
- f.Content = "Test Content";
- Response result = f.PostCall(api);
- Assert.Equal(JsonSerializer.Serialize(paramTest), JsonSerializer.Serialize(f.Parameters));
- }
+ [Fact]
+ public async Task PostCallAsync_WithUnicodeContent_SendsUnescapedUnicode()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ string capturedRequest = string.Empty;
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(async (request) =>
+ {
+ capturedRequest = await request.Content!.ReadAsStringAsync();
+ return new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent("{\"test\": \"OK\"}")
+ };
+ });
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
- [Fact]
- public void TestPostCall() {
- ApiClient api = new ApiClient("testkey");
- var mockHttp = new MockHttpMessageHandler();
- mockHttp.When(_defaultUri)
- .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
- var client = mockHttp.ToHttpClient();
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ executor.Content = "北京大学 👍🏾"; // Chinese characters and emoji
- api.AssignClient(client);
+ // Act
+ Response result = await executor.PostCallAsync(api);
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
- f.Content = "Test content";
- Response result = f.PostCall(api);
- Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
- }
+ // Assert
+ Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
+ // Verify that the request contains actual Unicode, not escape sequences
+ Assert.Contains("北京大学", capturedRequest);
+ }
- [Fact]
- public void TestGetCall() {
- ApiClient api = new ApiClient("testkey");
- var mockHttp = new MockHttpMessageHandler();
- mockHttp.When(_defaultUri)
- .Respond(HttpStatusCode.OK, "application/json", "{\"test\": \"OK\"}");
- var client = mockHttp.ToHttpClient();
+ [Fact]
+ public async Task PostCallAsync_ErrorResponse_ThrowsHttpRequestException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.BadRequest, "application/json", "{\"message\": \"Bad Request\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
- api.AssignClient(client);
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ executor.Content = "Test content";
- EndpointExecutor f = new EndpointExecutor(_params, _options, _urlParameters, "test");
- Response result = f.GetCall(api);
- Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
- }
+ // Act & Assert
+ await Assert.ThrowsAsync(
+ async () => await executor.PostCallAsync(api));
+ }
+
+ [Fact]
+ public async Task GetCallAsync_ErrorResponse_ThrowsHttpRequestException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(HttpStatusCode.NotFound, "application/json", "{\"message\": \"Not Found\"}");
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+
+ // Act & Assert
+ await Assert.ThrowsAsync(
+ async () => await executor.GetCallAsync(api));
}
+
+ [Fact]
+ public async Task PostCallAsync_TimeoutWithCancellation_ThrowsOperationCanceledException()
+ {
+ // Arrange
+ ApiClient api = new ApiClient("testkey");
+ var mockHttp = new MockHttpMessageHandler();
+ mockHttp.When(_defaultUri)
+ .Respond(async () =>
+ {
+ await Task.Delay(5000); // 5 second delay
+ return new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent("{\"test\": \"OK\"}")
+ };
+ });
+ var client = mockHttp.ToHttpClient();
+ api.AssignClient(client);
+
+ EndpointExecutor executor = new EndpointExecutor(_params, _options, _urlParameters, "test");
+ executor.Content = "Test content";
+ using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); // 100ms timeout
+
+ // Act & Assert
+ await Assert.ThrowsAnyAsync(
+ async () => await executor.PostCallAsync(api, cts.Token));
+ }
+
+ #endregion
}
diff --git a/tests/EntitiesTests.cs b/tests/EntitiesTests.cs
index 600d40a..716027f 100644
--- a/tests/EntitiesTests.cs
+++ b/tests/EntitiesTests.cs
@@ -1,51 +1,50 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class EntitiesTests
{
- public class EntitiesTests
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCalledWithText()
+ {
+ string text = "Bill Murray will appear in new Ghostbusters film.";
+ Entities e = new Entities(text);
+
+ Assert.Equal("entities", e.Endpoint);
+ Assert.Equal(text, e.Content);
+ }
+
+ [Fact]
+ public void SetLanguageAndGenre_SetsProperties_WhenCalled()
+ {
+ Entities e = new Entities("Sample text")
+ .SetLanguage("eng")
+ .SetGenre("social-media");
+
+ Assert.Equal("eng", e.Language);
+ Assert.Equal("", e.Genre);
+ }
+
+ [Fact]
+ public void SetUrlParameter_AddsParameterToUrlParameters_WhenCalled()
{
- [Fact]
- public void CheckBasicUsage()
- {
- string text = "Bill Murray will appear in new Ghostbusters film.";
- Entities e = new Entities(text);
-
- Assert.Equal("entities", e.Endpoint);
- Assert.Equal(text, e.Content);
- }
-
- [Fact]
- public void CheckWithLanguageAndGenre()
- {
- Entities e = new Entities("Sample text")
- .SetLanguage("eng")
- .SetGenre("social-media");
-
- Assert.Equal("eng", e.Language);
- Assert.Equal("", e.Genre);
- }
-
- [Fact]
- public void CheckWithUrlParameter()
- {
- Entities e = new Entities("Sample text")
- .SetUrlParameter("output", "rosette");
-
- Assert.Equal("rosette", e.UrlParameters["output"]);
- }
-
- [Fact]
- public void CheckFluentAPI()
- {
- Entities e = new Entities("Apple announced a new iPhone.")
- .SetLanguage("eng")
- .SetGenre("news")
- .SetOption("linkEntities", true)
- .SetUrlParameter("output", "rosette");
-
- Assert.Equal("eng", e.Language);
- Assert.True((bool)e.Options["linkEntities"]);
- Assert.Equal("rosette", e.UrlParameters["output"]);
- }
+ Entities e = new Entities("Sample text")
+ .SetUrlParameter("output", "rosette");
+
+ Assert.Equal("rosette", e.UrlParameters["output"]);
+ }
+
+ [Fact]
+ public void FluentAPI_AllowsMethodChaining_WhenSettingMultipleProperties()
+ {
+ Entities e = new Entities("Apple announced a new iPhone.")
+ .SetLanguage("eng")
+ .SetGenre("news")
+ .SetOption("linkEntities", true)
+ .SetUrlParameter("output", "rosette");
+
+ Assert.Equal("eng", e.Language);
+ Assert.True((bool)e.Options["linkEntities"]);
+ Assert.Equal("rosette", e.UrlParameters["output"]);
}
}
\ No newline at end of file
diff --git a/tests/LanguageTests.cs b/tests/LanguageTests.cs
index 0ec1de0..1ee9e71 100644
--- a/tests/LanguageTests.cs
+++ b/tests/LanguageTests.cs
@@ -1,43 +1,42 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class LanguageTests
{
- public class LanguageTests
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCalledWithText()
+ {
+ Language l = new Language("Por favor Señorita, says the man.");
+
+ Assert.Equal("language", l.Endpoint);
+ Assert.Equal("Por favor Señorita, says the man.", l.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsContentFromUri_WhenCalledWithUri()
+ {
+ Uri uri = new Uri("http://example.com");
+ Language l = new Language(uri);
+
+ Assert.Equal("http://example.com/", l.Content.ToString());
+ }
+
+ [Fact]
+ public void SetContent_UpdatesContent_WhenCalled()
{
- [Fact]
- public void CheckBasicUsage()
- {
- Language l = new Language("Por favor Señorita, says the man.");
-
- Assert.Equal("language", l.Endpoint);
- Assert.Equal("Por favor Señorita, says the man.", l.Content);
- }
-
- [Fact]
- public void CheckWithUri()
- {
- Uri uri = new Uri("http://example.com");
- Language l = new Language(uri);
-
- Assert.Equal("http://example.com/", l.Content.ToString());
- }
-
- [Fact]
- public void CheckContentUpdate()
- {
- Language l = new Language("Original text")
- .SetContent("Updated text");
-
- Assert.Equal("Updated text", l.Content);
- }
-
- [Fact]
- public void CheckWithGenre()
- {
- Language l = new Language("Sample text")
- .SetGenre("social-media");
-
- Assert.Equal("", l.Genre);
- }
+ Language l = new Language("Original text")
+ .SetContent("Updated text");
+
+ Assert.Equal("Updated text", l.Content);
+ }
+
+ [Fact]
+ public void SetGenre_SetsGenreProperty_WhenCalled()
+ {
+ Language l = new Language("Sample text")
+ .SetGenre("social-media");
+
+ Assert.Equal("", l.Genre);
}
}
\ No newline at end of file
diff --git a/tests/NameDeduplicationTests.cs b/tests/NameDeduplicationTests.cs
index 9b382a7..875be79 100644
--- a/tests/NameDeduplicationTests.cs
+++ b/tests/NameDeduplicationTests.cs
@@ -1,41 +1,40 @@
-using Rosette.Api.Endpoints;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class NameDeduplicationTests
{
- public class NameDeduplicationTests
- {
- [Fact]
- public void CheckBasicUsage() {
- List names = new List {
- new Name("foo"),
- new Name("bar")
- };
- NameDeduplication n = new NameDeduplication(names);
- Assert.Equal(names, n.Names);
- Assert.Equal(0.75f, n.Threshold);
- }
+ [Fact]
+ public void Constructor_SetsNamesAndThreshold_WhenCalledWithNames() {
+ List names = new List {
+ new Name("foo"),
+ new Name("bar")
+ };
+ NameDeduplication n = new NameDeduplication(names);
+ Assert.Equal(names, n.Names);
+ Assert.Equal(0.75f, n.Threshold);
+ }
- [Fact]
- public void CheckProfileID() {
- List names = new List {
- new Name("foo"),
- new Name("bar")
- };
- NameDeduplication n = new NameDeduplication(names).SetProfileID("profileid");
- Assert.Equal(names, n.Names);
- Assert.Equal("profileid", n.ProfileID);
- }
+ [Fact]
+ public void SetProfileID_SetsProfileID_WhenCalled() {
+ List names = new List {
+ new Name("foo"),
+ new Name("bar")
+ };
+ NameDeduplication n = new NameDeduplication(names).SetProfileID("profileid");
+ Assert.Equal(names, n.Names);
+ Assert.Equal("profileid", n.ProfileID);
+ }
- [Fact]
- public void CheckThreshold() {
- List names = new List {
- new Name("foo"),
- new Name("bar")
- };
- NameDeduplication n = new NameDeduplication(names).SetThreshold(0.8f);
- Assert.Equal(names, n.Names);
- Assert.Equal(0.8f, n.Threshold);
- }
+ [Fact]
+ public void SetThreshold_SetsThreshold_WhenCalled() {
+ List names = new List {
+ new Name("foo"),
+ new Name("bar")
+ };
+ NameDeduplication n = new NameDeduplication(names).SetThreshold(0.8f);
+ Assert.Equal(names, n.Names);
+ Assert.Equal(0.8f, n.Threshold);
}
}
diff --git a/tests/NameSimilarityTests.cs b/tests/NameSimilarityTests.cs
index ce17caa..8f1d778 100644
--- a/tests/NameSimilarityTests.cs
+++ b/tests/NameSimilarityTests.cs
@@ -1,20 +1,19 @@
-using Rosette.Api.Endpoints;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class NameSimilarityTests
{
- public class NameSimilarityTests
- {
- [Fact]
- public void CheckForNull() {
- var exception = Record.Exception(() => new NameSimilarity(null, null));
- Assert.IsType(exception);
- Assert.Equal("Value cannot be null. (Parameter 'name1')", exception.Message);
+ [Fact]
+ public void Constructor_ThrowsArgumentNullException_WhenNamesAreNull() {
+ var exception = Record.Exception(() => new NameSimilarity(null, null));
+ Assert.IsType(exception);
+ Assert.Equal("Value cannot be null. (Parameter 'name1')", exception.Message);
- Name rn = new Name("foo");
- exception = Record.Exception(() => new NameSimilarity(rn, null));
- Assert.IsType(exception);
- Assert.Equal("Value cannot be null. (Parameter 'name2')", exception.Message);
- }
+ Name rn = new Name("foo");
+ exception = Record.Exception(() => new NameSimilarity(rn, null));
+ Assert.IsType(exception);
+ Assert.Equal("Value cannot be null. (Parameter 'name2')", exception.Message);
}
}
diff --git a/tests/NameTests.cs b/tests/NameTests.cs
index 2b839bf..4813a40 100644
--- a/tests/NameTests.cs
+++ b/tests/NameTests.cs
@@ -1,60 +1,59 @@
-using Rosette.Api.Models;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class NameTests
{
- public class NameTests
- {
- [Fact]
- public void CheckName() {
- Name rn = new Name("foo");
- Assert.Equal("foo", rn.Text);
- Assert.Null(rn.EntityType);
- Assert.Null(rn.Language);
- Assert.Null(rn.Script);
- Assert.Null(rn.Gender);
- }
+ [Fact]
+ public void Constructor_SetsTextAndNullProperties_WhenCreatingName() {
+ Name rn = new Name("foo");
+ Assert.Equal("foo", rn.Text);
+ Assert.Null(rn.EntityType);
+ Assert.Null(rn.Language);
+ Assert.Null(rn.Script);
+ Assert.Null(rn.Gender);
+ }
- [Fact]
- public void CheckWithEntityType() {
- Name rn = new Name("foo").SetEntityType("PERSON");
- Assert.Equal("foo", rn.Text);
- Assert.Equal("PERSON", rn.EntityType);
- }
+ [Fact]
+ public void SetEntityType_SetsEntityType_WhenCalled() {
+ Name rn = new Name("foo").SetEntityType("PERSON");
+ Assert.Equal("foo", rn.Text);
+ Assert.Equal("PERSON", rn.EntityType);
+ }
- [Fact]
- public void CheckWithLanguage() {
- Name rn = new Name("foo").SetLanguage("eng");
- Assert.Equal("foo", rn.Text);
- Assert.Equal("eng", rn.Language);
- }
+ [Fact]
+ public void SetLanguage_SetsLanguage_WhenCalled() {
+ Name rn = new Name("foo").SetLanguage("eng");
+ Assert.Equal("foo", rn.Text);
+ Assert.Equal("eng", rn.Language);
+ }
- [Fact]
- public void CheckWithScript() {
- Name rn = new Name("foo").SetScript("zho");
- Assert.Equal("foo", rn.Text);
- Assert.Equal("zho", rn.Script);
- }
+ [Fact]
+ public void SetScript_SetsScript_WhenCalled() {
+ Name rn = new Name("foo").SetScript("zho");
+ Assert.Equal("foo", rn.Text);
+ Assert.Equal("zho", rn.Script);
+ }
- [Fact]
- public void CheckWithGender()
- {
- Name rn = new Name("foo").SetGender(GenderType.Female);
- Assert.Equal("foo", rn.Text);
- Assert.Equal(GenderType.Female, rn.Gender);
- }
+ [Fact]
+ public void SetGender_SetsGender_WhenCalled()
+ {
+ Name rn = new Name("foo").SetGender(GenderType.Female);
+ Assert.Equal("foo", rn.Text);
+ Assert.Equal(GenderType.Female, rn.Gender);
+ }
- [Fact]
- public void CheckAll() {
- Name rn = new Name("foo")
- .SetEntityType("PERSON")
- .SetLanguage("eng")
- .SetScript("zho")
- .SetGender(GenderType.Male);
- Assert.Equal("foo", rn.Text);
- Assert.Equal("PERSON", rn.EntityType);
- Assert.Equal("eng", rn.Language);
- Assert.Equal("zho", rn.Script);
- Assert.Equal(GenderType.Male, rn.Gender);
- }
+ [Fact]
+ public void FluentAPI_SetsAllProperties_WhenChaining() {
+ Name rn = new Name("foo")
+ .SetEntityType("PERSON")
+ .SetLanguage("eng")
+ .SetScript("zho")
+ .SetGender(GenderType.Male);
+ Assert.Equal("foo", rn.Text);
+ Assert.Equal("PERSON", rn.EntityType);
+ Assert.Equal("eng", rn.Language);
+ Assert.Equal("zho", rn.Script);
+ Assert.Equal(GenderType.Male, rn.Gender);
}
}
diff --git a/tests/NameTranslationTests.cs b/tests/NameTranslationTests.cs
index 164e277..2250439 100644
--- a/tests/NameTranslationTests.cs
+++ b/tests/NameTranslationTests.cs
@@ -1,41 +1,40 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
-namespace Rosette.Api.Tests
-{
- public class NameTranslationTests
- {
- [Fact]
- public void CheckBasicUsage() {
- NameTranslation n = new NameTranslation("foo");
- Assert.Equal("foo", n.Name);
- Assert.Equal("eng", n.TargetLanguage);
- Assert.Empty(n.EntityType);
- Assert.Empty(n.SourceLanguageOfOrigin);
- Assert.Empty(n.SourceLanguageOfUse);
- Assert.Empty(n.SourceScript);
- Assert.Empty(n.TargetScheme);
- Assert.Empty(n.TargetScript);
- }
+namespace Rosette.Api.Tests;
- [Fact]
- public void CheckAllUsage() {
- NameTranslation n = new NameTranslation("foo")
- .SetEntityType("PERSON")
- .SetSourceLanguageOfOrigin("eng")
- .SetSourceLanguageOfUse("eng")
- .SetSourceScript("zho")
- .SetTargetLanguage("spa")
- .SetTargetScheme("BGN")
- .SetTargetScript("eng");
- Assert.Equal("foo", n.Name);
- Assert.Equal("spa", n.TargetLanguage);
- Assert.Equal("PERSON", n.EntityType);
- Assert.Equal("eng", n.SourceLanguageOfOrigin);
- Assert.Equal("eng", n.SourceLanguageOfUse);
- Assert.Equal("zho", n.SourceScript);
- Assert.Equal("BGN", n.TargetScheme);
- Assert.Equal("eng", n.TargetScript);
- }
+public class NameTranslationTests
+{
+ [Fact]
+ public void Constructor_SetsNameAndDefaults_WhenCalledWithName() {
+ NameTranslation n = new NameTranslation("foo");
+ Assert.Equal("foo", n.Name);
+ Assert.Equal("eng", n.TargetLanguage);
+ Assert.Empty(n.EntityType);
+ Assert.Empty(n.SourceLanguageOfOrigin);
+ Assert.Empty(n.SourceLanguageOfUse);
+ Assert.Empty(n.SourceScript);
+ Assert.Empty(n.TargetScheme);
+ Assert.Empty(n.TargetScript);
+ }
+ [Fact]
+ public void FluentAPI_SetsAllProperties_WhenChaining() {
+ NameTranslation n = new NameTranslation("foo")
+ .SetEntityType("PERSON")
+ .SetSourceLanguageOfOrigin("eng")
+ .SetSourceLanguageOfUse("eng")
+ .SetSourceScript("zho")
+ .SetTargetLanguage("spa")
+ .SetTargetScheme("BGN")
+ .SetTargetScript("eng");
+ Assert.Equal("foo", n.Name);
+ Assert.Equal("spa", n.TargetLanguage);
+ Assert.Equal("PERSON", n.EntityType);
+ Assert.Equal("eng", n.SourceLanguageOfOrigin);
+ Assert.Equal("eng", n.SourceLanguageOfUse);
+ Assert.Equal("zho", n.SourceScript);
+ Assert.Equal("BGN", n.TargetScheme);
+ Assert.Equal("eng", n.TargetScript);
}
+
}
diff --git a/tests/RelationshipsTests.cs b/tests/RelationshipsTests.cs
index 5f2b01a..2e77e2a 100644
--- a/tests/RelationshipsTests.cs
+++ b/tests/RelationshipsTests.cs
@@ -1,35 +1,35 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
namespace Rosette.Api.Tests
{
public class RelationshipsTests
{
[Fact]
- public void CheckBasicUsage()
+ public void Constructor_SetsEndpointAndContent_WhenCalledWithText()
{
string text = "John works at Microsoft.";
Relationships r = new Relationships(text);
-
+
Assert.Equal("relationships", r.Endpoint);
Assert.Equal(text, r.Content);
}
[Fact]
- public void CheckWithLanguage()
+ public void SetLanguage_SetsLanguageProperty_WhenCalled()
{
Relationships r = new Relationships("Sample text")
.SetLanguage("eng");
-
+
Assert.Equal("eng", r.Language);
}
[Fact]
- public void CheckFluentAPI()
+ public void FluentAPI_AllowsMethodChaining_WhenSettingMultipleProperties()
{
Relationships r = new Relationships("Sample relationship text.")
.SetLanguage("eng")
.SetOption("accuracy", "high");
-
+
Assert.Equal("eng", r.Language);
Assert.Equal("high", r.Options["accuracy"]);
}
diff --git a/tests/ResponseTests.cs b/tests/ResponseTests.cs
index 1348bcb..9119639 100644
--- a/tests/ResponseTests.cs
+++ b/tests/ResponseTests.cs
@@ -1,28 +1,27 @@
-using Rosette.Api.Models;
+using Rosette.Api.Client.Models;
using System.Net;
using System.Text.Json;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class ResponseTests
{
- public class ResponseTests
- {
- [Fact]
- public void CheckStatusOK() {
- Dictionary data = new Dictionary {
- { "content", "Some sample content" },
- { "language", "eng" }
- };
- string json = JsonSerializer.Serialize(data);
+ [Fact]
+ public void Constructor_SetsStatusCodeAndContent_WhenHttpResponseIsOK() {
+ Dictionary data = new Dictionary {
+ { "content", "Some sample content" },
+ { "language", "eng" }
+ };
+ string json = JsonSerializer.Serialize(data);
- HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK);
- msg.Content = new StringContent(json);
- msg.Headers.Add("Test-Header", "Test Header Content");
+ HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK);
+ msg.Content = new StringContent(json);
+ msg.Headers.Add("Test-Header", "Test Header Content");
- Response response = new Response(msg);
+ Response response = new Response(msg);
- Assert.Equal((int)HttpStatusCode.OK, response.StatusCode);
- Assert.Equal(json, response.ContentAsJson());
+ Assert.Equal((int)HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(json, response.ContentAsJson());
- }
}
}
diff --git a/tests/SentencesTests.cs b/tests/SentencesTests.cs
index 55a1674..a3bef81 100644
--- a/tests/SentencesTests.cs
+++ b/tests/SentencesTests.cs
@@ -1,35 +1,34 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class SentencesTests
{
- public class SentencesTests
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCalledWithText()
+ {
+ string text = "This is the first sentence. This is the second sentence.";
+ Sentences s = new Sentences(text);
+
+ Assert.Equal("sentences", s.Endpoint);
+ Assert.Equal(text, s.Content);
+ }
+
+ [Fact]
+ public void SetLanguage_SetsLanguageProperty_WhenCalled()
{
- [Fact]
- public void CheckBasicUsage()
- {
- string text = "This is the first sentence. This is the second sentence.";
- Sentences s = new Sentences(text);
-
- Assert.Equal("sentences", s.Endpoint);
- Assert.Equal(text, s.Content);
- }
+ Sentences s = new Sentences("Sample text.")
+ .SetLanguage("eng");
+
+ Assert.Equal("eng", s.Language);
+ }
- [Fact]
- public void CheckWithLanguage()
- {
- Sentences s = new Sentences("Sample text.")
- .SetLanguage("eng");
-
- Assert.Equal("eng", s.Language);
- }
+ [Fact]
+ public void FluentAPI_AllowsMethodChaining_WhenSettingLanguage()
+ {
+ Sentences s = new Sentences("Text content.")
+ .SetLanguage("eng");
- [Fact]
- public void CheckFluentAPI()
- {
- Sentences s = new Sentences("Text content.")
- .SetLanguage("eng");
-
- Assert.Equal("eng", s.Language);
- }
+ Assert.Equal("eng", s.Language);
}
}
\ No newline at end of file
diff --git a/tests/SentimentTests.cs b/tests/SentimentTests.cs
index f6eac66..e521937 100644
--- a/tests/SentimentTests.cs
+++ b/tests/SentimentTests.cs
@@ -1,46 +1,45 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class SentimentTests
{
- public class SentimentTests
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCalledWithText()
+ {
+ Sentiment s = new Sentiment("This is a great product!");
+
+ Assert.Equal("sentiment", s.Endpoint);
+ Assert.Equal("This is a great product!", s.Content);
+ }
+
+ [Fact]
+ public void SetLanguage_SetsLanguageProperty_WhenCalled()
+ {
+ Sentiment s = new Sentiment("Sample text")
+ .SetLanguage("eng");
+
+ Assert.Equal("eng", s.Language);
+ Assert.Equal("Sample text", s.Content);
+ }
+
+ [Fact]
+ public void SetGenre_SetsGenreProperty_WhenCalled()
{
- [Fact]
- public void CheckBasicUsage()
- {
- Sentiment s = new Sentiment("This is a great product!");
-
- Assert.Equal("sentiment", s.Endpoint);
- Assert.Equal("This is a great product!", s.Content);
- }
-
- [Fact]
- public void CheckWithLanguage()
- {
- Sentiment s = new Sentiment("Sample text")
- .SetLanguage("eng");
-
- Assert.Equal("eng", s.Language);
- Assert.Equal("Sample text", s.Content);
- }
-
- [Fact]
- public void CheckWithGenre()
- {
- Sentiment s = new Sentiment("Sample text")
- .SetGenre("social-media");
-
- Assert.Equal("", s.Genre);
- }
-
- [Fact]
- public void CheckFluentAPI()
- {
- Sentiment s = new Sentiment("Great service!")
- .SetLanguage("eng")
- .SetOption("sentiment.threshold", 0.5);
-
- Assert.Equal("eng", s.Language);
- Assert.Equal(0.5, s.Options["sentiment.threshold"]);
- }
+ Sentiment s = new Sentiment("Sample text")
+ .SetGenre("social-media");
+
+ Assert.Equal("", s.Genre);
+ }
+
+ [Fact]
+ public void FluentAPI_AllowsMethodChaining_WhenSettingMultipleProperties()
+ {
+ Sentiment s = new Sentiment("Great service!")
+ .SetLanguage("eng")
+ .SetOption("sentiment.threshold", 0.5);
+
+ Assert.Equal("eng", s.Language);
+ Assert.Equal(0.5, s.Options["sentiment.threshold"]);
}
}
\ No newline at end of file
diff --git a/tests/SimilarTermsTests.cs b/tests/SimilarTermsTests.cs
index b410a45..bef7ac8 100644
--- a/tests/SimilarTermsTests.cs
+++ b/tests/SimilarTermsTests.cs
@@ -1,37 +1,36 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class SimilarTermsTests
{
- public class SimilarTermsTests
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCalledWithText()
+ {
+ SimilarTerms st = new SimilarTerms("happy");
+
+ Assert.Equal("semantics/similar", st.Endpoint);
+ Assert.Equal("happy", st.Content);
+ }
+
+ [Fact]
+ public void SetLanguage_SetsLanguageProperty_WhenCalled()
{
- [Fact]
- public void CheckBasicUsage()
- {
- SimilarTerms st = new SimilarTerms("happy");
-
- Assert.Equal("semantics/similar", st.Endpoint);
- Assert.Equal("happy", st.Content);
- }
+ SimilarTerms st = new SimilarTerms("computer")
+ .SetLanguage("eng");
+
+ Assert.Equal("eng", st.Language);
+ Assert.Equal("computer", st.Content);
+ }
- [Fact]
- public void CheckWithLanguage()
- {
- SimilarTerms st = new SimilarTerms("computer")
- .SetLanguage("eng");
-
- Assert.Equal("eng", st.Language);
- Assert.Equal("computer", st.Content);
- }
+ [Fact]
+ public void FluentAPI_AllowsMethodChaining_WhenSettingMultipleProperties()
+ {
+ SimilarTerms st = new SimilarTerms("innovation")
+ .SetLanguage("eng")
+ .SetOption("count", 10);
- [Fact]
- public void CheckFluentAPI()
- {
- SimilarTerms st = new SimilarTerms("innovation")
- .SetLanguage("eng")
- .SetOption("count", 10);
-
- Assert.Equal("eng", st.Language);
- Assert.Equal(10, st.Options["count"]);
- }
+ Assert.Equal("eng", st.Language);
+ Assert.Equal(10, st.Options["count"]);
}
}
\ No newline at end of file
diff --git a/tests/TokensTests.cs b/tests/TokensTests.cs
index abaa259..05124cf 100644
--- a/tests/TokensTests.cs
+++ b/tests/TokensTests.cs
@@ -1,34 +1,33 @@
-using Rosette.Api.Endpoints;
+using Rosette.Api.Client.Endpoints;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class TokensTests
{
- public class TokensTests
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCalledWithText()
+ {
+ Tokens t = new Tokens("This is sample text");
+
+ Assert.Equal("tokens", t.Endpoint);
+ Assert.Equal("This is sample text", t.Content);
+ }
+
+ [Fact]
+ public void SetLanguage_SetsLanguageProperty_WhenCalled()
{
- [Fact]
- public void CheckBasicUsage()
- {
- Tokens t = new Tokens("This is sample text");
-
- Assert.Equal("tokens", t.Endpoint);
- Assert.Equal("This is sample text", t.Content);
- }
+ Tokens t = new Tokens("Sample text")
+ .SetLanguage("eng");
+
+ Assert.Equal("eng", t.Language);
+ }
- [Fact]
- public void CheckWithLanguage()
- {
- Tokens t = new Tokens("Sample text")
- .SetLanguage("eng");
-
- Assert.Equal("eng", t.Language);
- }
+ [Fact]
+ public void FluentAPI_AllowsMethodChaining_WhenSettingLanguage()
+ {
+ Tokens t = new Tokens("Sample text")
+ .SetLanguage("jpn");
- [Fact]
- public void CheckFluentAPI()
- {
- Tokens t = new Tokens("Sample text")
- .SetLanguage("jpn");
-
- Assert.Equal("jpn", t.Language);
- }
+ Assert.Equal("jpn", t.Language);
}
}
\ No newline at end of file
diff --git a/tests/ValidEndpointTests.cs b/tests/ValidEndpointTests.cs
index a5f01b2..2265b9d 100644
--- a/tests/ValidEndpointTests.cs
+++ b/tests/ValidEndpointTests.cs
@@ -1,207 +1,206 @@
-using Rosette.Api.Endpoints;
-using Rosette.Api.Models;
+using Rosette.Api.Client.Endpoints;
+using Rosette.Api.Client.Models;
-namespace Rosette.Api.Tests
+namespace Rosette.Api.Tests;
+
+public class ValidEndpointTests
{
- public class ValidEndpointTests
- {
-
- [Fact]
- public void AddressSimilarityEndpoint()
- {
- var a = new UnfieldedAddressRecord { Address = "foo" };
-
- AddressSimilarity asim = new AddressSimilarity(a,a);
- Assert.Equal("address-similarity", asim.Endpoint);
- }
-
- [Fact]
- public void CategoriesEndpoint()
- {
- Categories c = new Categories("foo");
-
- Assert.Equal("categories", c.Endpoint);
- Assert.Equal("foo", c.Content);
- }
-
- [Fact]
- public void EntitiesEndpoint()
- {
- Entities e = new Entities("foo");
- Assert.Equal("entities", e.Endpoint);
- Assert.Equal("foo", e.Content);
- }
-
- [Fact]
- public void EventsEndpoint()
- {
- Events e = new Events("foo");
- Assert.Equal("events", e.Endpoint);
- Assert.Equal("foo", e.Content);
- }
-
- [Fact]
- public void InfoEndpoint()
- {
- Info i = new Info();
- Assert.Equal("info", i.Endpoint);
- }
-
- [Fact]
- public void LanguageEndpoint()
- {
- Language l = new Language("foo");
-
- Assert.Equal("language", l.Endpoint);
- Assert.Equal("foo", l.Content);
- }
-
- [Theory]
- [InlineData(MorphologyFeature.complete)]
- [InlineData(MorphologyFeature.compoundComponents)]
- [InlineData(MorphologyFeature.hanReadings)]
- [InlineData(MorphologyFeature.lemmas)]
- [InlineData(MorphologyFeature.partsOfSpeech)]
- public void MorphologyEndpoint(MorphologyFeature feature)
- {
- Morphology m = new Morphology("foo", feature);
-
- Assert.Equal("morphology/" + m.FeatureAsString(feature), m.Endpoint);
- Assert.Equal("foo", m.Content);
- }
-
- [Fact]
- public void NameDeduplicationEndpoint()
- {
- List names = [
- new Name("foo"),
- new Name("bar")
- ];
- NameDeduplication nd = new NameDeduplication(names);
-
- Assert.Equal("name-deduplication", nd.Endpoint);
- }
-
- [Fact]
- public void NameSimilarityEndpoint()
- {
- Name rn = new Name("foo");
- NameSimilarity ns = new NameSimilarity(rn, rn);
- Assert.Equal("name-similarity", ns.Endpoint);
- }
-
- [Fact]
- public void NameTranslationEndpoint()
- {
- NameTranslation nt = new NameTranslation("foo");
-
- Assert.Equal("name-translation", nt.Endpoint);
- }
-
- [Fact]
- public void PingEndpoint()
- {
- Ping p = new Ping();
- Assert.Equal("ping", p.Endpoint);
- }
-
- [Fact]
- public void RecordSimilarityEndpoint()
- {
- var fields = new Dictionary();
- var properties = new RecordSimilarityProperties();
- var records = new RecordSimilarityRecords();
-
- RecordSimilarity rs = new RecordSimilarity(fields, properties, records);
-
- Assert.Equal("record-similarity", rs.Endpoint);
- }
-
- [Fact]
- public void RelationshipsEndpoint()
- {
- Relationships r = new Relationships("foo");
-
- Assert.Equal("relationships", r.Endpoint);
- Assert.Equal("foo", r.Content);
- }
-
- [Fact]
- public void SemanticVectorsEndpoint()
- {
- SemanticsVector s = new SemanticsVector("foo");
- Assert.Equal("semantics/vector", s.Endpoint);
- Assert.Equal("foo", s.Content);
- }
-
- [Fact]
- public void SentencesEndpoint()
- {
- Sentences s = new Sentences("foo");
- Assert.Equal("sentences", s.Endpoint);
- Assert.Equal("foo", s.Content);
- }
-
- [Fact]
- public void SentimentEndpoint()
- {
- Sentiment s = new Sentiment("foo");
- Assert.Equal("sentiment", s.Endpoint);
- Assert.Equal("foo", s.Content);
- }
-
- [Fact]
- public void SimilarTermsEndpoint()
- {
- SimilarTerms st = new SimilarTerms("foo");
-
- Assert.Equal("semantics/similar", st.Endpoint);
- Assert.Equal("foo", st.Content);
- }
-
- [Fact]
- public void SyntaxDependenciesEndpoint()
- {
- SyntaxDependencies s = new SyntaxDependencies("foo");
-
- Assert.Equal("syntax/dependencies", s.Endpoint);
- Assert.Equal("foo", s.Content);
- }
-
- [Fact]
- public void TextEmbeddingEndpoint()
- {
- TextEmbedding t = new TextEmbedding("foo");
-
- Assert.Equal("text-embedding", t.Endpoint);
- Assert.Equal("foo", t.Content);
- }
-
- [Fact]
- public void TokensEndpoint()
- {
- Tokens t = new Tokens("foo");
-
- Assert.Equal("tokens", t.Endpoint);
- Assert.Equal("foo", t.Content);
- }
-
- [Fact]
- public void TopicsEndpoint()
- {
- Topics t = new Topics("foo");
-
- Assert.Equal("topics", t.Endpoint);
- Assert.Equal("foo", t.Content);
- }
-
- [Fact]
- public void TransliterationEndpoint()
- {
- Transliteration t = new Transliteration("foo");
-
- Assert.Equal("transliteration", t.Endpoint);
- Assert.Equal("foo", t.Content);
- }
+
+ [Fact]
+ public void Constructor_SetsEndpoint_WhenCreatingAddressSimilarity()
+ {
+ var a = new UnfieldedAddressRecord { Address = "foo" };
+
+ AddressSimilarity asim = new AddressSimilarity(a,a);
+ Assert.Equal("address-similarity", asim.Endpoint);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingCategories()
+ {
+ Categories c = new Categories("foo");
+
+ Assert.Equal("categories", c.Endpoint);
+ Assert.Equal("foo", c.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingEntities()
+ {
+ Entities e = new Entities("foo");
+ Assert.Equal("entities", e.Endpoint);
+ Assert.Equal("foo", e.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingEvents()
+ {
+ Events e = new Events("foo");
+ Assert.Equal("events", e.Endpoint);
+ Assert.Equal("foo", e.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpoint_WhenCreatingInfo()
+ {
+ Info i = new Info();
+ Assert.Equal("info", i.Endpoint);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingLanguage()
+ {
+ Language l = new Language("foo");
+
+ Assert.Equal("language", l.Endpoint);
+ Assert.Equal("foo", l.Content);
+ }
+
+ [Theory]
+ [InlineData(MorphologyFeature.complete)]
+ [InlineData(MorphologyFeature.compoundComponents)]
+ [InlineData(MorphologyFeature.hanReadings)]
+ [InlineData(MorphologyFeature.lemmas)]
+ [InlineData(MorphologyFeature.partsOfSpeech)]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingMorphologyWithFeature(MorphologyFeature feature)
+ {
+ Morphology m = new Morphology("foo", feature);
+
+ Assert.Equal("morphology/" + m.FeatureAsString(feature), m.Endpoint);
+ Assert.Equal("foo", m.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpoint_WhenCreatingNameDeduplication()
+ {
+ List names = [
+ new Name("foo"),
+ new Name("bar")
+ ];
+ NameDeduplication nd = new NameDeduplication(names);
+
+ Assert.Equal("name-deduplication", nd.Endpoint);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpoint_WhenCreatingNameSimilarity()
+ {
+ Name rn = new Name("foo");
+ NameSimilarity ns = new NameSimilarity(rn, rn);
+ Assert.Equal("name-similarity", ns.Endpoint);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpoint_WhenCreatingNameTranslation()
+ {
+ NameTranslation nt = new NameTranslation("foo");
+
+ Assert.Equal("name-translation", nt.Endpoint);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpoint_WhenCreatingPing()
+ {
+ Ping p = new Ping();
+ Assert.Equal("ping", p.Endpoint);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpoint_WhenCreatingRecordSimilarity()
+ {
+ var fields = new Dictionary();
+ var properties = new RecordSimilarityProperties();
+ var records = new RecordSimilarityRecords();
+
+ RecordSimilarity rs = new RecordSimilarity(fields, properties, records);
+
+ Assert.Equal("record-similarity", rs.Endpoint);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingRelationships()
+ {
+ Relationships r = new Relationships("foo");
+
+ Assert.Equal("relationships", r.Endpoint);
+ Assert.Equal("foo", r.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingSemanticsVector()
+ {
+ SemanticsVector s = new SemanticsVector("foo");
+ Assert.Equal("semantics/vector", s.Endpoint);
+ Assert.Equal("foo", s.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingSentences()
+ {
+ Sentences s = new Sentences("foo");
+ Assert.Equal("sentences", s.Endpoint);
+ Assert.Equal("foo", s.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingSentiment()
+ {
+ Sentiment s = new Sentiment("foo");
+ Assert.Equal("sentiment", s.Endpoint);
+ Assert.Equal("foo", s.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingSimilarTerms()
+ {
+ SimilarTerms st = new SimilarTerms("foo");
+
+ Assert.Equal("semantics/similar", st.Endpoint);
+ Assert.Equal("foo", st.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingSyntaxDependencies()
+ {
+ SyntaxDependencies s = new SyntaxDependencies("foo");
+
+ Assert.Equal("syntax/dependencies", s.Endpoint);
+ Assert.Equal("foo", s.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingTextEmbedding()
+ {
+ TextEmbedding t = new TextEmbedding("foo");
+
+ Assert.Equal("text-embedding", t.Endpoint);
+ Assert.Equal("foo", t.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingTokens()
+ {
+ Tokens t = new Tokens("foo");
+
+ Assert.Equal("tokens", t.Endpoint);
+ Assert.Equal("foo", t.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingTopics()
+ {
+ Topics t = new Topics("foo");
+
+ Assert.Equal("topics", t.Endpoint);
+ Assert.Equal("foo", t.Content);
+ }
+
+ [Fact]
+ public void Constructor_SetsEndpointAndContent_WhenCreatingTransliteration()
+ {
+ Transliteration t = new Transliteration("foo");
+
+ Assert.Equal("transliteration", t.Endpoint);
+ Assert.Equal("foo", t.Content);
}
}
\ No newline at end of file