diff --git a/.gitignore b/.gitignore index 466097b..2d4b255 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,14 @@ .DS_Store -/.dart_tool +.dart_tool # FVM Version Cache .fvm/ # Integration Test -/integration_test/petstore/petstore_api /integration_test/imposter.jar +/integration_test/petstore/petstore_api /integration_test/music_streaming/music_streaming_api +/integration_test/gov/gov_api + +# Dependencies +/pubspec.lock diff --git a/CHANGELOG.md b/CHANGELOG.md index d181de6..2bb3ab4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,44 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## 2025-06-15 + +### Changes + +--- + +Packages with breaking changes: + + - There are no breaking changes in this release. + +Packages with other changes: + + - [`tonik` - `v0.0.6`](#tonik---v006) + - [`tonik_core` - `v0.0.6`](#tonik_core---v006) + - [`tonik_generate` - `v0.0.6`](#tonik_generate---v006) + - [`tonik_parse` - `v0.0.6`](#tonik_parse---v006) + - [`tonik_util` - `v0.0.6`](#tonik_util---v006) + +--- + +#### `tonik` - `v0.0.6` + +#### `tonik_core` - `v0.0.6` + +#### `tonik_generate` - `v0.0.6` + + - **FIX**: proper handle dates. + - **FIX**: priority for exlict defined names of schemas. + - **FIX**: prio for explicitly defined names. + - **FIX**: proper hash code for classes with >20 properties. + +#### `tonik_parse` - `v0.0.6` + +#### `tonik_util` - `v0.0.6` + + - **FIX**: proper handle dates. + + ## 2025-06-02 ### Changes diff --git a/integration_test/gov/gov_test/.gitignore b/integration_test/gov/gov_test/.gitignore new file mode 100644 index 0000000..3cceda5 --- /dev/null +++ b/integration_test/gov/gov_test/.gitignore @@ -0,0 +1,7 @@ +# https://dart.dev/guides/libraries/private-files +# Created by `dart pub` +.dart_tool/ + +# Avoid committing pubspec.lock for library packages; see +# https://dart.dev/guides/libraries/private-files#pubspeclock. +pubspec.lock diff --git a/integration_test/gov/gov_test/analysis_options.yaml b/integration_test/gov/gov_test/analysis_options.yaml new file mode 100644 index 0000000..dee8927 --- /dev/null +++ b/integration_test/gov/gov_test/analysis_options.yaml @@ -0,0 +1,30 @@ +# This file configures the static analysis results for your project (errors, +# warnings, and lints). +# +# This enables the 'recommended' set of lints from `package:lints`. +# This set helps identify many issues that may lead to problems when running +# or consuming Dart code, and enforces writing Dart using a single, idiomatic +# style and format. +# +# If you want a smaller set of lints you can change this to specify +# 'package:lints/core.yaml'. These are just the most critical lints +# (the recommended set includes the core lints). +# The core lints are also what is used by pub.dev for scoring packages. + +include: package:lints/recommended.yaml + +# Uncomment the following section to specify additional rules. + +# linter: +# rules: +# - camel_case_types + +# analyzer: +# exclude: +# - path/to/excluded/files/** + +# For more information about the core and recommended set of lints, see +# https://dart.dev/go/core-lints + +# For additional information about configuring this file, see +# https://dart.dev/guides/language/analysis-options diff --git a/integration_test/gov/gov_test/imposter/imposter-config.json b/integration_test/gov/gov_test/imposter/imposter-config.json new file mode 100644 index 0000000..a2480b3 --- /dev/null +++ b/integration_test/gov/gov_test/imposter/imposter-config.json @@ -0,0 +1,7 @@ +{ + "plugin": "openapi", + "specFile": "../../openapi.yaml", + "response": { + "scriptFile": "response.groovy" + } +} \ No newline at end of file diff --git a/integration_test/gov/gov_test/imposter/response.groovy b/integration_test/gov/gov_test/imposter/response.groovy new file mode 100644 index 0000000..65422ea --- /dev/null +++ b/integration_test/gov/gov_test/imposter/response.groovy @@ -0,0 +1,7 @@ +// Get the response status from the request header +def responseStatus = context.request.headers['X-Response-Status'] ?: '200' + +// Set the response status code and use the OpenAPI specification +respond() + .withStatusCode(Integer.parseInt(responseStatus)) + .usingDefaultBehaviour() diff --git a/integration_test/gov/gov_test/pubspec.yaml b/integration_test/gov/gov_test/pubspec.yaml new file mode 100644 index 0000000..b4c67f7 --- /dev/null +++ b/integration_test/gov/gov_test/pubspec.yaml @@ -0,0 +1,19 @@ +name: gov_test +description: A starting point for Dart libraries or applications. +version: 1.0.0 +publish_to: none + +environment: + sdk: ^3.8.0 + +dependencies: + dio: ^5.8.0 + gov_api: + path: ../gov_api + path: ^1.8.3 + tonik_util: ^0.0.6 + +dev_dependencies: + test: ^1.24.0 + very_good_analysis: ^9.0.0 + diff --git a/integration_test/gov/gov_test/test/default_test.dart b/integration_test/gov/gov_test/test/default_test.dart new file mode 100644 index 0000000..59efdeb --- /dev/null +++ b/integration_test/gov/gov_test/test/default_test.dart @@ -0,0 +1,120 @@ +import 'package:dio/dio.dart'; +import 'package:gov_api/gov_api.dart'; +import 'package:test/test.dart'; +import 'package:tonik_util/tonik_util.dart'; + +import 'test_helper.dart'; + +void main() { + const port = 8080; + const baseUrl = 'http://localhost:$port'; + + late ImposterServer imposterServer; + + setUpAll(() async { + imposterServer = ImposterServer(port: port); + await setupImposterServer(imposterServer); + }); + + DefaultApi buildAlbumsApi({required String responseStatus}) { + return DefaultApi( + CustomServer( + baseUrl: baseUrl, + serverConfig: ServerConfig( + baseOptions: BaseOptions( + headers: {'X-Response-Status': responseStatus}, + ), + ), + ), + ); + } + + group('findForms', () { + test('200', () async { + final defaultApi = buildAlbumsApi(responseStatus: '200'); + + final response = await defaultApi.findForms(query: '10-10EZ'); + + expect(response, isA>()); + final success = response as TonikSuccess; + expect(success.response.statusCode, 200); + expect(success.value, isA()); + + final value = success.value as FindFormsResponse200; + expect(value.body, isA()); + + final body = value.body; + expect(body.data, isA>()); + + final formIndex = body.data.first; + expect(formIndex.attributes?.benefitCategories, isA>()); + expect(formIndex.id, isA()); + expect(formIndex.$type, isA()); + + final attributes = formIndex.attributes; + final benefitCategory = attributes?.benefitCategories?.first; + expect(benefitCategory?.name, isA()); + expect(benefitCategory?.description, isA()); + + expect(attributes?.deletedAt, isA()); + expect(attributes?.firstIssuedOn, isA()); + expect(attributes?.formDetailsUrl, isA()); + expect(attributes?.formName, isA()); + expect(attributes?.formToolIntro, isA()); + expect(attributes?.formToolUrl, isA()); + expect(attributes?.formType, isA()); + expect(attributes?.formUsage, isA()); + expect(attributes?.language, isA()); + expect(attributes?.lastRevisionOn, isA()); + expect(attributes?.lastSha256Change, isA()); + expect(attributes?.pages, isA()); + expect(attributes?.relatedForms, isA?>()); + expect(attributes?.sha256, isA()); + expect(attributes?.title, isA()); + expect(attributes?.url, isA()); + expect(attributes?.vaFormAdministration, isA()); + expect(attributes?.validPdf, isA()); + }); + + test('401', () async { + final defaultApi = buildAlbumsApi(responseStatus: '401'); + + final response = await defaultApi.findForms(); + + expect(response, isA>()); + final success = response as TonikSuccess; + + expect(success.response.statusCode, 401); + expect(success.value, isA()); + + final value = success.value as FindFormsResponse401; + expect(value.body, isA()); + + final body = value.body; + expect(body.message, isA()); + }); + + test('429', () async { + final defaultApi = buildAlbumsApi(responseStatus: '429'); + + final response = await defaultApi.findForms(); + + expect(response, isA>()); + final success = response as TonikSuccess; + + expect(success.response.statusCode, 429); + expect(success.value, isA()); + + final value = success.value as FindFormsResponse429; + expect(value.body, isA()); + }); + + test('unexpected status code', () async { + final defaultApi = buildAlbumsApi(responseStatus: '500'); + + final response = await defaultApi.findForms(); + + expect(response, isA>()); + }); + }); +} diff --git a/integration_test/gov/gov_test/test/test_helper.dart b/integration_test/gov/gov_test/test/test_helper.dart new file mode 100644 index 0000000..6347edb --- /dev/null +++ b/integration_test/gov/gov_test/test/test_helper.dart @@ -0,0 +1,87 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as path; +import 'package:test/test.dart'; + +class ImposterServer { + ImposterServer({required this.port}); + + Process? _process; + final int port; + + Future start() async { + final imposterJar = path.join( + Directory.current.parent.parent.path, + 'imposter.jar', + ); + + if (!File(imposterJar).existsSync()) { + throw Exception( + 'Imposter JAR not found at $imposterJar. Please download it first.', + ); + } + + _process = await Process.start( + 'java', + [ + '-jar', + imposterJar, + '--listenPort', + port.toString(), + '--configDir', + path.join(Directory.current.path, 'imposter'), + '--plugin', + 'openapi', + '--plugin', + 'rest', + ], + environment: { + ...Platform.environment, + 'IMPOSTER_LOG_LEVEL': 'DEBUG', + }, + ); + + _process!.stdout.transform(const Utf8Decoder()).listen((data) { + print('Imposter stdout: $data'); + }); + _process!.stderr.transform(const Utf8Decoder()).listen((data) { + print('Imposter stderr: $data'); + }); + + await _waitForImposterReady(); + } + + Future _waitForImposterReady({int timeoutSec = 10}) async { + final deadline = DateTime.now().add(Duration(seconds: timeoutSec)); + final client = HttpClient(); + + while (DateTime.now().isBefore(deadline)) { + try { + final request = await client.getUrl( + Uri.parse('http://localhost:$port'), + ); + await request.close(); + + return true; // No exception means the server is ready. + } on SocketException catch (_) { + // ignore + } + await Future.delayed(const Duration(milliseconds: 300)); + } + return false; + } + + Future stop() async { + if (_process != null) { + _process!.kill(); + await _process!.exitCode; + _process = null; + } + } +} + +Future setupImposterServer(ImposterServer server) async { + await server.start(); + addTearDown(() => server.stop()); +} diff --git a/integration_test/gov/openapi.yaml b/integration_test/gov/openapi.yaml new file mode 100644 index 0000000..5d1c219 --- /dev/null +++ b/integration_test/gov/openapi.yaml @@ -0,0 +1,431 @@ +openapi: 3.0.0 +servers: + - description: VA.gov API sandbox environment + url: https://sandbox-api.va.gov/services/va_forms/{version} + variables: + version: + default: v0 + - description: VA.gov API production environment + url: https://api.va.gov/services/va_forms/{version} + variables: + version: + default: v0 +info: + contact: + name: va.gov + description: | + Use the VA Forms API to search for VA forms, get the form's PDF link and metadata, and check for new versions. + + Visit our VA Lighthouse [Contact Us page](https://developer.va.gov/support) for further assistance. + + ## Background + This API offers an efficient way to stay up-to-date with the latest VA forms and information. The forms information listed on VA.gov matches the information returned by this API. + - Search by form number, keyword, or title + - Get a link to the form in PDF format + - Get detailed form metadata including the number of pages, related forms, benefit categories, language, and more + - Retrieve the latest date of PDF changes and the SHA256 checksum + - Identify when a form is deleted by the VA + + ## Technical summary + The VA Forms API collects form data from the official VA Form Repository on a nightly basis. The Index endpoint can return all available forms or, if an optional query parameter is passed, will return only forms that may relate to the query value. When a valid form name is passed to the Show endpoint, it will return a single form with additional metadata and full revision history. A JSON response is given with the PDF link (if published) and the corresponding form metadata. + + ### Authentication and authorization + The form information shared by this API is publicly available. API requests are authorized through a symmetric API token, provided in an HTTP header with name apikey. [Get a sandbox API Key](https://developer.va.gov/apply). + + ### Testing in sandbox environment + Form data in the sandbox environment is for testing your API only, and is not guaranteed to be up-to-date. This API also has a reduced API rate limit. When you're ready to move to production, be sure to [request a production API key.](https://developer.va.gov/go-live) + + ### SHA256 revision history + Each form is checked nightly for recent file changes. A corresponding SHA256 checksum is calculated, which provides a record of when the PDF changed and the SHA256 hash that was calculated. This allows end users to know that they have the most recent version and can verify the integrity of a previously downloaded PDF. + + ### Valid PDF link + Additionally, during the nightly refresh process, the link to the form PDF is verified and the `valid_pdf` metadata is updated accordingly. If marked `true`, the link is valid and is a current form. If marked `false`, the link is either broken or the form has been removed. + + ### Deleted forms + If the `deleted_at` metadata is set, that means the VA has removed this form from the repository and it is no longer to be used. + title: VA Forms + version: 0.0.0 + x-apisguru-categories: + - forms + x-logo: + url: https://prod-va-gov-assets.s3-us-gov-west-1.amazonaws.com/img/design/icons/apple-touch-icon.png + x-origin: + - format: openapi + url: https://api.va.gov/services/va_forms/docs/v0/api + version: "3.0" + x-providerName: va.gov + x-serviceName: forms +paths: + /forms: + get: + description: Returns an index of all available VA forms. Optionally, pass a query parameter to filter forms by form number or title. + operationId: findForms + parameters: + - description: Returns form data based on entered form name. + in: query + name: query + required: false + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + data: + items: + $ref: "#/components/schemas/FormsIndex" + type: array + required: + - data + type: object + description: VA Forms index response + "401": + content: + application/json: + schema: + properties: + message: + example: Invalid authentication credentials + type: string + description: Unauthorized + "429": + content: + application/json: + schema: + properties: + message: + example: API rate limit exceeded + type: string + description: Too many requests + security: + - apikey: [] + summary: Returns all VA Forms and their last revision date + tags: + - Forms + "/forms/{form_name}": + get: + description: Returns a single form and the full revision history + operationId: findFormByFormName + parameters: + - description: The VA form_name of the form being requested. The exact form name must be passed, including proper placement of prefixes and/or hyphens. + example: 10-10EZ + in: path + name: form_name + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + data: + $ref: "#/components/schemas/FormShow" + required: + - data + type: object + description: VA Form Show response + "401": + content: + application/json: + schema: + properties: + message: + example: Invalid authentication credentials + type: string + description: Unauthorized + "404": + content: + application/json: + schema: + properties: + errors: + items: + properties: + message: + example: Form not found + type: string + type: array + required: + - errors + type: object + description: Not Found + "429": + content: + application/json: + schema: + properties: + message: + example: API rate limit exceeded + type: string + description: Too many requests + security: + - apikey: [] + summary: Find form by form name + tags: + - Forms +components: + examples: {} + links: {} + parameters: {} + requestBodies: {} + responses: {} + schemas: + FormShow: + description: Data for a particular VA form, including form version history. + properties: + attributes: + properties: + benefit_categories: + description: Listing of benefit categories and match + items: + properties: + description: + description: Description of the benefit category of the form + example: VA health care + type: string + name: + description: Name of the benefit category of the form + example: Health care + type: string + nullable: true + type: array + created_at: + description: Internal field for VA.gov use + example: 2021-03-30T16:28:30.338Z + format: date-time + nullable: true + type: string + deleted_at: + description: The timestamp at which the form was deleted + example: null + format: date-time + nullable: true + type: string + first_issued_on: + description: The date the form first became available + example: 2016-07-10 + format: date + nullable: true + type: string + form_details_url: + description: Location on www.va.gov of the info page for this form + example: https://www.va.gov/find-forms/about-form-10-10ez + nullable: true + type: string + form_name: + description: Name of the VA Form + example: 10-10EZ + type: string + form_tool_intro: + description: Introductory text describing the VA online tool for this form + example: You can apply online instead of filling out and sending us the paper form. + nullable: true + type: string + form_tool_url: + description: Location of the online tool for this form + example: https://www.va.gov/health-care/apply/application/introduction + nullable: true + type: string + form_type: + description: VA Type of the form + example: benefit + nullable: true + type: string + form_usage: + description: A description of how the form is to be used + example:

Use VA Form 10-10EZ if you’re a Veteran and want to apply for VA health care. You must be enrolled in...

+ nullable: true + type: string + language: + description: Language code of the form + example: en + nullable: true + type: string + last_revision_on: + description: The date the form was last updated + example: 2020-01-17 + format: date + nullable: true + type: string + pages: + description: Number of pages contained in the form + example: 5 + type: integer + related_forms: + description: A listing of other forms that relate to current form + items: + example: 10-10EZR + type: string + nullable: true + type: array + sha256: + description: A sha256 hash of the form contents + example: 5fe171299ece147e8b456961a38e17f1391026f26e9e170229317bc95d9827b7 + nullable: true + type: string + title: + description: Title of the form as given by VA + example: Instructions and Enrollment Application for Health Benefits + type: string + url: + description: Web location of the form + example: https://www.va.gov/vaforms/medical/pdf/10-10EZ-fillable.pdf + type: string + va_form_administration: + description: The VA organization that administers the form + example: Veterans Health Administration + nullable: true + type: string + valid_pdf: + description: A flag indicating whether the form url was confirmed as a valid download + example: "true" + type: boolean + versions: + description: The version history of revisions to the form + items: + properties: + revision_on: + description: The date the sha256 hash was calculated + example: 2012-01-01 + format: date + type: string + sha256: + description: A sha256 hash of the form contents for that version + example: 5fe171299ece147e8b456961a38e17f1391026f26e9e170229317bc95d9827b7 + type: string + nullable: true + type: array + id: + description: JSON API identifier + example: 10-10-EZ + type: string + type: + description: JSON API type specification + example: va_form + type: string + FormsIndex: + description: A listing of available VA forms and their location. + properties: + attributes: + properties: + benefit_categories: + description: Listing of benefit categories and match + items: + properties: + description: + description: Description of the benefit category of the form + example: VA health care + type: string + name: + description: Name of the benefit category of the form + example: Health care + type: string + nullable: true + type: array + deleted_at: + description: The timestamp at which the form was deleted + example: "null" + format: date-time + nullable: true + type: string + first_issued_on: + description: The date the form first became available + example: 2016-07-10 + format: date + nullable: true + type: string + form_details_url: + description: Location on www.va.gov of the info page for this form + example: https://www.va.gov/find-forms/about-form-10-10ez + nullable: true + type: string + form_name: + description: Name of the VA Form + example: 10-10EZ + type: string + form_tool_intro: + description: Introductory text describing the VA online tool for this form + example: You can apply online instead of filling out and sending us the paper form. + nullable: true + type: string + form_tool_url: + description: Location of the online tool for this form + example: https://www.va.gov/health-care/apply/application/introduction + nullable: true + type: string + form_type: + description: VA Type of the form + example: benefit + nullable: true + type: string + form_usage: + description: A description of how the form is to be used + example:

Use VA Form 10-10EZ if you’re a Veteran and want to apply for VA health care. You must be enrolled in...

+ nullable: true + type: string + language: + description: Language code of the form + example: en + type: string + last_revision_on: + description: The date the form was last updated + example: 2020-01-17 + format: date + nullable: true + type: string + last_sha256_change: + description: The date of the last sha256 hash change + example: 2019-05-30 + format: date + nullable: true + type: string + pages: + description: Number of pages contained in the form + example: 5 + type: integer + related_forms: + description: A listing of other forms that relate to current form + items: + example: 10-10EZR + type: string + nullable: true + type: array + sha256: + description: A sha256 hash of the form contents + example: 6e6465e2e1c89225871daa9b6d86b92d1c263c7b02f98541212af7b35272372b + nullable: true + type: string + title: + description: Title of the form as given by VA + example: Instructions and Enrollment Application for Health Benefits + type: string + url: + description: Web location of the form + example: https://www.va.gov/vaforms/medical/pdf/10-10EZ-fillable.pdf + type: string + va_form_administration: + description: The VA organization that administers the form + example: Veterans Health Administration + nullable: true + type: string + valid_pdf: + description: A flag indicating whether the form url was confirmed as a valid download + example: "true" + type: boolean + id: + description: JSON API identifier + example: "5403" + type: string + type: + description: JSON API type specification + example: va_form + type: string + securitySchemes: + apikey: + in: header + name: apikey + type: apiKey \ No newline at end of file diff --git a/integration_test/music_streaming/music_streaming_test/analysis_options.yaml b/integration_test/music_streaming/music_streaming_test/analysis_options.yaml new file mode 100644 index 0000000..773cbeb --- /dev/null +++ b/integration_test/music_streaming/music_streaming_test/analysis_options.yaml @@ -0,0 +1,12 @@ + +include: package:very_good_analysis/analysis_options.yaml + +linter: + rules: + public_member_api_docs: false + avoid_print: false + +analyzer: + errors: + deprecated_member_use: ignore + \ No newline at end of file diff --git a/integration_test/music_streaming/music_streaming_test/imposter/imposter-config.json b/integration_test/music_streaming/music_streaming_test/imposter/imposter-config.json new file mode 100644 index 0000000..a2480b3 --- /dev/null +++ b/integration_test/music_streaming/music_streaming_test/imposter/imposter-config.json @@ -0,0 +1,7 @@ +{ + "plugin": "openapi", + "specFile": "../../openapi.yaml", + "response": { + "scriptFile": "response.groovy" + } +} \ No newline at end of file diff --git a/integration_test/music_streaming/music_streaming_test/imposter/response.groovy b/integration_test/music_streaming/music_streaming_test/imposter/response.groovy new file mode 100644 index 0000000..65422ea --- /dev/null +++ b/integration_test/music_streaming/music_streaming_test/imposter/response.groovy @@ -0,0 +1,7 @@ +// Get the response status from the request header +def responseStatus = context.request.headers['X-Response-Status'] ?: '200' + +// Set the response status code and use the OpenAPI specification +respond() + .withStatusCode(Integer.parseInt(responseStatus)) + .usingDefaultBehaviour() diff --git a/pubspec.lock b/integration_test/music_streaming/music_streaming_test/pubspec.lock similarity index 62% rename from pubspec.lock rename to integration_test/music_streaming/music_streaming_test/pubspec.lock index 1b7df99..0c8693c 100644 --- a/pubspec.lock +++ b/integration_test/music_streaming/music_streaming_test/pubspec.lock @@ -17,14 +17,6 @@ packages: url: "https://pub.dev" source: hosted version: "7.4.5" - ansi_styles: - dependency: transitive - description: - name: ansi_styles - sha256: "9c656cc12b3c27b17dd982b2cc5c0cfdfbdabd7bc8f3ae5e8542d9867b47ce8a" - url: "https://pub.dev" - source: hosted - version: "0.3.2+1" args: dependency: transitive description: @@ -57,86 +49,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.2" - build: - dependency: transitive - description: - name: build - sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0 - url: "https://pub.dev" - source: hosted - version: "2.4.2" - build_config: - dependency: transitive - description: - name: build_config - sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33" - url: "https://pub.dev" - source: hosted - version: "1.1.2" - build_daemon: - dependency: transitive - description: - name: build_daemon - sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa" - url: "https://pub.dev" - source: hosted - version: "4.0.4" - build_resolvers: - dependency: transitive - description: - name: build_resolvers - sha256: b9e4fda21d846e192628e7a4f6deda6888c36b5b69ba02ff291a01fd529140f0 - url: "https://pub.dev" - source: hosted - version: "2.4.4" - build_runner: - dependency: transitive - description: - name: build_runner - sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99" - url: "https://pub.dev" - source: hosted - version: "2.4.15" - build_runner_core: - dependency: transitive - description: - name: build_runner_core - sha256: "22e3aa1c80e0ada3722fe5b63fd43d9c8990759d0a2cf489c8c5d7b2bdebc021" - url: "https://pub.dev" - source: hosted - version: "8.0.0" - built_collection: - dependency: transitive - description: - name: built_collection - sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" - url: "https://pub.dev" - source: hosted - version: "5.1.1" - built_value: - dependency: transitive - description: - name: built_value - sha256: "082001b5c3dc495d4a42f1d5789990505df20d8547d42507c29050af6933ee27" - url: "https://pub.dev" - source: hosted - version: "8.10.1" - change_case: - dependency: transitive - description: - name: change_case - sha256: e41ef3df58521194ef8d7649928954805aeb08061917cf658322305e61568003 - url: "https://pub.dev" - source: hosted - version: "2.2.0" - charcode: - dependency: transitive - description: - name: charcode - sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a - url: "https://pub.dev" - source: hosted - version: "1.4.0" checked_yaml: dependency: transitive description: @@ -153,54 +65,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.0" - cli_launcher: - dependency: transitive - description: - name: cli_launcher - sha256: "5e7e0282b79e8642edd6510ee468ae2976d847a0a29b3916e85f5fa1bfe24005" - url: "https://pub.dev" - source: hosted - version: "0.3.1" - cli_util: - dependency: transitive - description: - name: cli_util - sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c - url: "https://pub.dev" - source: hosted - version: "0.4.2" - clock: - dependency: transitive - description: - name: clock - sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b - url: "https://pub.dev" - source: hosted - version: "1.1.2" - code_builder: - dependency: transitive - description: - name: code_builder - sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e" - url: "https://pub.dev" - source: hosted - version: "4.10.1" collection: - dependency: "direct main" + dependency: transitive description: name: collection sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" url: "https://pub.dev" source: hosted version: "1.19.1" - conventional_commit: - dependency: transitive - description: - name: conventional_commit - sha256: c40b1b449ce2a63fa2ce852f35e3890b1e182f5951819934c0e4a66254bc0dc3 - url: "https://pub.dev" - source: hosted - version: "0.6.1+1" convert: dependency: transitive description: @@ -225,16 +97,8 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.6" - dart_style: - dependency: "direct main" - description: - name: dart_style - sha256: "5b236382b47ee411741447c1f1e111459c941ea1b3f2b540dde54c210a3662af" - url: "https://pub.dev" - source: hosted - version: "3.1.0" dio: - dependency: transitive + dependency: "direct main" description: name: dio sha256: "253a18bbd4851fecba42f7343a1df3a9a4c1d31a2c1b37e221086b4fa8c8dbc9" @@ -257,14 +121,6 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" - fixnum: - dependency: transitive - description: - name: fixnum - sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be - url: "https://pub.dev" - source: hosted - version: "1.1.1" frontend_server_client: dependency: transitive description: @@ -281,22 +137,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.3" - graphs: - dependency: transitive - description: - name: graphs - sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" - url: "https://pub.dev" - source: hosted - version: "2.3.2" - http: - dependency: transitive - description: - name: http - sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b" - url: "https://pub.dev" - source: hosted - version: "1.4.0" http_multi_server: dependency: transitive description: @@ -313,14 +153,6 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.2" - intl: - dependency: transitive - description: - name: intl - sha256: "910f85bce16fb5c6f614e117efa303e85a1731bb0081edf3604a2ae6e9a3cc91" - url: "https://pub.dev" - source: hosted - version: "0.17.0" io: dependency: transitive description: @@ -345,16 +177,16 @@ packages: url: "https://pub.dev" source: hosted version: "4.9.0" - json_serializable: + lints: dependency: transitive description: - name: json_serializable - sha256: c50ef5fc083d5b5e12eef489503ba3bf5ccc899e487d691584699b4bdefeea8c + name: lints + sha256: a5e2b223cb7c9c8efdc663ef484fdd95bb243bff242ef5b13e26883547fce9a0 url: "https://pub.dev" source: hosted - version: "6.9.5" + version: "6.0.0" logging: - dependency: "direct main" + dependency: transitive description: name: logging sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 @@ -369,16 +201,8 @@ packages: url: "https://pub.dev" source: hosted version: "0.12.17" - melos: - dependency: "direct dev" - description: - name: melos - sha256: "51e7902a164d7563cf1b1de04272eb4348a551c1e7885875353e82e8928c90e0" - url: "https://pub.dev" - source: hosted - version: "7.0.0-dev.9" meta: - dependency: "direct main" + dependency: transitive description: name: meta sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" @@ -393,14 +217,13 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.0" - mustache_template: - dependency: transitive + music_streaming_api: + dependency: "direct main" description: - name: mustache_template - sha256: a46e26f91445bfb0b60519be280555b06792460b27b19e2b19ad5b9740df5d1c - url: "https://pub.dev" - source: hosted - version: "2.0.0" + path: "../music_streaming_api" + relative: true + source: path + version: "1.0.0" node_preamble: dependency: transitive description: @@ -425,14 +248,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" - platform: - dependency: transitive - description: - name: platform - sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" - url: "https://pub.dev" - source: hosted - version: "3.1.6" pool: dependency: transitive description: @@ -441,22 +256,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.5.1" - process: - dependency: transitive - description: - name: process - sha256: "44b4226c0afd4bc3b7c7e67d44c4801abd97103cf0c84609e2654b664ca2798c" - url: "https://pub.dev" - source: hosted - version: "5.0.4" - prompts: - dependency: transitive - description: - name: prompts - sha256: "3773b845e85a849f01e793c4fc18a45d52d7783b4cb6c0569fad19f9d0a774a1" - url: "https://pub.dev" - source: hosted - version: "2.0.0" pub_semver: dependency: transitive description: @@ -465,14 +264,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" - pub_updater: - dependency: transitive - description: - name: pub_updater - sha256: "739a0161d73a6974c0675b864fb0cf5147305f7b077b7f03a58fa7a9ab3e7e7d" - url: "https://pub.dev" - source: hosted - version: "0.5.0" pubspec_parse: dependency: transitive description: @@ -513,22 +304,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0" - source_gen: - dependency: transitive - description: - name: source_gen - sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b" - url: "https://pub.dev" - source: hosted - version: "2.0.0" - source_helper: - dependency: transitive - description: - name: source_helper - sha256: "86d247119aedce8e63f4751bd9626fc9613255935558447569ad42f9f5b48b3c" - url: "https://pub.dev" - source: hosted - version: "1.3.5" source_map_stack_trace: dependency: transitive description: @@ -553,14 +328,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.10.1" - spell_out_numbers: - dependency: "direct main" - description: - name: spell_out_numbers - sha256: "7ac80a4e306002526490654f32c4e26f4d97e110cb11dd7b5bd4dfe627452f57" - url: "https://pub.dev" - source: hosted - version: "1.0.0" stack_trace: dependency: transitive description: @@ -577,14 +344,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.4" - stream_transform: - dependency: transitive - description: - name: stream_transform - sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 - url: "https://pub.dev" - source: hosted - version: "2.1.1" string_scanner: dependency: transitive description: @@ -625,22 +384,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.6.11" - timing: - dependency: transitive - description: - name: timing - sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe" - url: "https://pub.dev" - source: hosted - version: "1.0.2" - tuple: - dependency: transitive + tonik_util: + dependency: "direct main" description: - name: tuple - sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151 + name: tonik_util + sha256: f16c86d5349fac40893d1d8ae87f6507192d8886f16ba6acefeabef4a61ae3ef url: "https://pub.dev" source: hosted - version: "2.0.2" + version: "0.0.5" typed_data: dependency: transitive description: @@ -653,10 +404,10 @@ packages: dependency: "direct dev" description: name: very_good_analysis - sha256: c529563be4cbba1137386f2720fb7ed69e942012a28b13398d8a5e3e6ef551a7 + sha256: e479fbc0941009262343db308133e121bf8660c2c81d48dd8e952df7b7e1e382 url: "https://pub.dev" source: hosted - version: "8.0.0" + version: "9.0.0" vm_service: dependency: transitive description: @@ -713,13 +464,5 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.3" - yaml_edit: - dependency: transitive - description: - name: yaml_edit - sha256: fb38626579fb345ad00e674e2af3a5c9b0cc4b9bfb8fd7f7ff322c7c9e62aef5 - url: "https://pub.dev" - source: hosted - version: "2.2.2" sdks: dart: ">=3.8.0 <4.0.0" diff --git a/integration_test/music_streaming/music_streaming_test/pubspec.yaml b/integration_test/music_streaming/music_streaming_test/pubspec.yaml new file mode 100644 index 0000000..27ed7d8 --- /dev/null +++ b/integration_test/music_streaming/music_streaming_test/pubspec.yaml @@ -0,0 +1,18 @@ +name: music_streaming_test +description: Integration tests for the music streaming API +version: 1.0.0 +publish_to: none + +environment: + sdk: ^3.8.0 + +dependencies: + dio: ^5.8.0 + music_streaming_api: + path: ../music_streaming_api + path: ^1.8.3 + tonik_util: ^0.0.2 + +dev_dependencies: + test: ^1.24.0 + very_good_analysis: ^9.0.0 diff --git a/integration_test/music_streaming/music_streaming_test/test/albums_test.dart b/integration_test/music_streaming/music_streaming_test/test/albums_test.dart new file mode 100644 index 0000000..9a7c481 --- /dev/null +++ b/integration_test/music_streaming/music_streaming_test/test/albums_test.dart @@ -0,0 +1,244 @@ +import 'package:dio/dio.dart'; +import 'package:music_streaming_api/music_streaming_api.dart'; +import 'package:test/test.dart'; +import 'package:tonik_util/tonik_util.dart'; + +import 'test_helper.dart'; + +void main() { + const port = 8080; + const baseUrl = 'http://localhost:$port/v1'; + + late ImposterServer imposterServer; + + setUpAll(() async { + imposterServer = ImposterServer(port: port); + await setupImposterServer(imposterServer); + }); + + AlbumsApi buildAlbumsApi({required String responseStatus}) { + return AlbumsApi( + CustomServer( + baseUrl: baseUrl, + serverConfig: ServerConfig( + baseOptions: BaseOptions( + headers: {'X-Response-Status': responseStatus}, + ), + ), + ), + ); + } + + group('getAnAlbum', () { + test('200', () async { + final albumsApi = buildAlbumsApi(responseStatus: '200'); + + final response = await albumsApi.getAnAlbum(id: '123'); + + expect(response, isA>()); + final success = response as TonikSuccess; + expect(success.response.statusCode, 200); + expect(success.value, isA()); + + final value = success.value as GetAnAlbumResponse200; + expect(value.body, isA()); + final albumBase = value.body.albumBase; + + expect(albumBase, isA()); + expect(albumBase.albumType, isA()); + expect(AlbumBaseAlbumType.values.map((v) => v.rawValue), [ + 'album', + 'single', + 'compilation', + ]); + expect(albumBase.totalTracks, isA()); + expect(albumBase.availableMarkets, isA>()); + expect(albumBase.externalUrls, isA()); + + expect(albumBase.href, isA()); + expect(albumBase.id, isA()); + expect(albumBase.images, isA>()); + expect(albumBase.name, isA()); + expect(albumBase.releaseDate, isA()); + expect( + albumBase.releaseDatePrecision, + isA(), + ); + expect(AlbumBaseReleaseDatePrecision.values.map((v) => v.rawValue), [ + 'year', + 'month', + 'day', + ]); + expect(albumBase.restrictions, isA()); + expect(albumBase.$type, isA()); + expect(AlbumBaseType.values.map((v) => v.rawValue), ['album']); + expect(albumBase.uri, isA()); + + final externalUrls = albumBase.externalUrls.externalUrlObject; + expect(externalUrls.spotify, isA()); + + final image = albumBase.images.first; + expect(image.url, isA()); + expect(image.height, isA()); + expect(image.width, isA()); + + final releaseDatePrecision = + albumBase.restrictions?.albumRestrictionObject; + expect(releaseDatePrecision?.reason, isA()); + expect(AlbumRestrictionObjectReason.values.map((v) => v.rawValue), [ + 'market', + 'product', + 'explicit', + ]); + + final albumObject = value.body.albumObjectModel; + expect(albumObject, isA()); + + // Note: api document intends to have properties of + // [SimplifiedArtistObject] to be non-nullable, but + // required is defined on wrong level and will get + // ingnored by tonic. + expect(albumObject.artists, isA?>()); + final artist = albumObject.artists?.first; + expect(artist?.externalUrls, isA()); + expect(artist?.externalUrls?.externalUrlObject, isA()); + expect(artist?.externalUrls?.externalUrlObject.spotify, isA()); + expect(artist?.href, isA()); + expect(artist?.id, isA()); + expect(artist?.name, isA()); + expect(artist?.$type, isA()); + expect(SimplifiedArtistObjectType.values.map((v) => v.rawValue), [ + 'artist', + ]); + expect(artist?.uri, isA()); + + expect(albumObject.tracks, isA()); + expect( + albumObject.tracks?.pagingSimplifiedTrackObject, + isA(), + ); + final track = albumObject.tracks?.pagingSimplifiedTrackObject; + expect(track?.pagingObject, isA()); + expect(track?.pagingObject.href, isA()); + expect(track?.pagingObject.limit, isA()); + expect(track?.pagingObject.next, isA()); + expect(track?.pagingObject.offset, isA()); + expect(track?.pagingObject.previous, isA()); + expect(track?.pagingObject.total, isA()); + + expect( + track?.pagingSimplifiedTrackObjectModel, + isA(), + ); + expect( + track?.pagingSimplifiedTrackObjectModel.items, + isA>(), + ); + final trackItem = track?.pagingSimplifiedTrackObjectModel.items?.first; + expect(trackItem?.artists, isA?>()); + expect(trackItem?.availableMarkets, isA?>()); + expect(trackItem?.discNumber, isA()); + expect(trackItem?.durationMs, isA()); + expect(trackItem?.explicit, isA()); + expect( + trackItem?.externalUrls, + isA(), + ); + expect( + trackItem?.externalUrls?.externalUrlObject, + isA(), + ); + expect( + trackItem?.externalUrls?.externalUrlObject.spotify, + isA(), + ); + expect(trackItem?.href, isA()); + expect(trackItem?.id, isA()); + expect(trackItem?.isPlayable, isA()); + expect(trackItem?.linkedFrom, isA()); + expect( + trackItem?.linkedFrom?.linkedTrackObject.externalUrls, + isA(), + ); + expect(trackItem?.linkedFrom?.linkedTrackObject.href, isA()); + expect(trackItem?.linkedFrom?.linkedTrackObject.id, isA()); + expect(trackItem?.linkedFrom?.linkedTrackObject.$type, isA()); + expect(trackItem?.linkedFrom?.linkedTrackObject.uri, isA()); + expect( + trackItem?.restrictions, + isA(), + ); + expect( + trackItem?.restrictions?.trackRestrictionObject.reason, + isA(), + ); + expect(trackItem?.name, isA()); + expect(trackItem?.previewUrl, isA()); + expect(trackItem?.trackNumber, isA()); + expect(trackItem?.$type, isA()); + expect(trackItem?.uri, isA()); + expect(trackItem?.isLocal, isA()); + + expect(albumObject.copyrights, isA?>()); + final copyright = albumObject.copyrights?.first; + expect(copyright?.text, isA()); + expect(copyright?.$type, isA()); + + expect(albumObject.externalIds, isA()); + expect(albumObject.genres, isA?>()); + expect(albumObject.label, isA()); + expect(albumObject.popularity, isA()); + }); + + test('401', () async { + final albumsApi = buildAlbumsApi(responseStatus: '401'); + + final response = await albumsApi.getAnAlbum(id: 'abc', market: 'en'); + + expect(response, isA>()); + final success = response as TonikSuccess; + expect(success.response.statusCode, 401); + expect(success.value, isA()); + + final value = success.value as GetAnAlbumResponse401; + expect(value.body, isA()); + expect(value.body.error, isA()); + expect(value.body.error.status, isA()); + expect(value.body.error.message, isA()); + }); + + test('403', () async { + final albumsApi = buildAlbumsApi(responseStatus: '403'); + + final response = await albumsApi.getAnAlbum(id: 'abc', market: 'en'); + + expect(response, isA>()); + final success = response as TonikSuccess; + expect(success.response.statusCode, 403); + expect(success.value, isA()); + + final value = success.value as GetAnAlbumResponse403; + expect(value.body, isA()); + expect(value.body.error, isA()); + expect(value.body.error.status, isA()); + expect(value.body.error.message, isA()); + }); + + test('429', () async { + final albumsApi = buildAlbumsApi(responseStatus: '429'); + + final response = await albumsApi.getAnAlbum(id: 'abc', market: 'en'); + + expect(response, isA>()); + final success = response as TonikSuccess; + expect(success.response.statusCode, 429); + expect(success.value, isA()); + + final value = success.value as GetAnAlbumResponse429; + expect(value.body, isA()); + expect(value.body.error, isA()); + expect(value.body.error.status, isA()); + expect(value.body.error.message, isA()); + }); + }); +} diff --git a/integration_test/music_streaming/music_streaming_test/test/test_helper.dart b/integration_test/music_streaming/music_streaming_test/test/test_helper.dart new file mode 100644 index 0000000..6347edb --- /dev/null +++ b/integration_test/music_streaming/music_streaming_test/test/test_helper.dart @@ -0,0 +1,87 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as path; +import 'package:test/test.dart'; + +class ImposterServer { + ImposterServer({required this.port}); + + Process? _process; + final int port; + + Future start() async { + final imposterJar = path.join( + Directory.current.parent.parent.path, + 'imposter.jar', + ); + + if (!File(imposterJar).existsSync()) { + throw Exception( + 'Imposter JAR not found at $imposterJar. Please download it first.', + ); + } + + _process = await Process.start( + 'java', + [ + '-jar', + imposterJar, + '--listenPort', + port.toString(), + '--configDir', + path.join(Directory.current.path, 'imposter'), + '--plugin', + 'openapi', + '--plugin', + 'rest', + ], + environment: { + ...Platform.environment, + 'IMPOSTER_LOG_LEVEL': 'DEBUG', + }, + ); + + _process!.stdout.transform(const Utf8Decoder()).listen((data) { + print('Imposter stdout: $data'); + }); + _process!.stderr.transform(const Utf8Decoder()).listen((data) { + print('Imposter stderr: $data'); + }); + + await _waitForImposterReady(); + } + + Future _waitForImposterReady({int timeoutSec = 10}) async { + final deadline = DateTime.now().add(Duration(seconds: timeoutSec)); + final client = HttpClient(); + + while (DateTime.now().isBefore(deadline)) { + try { + final request = await client.getUrl( + Uri.parse('http://localhost:$port'), + ); + await request.close(); + + return true; // No exception means the server is ready. + } on SocketException catch (_) { + // ignore + } + await Future.delayed(const Duration(milliseconds: 300)); + } + return false; + } + + Future stop() async { + if (_process != null) { + _process!.kill(); + await _process!.exitCode; + _process = null; + } + } +} + +Future setupImposterServer(ImposterServer server) async { + await server.start(); + addTearDown(() => server.stop()); +} diff --git a/integration_test/petstore/petstore_test/pubspec.yaml b/integration_test/petstore/petstore_test/pubspec.yaml index 047addc..6e483f5 100644 --- a/integration_test/petstore/petstore_test/pubspec.yaml +++ b/integration_test/petstore/petstore_test/pubspec.yaml @@ -16,5 +16,5 @@ dependencies: dev_dependencies: test: ^1.24.0 - very_good_analysis: ^7.0.0 + very_good_analysis: ^9.0.0 diff --git a/integration_test/petstore/petstore_test/test/store_test.dart b/integration_test/petstore/petstore_test/test/store_test.dart index db39421..40e2312 100644 --- a/integration_test/petstore/petstore_test/test/store_test.dart +++ b/integration_test/petstore/petstore_test/test/store_test.dart @@ -16,7 +16,7 @@ void main() { await setupImposterServer(imposterServer); }); - StoreApi buildStoreApi({required String responseStatus}) { + StoreApi buildStoreApi({required String responseStatus}) { return StoreApi( CustomServer( baseUrl: baseUrl, diff --git a/integration_test/petstore/petstore_test/test/test_helper.dart b/integration_test/petstore/petstore_test/test/test_helper.dart index 5af0ef0..6347edb 100644 --- a/integration_test/petstore/petstore_test/test/test_helper.dart +++ b/integration_test/petstore/petstore_test/test/test_helper.dart @@ -6,7 +6,7 @@ import 'package:test/test.dart'; class ImposterServer { ImposterServer({required this.port}); - + Process? _process; final int port; @@ -22,22 +22,25 @@ class ImposterServer { ); } - _process = await Process.start('java', [ - '-jar', - imposterJar, - '--listenPort', - port.toString(), - '--configDir', - path.join(Directory.current.path, 'imposter'), - '--plugin', - 'openapi', - '--plugin', - 'rest', - ], - environment: { - ...Platform.environment, - 'IMPOSTER_LOG_LEVEL': 'DEBUG', - }); + _process = await Process.start( + 'java', + [ + '-jar', + imposterJar, + '--listenPort', + port.toString(), + '--configDir', + path.join(Directory.current.path, 'imposter'), + '--plugin', + 'openapi', + '--plugin', + 'rest', + ], + environment: { + ...Platform.environment, + 'IMPOSTER_LOG_LEVEL': 'DEBUG', + }, + ); _process!.stdout.transform(const Utf8Decoder()).listen((data) { print('Imposter stdout: $data'); diff --git a/integration_test/setup.sh b/integration_test/setup.sh index a87b847..472b9c6 100755 --- a/integration_test/setup.sh +++ b/integration_test/setup.sh @@ -21,6 +21,9 @@ cd petstore/petstore_api && dart pub get && cd ../.. dart run ../packages/tonik/bin/tonik.dart -p music_streaming_api -s music_streaming/openapi.yaml -o music_streaming --log-level verbose cd music_streaming/music_streaming_api && dart pub get && cd ../.. +dart run ../packages/tonik/bin/tonik.dart -p gov_api -s gov/openapi.yaml -o gov --log-level verbose +cd gov/gov_api && dart pub get && cd ../.. + # Download Imposter JAR only if it doesn't exist if [ ! -f imposter.jar ]; then echo "Downloading Imposter JAR..." diff --git a/packages/tonik/CHANGELOG.md b/packages/tonik/CHANGELOG.md index c83e019..a9ba185 100644 --- a/packages/tonik/CHANGELOG.md +++ b/packages/tonik/CHANGELOG.md @@ -1,3 +1,5 @@ +## 0.0.6 + ## 0.0.5 ## 0.0.4 diff --git a/packages/tonik/README.md b/packages/tonik/README.md index 4328338..5f80f6f 100644 --- a/packages/tonik/README.md +++ b/packages/tonik/README.md @@ -8,12 +8,12 @@ pub verion pub likes stars on github -tests +tests + +

- - # Tonik A Dart code generator for OpenAPI 3.0 and 3.1 specifications. diff --git a/packages/tonik/bin/tonik.dart b/packages/tonik/bin/tonik.dart index e2b171b..73ee388 100644 --- a/packages/tonik/bin/tonik.dart +++ b/packages/tonik/bin/tonik.dart @@ -142,7 +142,8 @@ void main(List arguments) { } on Object catch (e, s) { logger ..fine('Failed to parse OpenAPI document', e, s) - ..severe('Unexpected error while parsing OpenAPI document. ' + ..severe( + 'Unexpected error while parsing OpenAPI document. ' 'Unexpected error while parsing OpenAPI document. ' 'If you think your document is valid, please run ' 'with verbose logging and report this issue at $issueUrl', diff --git a/packages/tonik/pubspec.yaml b/packages/tonik/pubspec.yaml index 07d446f..df60006 100644 --- a/packages/tonik/pubspec.yaml +++ b/packages/tonik/pubspec.yaml @@ -1,6 +1,6 @@ name: tonik description: A Dart code generator for OpenAPI 3.0 and 3.1 specifications. -version: 0.0.5 +version: 0.0.6 repository: https://github.com/t-unit/tonik resolution: workspace @@ -20,12 +20,11 @@ environment: dependencies: args: ^2.5.0 logging: ^1.3.0 - tonik_core: ^0.0.5 - tonik_generate: ^0.0.5 - tonik_parse: ^0.0.5 + tonik_core: ^0.0.6 + tonik_generate: ^0.0.6 + tonik_parse: ^0.0.6 yaml: ^3.1.3 dev_dependencies: path: ^1.9.1 test: ^1.24.0 - very_good_analysis: ^8.0.0 diff --git a/packages/tonik/test/src/openapi_loader_test.dart b/packages/tonik/test/src/openapi_loader_test.dart index e5d2bca..211eb9d 100644 --- a/packages/tonik/test/src/openapi_loader_test.dart +++ b/packages/tonik/test/src/openapi_loader_test.dart @@ -20,7 +20,7 @@ void main() { group('loadOpenApiDocument', () { test('loads valid JSON file', () { final jsonFile = File(path.join(tempDir.path, 'test.json')) - ..writeAsStringSync(''' + ..writeAsStringSync(''' { "openapi": "3.0.0", "info": { @@ -39,7 +39,7 @@ void main() { test('loads valid YAML file', () { final yamlFile = File(path.join(tempDir.path, 'test.yaml')) - ..writeAsStringSync(''' + ..writeAsStringSync(''' openapi: 3.0.0 info: title: Test API @@ -69,7 +69,7 @@ info: test('throws on unsupported file extension', () { final txtFile = File(path.join(tempDir.path, 'test.txt')) - ..writeAsStringSync('invalid'); + ..writeAsStringSync('invalid'); expect( () => loadOpenApiDocument(txtFile.path), @@ -79,7 +79,7 @@ info: test('throws on invalid JSON', () { final jsonFile = File(path.join(tempDir.path, 'invalid.json')) - ..writeAsStringSync('invalid json'); + ..writeAsStringSync('invalid json'); expect( () => loadOpenApiDocument(jsonFile.path), @@ -95,7 +95,7 @@ info: test('throws on invalid YAML', () { final yamlFile = File(path.join(tempDir.path, 'invalid.yaml')) - ..writeAsStringSync(''' + ..writeAsStringSync(''' invalid yaml: - misaligned: wrong indentation @@ -110,7 +110,7 @@ invalid yaml: test('handles complex YAML structures', () { final yamlFile = File(path.join(tempDir.path, 'complex.yaml')) - ..writeAsStringSync(''' + ..writeAsStringSync(''' openapi: 3.0.0 info: title: Complex API diff --git a/packages/tonik_core/CHANGELOG.md b/packages/tonik_core/CHANGELOG.md index 47f0e8a..9396082 100644 --- a/packages/tonik_core/CHANGELOG.md +++ b/packages/tonik_core/CHANGELOG.md @@ -1,3 +1,5 @@ +## 0.0.6 + ## 0.0.5 ## 0.0.4 diff --git a/packages/tonik_core/lib/src/model/model.dart b/packages/tonik_core/lib/src/model/model.dart index c2ba93e..bc92452 100644 --- a/packages/tonik_core/lib/src/model/model.dart +++ b/packages/tonik_core/lib/src/model/model.dart @@ -45,9 +45,9 @@ class AliasModel extends Model with NamedModel { final Model model; Model get resolved => switch (model) { - final AliasModel alias => alias.resolved, - _ => model, - }; + final AliasModel alias => alias.resolved, + _ => model, + }; @override EncodingShape get encodingShape => resolved.encodingShape; diff --git a/packages/tonik_core/pubspec.yaml b/packages/tonik_core/pubspec.yaml index 694bcfb..53e6254 100644 --- a/packages/tonik_core/pubspec.yaml +++ b/packages/tonik_core/pubspec.yaml @@ -1,6 +1,6 @@ name: tonik_core description: Core data structures and utilities for Tonik. -version: 0.0.5 +version: 0.0.6 repository: https://github.com/t-unit/tonik resolution: workspace @@ -14,5 +14,4 @@ dependencies: dev_dependencies: build_runner: ^2.4.15 test: ^1.24.0 - very_good_analysis: ^8.0.0 diff --git a/packages/tonik_generate/CHANGELOG.md b/packages/tonik_generate/CHANGELOG.md index 7149c21..0eb61b4 100644 --- a/packages/tonik_generate/CHANGELOG.md +++ b/packages/tonik_generate/CHANGELOG.md @@ -1,3 +1,10 @@ +## 0.0.6 + + - **FIX**: proper handle dates. + - **FIX**: priority for exlict defined names of schemas. + - **FIX**: prio for explicitly defined names. + - **FIX**: proper hash code for classes with >20 properties. + ## 0.0.5 ## 0.0.4 diff --git a/packages/tonik_generate/lib/src/analysis_options_generator.dart b/packages/tonik_generate/lib/src/analysis_options_generator.dart new file mode 100644 index 0000000..1d65ffc --- /dev/null +++ b/packages/tonik_generate/lib/src/analysis_options_generator.dart @@ -0,0 +1,35 @@ +import 'dart:io'; +import 'package:path/path.dart' as path; + +void generateAnalysisOptions({ + required String outputDirectory, + required String package, +}) { + final packageDir = path.join(outputDirectory, package); + final analysisOptionsFile = File( + path.join(packageDir, 'analysis_options.yaml'), + ); + + if (!analysisOptionsFile.parent.existsSync()) { + analysisOptionsFile.parent.createSync(recursive: true); + } + + const content = ''' +include: package:lints/recommended.yaml + +analyzer: + errors: + lines_longer_than_80_chars: ignore + unnecessary_raw_strings: ignore + unnecessary_brace_in_string_interps: ignore + no_leading_underscores_for_local_identifiers: ignore + cascade_invocations: ignore + deprecated_member_use_from_same_package: ignore + no_leading_underscores_for_library_prefixes: ignore + unused_import: ignore + prefer_is_empty: ignore + unnecessary_nullable_for_final_variable_declarations: ignore +'''; + + analysisOptionsFile.writeAsStringSync(content); +} diff --git a/packages/tonik_generate/lib/src/api_client/api_client_file_generator.dart b/packages/tonik_generate/lib/src/api_client/api_client_file_generator.dart index 2c4efb2..fa405ec 100644 --- a/packages/tonik_generate/lib/src/api_client/api_client_file_generator.dart +++ b/packages/tonik_generate/lib/src/api_client/api_client_file_generator.dart @@ -29,14 +29,14 @@ class ApiClientFileGenerator { ]); Directory(clientDirectory).createSync(recursive: true); - + // Get the servers list final servers = apiDocument.servers.toList(); // Process operations with tags for (final entry in apiDocument.operationsByTag.entries) { final result = apiClientGenerator.generate( - entry.value, + entry.value, entry.key, servers, ); diff --git a/packages/tonik_generate/lib/src/generator.dart b/packages/tonik_generate/lib/src/generator.dart index 09c8eaf..a35fb18 100644 --- a/packages/tonik_generate/lib/src/generator.dart +++ b/packages/tonik_generate/lib/src/generator.dart @@ -1,4 +1,5 @@ import 'package:tonik_core/tonik_core.dart'; +import 'package:tonik_generate/src/analysis_options_generator.dart'; import 'package:tonik_generate/src/api_client/api_client_file_generator.dart'; import 'package:tonik_generate/src/api_client/api_client_generator.dart'; import 'package:tonik_generate/src/library_generator.dart'; @@ -132,6 +133,11 @@ class Generator { package: package, ); + generateAnalysisOptions( + outputDirectory: outputDirectory, + package: package, + ); + modelGenerator.writeFiles( apiDocument: apiDocument, outputDirectory: outputDirectory, diff --git a/packages/tonik_generate/lib/src/model/class_generator.dart b/packages/tonik_generate/lib/src/model/class_generator.dart index dd604c4..8f5f4cf 100644 --- a/packages/tonik_generate/lib/src/model/class_generator.dart +++ b/packages/tonik_generate/lib/src/model/class_generator.dart @@ -183,6 +183,26 @@ class ClassGenerator { Constructor _buildFromSimpleConstructor(String className, ClassModel model) { final normalizedProperties = normalizeProperties(model.properties.toList()); + + // If there are no properties, just return the constructor call + if (normalizedProperties.isEmpty) { + return Constructor( + (b) => + b + ..factory = true + ..name = 'fromSimple' + ..requiredParameters.add( + Parameter( + (b) => + b + ..name = 'value' + ..type = refer('String?', 'dart:core'), + ), + ) + ..body = Code('return $className();'), + ); + } + final propertyAssignments = >[]; for (var i = 0; i < normalizedProperties.length; i++) { final prop = normalizedProperties[i]; @@ -258,6 +278,11 @@ class ClassGenerator { Code _buildFromJsonBody(String className, ClassModel model) { final normalizedProperties = normalizeProperties(model.properties.toList()); + // If there are no properties, just return the constructor call + if (normalizedProperties.isEmpty) { + return Block.of([Code('return $className();')]); + } + final codes = [ Code("final map = json.decodeMap(context: '$className');"), ]; diff --git a/packages/tonik_generate/lib/src/model/one_of_generator.dart b/packages/tonik_generate/lib/src/model/one_of_generator.dart index 06976db..6ec9beb 100644 --- a/packages/tonik_generate/lib/src/model/one_of_generator.dart +++ b/packages/tonik_generate/lib/src/model/one_of_generator.dart @@ -366,8 +366,9 @@ class OneOfGenerator { // Throw if no match found. blocks.add( - generateJsonDecodingExceptionExpression('Invalid JSON for $className') - .statement, + generateJsonDecodingExceptionExpression( + 'Invalid JSON for $className', + ).statement, ); return Block.of(blocks); diff --git a/packages/tonik_generate/lib/src/naming/name_manager.dart b/packages/tonik_generate/lib/src/naming/name_manager.dart index aadbe2d..a3c7671 100644 --- a/packages/tonik_generate/lib/src/naming/name_manager.dart +++ b/packages/tonik_generate/lib/src/naming/name_manager.dart @@ -58,7 +58,16 @@ class NameManager { _logServerName(entry.value, entry.key); } - for (final model in models) { + for (final model in models.where( + (m) => m is NamedModel && m.name != null, + )) { + final name = modelName(model); + _logModelName(name, model); + } + + for (final model in models.where( + (m) => m is! NamedModel || m.name == null, + )) { final name = modelName(model); _logModelName(name, model); } diff --git a/packages/tonik_generate/lib/src/operation/parse_generator.dart b/packages/tonik_generate/lib/src/operation/parse_generator.dart index 99d45a1..0b7fb9a 100644 --- a/packages/tonik_generate/lib/src/operation/parse_generator.dart +++ b/packages/tonik_generate/lib/src/operation/parse_generator.dart @@ -16,11 +16,12 @@ class ParseGenerator { /// Generates the _parseResponse method for the operation. Method generateParseResponseMethod(Operation operation) { final responses = operation.responses; - final responseType = resultTypeForOperation( - operation, - nameManager, - package, - ).types.first; + final responseType = + resultTypeForOperation( + operation, + nameManager, + package, + ).types.first; final cases = []; // Check if we have a default response with null content type @@ -49,7 +50,7 @@ class ParseGenerator { } } - // Only add a default case if we don't have a default response with + // Only add a default case if we don't have a default response with // null content type final switchCases = [ const Code( @@ -60,17 +61,19 @@ class ParseGenerator { ]; if (!hasDefaultWithNullContentType) { - switchCases.add(Block.of([ - const Code('default:'), - const Code( - "final content = response.headers.value('content-type') " - "?? 'not specified';", - ), - const Code('final status = response.statusCode;'), - generateDecodingExceptionExpression( - r'Unexpected content type: $content for status code: $status', - ).statement, - ]),); + switchCases.add( + Block.of([ + const Code('default:'), + const Code( + "final content = response.headers.value('content-type') " + "?? 'not specified';", + ), + const Code('final status = response.statusCode;'), + generateDecodingExceptionExpression( + r'Unexpected content type: $content for status code: $status', + ).statement, + ]), + ); } switchCases.add(const Code('}')); diff --git a/packages/tonik_generate/lib/src/pubspec_generator.dart b/packages/tonik_generate/lib/src/pubspec_generator.dart index ef578fb..7bb991e 100644 --- a/packages/tonik_generate/lib/src/pubspec_generator.dart +++ b/packages/tonik_generate/lib/src/pubspec_generator.dart @@ -25,8 +25,9 @@ dependencies: big_decimal: ^0.5.0 collection: ^1.17.0 dio: ^5.8.0+1 + lints: ^6.0.0 meta: ^1.16.0 - tonik_util: ^0.0.5 + tonik_util: ^0.0.6 '''; pubspecFile.writeAsStringSync(content); diff --git a/packages/tonik_generate/lib/src/response_wrapper/response_wrapper_generator.dart b/packages/tonik_generate/lib/src/response_wrapper/response_wrapper_generator.dart index 7cfc1b9..f5601d7 100644 --- a/packages/tonik_generate/lib/src/response_wrapper/response_wrapper_generator.dart +++ b/packages/tonik_generate/lib/src/response_wrapper/response_wrapper_generator.dart @@ -84,7 +84,7 @@ class ResponseWrapperGenerator { (response.bodyCount > 1 || response.hasHeaders)) { final responseClassName = nameManager.responseNames(response.resolved).baseName; - + bodyField = Field( (b) => b diff --git a/packages/tonik_generate/lib/src/server/server_file_generator.dart b/packages/tonik_generate/lib/src/server/server_file_generator.dart index fcaefd8..488c832 100644 --- a/packages/tonik_generate/lib/src/server/server_file_generator.dart +++ b/packages/tonik_generate/lib/src/server/server_file_generator.dart @@ -40,4 +40,4 @@ class ServerFileGenerator { final filePath = path.join(serverDirPath, result.filename); File(filePath).writeAsStringSync(result.code); } -} +} diff --git a/packages/tonik_generate/lib/src/util/doc_comment_formatter.dart b/packages/tonik_generate/lib/src/util/doc_comment_formatter.dart index 55e774d..c3860aa 100644 --- a/packages/tonik_generate/lib/src/util/doc_comment_formatter.dart +++ b/packages/tonik_generate/lib/src/util/doc_comment_formatter.dart @@ -1,18 +1,18 @@ /// Formats a single string as a doc comment. -/// +/// /// If the string is multiline, each line will be prefixed with '/// '. /// Returns an empty list if the input is null or empty. List formatDocComment(String? text) { if (text == null || text.isEmpty) { return []; } - + // Split by newlines and prefix each line with '/// ' return text.split('\n').map((line) => '/// $line').toList(); } /// Formats a list of strings as doc comments. -/// +/// /// Each string in the list is processed with [formatDocComment], /// and the results are flattened into a single list. /// Null and empty strings are filtered out. @@ -23,12 +23,12 @@ List formatDocComments(List? texts) { } final result = []; - + for (final text in texts) { if (text != null && text.isNotEmpty) { result.addAll(formatDocComment(text)); } } - + return result; -} +} diff --git a/packages/tonik_generate/lib/src/util/exception_code_generator.dart b/packages/tonik_generate/lib/src/util/exception_code_generator.dart index 5580b9d..ec738fb 100644 --- a/packages/tonik_generate/lib/src/util/exception_code_generator.dart +++ b/packages/tonik_generate/lib/src/util/exception_code_generator.dart @@ -1,7 +1,5 @@ import 'package:code_builder/code_builder.dart'; - - /// Generates a throw expression for ArgumentError. Expression generateArgumentErrorExpression(String message) { return _generateExceptionExpression('ArgumentError', message); diff --git a/packages/tonik_generate/lib/src/util/format_with_header.dart b/packages/tonik_generate/lib/src/util/format_with_header.dart index 6a51ab5..d6f305d 100644 --- a/packages/tonik_generate/lib/src/util/format_with_header.dart +++ b/packages/tonik_generate/lib/src/util/format_with_header.dart @@ -1,19 +1,10 @@ import 'package:dart_style/dart_style.dart'; extension FormatWithHeader on DartFormatter { - static const _ignores = [ - 'lines_longer_than_80_chars', - 'unnecessary_raw_strings', - 'unnecessary_brace_in_string_interps', - 'no_leading_underscores_for_local_identifiers', - 'cascade_invocations', - 'prefer_is_empty', - ]; - String formatWithHeader(String code) { return format(''' // Generated code - do not modify by hand -${_ignores.map((i) => '// ignore_for_file: $i').join('\n')} + $code'''); } } diff --git a/packages/tonik_generate/lib/src/util/hash_code_generator.dart b/packages/tonik_generate/lib/src/util/hash_code_generator.dart index e882b22..be1d733 100644 --- a/packages/tonik_generate/lib/src/util/hash_code_generator.dart +++ b/packages/tonik_generate/lib/src/util/hash_code_generator.dart @@ -80,7 +80,7 @@ Method generateHashCodeMethod({ refer( 'Object', 'dart:core', - ).property('hash').call(hashArgs, {}, []).returned.statement, + ).property('hashAll').call([literalList(hashArgs)]).returned.statement, ); } diff --git a/packages/tonik_generate/lib/src/util/response_property_normalizer.dart b/packages/tonik_generate/lib/src/util/response_property_normalizer.dart index 1b9c137..ea7ef4c 100644 --- a/packages/tonik_generate/lib/src/util/response_property_normalizer.dart +++ b/packages/tonik_generate/lib/src/util/response_property_normalizer.dart @@ -7,7 +7,6 @@ List<({String normalizedName, Property property, ResponseHeader? header})> normalizeResponseProperties(ResponseObject response) { final headerMap = {}; - final headerProperties = response.headers.entries.map((header) { final property = Property( name: diff --git a/packages/tonik_generate/lib/src/util/response_type_generator.dart b/packages/tonik_generate/lib/src/util/response_type_generator.dart index 4666e0f..281898e 100644 --- a/packages/tonik_generate/lib/src/util/response_type_generator.dart +++ b/packages/tonik_generate/lib/src/util/response_type_generator.dart @@ -4,7 +4,7 @@ import 'package:tonik_core/tonik_core.dart'; import 'package:tonik_generate/src/naming/name_manager.dart'; import 'package:tonik_generate/src/util/type_reference_generator.dart'; -/// Generates the appropriate return type for an operation +/// Generates the appropriate return type for an operation /// based on its responses. TypeReference resultTypeForOperation( Operation operation, @@ -63,4 +63,4 @@ TypeReference resultTypeForOperation( ), ), }; -} +} diff --git a/packages/tonik_generate/lib/src/util/to_json_value_expression_generator.dart b/packages/tonik_generate/lib/src/util/to_json_value_expression_generator.dart index eaf0927..7d0a55d 100644 --- a/packages/tonik_generate/lib/src/util/to_json_value_expression_generator.dart +++ b/packages/tonik_generate/lib/src/util/to_json_value_expression_generator.dart @@ -47,8 +47,9 @@ String? _getSerializationSuffix(Model model, bool isNullable) { isNullable || (model is EnumModel && model.isNullable) ? '?' : ''; return switch (model) { - DateTimeModel() || DateModel() => '$nullablePart.toIso8601String()', + DateTimeModel() => '$nullablePart.toIso8601String()', DecimalModel() => '$nullablePart.toString()', + DateModel() || EnumModel() || ClassModel() || AllOfModel() || diff --git a/packages/tonik_generate/lib/src/util/type_reference_generator.dart b/packages/tonik_generate/lib/src/util/type_reference_generator.dart index 9be2bb4..63d6e85 100644 --- a/packages/tonik_generate/lib/src/util/type_reference_generator.dart +++ b/packages/tonik_generate/lib/src/util/type_reference_generator.dart @@ -71,8 +71,8 @@ TypeReference typeReference( DateModel _ => TypeReference( (b) => b - ..symbol = 'DateTime' - ..url = 'dart:core' + ..symbol = 'Date' + ..url = 'package:tonik_util/tonik_util.dart' ..isNullable = isNullableOverride, ), DecimalModel _ => TypeReference( @@ -87,8 +87,7 @@ TypeReference typeReference( b ..symbol = nameManager.modelName(m) ..url = package - ..isNullable = - isNullableOverride, + ..isNullable = isNullableOverride, ), }; } diff --git a/packages/tonik_generate/pubspec.yaml b/packages/tonik_generate/pubspec.yaml index 0ab9a31..ef81ba1 100644 --- a/packages/tonik_generate/pubspec.yaml +++ b/packages/tonik_generate/pubspec.yaml @@ -1,6 +1,6 @@ name: tonik_generate description: A code generation package for Tonik. -version: 0.0.5 +version: 0.0.6 repository: https://github.com/t-unit/tonik resolution: workspace @@ -16,8 +16,7 @@ dependencies: meta: ^1.16.0 path: ^1.9.1 spell_out_numbers: ^1.0.0 - tonik_core: ^0.0.5 + tonik_core: ^0.0.6 dev_dependencies: test: ^1.24.0 - very_good_analysis: ^8.0.0 diff --git a/packages/tonik_generate/test/src/api_client/api_client_file_generator_test.dart b/packages/tonik_generate/test/src/api_client/api_client_file_generator_test.dart index 7d69fed..379f41d 100644 --- a/packages/tonik_generate/test/src/api_client/api_client_file_generator_test.dart +++ b/packages/tonik_generate/test/src/api_client/api_client_file_generator_test.dart @@ -215,7 +215,7 @@ void main() { // Read the generated file to verify it contains the operation final fileContent = File(clientDir.listSync().first.path).readAsStringSync(); - + expect(fileContent, contains('untaggedOperation')); expect(fileContent, contains('class DefaultApi')); }); diff --git a/packages/tonik_generate/test/src/model/all_of_generator_test.dart b/packages/tonik_generate/test/src/model/all_of_generator_test.dart index 4c9030e..1a67894 100644 --- a/packages/tonik_generate/test/src/model/all_of_generator_test.dart +++ b/packages/tonik_generate/test/src/model/all_of_generator_test.dart @@ -327,7 +327,7 @@ void main() { const expectedHashCode = ''' @override int get hashCode { - return Object.hash(base, mixin); + return Object.hashAll([base, mixin]); } '''; @@ -472,7 +472,7 @@ void main() { const expectedHashCode = ''' @override int get hashCode { - return Object.hash(status, string); + return Object.hashAll([status, string]); } '''; @@ -501,14 +501,14 @@ void main() { expect(combinedClass.fields, hasLength(2)); expect( combinedClass.fields.map((f) => f.name), - containsAll(['dateTime', 'string']), + containsAll(['date', 'string']), ); // Check field types final dateField = combinedClass.fields.firstWhere( - (f) => f.name == 'dateTime', + (f) => f.name == 'date', ); - expect(dateField.type?.accept(emitter).toString(), 'DateTime'); + expect(dateField.type?.accept(emitter).toString(), 'Date'); final stringField = combinedClass.fields.firstWhere( (f) => f.name == 'string', @@ -517,7 +517,7 @@ void main() { // Check toJson - should return the ISO string const expectedToJson = ''' - Object? toJson() => dateTime.toIso8601String(); + Object? toJson() => date.toJson(); '''; expect( @@ -529,7 +529,7 @@ void main() { const expectedFromJson = ''' factory DateStringModel.fromJson(Object? json) { return DateStringModel( - dateTime: json.decodeJsonDate(context: r'DateStringModel'), + date: json.decodeJsonDate(context: r'DateStringModel'), string: json.decodeJsonString(context: r'DateStringModel'), ); } diff --git a/packages/tonik_generate/test/src/model/class_hash_code_generator_test.dart b/packages/tonik_generate/test/src/model/class_hash_code_generator_test.dart index f3ba80b..588fda2 100644 --- a/packages/tonik_generate/test/src/model/class_hash_code_generator_test.dart +++ b/packages/tonik_generate/test/src/model/class_hash_code_generator_test.dart @@ -54,7 +54,7 @@ void main() { const expectedMethod = ''' @override - int get hashCode { return Object.hash(name, age); } + int get hashCode { return Object.hashAll([name, age]); } '''; final generatedClass = generator.generateClass(model); @@ -102,7 +102,7 @@ void main() { const expectedMethod = ''' @override - int get hashCode { return Object.hash(id, name, email, age); } + int get hashCode { return Object.hashAll([id, name, email, age]); } '''; final generatedClass = generator.generateClass(model); @@ -136,7 +136,7 @@ void main() { const expectedMethod = ''' @override - int get hashCode { return Object.hash(name, bio); } + int get hashCode { return Object.hashAll([name, bio]); } '''; final generatedClass = generator.generateClass(model); @@ -170,7 +170,7 @@ void main() { const expectedMethod = ''' @override - int get hashCode { return Object.hash(firstName, lastName); } + int get hashCode { return Object.hashAll([firstName, lastName]); } '''; final generatedClass = generator.generateClass(model); @@ -209,7 +209,7 @@ void main() { @override int get hashCode { const deepEquals = DeepCollectionEquality(); - return Object.hash(name, deepEquals.hash(tags)); + return Object.hashAll([name, deepEquals.hash(tags)]); } '''; @@ -252,7 +252,7 @@ void main() { @override int get hashCode { const deepEquals = DeepCollectionEquality(); - return Object.hash(name, deepEquals.hash(nestedList)); + return Object.hashAll([name, deepEquals.hash(nestedList)]); } '''; diff --git a/packages/tonik_generate/test/src/model/class_json_generator_test.dart b/packages/tonik_generate/test/src/model/class_json_generator_test.dart index 2b391bb..7fb5505 100644 --- a/packages/tonik_generate/test/src/model/class_json_generator_test.dart +++ b/packages/tonik_generate/test/src/model/class_json_generator_test.dart @@ -597,5 +597,43 @@ void main() { contains(collapseWhitespace(expectedMethod)), ); }); + + test('generates fromJson method for class without properties', () { + final model = ClassModel( + context: context, + name: 'EmptyClass', + properties: const [], + ); + + const expectedMethod = ''' + factory EmptyClass.fromJson(Object? json) { + return EmptyClass(); + }'''; + + final generatedClass = generator.generateClass(model); + expect( + collapseWhitespace(format(generatedClass.accept(emitter).toString())), + contains(collapseWhitespace(expectedMethod)), + ); + }); + + test('generates fromSimple method for class without properties', () { + final model = ClassModel( + context: context, + name: 'EmptyClass', + properties: const [], + ); + + const expectedMethod = ''' + factory EmptyClass.fromSimple(String? value) { + return EmptyClass(); + }'''; + + final generatedClass = generator.generateClass(model); + expect( + collapseWhitespace(format(generatedClass.accept(emitter).toString())), + contains(collapseWhitespace(expectedMethod)), + ); + }); }); } diff --git a/packages/tonik_generate/test/src/model/class_simple_generator_test.dart b/packages/tonik_generate/test/src/model/class_simple_generator_test.dart index 420155c..8189a6a 100644 --- a/packages/tonik_generate/test/src/model/class_simple_generator_test.dart +++ b/packages/tonik_generate/test/src/model/class_simple_generator_test.dart @@ -232,7 +232,7 @@ void main() { ); } '''; - + expect( collapseWhitespace(classCode), contains(collapseWhitespace(expectedMethod)), @@ -355,7 +355,7 @@ void main() { ); } '''; - + expect( collapseWhitespace(classCode), contains(collapseWhitespace(expectedMethod)), diff --git a/packages/tonik_generate/test/src/model/typedef_generator_test.dart b/packages/tonik_generate/test/src/model/typedef_generator_test.dart index fe4f88c..4d9d270 100644 --- a/packages/tonik_generate/test/src/model/typedef_generator_test.dart +++ b/packages/tonik_generate/test/src/model/typedef_generator_test.dart @@ -113,7 +113,7 @@ void main() { (model: NumberModel(context: context), expectedType: 'num'), (model: BooleanModel(context: context), expectedType: 'bool'), (model: DateTimeModel(context: context), expectedType: 'DateTime'), - (model: DateModel(context: context), expectedType: 'DateTime'), + (model: DateModel(context: context), expectedType: 'Date'), (model: DecimalModel(context: context), expectedType: 'BigDecimal'), ]; diff --git a/packages/tonik_generate/test/src/naming/name_generator_test.dart b/packages/tonik_generate/test/src/naming/name_generator_test.dart index b2c3858..8e2e473 100644 --- a/packages/tonik_generate/test/src/naming/name_generator_test.dart +++ b/packages/tonik_generate/test/src/naming/name_generator_test.dart @@ -1086,7 +1086,10 @@ void main() { final generator = NameGenerator(); final servers = [ const Server(url: 'https://api.dev.example.com', description: null), - const Server(url: 'https://api.staging.example.com', description: null), + const Server( + url: 'https://api.staging.example.com', + description: null, + ), const Server(url: 'https://api.prod.example.com', description: null), ]; @@ -1178,7 +1181,8 @@ void main() { expect(result.serverMap[servers[0]], 'CustomServer'); expect(result.customName, r'CustomServer$'); expect(result.baseName, 'ApiServer'); - }); + }, + ); test('uses default names on invalid URLs', () { final generator = NameGenerator(); diff --git a/packages/tonik_generate/test/src/naming/name_manager_test.dart b/packages/tonik_generate/test/src/naming/name_manager_test.dart index 4102156..2eb923e 100644 --- a/packages/tonik_generate/test/src/naming/name_manager_test.dart +++ b/packages/tonik_generate/test/src/naming/name_manager_test.dart @@ -599,6 +599,70 @@ void main() { expect(baseName2, baseName); expect(identical(implementationNames, implementationNames2), isTrue); }); + + group('model naming behavior', () { + late Context userContext; + + setUp(() { + userContext = Context.initial().pushAll([ + 'components', + 'schemas', + 'user', + ]); + }); + + test( + 'named model keeps original name and anonymous model gets Model suffix', + () { + final models = [ + ClassModel( + name: 'User', + properties: const [], + context: userContext, + ), + ClassModel(properties: const [], context: userContext), + ]; + + manager.prime( + models: models, + responses: const [], + operations: const [], + tags: const [], + requestBodies: const [], + servers: const [], + ); + + expect(manager.modelName(models[0]), 'User'); + expect(manager.modelName(models[1]), 'UserModel'); + }, + ); + + test( + 'named model takes precedence over anonymous model with same context', + () { + final models = [ + ClassModel(properties: const [], context: userContext), + ClassModel( + name: 'User', + properties: const [], + context: userContext, + ), + ]; + + manager.prime( + models: models, + responses: const [], + operations: const [], + tags: const [], + requestBodies: const [], + servers: const [], + ); + + expect(manager.modelName(models[0]), 'UserModel'); + expect(manager.modelName(models[1]), 'User'); + }, + ); + }); }); group('Server names with list-based caching', () { @@ -626,10 +690,10 @@ void main() { const Server(url: 'https://staging.example.com', description: null), const Server(url: 'https://dev.example.com', description: null), ]; - + // Identity should be different but content equal expect(identical(servers, identicalContentServers), isFalse); - + // Second call with different list but same content should use cache final result2 = manager.serverNames(identicalContentServers); @@ -637,18 +701,18 @@ void main() { expect(result1.serverMap.length, result2.serverMap.length); expect(result1.baseName, result2.baseName); expect(result1.customName, result2.customName); - + // The cache should only have one entry despite using two different lists expect(manager.serverNamesCache.length, 1); - + // Check that corresponding servers in each list have the same names for (var i = 0; i < servers.length; i++) { final server1 = servers[i]; final server2 = identicalContentServers[i]; - + final name1 = result1.serverMap[server1]; final name2 = result2.serverMap[server2]; - + expect(name1, name2); } }); @@ -674,28 +738,28 @@ void main() { // Verify the server names are cached expect(manager.serverNamesCache.length, 1); - + // Verify the cache contains the correct key expect(manager.serverNamesCache.containsKey(cacheKey), isTrue); - + // Get the cached result final cachedResult = manager.serverNamesCache[cacheKey]!; - + // Verify the cached result has correct server map size expect(cachedResult.serverMap.length, 2); - + // Check that the servers are properly mapped to their expected names for (final server in servers) { final name = cachedResult.serverMap[server]; expect(name != null, isTrue); - + if (server.url == 'https://api.example.com') { expect(name!.startsWith('Api'), isTrue); } else if (server.url == 'https://staging.example.com') { expect(name!.startsWith('Staging'), isTrue); } } - + // Verify custom name exists expect(cachedResult.customName.contains('Custom'), isTrue); }); diff --git a/packages/tonik_generate/test/src/operation/data_generator_test.dart b/packages/tonik_generate/test/src/operation/data_generator_test.dart index 284bfd5..66c8e16 100644 --- a/packages/tonik_generate/test/src/operation/data_generator_test.dart +++ b/packages/tonik_generate/test/src/operation/data_generator_test.dart @@ -239,8 +239,8 @@ void main() { ); const expectedMethod = ''' - Object? _data({required DateTime? body}) { - return body?.toIso8601String(); + Object? _data({required Date? body}) { + return body?.toJson(); } '''; diff --git a/packages/tonik_generate/test/src/operation/operation_generator_response_test.dart b/packages/tonik_generate/test/src/operation/operation_generator_response_test.dart index e9eba7b..b3b8c0b 100644 --- a/packages/tonik_generate/test/src/operation/operation_generator_response_test.dart +++ b/packages/tonik_generate/test/src/operation/operation_generator_response_test.dart @@ -169,49 +169,47 @@ void main() { ); }); - test( - 'returns result with model for single status code with body only', - () { - final operation = Operation( - operationId: 'bodyStatus', - context: context, - summary: '', - description: '', - tags: const {}, - isDeprecated: false, - path: '/body', - method: HttpMethod.get, - headers: const {}, - queryParameters: const {}, - pathParameters: const {}, - requestBody: null, - responses: { - const ExplicitResponseStatus(statusCode: 200): ResponseObject( - name: 'BodyResponse', - context: context, - headers: const {}, - description: '', - bodies: { - ResponseBody( - model: StringModel(context: context), - rawContentType: 'application/json', - contentType: ContentType.json, - ), - }, - ), - }, - ); - const normalizedParams = NormalizedRequestParameters( - pathParameters: [], - queryParameters: [], - headers: [], - ); - final method = generator.generateCallMethod( - operation, - normalizedParams, - ); - expect( - method.returns?.accept(emitter).toString(), + test('returns result with model for single status code with body only', () { + final operation = Operation( + operationId: 'bodyStatus', + context: context, + summary: '', + description: '', + tags: const {}, + isDeprecated: false, + path: '/body', + method: HttpMethod.get, + headers: const {}, + queryParameters: const {}, + pathParameters: const {}, + requestBody: null, + responses: { + const ExplicitResponseStatus(statusCode: 200): ResponseObject( + name: 'BodyResponse', + context: context, + headers: const {}, + description: '', + bodies: { + ResponseBody( + model: StringModel(context: context), + rawContentType: 'application/json', + contentType: ContentType.json, + ), + }, + ), + }, + ); + const normalizedParams = NormalizedRequestParameters( + pathParameters: [], + queryParameters: [], + headers: [], + ); + final method = generator.generateCallMethod( + operation, + normalizedParams, + ); + expect( + method.returns?.accept(emitter).toString(), 'Future>', ); }); diff --git a/packages/tonik_generate/test/src/response/response_class_generator_test.dart b/packages/tonik_generate/test/src/response/response_class_generator_test.dart index ca46a52..ae48ec6 100644 --- a/packages/tonik_generate/test/src/response/response_class_generator_test.dart +++ b/packages/tonik_generate/test/src/response/response_class_generator_test.dart @@ -311,7 +311,7 @@ void main() { const expectedMethod = ''' @override int get hashCode { - return Object.hash(xTest, body); + return Object.hashAll([xTest, body]); } '''; @@ -361,7 +361,7 @@ void main() { const expectedMethod = ''' @override int get hashCode { - return Object.hash(xTest, body, xOther); + return Object.hashAll([xTest, body, xOther]); } '''; @@ -406,7 +406,7 @@ void main() { @override int get hashCode { const deepEquals = DeepCollectionEquality(); - return Object.hash(deepEquals.hash(xList), body); + return Object.hashAll([deepEquals.hash(xList), body]); } '''; diff --git a/packages/tonik_generate/test/src/server/server_file_generator_test.dart b/packages/tonik_generate/test/src/server/server_file_generator_test.dart index 8b1b600..580bd63 100644 --- a/packages/tonik_generate/test/src/server/server_file_generator_test.dart +++ b/packages/tonik_generate/test/src/server/server_file_generator_test.dart @@ -100,17 +100,17 @@ void main() { final serverDir = Directory( path.join(tempDir.path, 'test_package', 'lib', 'src', 'server'), ); - + expect(serverDir.listSync(), hasLength(1)); - + // Get file name and content final generatedFile = serverDir.listSync().first; final actualFileName = path.basename(generatedFile.path); final fileContent = File(generatedFile.path).readAsStringSync(); - + // Check file name expect(actualFileName, equals('api_server.dart')); - + // Check file content expect(fileContent, contains('sealed class ApiServer')); expect(fileContent, contains('class ProductionServer')); @@ -128,7 +128,7 @@ void main() { models: {}, responseHeaders: {}, requestHeaders: {}, - servers: {}, // Empty servers collection + servers: {}, // Empty servers collection operations: {}, responses: {}, queryParameters: {}, @@ -148,17 +148,17 @@ void main() { ); expect(serverDir.existsSync(), isTrue); expect(serverDir.listSync(), hasLength(1)); - + // Get file content final generatedFile = serverDir.listSync().first; final fileContent = File(generatedFile.path).readAsStringSync(); - + // Expect base class and custom class to be generated expect(fileContent, contains('sealed class ApiServer')); expect(fileContent, contains('class CustomServer')); - + // No server-specific classes should be present expect(fileContent.split('class').length, 3); }); }); -} +} diff --git a/packages/tonik_generate/test/src/server/server_generator_test.dart b/packages/tonik_generate/test/src/server/server_generator_test.dart index 77c768c..8f32742 100644 --- a/packages/tonik_generate/test/src/server/server_generator_test.dart +++ b/packages/tonik_generate/test/src/server/server_generator_test.dart @@ -65,7 +65,7 @@ void main() { test('generates constructor with named parameters', () { final constructor = baseClass.constructors.first; - // Constructor should not be const since _dio is not final + // Constructor should not be const since _dio is not final // and initialized later expect(constructor.constant, isFalse); expect(constructor.optionalParameters.length, 2); @@ -121,7 +121,7 @@ void main() { final productionClass = generatedClasses[1]; final productionConstructor = productionClass.constructors.first; - // Constructor should not be const since base class + // Constructor should not be const since base class // constructor isn't const expect(productionConstructor.constant, isFalse); expect(productionConstructor.optionalParameters.length, 1); @@ -155,7 +155,7 @@ void main() { final stagingClass = generatedClasses[2]; final stagingConstructor = stagingClass.constructors.first; - // Constructor should not be const since base class constructor + // Constructor should not be const since base class constructor // isn't const expect(stagingConstructor.constant, isFalse); expect(stagingConstructor.optionalParameters.length, 1); @@ -191,7 +191,7 @@ void main() { final customClass = generatedClasses.last; final customConstructor = customClass.constructors.first; - // Constructor should not be const since base class constructor + // Constructor should not be const since base class constructor // isn't const expect(customConstructor.constant, isFalse); expect(customConstructor.optionalParameters.length, 2); diff --git a/packages/tonik_generate/test/src/util/doc_comment_formatter_test.dart b/packages/tonik_generate/test/src/util/doc_comment_formatter_test.dart index bc9d990..8f7452b 100644 --- a/packages/tonik_generate/test/src/util/doc_comment_formatter_test.dart +++ b/packages/tonik_generate/test/src/util/doc_comment_formatter_test.dart @@ -5,7 +5,7 @@ void main() { group('doc comment formatter', () { test('formats a single line string', () { final result = formatDocComment('This is a doc comment'); - + expect(result, isNotEmpty); expect(result.length, 1); expect(result.first, '/// This is a doc comment'); @@ -15,7 +15,7 @@ void main() { final result = formatDocComment( 'This is a multiline\ndoc comment\nwith three lines', ); - + expect(result, isNotEmpty); expect(result.length, 3); expect(result[0], '/// This is a multiline'); @@ -25,13 +25,13 @@ void main() { test('returns empty list for null string', () { final result = formatDocComment(null); - + expect(result, isEmpty); }); test('returns empty list for empty string', () { final result = formatDocComment(''); - + expect(result, isEmpty); }); @@ -43,7 +43,7 @@ void main() { '', 'Last line', ]); - + expect(result, isNotEmpty); expect(result.length, 3); expect(result[0], '/// First line'); @@ -53,19 +53,19 @@ void main() { test('returns empty list for null list', () { final result = formatDocComments(null); - + expect(result, isEmpty); }); test('returns empty list for empty list', () { final result = formatDocComments([]); - + expect(result, isEmpty); }); test('returns empty list for list of nulls and empty strings', () { final result = formatDocComments([null, '', null]); - + expect(result, isEmpty); }); @@ -74,7 +74,7 @@ void main() { 'First\nMultiline', 'Second', ]); - + expect(result, isNotEmpty); expect(result.length, 3); expect(result[0], '/// First'); @@ -82,4 +82,4 @@ void main() { expect(result[2], '/// Second'); }); }); -} +} diff --git a/packages/tonik_generate/test/src/util/from_json_value_expression_generator_test.dart b/packages/tonik_generate/test/src/util/from_json_value_expression_generator_test.dart index 4fab605..ee76425 100644 --- a/packages/tonik_generate/test/src/util/from_json_value_expression_generator_test.dart +++ b/packages/tonik_generate/test/src/util/from_json_value_expression_generator_test.dart @@ -514,14 +514,15 @@ void main() { context: context, ); - final expresion = buildFromJsonValueExpression( - 'value', - model: nestedListModel, - nameManager: nameManager, - package: 'package:my_package/my_package.dart', - contextClass: 'Order', - contextProperty: 'items', - ).accept(emitter).toString(); + final expresion = + buildFromJsonValueExpression( + 'value', + model: nestedListModel, + nameManager: nameManager, + package: 'package:my_package/my_package.dart', + contextClass: 'Order', + contextProperty: 'items', + ).accept(emitter).toString(); expect( expresion, diff --git a/packages/tonik_generate/test/src/util/from_simple_value_expression_generator_test.dart b/packages/tonik_generate/test/src/util/from_simple_value_expression_generator_test.dart index 9aea25b..244a69a 100644 --- a/packages/tonik_generate/test/src/util/from_simple_value_expression_generator_test.dart +++ b/packages/tonik_generate/test/src/util/from_simple_value_expression_generator_test.dart @@ -296,7 +296,7 @@ void main() { test('passes context parameter to decode methods when provided', () { final value = refer('value'); - + expect( buildSimpleValueExpression( value, diff --git a/packages/tonik_generate/test/src/util/hash_code_generator_test.dart b/packages/tonik_generate/test/src/util/hash_code_generator_test.dart index ade3fbd..1f773a8 100644 --- a/packages/tonik_generate/test/src/util/hash_code_generator_test.dart +++ b/packages/tonik_generate/test/src/util/hash_code_generator_test.dart @@ -95,7 +95,58 @@ void main() { @override int get hashCode { const deepEquals = DeepCollectionEquality(); - return Object.hash(id, deepEquals.hash(items), name); + return Object.hashAll([id, deepEquals.hash(items), name]); + } + '''; + + expect( + collapseWhitespace(formatMethod(method)), + contains(collapseWhitespace(expectedMethod)), + ); + }); + + test('generates hash code method for class with many properties', () { + final method = generateHashCodeMethod( + properties: List.generate( + 25, + (i) => ( + normalizedName: 'prop$i', + hasCollectionValue: i.isEven, + ), + ), + ); + + const expectedMethod = ''' + @override + int get hashCode { + const deepEquals = DeepCollectionEquality(); + return Object.hashAll([ + deepEquals.hash(prop0), + prop1, + deepEquals.hash(prop2), + prop3, + deepEquals.hash(prop4), + prop5, + deepEquals.hash(prop6), + prop7, + deepEquals.hash(prop8), + prop9, + deepEquals.hash(prop10), + prop11, + deepEquals.hash(prop12), + prop13, + deepEquals.hash(prop14), + prop15, + deepEquals.hash(prop16), + prop17, + deepEquals.hash(prop18), + prop19, + deepEquals.hash(prop20), + prop21, + deepEquals.hash(prop22), + prop23, + deepEquals.hash(prop24), + ]); } '''; diff --git a/packages/tonik_generate/test/src/util/to_json_value_expression_generator_test.dart b/packages/tonik_generate/test/src/util/to_json_value_expression_generator_test.dart index 4f48260..f54b21a 100644 --- a/packages/tonik_generate/test/src/util/to_json_value_expression_generator_test.dart +++ b/packages/tonik_generate/test/src/util/to_json_value_expression_generator_test.dart @@ -67,7 +67,7 @@ void main() { ); expect( buildToJsonPropertyExpression('dueDate', property), - 'dueDate?.toIso8601String()', + 'dueDate?.toJson()', ); }); diff --git a/packages/tonik_parse/CHANGELOG.md b/packages/tonik_parse/CHANGELOG.md index ca6a9fc..85629aa 100644 --- a/packages/tonik_parse/CHANGELOG.md +++ b/packages/tonik_parse/CHANGELOG.md @@ -1,3 +1,5 @@ +## 0.0.6 + ## 0.0.5 ## 0.0.4 diff --git a/packages/tonik_parse/pubspec.yaml b/packages/tonik_parse/pubspec.yaml index 6f1e610..0dfe1a0 100644 --- a/packages/tonik_parse/pubspec.yaml +++ b/packages/tonik_parse/pubspec.yaml @@ -1,6 +1,6 @@ name: tonik_parse description: The parsing module for Tonik. -version: 0.0.5 +version: 0.0.6 repository: https://github.com/t-unit/tonik resolution: workspace @@ -11,10 +11,9 @@ dependencies: collection: ^1.19.1 json_annotation: ^4.9.0 logging: ^1.3.0 - tonik_core: ^0.0.5 + tonik_core: ^0.0.6 dev_dependencies: build_runner: ^2.3.3 json_serializable: ^6.8.0 test: ^1.24.0 - very_good_analysis: ^8.0.0 diff --git a/packages/tonik_util/CHANGELOG.md b/packages/tonik_util/CHANGELOG.md index b0c37af..8a18a94 100644 --- a/packages/tonik_util/CHANGELOG.md +++ b/packages/tonik_util/CHANGELOG.md @@ -1,3 +1,7 @@ +## 0.0.6 + + - **FIX**: proper handle dates. + ## 0.0.5 ## 0.0.4 diff --git a/packages/tonik_util/lib/src/date.dart b/packages/tonik_util/lib/src/date.dart index 0f94661..b422e3f 100644 --- a/packages/tonik_util/lib/src/date.dart +++ b/packages/tonik_util/lib/src/date.dart @@ -10,7 +10,7 @@ import 'package:tonik_util/src/decoding/simple_decoder.dart'; class Date { /// Creates a new [Date] instance. /// - /// Throws [RangeError] if any of the date components are invalid. + /// Throws [FormatException] if any of the date components are invalid. Date(this.year, this.month, this.day) { _validate(); } @@ -24,7 +24,8 @@ class Date { /// Creates a [Date] from an ISO 8601 formatted string (YYYY-MM-DD). /// - /// Throws [FormatException] if the string is not in the correct format. + /// Throws [FormatException] if the string is not in the correct format + /// or if any of the date components are invalid. factory Date.fromString(String dateString) { final parts = dateString.split('-'); if (parts.length != 3) { @@ -37,7 +38,7 @@ class Date { final day = int.parse(parts[2]); final date = Date(year, month, day).._validate(); return date; - } on FormatException { + } on Object { throw const FormatException('Invalid date format. Expected YYYY-MM-DD'); } } @@ -114,12 +115,17 @@ class Date { void _validate() { if (month < 1 || month > 12) { - throw RangeError.range(month, 1, 12, 'month'); + throw FormatException( + 'Invalid month: $month. Month must be between 1 and 12.', + ); } final daysInMonth = DateTime(year, month + 1, 0).day; if (day < 1 || day > daysInMonth) { - throw RangeError.range(day, 1, daysInMonth, 'day'); + throw FormatException( + 'Invalid day: $day. Day must be between 1 and $daysInMonth for ' + 'month $month.', + ); } } } diff --git a/packages/tonik_util/lib/src/decoding/json_decoder.dart b/packages/tonik_util/lib/src/decoding/json_decoder.dart index 4192acf..957f61d 100644 --- a/packages/tonik_util/lib/src/decoding/json_decoder.dart +++ b/packages/tonik_util/lib/src/decoding/json_decoder.dart @@ -1,4 +1,5 @@ import 'package:big_decimal/big_decimal.dart'; +import 'package:tonik_util/src/date.dart'; import 'package:tonik_util/src/decoding/decoding_exception.dart'; /// Extensions for decoding JSON values. @@ -348,4 +349,46 @@ extension JsonDecoder on Object? { } return this! as bool; } + + /// Decodes a JSON value to a Date. + /// + /// Expects ISO 8601 format string (YYYY-MM-DD). + /// Throws [InvalidTypeException] if the value is not a valid date string + /// or if the value is null. + Date decodeJsonDate({String? context}) { + if (this == null) { + throw InvalidTypeException( + value: 'null', + targetType: Date, + context: context, + ); + } + if (this is! String) { + throw InvalidTypeException( + value: toString(), + targetType: Date, + context: context, + ); + } + try { + return Date.fromString(this! as String); + } on FormatException catch (e) { + throw InvalidTypeException( + value: this! as String, + targetType: Date, + context: e.message, + ); + } + } + + /// Decodes a JSON value to a nullable Date. + /// + /// Returns null if the value is null or an empty string. + /// Throws [InvalidTypeException] if the value is not a valid date string. + Date? decodeJsonNullableDate({String? context}) { + if (this == null || (this is String && (this! as String).isEmpty)) { + return null; + } + return decodeJsonDate(context: context); + } } diff --git a/packages/tonik_util/lib/src/decoding/simple_decoder.dart b/packages/tonik_util/lib/src/decoding/simple_decoder.dart index c5f7957..9f7d9a8 100644 --- a/packages/tonik_util/lib/src/decoding/simple_decoder.dart +++ b/packages/tonik_util/lib/src/decoding/simple_decoder.dart @@ -1,4 +1,5 @@ import 'package:big_decimal/big_decimal.dart'; +import 'package:tonik_util/src/date.dart'; import 'package:tonik_util/src/decoding/decoding_exception.dart'; /// Extensions for decoding simple form values from strings. @@ -253,4 +254,49 @@ extension SimpleDecoder on String? { if (this?.isEmpty ?? true) return null; return decodeSimpleStringNullableList(context: context); } + + /// Decodes a string to a Date. + /// + /// The string must be in ISO 8601 format (YYYY-MM-DD). + /// Throws [FormatException] if the string is not in the correct format or if + /// any of the date components are invalid. + /// Throws [InvalidTypeException] if the value is null or empty. + Date decodeSimpleDate({String? context}) { + if (this == null) { + throw InvalidTypeException( + value: 'null', + targetType: Date, + context: context, + ); + } + if (this!.isEmpty) { + throw InvalidTypeException( + value: 'empty string', + targetType: Date, + context: context, + ); + } + try { + return Date.fromString(this!); + } on FormatException { + rethrow; + } on Object { + throw InvalidTypeException( + value: this!, + targetType: Date, + context: context, + ); + } + } + + /// Decodes a string to a nullable Date. + /// + /// Returns null if the string is empty or null. + /// The string must be in ISO 8601 format (YYYY-MM-DD). + /// Throws [FormatException] if the string is not in the correct format or if + /// any of the date components are invalid. + Date? decodeSimpleNullableDate({String? context}) { + if (this?.isEmpty ?? true) return null; + return decodeSimpleDate(context: context); + } } diff --git a/packages/tonik_util/lib/src/dio/server_config.dart b/packages/tonik_util/lib/src/dio/server_config.dart index f5fa6f4..8f4c48e 100644 --- a/packages/tonik_util/lib/src/dio/server_config.dart +++ b/packages/tonik_util/lib/src/dio/server_config.dart @@ -50,15 +50,15 @@ class ServerConfig { // Set the server URL dio.options.baseUrl = serverUrl; - + // Add all interceptors for (final interceptor in interceptors) { dio.interceptors.add(interceptor); } - + // Set httpClientAdapter if provided if (httpClientAdapter != null) { dio.httpClientAdapter = httpClientAdapter!; } } -} +} diff --git a/packages/tonik_util/pubspec.yaml b/packages/tonik_util/pubspec.yaml index 00b6106..2bccc0a 100644 --- a/packages/tonik_util/pubspec.yaml +++ b/packages/tonik_util/pubspec.yaml @@ -1,6 +1,6 @@ name: tonik_util description: Runtime tools for packages generated by Tonik. -version: 0.0.5 +version: 0.0.6 repository: https://github.com/t-unit/tonik resolution: workspace @@ -15,4 +15,3 @@ dependencies: dev_dependencies: test: ^1.24.0 - very_good_analysis: ^8.0.0 diff --git a/packages/tonik_util/test/src/date_test.dart b/packages/tonik_util/test/src/date_test.dart index 98c3be7..25ce1b3 100644 --- a/packages/tonik_util/test/src/date_test.dart +++ b/packages/tonik_util/test/src/date_test.dart @@ -98,13 +98,25 @@ void main() { }); test('fromJson throws on invalid date values', () { - expect(() => Date.fromJson('2024-00-15'), throwsA(isA())); - expect(() => Date.fromJson('2024-13-15'), throwsA(isA())); - expect(() => Date.fromJson('2024-03-00'), throwsA(isA())); - expect(() => Date.fromJson('2024-03-32'), throwsA(isA())); + expect( + () => Date.fromJson('2024-00-15'), + throwsA(isA()), + ); + expect( + () => Date.fromJson('2024-13-15'), + throwsA(isA()), + ); + expect( + () => Date.fromJson('2024-03-00'), + throwsA(isA()), + ); + expect( + () => Date.fromJson('2024-03-32'), + throwsA(isA()), + ); expect( () => Date.fromJson('2024-02-30'), - throwsA(isA()), + throwsA(isA()), ); // February 30th }); @@ -128,24 +140,36 @@ void main() { }); test('fromSimple throws on invalid date values', () { - expect(() => Date.fromSimple('2024-00-15'), throwsA(isA())); - expect(() => Date.fromSimple('2024-13-15'), throwsA(isA())); - expect(() => Date.fromSimple('2024-03-00'), throwsA(isA())); - expect(() => Date.fromSimple('2024-03-32'), throwsA(isA())); + expect( + () => Date.fromSimple('2024-00-15'), + throwsA(isA()), + ); + expect( + () => Date.fromSimple('2024-13-15'), + throwsA(isA()), + ); + expect( + () => Date.fromSimple('2024-03-00'), + throwsA(isA()), + ); + expect( + () => Date.fromSimple('2024-03-32'), + throwsA(isA()), + ); expect( () => Date.fromSimple('2024-02-30'), - throwsA(isA()), + throwsA(isA()), ); // February 30th }); test('validates date components', () { - expect(() => Date(2024, 0, 15), throwsA(isA())); - expect(() => Date(2024, 13, 15), throwsA(isA())); - expect(() => Date(2024, 3, 0), throwsA(isA())); - expect(() => Date(2024, 3, 32), throwsA(isA())); + expect(() => Date(2024, 0, 15), throwsA(isA())); + expect(() => Date(2024, 13, 15), throwsA(isA())); + expect(() => Date(2024, 3, 0), throwsA(isA())); + expect(() => Date(2024, 3, 32), throwsA(isA())); expect( () => Date(2024, 2, 30), - throwsA(isA()), + throwsA(isA()), ); // February 30th }); }); diff --git a/packages/tonik_util/test/src/decoding/json_decoder_test.dart b/packages/tonik_util/test/src/decoding/json_decoder_test.dart index f2cc630..1b21dc2 100644 --- a/packages/tonik_util/test/src/decoding/json_decoder_test.dart +++ b/packages/tonik_util/test/src/decoding/json_decoder_test.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:big_decimal/big_decimal.dart'; import 'package:test/test.dart'; +import 'package:tonik_util/src/date.dart'; import 'package:tonik_util/src/decoding/decoding_exception.dart'; import 'package:tonik_util/src/decoding/json_decoder.dart'; @@ -196,6 +197,72 @@ void main() { ); }); }); + + group('Date', () { + test('decodes Date values', () { + final date = Date(2024, 3, 15); + expect('2024-03-15'.decodeJsonDate(), date); + expect( + () => 123.decodeJsonDate(), + throwsA(isA()), + ); + expect( + () => null.decodeJsonDate(), + throwsA(isA()), + ); + expect( + () => '2024-00-15'.decodeJsonDate(), + throwsA(isA()), + ); + expect( + () => '2024-13-15'.decodeJsonDate(), + throwsA(isA()), + ); + expect( + () => '2024-03-00'.decodeJsonDate(), + throwsA(isA()), + ); + expect( + () => '2024-03-32'.decodeJsonDate(), + throwsA(isA()), + ); + expect( + () => '2024-02-30'.decodeJsonDate(), + throwsA(isA()), + ); + }); + + test('decodes nullable Date values', () { + final date = Date(2024, 3, 15); + expect('2024-03-15'.decodeJsonNullableDate(), date); + expect(null.decodeJsonNullableDate(), isNull); + expect(''.decodeJsonNullableDate(), isNull); + expect( + () => 123.decodeJsonNullableDate(), + throwsA(isA()), + ); + expect( + () => '2024-00-15'.decodeJsonNullableDate(), + throwsA(isA()), + ); + expect( + () => '2024-13-15'.decodeJsonNullableDate(), + throwsA(isA()), + ); + expect( + () => '2024-03-00'.decodeJsonNullableDate(), + throwsA(isA()), + ); + expect( + () => '2024-03-32'.decodeJsonNullableDate(), + throwsA(isA()), + ); + expect( + () => '2024-02-30'.decodeJsonNullableDate(), + throwsA(isA()), + ); + }); + }); }); group('List', () { diff --git a/packages/tonik_util/test/src/decoding/simple_decoder_test.dart b/packages/tonik_util/test/src/decoding/simple_decoder_test.dart index 85818cc..366b6a1 100644 --- a/packages/tonik_util/test/src/decoding/simple_decoder_test.dart +++ b/packages/tonik_util/test/src/decoding/simple_decoder_test.dart @@ -1,5 +1,6 @@ import 'package:big_decimal/big_decimal.dart'; import 'package:test/test.dart'; +import 'package:tonik_util/src/date.dart'; import 'package:tonik_util/src/decoding/decoding_exception.dart'; import 'package:tonik_util/src/decoding/simple_decoder.dart'; @@ -70,6 +71,39 @@ void main() { throwsA(isA()), ); }); + + test('decodes Date values', () { + final date = Date(2024, 3, 15); + expect('2024-03-15'.decodeSimpleDate(), date); + expect( + () => 'not-a-date'.decodeSimpleDate(), + throwsA(isA()), + ); + expect( + () => null.decodeSimpleDate(), + throwsA(isA()), + ); + expect( + () => '2024-00-15'.decodeSimpleDate(), + throwsA(isA()), + ); + expect( + () => '2024-13-15'.decodeSimpleDate(), + throwsA(isA()), + ); + expect( + () => '2024-03-00'.decodeSimpleDate(), + throwsA(isA()), + ); + expect( + () => '2024-03-32'.decodeSimpleDate(), + throwsA(isA()), + ); + expect( + () => '2024-02-30'.decodeSimpleDate(), + throwsA(isA()), + ); + }); }); group('Nullable Values', () { @@ -79,12 +113,14 @@ void main() { expect(''.decodeSimpleNullableBool(), isNull); expect(''.decodeSimpleNullableDateTime(), isNull); expect(''.decodeSimpleNullableBigDecimal(), isNull); + expect(''.decodeSimpleNullableDate(), isNull); expect(null.decodeSimpleNullableInt(), isNull); expect(null.decodeSimpleNullableDouble(), isNull); expect(null.decodeSimpleNullableBool(), isNull); expect(null.decodeSimpleNullableDateTime(), isNull); expect(null.decodeSimpleNullableBigDecimal(), isNull); + expect(null.decodeSimpleNullableDate(), isNull); }); test('decodes non-empty strings for nullable types', () { @@ -99,6 +135,10 @@ void main() { '3.14'.decodeSimpleNullableBigDecimal(), BigDecimal.parse('3.14'), ); + expect( + '2024-03-15'.decodeSimpleNullableDate(), + Date(2024, 3, 15), + ); }); }); @@ -124,6 +164,10 @@ void main() { () => ''.decodeSimpleBigDecimal(), throwsA(isA()), ); + expect( + () => ''.decodeSimpleDate(), + throwsA(isA()), + ); }); }); diff --git a/packages/tonik_util/test/src/encoder/deep_object_encoder_test.dart b/packages/tonik_util/test/src/encoder/deep_object_encoder_test.dart index 1182669..9bfd98b 100644 --- a/packages/tonik_util/test/src/encoder/deep_object_encoder_test.dart +++ b/packages/tonik_util/test/src/encoder/deep_object_encoder_test.dart @@ -7,10 +7,14 @@ void main() { group('DeepObjectEncoder', () { test('encodes a simple object', () { - final result = encoder.encode('filter', { - 'color': 'red', - 'size': 'large', - }, allowEmpty: true,); + final result = encoder.encode( + 'filter', + { + 'color': 'red', + 'size': 'large', + }, + allowEmpty: true, + ); expect(result, [ (name: 'filter[color]', value: 'red'), @@ -19,10 +23,14 @@ void main() { }); test('encodes boolean properties', () { - final result = encoder.encode('filter', { - 'active': true, - 'premium': false, - }, allowEmpty: true,); + final result = encoder.encode( + 'filter', + { + 'active': true, + 'premium': false, + }, + allowEmpty: true, + ); expect(result, [ (name: 'filter[active]', value: 'true'), @@ -31,10 +39,14 @@ void main() { }); test('encodes an object with a null value', () { - final result = encoder.encode('filter', { - 'color': null, - 'size': 'large', - }, allowEmpty: true,); + final result = encoder.encode( + 'filter', + { + 'color': null, + 'size': 'large', + }, + allowEmpty: true, + ); expect(result, [ (name: 'filter[color]', value: ''), @@ -53,9 +65,13 @@ void main() { }); test('encodes nested objects', () { - final result = encoder.encode('filter', { - 'product': {'color': 'blue', 'size': 'medium'}, - }, allowEmpty: true,); + final result = encoder.encode( + 'filter', + { + 'product': {'color': 'blue', 'size': 'medium'}, + }, + allowEmpty: true, + ); expect(result, [ (name: 'filter[product][color]', value: 'blue'), @@ -64,11 +80,15 @@ void main() { }); test('encodes deeply nested objects', () { - final result = encoder.encode('filter', { - 'product': { - 'attributes': {'color': 'blue', 'size': 'medium'}, + final result = encoder.encode( + 'filter', + { + 'product': { + 'attributes': {'color': 'blue', 'size': 'medium'}, + }, }, - }, allowEmpty: true,); + allowEmpty: true, + ); expect(result, [ (name: 'filter[product][attributes][color]', value: 'blue'), @@ -78,9 +98,13 @@ void main() { test('throws for objects containing arrays', () { expect( - () => encoder.encode('filter', { - 'colors': ['red', 'blue', 'green'], - }, allowEmpty: true,), + () => encoder.encode( + 'filter', + { + 'colors': ['red', 'blue', 'green'], + }, + allowEmpty: true, + ), throwsA(isA()), ); }); @@ -95,20 +119,28 @@ void main() { test('throws for objects containing sets', () { expect( - () => encoder.encode('filter', { - 'sizes': {'small', 'medium', 'large'}, - }, allowEmpty: true,), + () => encoder.encode( + 'filter', + { + 'sizes': {'small', 'medium', 'large'}, + }, + allowEmpty: true, + ), throwsA(isA()), ); }); test('encodes a complex object with various types', () { - final result = encoder.encode('params', { - 'name': 'John', - 'age': 30, - 'active': true, - 'address': {'street': '123 Main St', 'city': 'New York'}, - }, allowEmpty: true,); + final result = encoder.encode( + 'params', + { + 'name': 'John', + 'age': 30, + 'active': true, + 'address': {'street': '123 Main St', 'city': 'New York'}, + }, + allowEmpty: true, + ); expect(result, [ (name: 'params[name]', value: 'John'), @@ -180,11 +212,15 @@ void main() { group('allowEmpty parameter', () { test('allows empty values when allowEmpty is true', () { - final result = encoder.encode('filter', { - 'emptyString': '', - 'emptyMap': {}, - 'normalValue': 'test', - }, allowEmpty: true,); + final result = encoder.encode( + 'filter', + { + 'emptyString': '', + 'emptyMap': {}, + 'normalValue': 'test', + }, + allowEmpty: true, + ); expect(result, [ (name: 'filter[emptyString]', value: ''), @@ -195,10 +231,14 @@ void main() { test('throws when allowEmpty is false and value is empty string', () { expect( - () => encoder.encode('filter', { - 'emptyString': '', - 'normalValue': 'test', - }, allowEmpty: false,), + () => encoder.encode( + 'filter', + { + 'emptyString': '', + 'normalValue': 'test', + }, + allowEmpty: false, + ), throwsA(isA()), ); }); @@ -213,10 +253,14 @@ void main() { test('throws when allowEmpty is false and nested map is empty', () { expect( - () => encoder.encode('filter', { - 'nested': {}, - 'normalValue': 'test', - }, allowEmpty: false,), + () => encoder.encode( + 'filter', + { + 'nested': {}, + 'normalValue': 'test', + }, + allowEmpty: false, + ), throwsA(isA()), ); }); @@ -238,10 +282,14 @@ void main() { }); test('allows non-empty values when allowEmpty is false', () { - final result = encoder.encode('filter', { - 'string': 'value', - 'nested': {'inner': 'value'}, - }, allowEmpty: false,); + final result = encoder.encode( + 'filter', + { + 'string': 'value', + 'nested': {'inner': 'value'}, + }, + allowEmpty: false, + ); expect(result, [ (name: 'filter[string]', value: 'value'), diff --git a/pubspec.yaml b/pubspec.yaml index 403f4d7..9d59be4 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -26,7 +26,7 @@ dependencies: dev_dependencies: melos: ^7.0.0-dev.9 test: ^1.25.15 - very_good_analysis: ^8.0.0 + very_good_analysis: ^9.0.0 melos: scripts: