diff --git a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java index a156d6a436d..6c2c38a8f9e 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java @@ -61,6 +61,7 @@ public void processOpts() { ctsManager.addTestsSupportingFiles(supportingFiles); testsGenerators.add(new TestsRequest(ctsManager)); + testsGenerators.add(new TestsClient(ctsManager, true)); testsGenerators.add(new TestsClient(ctsManager, false)); } else if (mode.equals("snippets")) { diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java index 15d30f0c913..e22491379f1 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java @@ -43,7 +43,18 @@ public void addSupportingFiles(List supportingFiles, String outp Helpers.createClientName(client, language) + extension ) ); + if (new File("templates/" + language + "/tests/e2e/e2e.mustache").exists()) { + if (this.client.equals("search")) { + supportingFiles.add( + new SupportingFile( + "tests/e2e/e2eAlt.mustache", + "tests/output/" + language + "/" + outputFolder + "/e2eAlt", + Helpers.createClientName(client, language) + extension + ) + ); + } + supportingFiles.add( new SupportingFile( "tests/e2e/e2e.mustache", diff --git a/templates/csharp/tests/e2e/e2eAlt.mustache b/templates/csharp/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..efd57613ba5 --- /dev/null +++ b/templates/csharp/tests/e2e/e2eAlt.mustache @@ -0,0 +1,77 @@ +// {{generationBanner}} +using Algolia.Search.Http; +using Algolia.Search.Clients; +using Algolia.Search.Models.{{clientPrefix}}; +using Algolia.Search.Serializer; +using Algolia.Search.Tests.Utils; +using Xunit; +using System.Text.Json; +using Quibble.Xunit; +using dotenv.net; +{{#isSearchClient}} +using Action = Algolia.Search.Models.Search.Action; +using Range = Algolia.Search.Models.Search.Range; +{{/isSearchClient}} +{{#isIngestionClient}} +using Action = Algolia.Search.Models.Ingestion.Action; +{{/isIngestionClient}} +{{#isCompositionClient}} +using Action = Algolia.Search.Models.Composition.Action; +{{/isCompositionClient}} + +namespace Algolia.Search.e2eAlt; + +public class {{client}}RequestTestsE2EAlt +{ + private readonly {{client}} client; + + public {{client}}RequestTestsE2EAlt() + { + DotEnv.Load(options: new DotEnvOptions(ignoreExceptions: true, probeForEnv: true, probeLevelsToSearch: 8, envFilePaths: new[] { ".env" })); + + var appId = Environment.GetEnvironmentVariable("METIS_APPLICATION_ID"); + if (appId == null) + { + throw new Exception("please provide an `METIS_APPLICATION_ID` env var for e2e tests"); + } + + var apiKey = Environment.GetEnvironmentVariable("METIS_API_KEY"); + if (apiKey == null) + { + throw new Exception("please provide an `METIS_API_KEY` env var for e2e tests"); + } + + client = new {{client}}(new {{clientPrefix}}Config(appId, apiKey{{#hasRegionalHost}},"{{defaultRegion}}"{{/hasRegionalHost}})); + } + + [Fact] + public void Dispose() + { + + } + + {{#blocksE2E}} + {{#tests}} + [Fact(DisplayName = "{{{testName}}}")] + public async Task {{#lambda.pascalcase}}{{method}}Test{{testIndex}}{{/lambda.pascalcase}}() + { + try { + var resp = {{> tests/method}}; + {{#response}} + {{#statusCode}} + // Check status code {{statusCode}} + Assert.NotNull(resp); + {{/statusCode}} + + {{#body}} + JsonAssert.EqualOverrideDefault("{{#lambda.escapeQuotes}}{{{.}}}{{/lambda.escapeQuotes}}", JsonSerializer.Serialize(resp, JsonConfig.Options), new JsonDiffConfig(true)); + {{/body}} + } catch (Exception e) + { + Assert.Fail("An exception was thrown: " + e.Message); + } + {{/response}} + } + {{/tests}} + {{/blocksE2E}} +} \ No newline at end of file diff --git a/templates/go/tests/e2e/e2eAlt.mustache b/templates/go/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..def6fd34791 --- /dev/null +++ b/templates/go/tests/e2e/e2eAlt.mustache @@ -0,0 +1,71 @@ +// {{generationBanner}} +package e2eAlt + +import ( + "encoding/json" + "os" + "testing" + + "github.com/stretchr/testify/require" + "github.com/kinbiko/jsonassert" + "github.com/joho/godotenv" + + "gotests/tests" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/{{clientImport}}" +) + +func createE2E{{#lambda.titlecase}}{{clientPrefix}}{{/lambda.titlecase}}Client(t *testing.T) *{{clientPrefix}}.APIClient { + t.Helper() + + appID := os.Getenv("METIS_APPLICATION_ID") + if appID == "" && os.Getenv("CI") != "true" { + err := godotenv.Load("../../../../.env") + require.NoError(t, err) + appID = os.Getenv("METIS_APPLICATION_ID") + } + apiKey := os.Getenv("METIS_API_KEY") + client, err := {{clientPrefix}}.NewClient(appID, apiKey, {{#hasRegionalHost}}{{clientPrefix}}.{{#lambda.uppercase}}{{defaultRegion}}{{/lambda.uppercase}},{{/hasRegionalHost}}) + require.NoError(t, err) + + return client +} + +{{#blocksE2E}} +func Test{{#lambda.titlecase}}{{clientPrefix}}{{/lambda.titlecase}}E2E_{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}(t *testing.T) { + t.Parallel() + {{#tests}} + t.Run("{{{testName}}}", func(t *testing.T) { + t.Parallel() + + client := createE2E{{#lambda.titlecase}}{{clientPrefix}}{{/lambda.titlecase}}Client(t) + res, err := {{> tests/method}} + require.NoError(t, err) + _ = res + + {{#response}} + {{#body}} + rawBody, err := json.Marshal(res) + require.NoError(t, err) + + var rawBodyMap any + err = json.Unmarshal(rawBody, &rawBodyMap) + require.NoError(t, err) + + expectedBodyRaw := `{{{.}}}` + var expectedBody any + err = json.Unmarshal([]byte(expectedBodyRaw), &expectedBody) + require.NoError(t, err) + + unionBody := tests.Union(t, expectedBody, rawBodyMap) + unionBodyRaw, err := json.Marshal(unionBody) + require.NoError(t, err) + + jsonassert.New(t).Assertf(string(unionBodyRaw), "%s", expectedBodyRaw) + {{/body}} + {{/response}} + }) +{{/tests}} +} + +{{/blocksE2E}} \ No newline at end of file diff --git a/templates/java/tests/e2e/e2eAlt.mustache b/templates/java/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..43aeedd2b86 --- /dev/null +++ b/templates/java/tests/e2e/e2eAlt.mustache @@ -0,0 +1,54 @@ +package com.algolia.e2eAlt; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import com.algolia.api.{{client}}; +import com.algolia.config.*; +import com.algolia.model.{{import}}.*; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import io.github.cdimascio.dotenv.Dotenv; +import java.util.*; +import java.time.Duration; +import org.junit.jupiter.api.*; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class {{client}}RequestsTestsE2EAlt { + private {{client}} client; + private ObjectMapper json; + + @BeforeAll + void init() { + this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + + if ("true".equals(System.getenv("CI"))) { + this.client = new {{client}}(System.getenv("METIS_APPLICATION_ID"), System.getenv("METIS_API_KEY"){{#hasRegionalHost}}, "{{defaultRegion}}"{{/hasRegionalHost}}); + } else { + Dotenv dotenv = Dotenv.configure().directory("../../").load(); + this.client = new {{client}}(dotenv.get("METIS_APPLICATION_ID"), dotenv.get("METIS_API_KEY"){{#hasRegionalHost}}, "{{defaultRegion}}"{{/hasRegionalHost}}); + } + } + + @AfterAll + void tearUp() throws Exception { + client.close(); + } + + {{#blocksE2E}} + {{#tests}} + @Test + @DisplayName("{{{testName}}}") + void {{method}}Test{{testIndex}}() { + {{returnType}} res = {{> tests/method}}; + {{#response}} + {{#body}} + assertDoesNotThrow(() -> JSONAssert.assertEquals("{{#lambda.escapeQuotes}}{{{body}}}{{/lambda.escapeQuotes}}", json.writeValueAsString(res), JSONCompareMode.LENIENT)); + {{/body}} + {{/response}} + } + {{/tests}} + {{/blocksE2E}} +} \ No newline at end of file diff --git a/templates/javascript/tests/e2e/e2eAlt.mustache b/templates/javascript/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..a793a9e09ac --- /dev/null +++ b/templates/javascript/tests/e2e/e2eAlt.mustache @@ -0,0 +1,37 @@ +// {{generationBanner}} +import { describe, test, expect } from 'vitest'; + +import { union } from '../helpers.js'; + +import { {{{clientName}}} } from '{{{importPackage}}}'; +import type { RequestOptions } from '@algolia/client-common'; + +if (!process.env.METIS_APPLICATION_ID) { + throw new Error("please provide an `METIS_APPLICATION_ID` env var for e2e tests"); +} + +if (!process.env.METIS_API_KEY) { + throw new Error("please provide an `METIS_API_KEY` env var for e2e tests"); +} + +const client = {{{clientName}}}(process.env.METIS_APPLICATION_ID, process.env.METIS_API_KEY){{^isStandaloneClient}}.{{{initMethod}}}({{#hasRegionalHost}} {region:'{{{defaultRegion}}}'} {{/hasRegionalHost}}){{/isStandaloneClient}}; + +{{#blocksE2E}} +describe('{{operationId}}', () => { + {{#tests}} + test('{{{testName}}}', async () => { + {{#response}} + {{#body}}const resp = {{/body}}{{> tests/method}}; + + {{#body}} + const expectedBody = {{{.}}}; + + expect(expectedBody).toEqual(union(expectedBody, resp)); + {{/body}} + {{/response}} + }); + + {{/tests}} +}) + +{{/blocksE2E}} \ No newline at end of file diff --git a/templates/kotlin/tests/e2e/e2eAlt.mustache b/templates/kotlin/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..62c202f31d2 --- /dev/null +++ b/templates/kotlin/tests/e2e/e2eAlt.mustache @@ -0,0 +1,56 @@ +// {{generationBanner}} +package com.algolia.e2eAlt + +import com.algolia.client.api.{{client}} +import com.algolia.client.model.{{import}}.* +import com.algolia.client.configuration.* +import com.algolia.client.transport.* +import com.algolia.utils.* +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import io.ktor.http.* +import io.github.cdimascio.dotenv.Dotenv +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlinx.serialization.encodeToString +import kotlin.test.* +import kotlin.time.Duration.Companion.milliseconds + +{{#isCompositionClient}} +import com.algolia.client.model.{{import}}.RequestBody +{{/isCompositionClient}} + +class {{clientPrefix}}AltTest { + + var client: {{client}}; + + init { + if (System.getenv("CI") == "true") { + this.client = {{client}}(appId = System.getenv("METIS_APPLICATION_ID"), apiKey = System.getenv("METIS_API_KEY"){{#hasRegionalHost}}, region = "{{defaultRegion}}", {{/hasRegionalHost}}); + } else { + val dotenv = Dotenv.configure().directory("../../").load() + this.client = {{client}}(appId = dotenv["METIS_APPLICATION_ID"], apiKey = dotenv["METIS_API_KEY"]{{#hasRegionalHost}}, region = "{{defaultRegion}}", {{/hasRegionalHost}}); + } + } + + {{#blocksE2E}} + {{#tests}} + @Test + fun `{{#lambda.replaceBacktick}}{{{testName}}}{{testIndex}}{{/lambda.replaceBacktick}}`() = runTest { + client.runTest( + call = { + {{> tests/method}} + }, + {{#response}} + {{#body}} + response = { + JSONAssert.assertEquals("{{#lambda.escapeQuotes}}{{{body}}}{{/lambda.escapeQuotes}}", Json.encodeToString(it), JSONCompareMode.LENIENT) + }, + {{/body}} + {{/response}} + ) + } + + {{/tests}} + {{/blocksE2E}} +} \ No newline at end of file diff --git a/templates/php/tests/e2e/e2eAlt.mustache b/templates/php/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..be190461de8 --- /dev/null +++ b/templates/php/tests/e2e/e2eAlt.mustache @@ -0,0 +1,68 @@ +load(); +} + +#[CoversClass({{client}}::class)] +class {{clientPrefix}}AltTest extends TestCase +{ + protected function union($expected, $received): mixed + { + if (is_array($expected)) { + $res = []; + // array and object are the same thing in PHP (magic ✨) + foreach ($expected as $k => $v) { + $res[$k] = $this->union($v, $received[$k]); + } + + return $res; + } + + return $received; + } + + protected function getClient(): {{client}} + { + return {{client}}::create($_ENV['METIS_APPLICATION_ID'], $_ENV['METIS_API_KEY']{{#hasRegionalHost}},'{{defaultRegion}}' {{/hasRegionalHost}}); + } + + {{#blocksE2E}} + {{#tests}} + #[TestDox('{{{testName}}}')] + public function test{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}{{testIndex}}(): void + { + $client = $this->getClient(); + $resp = {{> tests/method}}; + + {{#response}} + {{#body}} + $expected = json_decode('{{{.}}}', true); + + $this->assertEquals($this->union($expected, $resp), $expected); + {{/body}} + {{/response}} + } + {{/tests}} + {{/blocksE2E}} +} \ No newline at end of file diff --git a/templates/python/tests/e2e/e2eAlt.mustache b/templates/python/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..c4a59ebd8fa --- /dev/null +++ b/templates/python/tests/e2e/e2eAlt.mustache @@ -0,0 +1,51 @@ +# {{generationBanner}} +from time import time +from os import environ +from json import loads +from algoliasearch.{{{import}}}.client import {{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}} +from algoliasearch.{{{import}}}.client import {{#lambda.pascalcase}}{{{client}}}Sync{{/lambda.pascalcase}} +from algoliasearch.{{{import}}}.config import {{#lambda.pascalcase}}{{clientPrefix}}Config{{/lambda.pascalcase}} +from algoliasearch.search.models import ( + BatchResponse, + UpdatedAtResponse, + GetTaskResponse, +) +from ..helpers import Helpers +from dotenv import load_dotenv + +load_dotenv("../../.env") + +{{#modes}} +class Test{{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}{{#isSyncClient}}Sync{{/isSyncClient}}E2EAlt: + _helpers = Helpers() + _e2e_app_id = environ.get("METIS_APPLICATION_ID") + if _e2e_app_id is None: + raise Exception("please provide an `METIS_APPLICATION_ID` env var for e2e tests") + + _e2e_api_key = environ.get("METIS_API_KEY") + if _e2e_api_key is None: + raise Exception("please provide an `METIS_API_KEY` env var for e2e tests") + + {{#blocksE2E}} + {{#tests}} + {{^isSyncClient}}async {{/isSyncClient}}def test_{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}_{{testIndex}}(self): + """ + {{{testName}}} + """ + raw_resp = {{^isSyncClient}}await {{/isSyncClient}}{{#lambda.pascalcase}}{{{client}}}{{#isSyncClient}}Sync{{/isSyncClient}}{{/lambda.pascalcase}}(self._e2e_app_id, self._e2e_api_key{{#hasRegionalHost}}, "{{{defaultRegion}}}"{{/hasRegionalHost}}).{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}_with_http_info({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) + {{#response}} + {{#statusCode}} + assert raw_resp.status_code == {{statusCode}} + {{/statusCode}} + + + {{#body}} + resp = {{^isSyncClient}}await {{/isSyncClient}}{{#lambda.pascalcase}}{{{client}}}{{#isSyncClient}}Sync{{/isSyncClient}}{{/lambda.pascalcase}}(self._e2e_app_id, self._e2e_api_key{{#hasRegionalHost}}, "{{{defaultRegion}}}"{{/hasRegionalHost}}).{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) + _expected_body = loads("""{{{.}}}""") + assert self._helpers.union(_expected_body, self._helpers.unwrap(resp)) == _expected_body + {{/body}} + {{/response}} + + {{/tests}} + {{/blocksE2E}} +{{/modes}} \ No newline at end of file diff --git a/templates/ruby/tests/e2e/e2eAlt.mustache b/templates/ruby/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..595a5a4d4f1 --- /dev/null +++ b/templates/ruby/tests/e2e/e2eAlt.mustache @@ -0,0 +1,38 @@ +# {{generationBanner}} +require 'algolia' +require 'test/unit' +require 'dotenv' +require_relative '../helpers' + +Dotenv.load('../../.env') + +class Test{{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}E2EAlt < Test::Unit::TestCase + def setup + @client = Algolia::{{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}.create( + ENV.fetch('METIS_APPLICATION_ID', nil), + ENV.fetch('METIS_API_KEY', nil){{#hasRegionalHost}}, + '{{{defaultRegion}}}'{{/hasRegionalHost}} + ) + end + + {{#blocksE2E}} + {{#tests}} + # {{{testName}}} + def test_{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}{{testIndex}} + res = @{{> tests/method}} + + {{#response}} + {{#statusCode}} + assert_equal(res.status, {{statusCode}}) + {{/statusCode}} + {{#body}} + res = @client.{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}}{ {{#requestOptions.headers.parameters}}:header_params => JSON.parse('{{{.}}}', :symbolize_names => true),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}:query_params => JSON.parse('{{{.}}}', :symbolize_names => true){{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) + expected_body = JSON.parse(%q({{{.}}})) + assert_equal(expected_body, union(expected_body, JSON.parse(res.to_json))) + {{/body}} + {{/response}} + end + + {{/tests}} + {{/blocksE2E}} +end \ No newline at end of file diff --git a/templates/scala/tests/e2e/e2eAlt.mustache b/templates/scala/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..e6dd2e131fd --- /dev/null +++ b/templates/scala/tests/e2e/e2eAlt.mustache @@ -0,0 +1,70 @@ +// {{generationBanner}} +package algoliasearch.e2eAlt + +import algoliasearch.api.{{client}} +import algoliasearch.config.* +import algoliasearch.{{import}}.* +import org.json4s.* +import org.json4s.native.JsonParser.* +import org.scalatest.funsuite.AnyFunSuite +import io.github.cdimascio.dotenv.Dotenv +import org.json4s.native.Serialization +import org.json4s.native.Serialization.write + +import java.util.concurrent.TimeUnit +import scala.concurrent.duration.Duration +import scala.concurrent.{Await, ExecutionContextExecutor} + +class {{clientPrefix}}AltTest extends AnyFunSuite { + implicit val ec: ExecutionContextExecutor = scala.concurrent.ExecutionContext.global + implicit val formats: Formats = JsonSupport.format + + def testClient(): {{client}} = { + {{#hasRegionalHost}} + val region = {{#fallbackToAliasHost}}Some("{{defaultRegion}}"){{/fallbackToAliasHost}}{{^fallbackToAliasHost}}"{{defaultRegion}}"{{/fallbackToAliasHost}} + {{/hasRegionalHost}} + if (System.getenv("CI") == "true") { + {{client}}( + appId = System.getenv("METIS_APPLICATION_ID"), + apiKey = System.getenv("METIS_API_KEY"){{#hasRegionalHost}}, + region = region{{/hasRegionalHost}} + ) + } else { + val dotenv = Dotenv.configure.directory("../../").load + {{client}}( + appId = dotenv.get("METIS_APPLICATION_ID"), + apiKey = dotenv.get("METIS_API_KEY"){{#hasRegionalHost}}, + region = region{{/hasRegionalHost}} + ) + } + } + + {{#blocksE2E}} + {{#tests}} + + test("{{{testName}}}{{testIndex}}") { + val client = testClient() + val future = {{> tests/method}} + + val response = Await.result(future, Duration.Inf) + {{#response}} + {{#body}} + val expected = parse("""{{{body}}}""") + val extracted = Extraction.decompose(response) + val diffRes = expected.diff(extracted) + if (diffRes.deleted != JNothing) { + println(s"This was expected and not found in the deserialized response: ${write(diffRes.deleted)}") + } + if (diffRes.changed != JNothing) { + println(s"The expectation was different than what was found in the deserialized response: ${write(diffRes.changed)}") + } + if (diffRes.deleted != JNothing || diffRes.changed != JNothing) { + fail("there is a difference between received and expected") + } + {{/body}} + {{/response}} + } + + {{/tests}} + {{/blocksE2E}} +} \ No newline at end of file diff --git a/templates/swift/tests/e2e/e2eAlt.mustache b/templates/swift/tests/e2e/e2eAlt.mustache new file mode 100644 index 00000000000..e266d3ca9d0 --- /dev/null +++ b/templates/swift/tests/e2e/e2eAlt.mustache @@ -0,0 +1,77 @@ +// {{generationBanner}} +import XCTest + +import Utils +import DotEnv + +@testable import Core +@testable import {{import}} + +final class {{client}}RequestsTestsE2EAlt: XCTestCase { + + static var APPLICATION_ID = "my_application_id" + static var API_KEY = "my_api_key" + static var client: {{client}}? + + override class func setUp() { + if !(Bool(ProcessInfo.processInfo.environment["CI"] ?? "false") ?? false) { + do { + let currentFileURL = try XCTUnwrap(URL(string: #file)) + + let packageDirectoryURL = currentFileURL + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + + let dotEnvURL = packageDirectoryURL + .appendingPathComponent(".env") + dump(dotEnvURL.absoluteString) + try DotEnv.load(path: dotEnvURL.absoluteString, encoding: .utf8, overwrite: true) + } catch { + XCTFail("Unable to load .env file") + } + } + + do { + APPLICATION_ID = try XCTUnwrap(ProcessInfo.processInfo.environment["METIS_APPLICATION_ID"]) + } catch { + XCTFail("Please provide an `METIS_APPLICATION_ID` env var for e2e tests") + } + + do { + API_KEY = try XCTUnwrap(ProcessInfo.processInfo.environment["METIS_API_KEY"]) + } catch { + XCTFail("Please provide an `METIS_API_KEY` env var for e2e tests") + } + + client = try? {{client}}(appID: APPLICATION_ID, apiKey: API_KEY{{#hasRegionalHost}}, region: .{{defaultRegion}}{{/hasRegionalHost}}) + } + + {{#blocksE2E}} + {{#tests}} + /** + {{{testName}}} + */ + func test{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}Test{{testIndex}}() async throws { + guard let client = {{client}}RequestsTestsE2E.client else { + XCTFail("E2E client is not initialized") + return + } + + {{#response}} + let response{{#isGeneric}}: Response<{{#lambda.prefix}}{{{returnType}}}{{/lambda.prefix}}<{{#lambda.prefix}}Hit{{/lambda.prefix}}>>{{/isGeneric}} = {{> tests/method}} + {{#body}} + try XCTLenientAssertEqual(received: XCTUnwrap(response.body), expected: "{{#lambda.escapeJSON}}{{{body}}}{{/lambda.escapeJSON}}") + {{/body}} + + {{#statusCode}} + XCTAssertEqual(response.statusCode, {{statusCode}}) + {{/statusCode}} + {{/response}} + } + {{/tests}} + + {{/blocksE2E}} +} \ No newline at end of file