diff --git a/.editorconfig b/.editorconfig index 24e419b8..896594d1 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,227 +1,149 @@ -# Remove the line below if you want to inherit .editorconfig settings from higher directories +# Remove the line below if you want to inherit .editorconfig settings from higher directories. root = true -# C# files +[*] +end_of_line = lf +insert_final_newline = true + +[*.{cmd,ps1}] +end_of_line = crlf + [*.cs] -guidelines = 120, 140 +guidelines = 120 +max_line_length = 100 -#### Core EditorConfig Options #### +csharp_style_namespace_declarations = file_scoped +dotnet_code_quality.CA1062.null_check_validation_methods = Werecodent.CreateAndFake.Design.ArgumentGuard.ThrowIfNull -# Indentation and spacing -indent_size = 4 -indent_style = space -tab_width = 4 +#### Naming styles: #### -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### - -# Organize usings -dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = true - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:silent -dotnet_style_qualification_for_field = false:silent -dotnet_style_qualification_for_method = false:silent -dotnet_style_qualification_for_property = false:silent - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true:silent -dotnet_style_predefined_type_for_member_access = true:silent - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent - -# Expression-level preferences -csharp_style_deconstructed_variable_declaration = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion -csharp_style_throw_expression = true:suggestion -dotnet_style_coalesce_expression = true:suggestion -dotnet_style_collection_initializer = true:suggestion -dotnet_style_explicit_tuple_names = true:suggestion -dotnet_style_null_propagation = true:suggestion -dotnet_style_object_initializer = true:suggestion -dotnet_style_prefer_auto_properties = true:silent -dotnet_style_prefer_compound_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_assignment = true:silent -dotnet_style_prefer_conditional_expression_over_return = true:silent -dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion -dotnet_style_prefer_inferred_tuple_names = true:suggestion -dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion - -# Field preferences -dotnet_style_readonly_field = true:suggestion - -# Parameter preferences -dotnet_code_quality_unused_parameters = all:suggestion - -#### C# Coding Conventions #### - -# var preferences -csharp_style_var_elsewhere = false:silent -csharp_style_var_for_built_in_types = false:silent -csharp_style_var_when_type_is_apparent = false:silent - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:silent -csharp_style_expression_bodied_constructors = false:silent -csharp_style_expression_bodied_indexers = true:silent -csharp_style_expression_bodied_lambdas = true:silent -csharp_style_expression_bodied_local_functions = false:silent -csharp_style_expression_bodied_methods = false:silent -csharp_style_expression_bodied_operators = false:silent -csharp_style_expression_bodied_properties = true:silent - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true:suggestion -csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion -csharp_style_prefer_switch_expression = true:suggestion - -# Null-checking preferences -csharp_style_conditional_delegate_call = true:suggestion - -# Modifier preferences -csharp_prefer_static_local_function = true:suggestion -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async - -# Code-block preferences -csharp_prefer_braces = true:silent -csharp_prefer_simple_using_statement = true:suggestion - -# Expression-level preferences -csharp_prefer_simple_default_expression = true:suggestion -csharp_style_pattern_local_over_anonymous_function = true:suggestion -csharp_style_prefer_index_operator = true:suggestion -csharp_style_prefer_range_operator = true:suggestion -csharp_style_unused_value_assignment_preference = discard_variable:suggestion -csharp_style_unused_value_expression_statement_preference = discard_variable:silent - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace:silent - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = one_less_than_current -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.private_or_internal_static_field_should_be_begins_with__pascal.severity = warning -dotnet_naming_rule.private_or_internal_static_field_should_be_begins_with__pascal.symbols = private_or_internal_static_field -dotnet_naming_rule.private_or_internal_static_field_should_be_begins_with__pascal.style = begins_with__pascal - -dotnet_naming_rule.private_or_internal_field_should_be_begins_with__camel.severity = warning -dotnet_naming_rule.private_or_internal_field_should_be_begins_with__camel.symbols = private_or_internal_field -dotnet_naming_rule.private_or_internal_field_should_be_begins_with__camel.style = begins_with__camel - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field -dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private -dotnet_naming_symbols.private_or_internal_field.required_modifiers = - -dotnet_naming_symbols.private_or_internal_static_field.applicable_kinds = field -dotnet_naming_symbols.private_or_internal_static_field.applicable_accessibilities = internal, private -dotnet_naming_symbols.private_or_internal_static_field.required_modifiers = static - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case +# Define naming styles: +dotnet_naming_style.underscored_camel.required_prefix = _ +dotnet_naming_style.underscored_camel.capitalization = camel_case -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case +dotnet_naming_style.underscored_pascal.required_prefix = _ +dotnet_naming_style.underscored_pascal.capitalization = pascal_case -dotnet_naming_style.begins_with__camel.required_prefix = _ -dotnet_naming_style.begins_with__camel.required_suffix = -dotnet_naming_style.begins_with__camel.word_separator = -dotnet_naming_style.begins_with__camel.capitalization = camel_case +dotnet_naming_style.underscored_i.required_prefix = I +dotnet_naming_style.underscored_i.capitalization = pascal_case -dotnet_naming_style.begins_with__pascal.required_prefix = _ -dotnet_naming_style.begins_with__pascal.required_suffix = -dotnet_naming_style.begins_with__pascal.word_separator = -dotnet_naming_style.begins_with__pascal.capitalization = pascal_case +dotnet_naming_style.pascal_case.capitalization = pascal_case -csharp_style_namespace_declarations = file_scoped -dotnet_code_quality.CA1062.null_check_validation_methods = CreateAndFake.Design.ArgumentGuard.ThrowIfNull \ No newline at end of file +dotnet_naming_style.camel_case.capitalization = camel_case + +# Define symbol groups: +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private + +dotnet_naming_symbols.private_static_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private +dotnet_naming_symbols.private_static_fields.required_modifiers = static + +dotnet_naming_symbols.interfaces.applicable_kinds = interface + +dotnet_naming_symbols.structures.applicable_kinds = class, struct, interface, enum, property, event, method, type_parameter + +dotnet_naming_symbols.locals.applicable_kinds = parameters, local, local_function + +# Define naming rules: +dotnet_naming_rule.private_fields_prefix.symbols = private_fields +dotnet_naming_rule.private_fields_prefix.style = underscored_camel +dotnet_naming_rule.private_fields_prefix.severity = warning + +dotnet_naming_rule.private_static_fields_prefix.symbols = private_static_fields +dotnet_naming_rule.private_static_fields_prefix.style = underscored_pascal +dotnet_naming_rule.private_static_fields_prefix.severity = warning + +dotnet_naming_rule.interfaces_prefix.symbols = interfaces +dotnet_naming_rule.interfaces_prefix.style = begins_with_i +dotnet_naming_rule.interfaces_prefix.severity = warning + +dotnet_naming_rule.structures_casing.symbols = structures +dotnet_naming_rule.structures_casing.style = pascal_case +dotnet_naming_rule.structures_casing.severity = warning + +dotnet_naming_rule.locals_casing.symbols = locals +dotnet_naming_rule.locals_casing.style = camel_case +dotnet_naming_rule.locals_casing.severity = warning + +#### Analyzer Overrides #### + +dotnet_analyzer_diagnostic.severity = warning + +# Controlled by CSharpier. +dotnet_diagnostic.IDE0055.severity = None +dotnet_diagnostic.MA0051.severity = None + +# Bad warnings that can create bugs or are clearly intended behavior. +dotnet_diagnostic.CA1000.severity = None +dotnet_diagnostic.CA1040.severity = None +dotnet_diagnostic.MA0018.severity = None +dotnet_diagnostic.MA0130.severity = None +dotnet_diagnostic.MA0165.severity = None +dotnet_diagnostic.RCS1241.severity = None +dotnet_diagnostic.S1133.severity = None +dotnet_diagnostic.S1694.severity = None +dotnet_diagnostic.S1994.severity = None +dotnet_diagnostic.S3011.severity = None +dotnet_diagnostic.S3220.severity = None +dotnet_diagnostic.S3453.severity = None +dotnet_diagnostic.S3878.severity = None + +# Redundancy that's good for clarity. +dotnet_diagnostic.CA1805.severity = None +dotnet_diagnostic.RCS1033.severity = None +dotnet_diagnostic.RCS1034.severity = None +dotnet_diagnostic.RCS1071.severity = None +dotnet_diagnostic.RCS1129.severity = None +dotnet_diagnostic.RCS1188.severity = None +dotnet_diagnostic.S108.severity = None +dotnet_diagnostic.S1125.severity = None +dotnet_diagnostic.S1199.severity = None +dotnet_diagnostic.S3626.severity = None + +# Unnecessary overcaution against default behavior that hurts readability. +dotnet_diagnostic.IDE0045.severity = None +dotnet_diagnostic.IDE0046.severity = None +dotnet_diagnostic.IDE0048.severity = None +dotnet_diagnostic.MA0002.severity = None +dotnet_diagnostic.MA0003.severity = None +dotnet_diagnostic.MA0006.severity = None +dotnet_diagnostic.MA0076.severity = None +dotnet_diagnostic.MA0169.severity = None +dotnet_diagnostic.MA0219.severity = None +dotnet_diagnostic.RCS1089.severity = None +dotnet_diagnostic.RCS1123.severity = None +dotnet_diagnostic.S1751.severity = None +dotnet_diagnostic.S2743.severity = None +dotnet_diagnostic.S3993.severity = None + +# Design choice. +dotnet_diagnostic.MA0029.severity = None +dotnet_diagnostic.MA0071.severity = None +dotnet_diagnostic.RCS1112.severity = None +dotnet_diagnostic.RCS1211.severity = None +dotnet_diagnostic.S3267.severity = None + +# Unavoidable for handling anything thrown at the libary. +dotnet_diagnostic.CA1031.severity = None +dotnet_diagnostic.RCS1075.severity = None + +# Deprecated. +dotnet_diagnostic.MA0038.severity = None +dotnet_diagnostic.MA0041.severity = None + +# Not supported in all .NET versions. +dotnet_diagnostic.CA1865.severity = None +dotnet_diagnostic.CA2249.severity = None +dotnet_diagnostic.IDE0057.severity = None +dotnet_diagnostic.IDE0066.severity = None +dotnet_diagnostic.IDE0370.severity = None +dotnet_diagnostic.MA0001.severity = None +dotnet_diagnostic.MA0089.severity = None +dotnet_diagnostic.S8969.severity = None + +# Specifically for Visual Studio extensions and don't apply to this library. +dotnet_diagnostic.VSTHRD003.severity = None + +# False positive when calling tester methods. +dotnet_diagnostic.S2699.severity = None diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..1f43934a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +* text=auto eol=lf +*.cmd text eol=crlf +*.ps1 text eol=crlf diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md deleted file mode 100644 index 399e74cc..00000000 --- a/.github/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,132 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, caste, color, religion, or sexual -identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall - community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or advances of - any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, - without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official email address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -[createandfaketeam@gmail.com](mailto:createandfaketeam@gmail.com). -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of -actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent -ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the -community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.1, available at -[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. - -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. - -For answers to common questions about this code of conduct, see the FAQ at -[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at -[https://www.contributor-covenant.org/translations][translations]. - -[homepage]: https://www.contributor-covenant.org -[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index 7ca0bd9b..00000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,114 +0,0 @@ -# Contributing - -Thank you for your interest in contributing. - -Please first discuss the change you wish to make via issue/request, email, or any other method with the owners of this repository before making changes. Failure to do so will likely lead to a declined pull request regardless of quality. - -Make sure to refer to and follow the [code of conduct](CODE_OF_CONDUCT.md). - -## Quality Requirements - -* No external dependencies. -* 100% test coverage. -* Proper comments. -* Updated documentation. -* Follow the project code style. -* No #region. - -Pull requests will be reviewed thoroughly to maintain project quality. - -## Windows Environment Recommended Setup - -1) Install [VS Community](https://visualstudio.microsoft.com/vs/community/). -2) Clone the repository locally. -3) To see build options, run from cmd prompt: "./build/run.cmd --help" -4) Verify project state by running from cmd prompt: "./build/run.cmd test" - -May optionally use VS Code installs from other setups instead. - -## Linux Environment Recommended Setup - -1) Install packages for: - A) [.NET frameworks](https://dotnet.microsoft.com/download/) - B) [Mono](https://www.mono-project.com/download/stable/#download-lin/) - C) [VS Code](https://code.visualstudio.com/download/) -2) Install VS Code extensions: - A) C# Dev Kit - B) EditorConfig for VS Code - C) Code Spell Checker - D) GitHub Pull Request and Issues - E) GitHub Actions -3) Clone the repository in the editor, then: - A) Run from terminal: "chmod +x ./build/run.sh" - B) To see build options, run from terminal: "./build/run.sh --help" - C) Verify project state by running from terminal: "./build/run.sh test" - -## Mac Dev Environment Recommended Setup - -1) Install Command Line Developer Tools via the Terminal: - A) Check if installed: ‘xcode-select -p’ - B) If not, run: ‘code-select —install’ - C) Verify git works: ‘git —version’ -2) Install VS Code: https://code.visualstudio.com/download -3) Install VS Code extensions: - A) C# Dev Kit - B) EditorConfig for VS Code - C) Code Spell Checker - D) GitHub Pull Request and Issues - E) GitHub Actions -4) Clone the repository in the editor, then: - A) Follow all prompts for signing in/downloads. - B) To see build options, run from terminal: "./build/run.sh --help" - C) Verify project state by running from terminal: "./build/run.sh test" - -# Git & GPG Quick Setup Example - -Set the following git configuration settings, replacing [xxx] with valid personal values: - -1) git config --global user.name "[xxx]" -2) git config --global user.email "[xxx]@users.noreply.github.com" -3) git config --global user.signingKey [XXX] -4) git config --global tag.gpgSign true -5) git config --global commit.gpgSign true -6) git config --global push.gpgSign "if-asked" - -Read more about GPG keys in the following section. - -## Developer Certificate of Origin (DCO) - -To allow contributions to be used by the project, developers must declare that they can and do give rights to use that code. This is done by signing off on commits by appending a message at the end of the commit for all owners in the format: - -``` -Signed-off-by: FirstName LastName -``` - -This can be accomplished manually or by using -s or --signoff when committing. Github can verify this signature with your GPG key, which you can learn about [here](https://help.github.com/articles/signing-commits-with-gpg/). By signing off your commits to this repository, you're confirming that you've read DCO and agree with it, which can be found at https://developercertificate.org/ or read below: - - -``` -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index b4cbf53d..00000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -name: Report a bug -about: Ask for something to be fixed -title: '' -labels: 'bug' -assignees: '' - ---- - - - - -## Expected Behavior - - -## Current Behavior - - -## Possible Solution - - -## Steps to Reproduce - -1. -2. - -## Additional Information - diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index a1a9ed10..00000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,8 +0,0 @@ -blank_issues_enabled: true -contact_links: - - name: Ask a question - url: ../../../discussions - about: Get help using discussions - - name: Contact us via email - url: mailto:createandfaketeam@gmail.com - about: Communicate privately if necessary \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 51decced..00000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Request a feature -about: Suggest an idea or want -title: '' -labels: 'enhancement' -assignees: '' - ---- - - - - -## Wanted Behavior - - -## Possible Solution - - -## Additional Information - diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 94a94f12..00000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,12 +0,0 @@ - - - - -## Summary - - -## Fulfills - - -* Closes #xx -* Closes #xx diff --git a/.github/SECURITY.md b/.github/SECURITY.md deleted file mode 100644 index 6d87b5bd..00000000 --- a/.github/SECURITY.md +++ /dev/null @@ -1,15 +0,0 @@ -# Security Policy - -## Overview - -Create & Fake is a completely self-contained test framework and should not pose any risk for users. The source code itself should contain no passwords or user information. - -## Supported Versions - -| Version | Supported | -| ------- | ------------------ | -| Latest | :white_check_mark: | - -## Reporting a Vulnerability - -As a testing solution Create & Fake is not released with production code and any potential vulnerabilities pose little to no risk for users. Thus vulnerabilities can be posted as regular issues and will be worked on as normal. If you feel there is an actual risk, you may instead email [createandfaketeam@gmail.com](mailto:createandfaketeam@gmail.com). diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml new file mode 100644 index 00000000..bf6ee757 --- /dev/null +++ b/.github/workflows/coverage.yml @@ -0,0 +1,30 @@ +name: Coverage + +on: + push: + branches: [ master, main ] + pull_request: + branches: [ master, main ] + +jobs: + coverage: + runs-on: windows-2025 + environment: staging + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 11.0.x + 10.0.x + 9.0.x + - name: Build & Check Test Coverage + shell: cmd + run: ./build/run.cmd coverage + - name: Upload Coverage + uses: codecov/codecov-action@v6 + with: + directory: ./artifacts/coverage + token: ${{ Secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/debug.yml b/.github/workflows/debug.yml new file mode 100644 index 00000000..06986bc0 --- /dev/null +++ b/.github/workflows/debug.yml @@ -0,0 +1,25 @@ +name: Debug + +on: + workflow_dispatch: + +jobs: + testing: + runs-on: ubuntu-latest + environment: staging + timeout-minutes: 10 + steps: + - uses: actions/checkout@v6 + - name: Install ICU + run: apt-get update && apt-get install libicu78 + shell: bash + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 11.0.x + 10.0.x + 9.0.x + - name: Build & Test (Debug) + run: ./build/run.sh debugCrash + shell: bash diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index ad370816..ad3ec8ff 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -2,51 +2,29 @@ name: Integration on: push: - branches: [ master ] + branches: [ master, main ] pull_request: - branches: [ master ] + branches: [ master, main ] jobs: - ubuntu: - runs-on: ubuntu-latest + testing: + strategy: + matrix: + os: [ubuntu-latest, macOS-latest, windows-latest] + fail-fast: false + runs-on: ${{ matrix.os }} + environment: staging + timeout-minutes: 20 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Setup .NET - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - 8.0.x - 7.0.x + 11.0.x + 10.0.x + 9.0.x - name: Build & Test run: ./build/run.sh test - - mac: - runs-on: macOS-latest - steps: - - uses: actions/checkout@v4 - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: | - 8.0.x - 7.0.x - - name: Build & Test - run: bash build/run.sh test - - windows: - runs-on: windows-2019 - steps: - - uses: actions/checkout@v4 - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: | - 8.0.x - 7.0.x - - name: Build & Test & Coverage - run: ./build/run.cmd test coverage - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - directory: ./artifacts/coverage - token: ${{ secrets.CODECOV_TOKEN }} + shell: bash + \ No newline at end of file diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 00000000..e1ba3ad7 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,53 @@ +name: Pages + +on: + push: + branches: [ master, main ] + pull_request: + branches: [ master, main ] + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 10.0.x + + - name: Setup Pages + uses: actions/configure-pages@v6 + + - name: Build Site + run: ./build/run.sh buildSite + shell: bash + + - name: Upload artifact + uses: actions/upload-pages-artifact@v5 + with: + path: ./artifacts/site + + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v5 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 0d19fb32..a40640f8 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -7,16 +7,19 @@ on: jobs: nuget: runs-on: ubuntu-latest + environment: production steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: - fetch-depth: 0 + fetch-depth: 0 # All history to ensure proper tagging. - name: Setup .NET - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - 8.0.x + 11.0.x + 10.0.x + 9.0.x - name: Build & Pack run: ./build/run.sh pack - name: Publish to NuGet - run: dotnet nuget push ./artifacts/releases/*.nupkg -k ${{ secrets.NUGET_KEY }} -s https://api.nuget.org/v3/index.json --skip-duplicate + run: dotnet nuget push ./artifacts/releases/*.nupkg -k ${{ Secrets.NUGET_KEY }} -s https://api.nuget.org/v3/index.json --skip-duplicate diff --git a/.gitignore b/.gitignore index f628d0ad..ea1a12cc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,6 @@ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore # User-specific files @@ -23,6 +9,7 @@ *.user *.userosscache *.sln.docstates +*.env # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs @@ -35,17 +22,37 @@ mono_crash.* [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ -x64/ -x86/ + +[Dd]ebug/x64/ +[Dd]ebugPublic/x64/ +[Rr]elease/x64/ +[Rr]eleases/x64/ +bin/x64/ +obj/x64/ + +[Dd]ebug/x86/ +[Dd]ebugPublic/x86/ +[Rr]elease/x86/ +[Rr]eleases/x86/ +bin/x86/ +obj/x86/ + [Ww][Ii][Nn]32/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ +[Aa][Rr][Mm]64[Ee][Cc]/ bld/ -[Bb]in/ [Oo]bj/ +[Oo]ut/ [Ll]og/ [Ll]ogs/ +# Build results on 'Bin' directories +**/[Bb]in/* +# Uncomment if you have tasks that rely on *.refresh files to move binaries +# (https://github.com/github/gitignore/pull/3736) +#!**/[Bb]in/*.refresh + # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot @@ -57,12 +64,16 @@ Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* +*.trx # NUnit *.VisualState.xml TestResult.xml nunit-*.xml +# Approval Tests result files +*.received.* + # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ @@ -75,6 +86,7 @@ BenchmarkDotNet.Artifacts/ project.lock.json project.fragment.lock.json artifacts/ +.artifacts/ # ASP.NET Scaffolding ScaffoldingReadMe.txt @@ -89,6 +101,7 @@ StyleCopReport.xml *.ilk *.meta *.obj +*.idb *.iobj *.pch *.pdb @@ -96,6 +109,8 @@ StyleCopReport.xml *.pgc *.pgd *.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp *.sbr *.tlb *.tli @@ -167,6 +182,7 @@ coverage*.info # NCrunch _NCrunch_* +.NCrunch_* .*crunch*.local.xml nCrunchTemp_* @@ -308,9 +324,6 @@ node_modules/ # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw -# Visual Studio 6 auto-generated project file (contains which files were open etc.) -*.vbp - # Visual Studio 6 workspace and project file (working project files containing files to include in project) *.dsw *.dsp @@ -328,22 +341,22 @@ node_modules/ _Pvt_Extensions # Paket dependency manager -.paket/paket.exe +**/.paket/paket.exe paket-files/ # FAKE - F# Make -.fake/ +**/.fake/ # CodeRush personal settings -.cr/personal +**/.cr/personal # Python Tools for Visual Studio (PTVS) -__pycache__/ +**/__pycache__/ *.pyc # Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config +#tools/** +#!tools/packages.config # Tabs Studio *.tss @@ -365,15 +378,19 @@ ASALocalRun/ # MSBuild Binary and Structured Log *.binlog +MSBuild_Logs/ + +# AWS SAM Build and Temporary Artifacts folder +.aws-sam # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder -.mfractor/ +**/.mfractor/ # Local History for Visual Studio -.localhistory/ +**/.localhistory/ # Visual Studio History (VSHistory) files .vshistory/ @@ -385,17 +402,25 @@ healthchecksdb MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder -.ionide/ +**/.ionide/ # Fody - auto-generated XML schema FodyWeavers.xsd # VS Code files for those working on multiple tools -*.code-workspace +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets # Local History for Visual Studio Code .history/ +# Built Visual Studio Code Extensions +*.vsix + # Windows Installer files from build outputs *.cab *.msi @@ -407,4 +432,4 @@ FodyWeavers.xsd *.sln.iml # Mac -*.DS_Store \ No newline at end of file +*.DS_Store diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000..8b12dbfb --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,8 @@ +{ + "recommendations": [ + "ms-dotnettools.csdevkit", + "editorconfig.editorconfig", + "streetsidesoftware.code-spell-checker", + "csharpier.csharpier-vscode" + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 19898a06..797fd76b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,49 +1,60 @@ -// Extension: EditorConfig for VS Code { "omnisharp.enableEditorConfigSupport": true, - "omnisharp.organizeImportsOnFormat": true, + "dotnet.formatting.organizeImportsOnFormat": true, + "dotnet.testWindow.skipTargetFrameworkCompatibilityCheck": true, + "dotnet.unitTests.runSettingsPath": "./tests/TestSettings.runsettings", + "dotnet.defaultSolution": "CreateAndFakeCode.slnx", "git.enableSmartCommit": true, "git.enableCommitSigning": true, "editor.formatOnSave": true, "editor.codeActionsOnSave": { - "source.organizeImports": "explicit" + "source.organizeImports": "always", }, "editor.rulers": [ - 120, - 140 + 120 ], "[csharp]": { - "editor.defaultFormatter": "ms-dotnettools.csharp" + "editor.defaultFormatter": "csharpier.csharpier-vscode" + }, + "[xml]": { + "editor.defaultFormatter": "csharpier.csharpier-vscode" + }, + "json.schemaDownload.trustedDomains": { + "https://raw.githubusercontent.com/dotnet/docfx/main/schemas/docfx.schema.json": true }, - // Extension: Code Spell Checker "cSpell.words": [ - "Assem", - "autobuild", + "Analyser", + "ASPNETCORE", "Browsable", "Callvirt", "Castclass", "Chainer", + "changefreq", "Cloneable", "cloneables", "cloner", "cobertura", - "codacy", "codecov", - "codeql", "comparables", + "cooldown", + "cref", + "datacollector", "Delegators", - "dotnettools", + "docfx", "Duplicatable", - "duplicatables", "enumerables", "equatables", "finalizer", "FIRSTNAME", "FULLNAME", + "Generatable", "globaltool", "gpgsign", "hasher", "Hashtable", + "inheritdoc", + "Initializable", + "LASTEXITCODE", "LASTNAME", "Ldarg", "Ldelem", @@ -52,22 +63,33 @@ "Ldloc", "Ldstr", "Ldtoken", + "libicu", + "Lindhart", + "Linq", "Memberwise", + "Meziantou", "MIDDLENAME", + "mscorlib", "Mutatable", + "nameof", "NETCOREAPP", "NETFRAMEWORK", + "netstandard", "Newarr", "Newobj", + "Newtonsoft", "noreply", "nuget", + "nunit", "nupkg", - "omnisharp", - "outofbounds", + "paramref", + "Pkgcoverlet", + "Randomizable", "Randomizer", "Reflectable", "reportgenerator", - "serializables", + "Roslynator", + "runsettings", "signoff", "Stelem", "Stfld", @@ -76,10 +98,25 @@ "Subclasser", "SYSLIB", "targetdir", + "testsettings", + "Unconfigured", "Uninstantiated", + "Unwrapper", + "VSTHRD", + "Werecodent", "Xunit" ], "cSpell.ignorePaths": [ - "src/CreateAndFake/Design/Data/" - ] + "**/usr/local/share/dotnet", + "**/var/folders/", + ".vscode/", + "artifacts/", + "site/template/", + "src/Design/Data/", + ".editorconfig", + ".gitignore", + "nuget.config", + ], + "editor.inlineSuggest.enabled": false, + "explorer.autoReveal": "focusNoScroll" } \ No newline at end of file diff --git a/CreateAndFakeCode.sln b/CreateAndFakeCode.sln deleted file mode 100644 index 2181c3e6..00000000 --- a/CreateAndFakeCode.sln +++ /dev/null @@ -1,40 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29306.81 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CreateAndFake", "src\CreateAndFake\CreateAndFake.csproj", "{F77EEEB8-3D72-4BF9-A8FA-A2A0D136169B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CreateAndFakeTests", "tests\CreateAndFakeTests\CreateAndFakeTests.csproj", "{FDB610D5-22AD-41F1-8E10-DFD3F0C7E7B5}" - ProjectSection(ProjectDependencies) = postProject - {F77EEEB8-3D72-4BF9-A8FA-A2A0D136169B} = {F77EEEB8-3D72-4BF9-A8FA-A2A0D136169B} - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Build", "src\Build\Build.csproj", "{8A9DE4F2-4FA4-4201-AC52-5A5FEB52BCCF}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F77EEEB8-3D72-4BF9-A8FA-A2A0D136169B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F77EEEB8-3D72-4BF9-A8FA-A2A0D136169B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F77EEEB8-3D72-4BF9-A8FA-A2A0D136169B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F77EEEB8-3D72-4BF9-A8FA-A2A0D136169B}.Release|Any CPU.Build.0 = Release|Any CPU - {FDB610D5-22AD-41F1-8E10-DFD3F0C7E7B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FDB610D5-22AD-41F1-8E10-DFD3F0C7E7B5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FDB610D5-22AD-41F1-8E10-DFD3F0C7E7B5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FDB610D5-22AD-41F1-8E10-DFD3F0C7E7B5}.Release|Any CPU.Build.0 = Release|Any CPU - {8A9DE4F2-4FA4-4201-AC52-5A5FEB52BCCF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8A9DE4F2-4FA4-4201-AC52-5A5FEB52BCCF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8A9DE4F2-4FA4-4201-AC52-5A5FEB52BCCF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8A9DE4F2-4FA4-4201-AC52-5A5FEB52BCCF}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {2E04E3CC-869E-469A-BE61-FE8C557D937F} - EndGlobalSection -EndGlobal diff --git a/CreateAndFakeCode.slnx b/CreateAndFakeCode.slnx new file mode 100644 index 00000000..b6c58c9c --- /dev/null +++ b/CreateAndFakeCode.slnx @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md index a707e949..370b7924 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ # Create & Fake -[![NuGet](https://img.shields.io/nuget/v/CreateAndFake)](https://www.nuget.org/packages/CreateAndFake) [![Build](https://github.com/CreateAndFake/CreateAndFake/workflows/Integration/badge.svg)](../../actions?query=workflow%3AIntegration) [![CodeCov Coverage](https://codecov.io/gh/CreateAndFake/CreateAndFake/branch/master/graph/badge.svg)](https://codecov.io/gh/CreateAndFake/CreateAndFake/branch/master) [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](code_of_conduct.md) +[![NuGet](https://img.shields.io/nuget/v/CreateAndFake)](https://www.nuget.org/packages/CreateAndFake) [![Build](https://github.com/Werecodent/CreateAndFake/actions/workflows/integration.yml/badge.svg?branch=main)](https://github.com/Werecodent/CreateAndFake/actions/workflows/integration.yml) [![CodeCov Coverage](https://codecov.io/gh/Werecodent/CreateAndFake/branch/main/graph/badge.svg)](https://codecov.io/gh/Werecodent/CreateAndFake/branch/main) -A C# class library that handles mocking, test data generation, and validation. Designed to handle the bulk of test setup quickly and easily so that developers can focus on the behavior to test, making tests easier to develop and maintain: +A test support library that makes robust testing easy by handling all manners of test data generation, mocking, comparisons and validation. Designed to handle the bulk of test setup quickly and easily so that developers can focus on the behavior to test, making tests easier to develop and maintain: ```c# // xUnit attributes used to automatically create the parameters. [Theory, RandomData] -internal static void TestGetMovieDirectors( - [Fake] IStorage db, Endpoint api, [Size(2)] Details[] movies) +internal static void GetDirectors_UtilizesYearToPruneDirectors( + [Fake] IStorage db, [Injected] Endpoint api, [Size(2)] Details[] movies) { // Setup fake behavior using randomized movie data (times optional). db.Find(movies[0].Name).SetupReturn(movies, Times.Once); @@ -17,15 +17,15 @@ internal static void TestGetMovieDirectors( api.GetDirectors(movies[0].Name, movies[0].Year).Assert().Is(movies[0].Directors); // Optionally check all behavior called as expected. - db.VerifyAllCalls(); + db.Assert().Called(); } ``` -By default, all behavior works not by reference but by value even for complex objects. Using the extension methods and attributes are optional as all functionality are present in customizable tools: +By default, all behavior works not by reference but by value even for complex objects. Using the fluent extension methods and attributes are optional as all functionality are present in customizable tools: ```C# [Fact] -internal static void TestChangingZipCodeUpdatesAddress() +internal static void MailingAddress_VerifyChangingZipCodeUpdatesAddress() { // Randomizer uses readable values for some properties like 'FirstName'. User details = Tools.Randomizer.Create(); @@ -37,46 +37,68 @@ internal static void TestChangingZipCodeUpdatesAddress() details.ZipCode = Tools.Mutator.Variant(details.ZipCode); // Asserter performs checks based upon value. - Tools.Asserter.IsNot(copy.MailingAddress, details.MailingAddress); + Tools.Asserter.IsNot(details.MailingAddress, copy.MailingAddress); } ``` A key benefit of the library is in how the tools are logically integrated with each other. For example, the `Randomizer` will use stubs for interfaces that have no known implementations in the code. Or the mocks created by the `Faker` utilize value equality in matching arguments. -* `Asserter` - Handles common test scenarios. -* `Faker` - Creates mocks and stubs. -* `Randomizer` - Creates random instances of any type. -* `Duplicator` - Creates deep clones of objects. -* `Mutator` - Mutates objects or creates variants. -* `Valuer` - Compares objects by value. -* `Tester` - Automates common tests. +* `Asserter` - Verify object states and behavior. +* `Duplicator` - Deep clone objects. +* `Extractor` - Flatten the contents of objects. +* `Faker` - Simulate behavior via stubs/mocks. +* `Mutator` - Modify the state of objects or create variants. +* `Randomizer` - Create objects populated with random values. +* `Runner` - Generate method data and run them. +* `Tester` - Test common scenarios. +* `Valuer` - Compare objects by value via reflection if needed. -Visit the [documentation site](https://createandfake.github.io/CreateAndFake/) for more information and how to get started. +Visit the [documentation site](https://werecodent.github.io/CreateAndFake/) for more information and how to get started. ## Installation -* Install using: - -``` -dotnet add package CreateAndFake -``` - -* Use in a class by adding: - -``` -using CreateAndFake; -using CreateAndFake.Fluent; -``` +There are three levels of packages that can be utilized for different purposes. +1) `Werecodent.CreateAndFake.Design` - Optional support library for non-test projects. +2) `Werecodent.CreateAndFake` - Provides the tools to use in test projects. +3) `Werecodent.CreateAndFake.[UnitTestFramework]` - Provides attribute support for a unit test framework. + +Versions for the packages are synchronized and released alongside each other. Reference the wanted package using NuGet by following these instructions: + +1) For attribute support, identify the `[UnitTestFramework]` you're using from the available options below: + * MSTest.v3 (2.2.1 -> 4.0.0) + * MSTest.v4 (4.0.0+) + * NUnit.v3 (3.10.0+) + * xUnit.v2 (2.2.0 -> 3.0.0) + * xUnit.v3 (3.0.0+) + +2) For attribute support, install using one of the following command (replace `[UnitTestFramework]` with your chosen version): + ```sh + dotnet add package Werecodent.CreateAndFake.[UnitTestFramework] + ``` + +3) Alternatively, install using the following command for just tool support (already included in the attribute support version): + ```sh + dotnet add package Werecodent.CreateAndFake + ``` + +4) It's recommended to add the following lines to your tests.csproj file for ease of use: + ```xml + + + + + + ``` ## Documentation -The documentation site is located here: https://createandfake.github.io/CreateAndFake/ +The documentation site is located here: https://werecodent.github.io/CreateAndFake/ -The raw files can be viewed from the doc folder or built into a local site using Jekyll. +The raw files can be viewed from the doc folder or built into a local site using "./build/run.sh serveSite". ## Contributing -If you're looking to contribute, thanks for your interest. Feel free to submit reports for any issues you can find, or request potential features you'd like to see [here](../../issues). If you wish to contribute code to the project, refer to the contributing guidelines [here](.github/CONTRIBUTING.md) which includes dev environment setup. Please follow the [code of conduct](.github/CODE_OF_CONDUCT.md) when contributing. +If you're looking to contribute, thanks for your interest. Feel free to submit reports for any issues you can find, or request potential features you'd like to see [here](../../issues). If you wish to contribute code to the project, refer to the [contributing](https://github.com/Werecodent/.github/blob/main/CONTRIBUTING.md) requirements and the [support](https://github.com/Werecodent/.github/blob/main/SUPPORT.md) guide for environment setup. Please follow the [code of conduct](https://github.com/Werecodent/.github/blob/main/CODE_OF_CONDUCT.md) when contributing. ## License @@ -86,8 +108,11 @@ View the [license](LICENSE.txt) file for more details. ## Acknowledgments -* [xUnit](https://xunit.github.io/): For running tests. -* [Coverlet](https://github.com/tonerdo/coverlet) + [ReportGenerator](https://danielpalme.github.io/ReportGenerator/) + [CodeCov](https://codecov.io/): For test coverage. +* [xUnit](https://github.com/xunit/xunit) + [NUnit](https://github.com/nunit/nunit) + [MSTest](https://github.com/microsoft/testfx): For running tests. +* [Coverlet](https://github.com/tonerdo/coverlet) + [ReportGenerator](https://danielpalme.github.io/ReportGenerator) + [CodeCov](https://codecov.io): For test coverage. * [Bullseye](https://github.com/adamralph/bullseye) + [SimpleExec](https://github.com/adamralph/simple-exec) + [MinVer](https://github.com/adamralph/minver): For project building. -* [GitHub](https://github.com/): For hosting code. -* [Microsoft](https://visualstudio.microsoft.com/vs/features/net-development/): For C# and editors. +* [AsyncFixer](https://github.com/semihokur/AsyncFixer) + [MissingAwaitWarning](https://github.com/ykoksen/unused-task-warning) + [Meziantou.Analyzer](https://github.com/meziantou/Meziantou.Analyzer) + [Sonar](https://github.com/SonarSource/sonar-dotnet): For code analyzers. +* [DocFX](https://github.com/dotnet/docfx): For building the documentation site. +* [CSharpier](https://github.com/belav/csharpier): For formatting code. +* [GitHub](https://github.com): For hosting code. +* [Microsoft](https://visualstudio.microsoft.com/vs/features/net-development): For C# and editors. diff --git a/build/run.ps1 b/build/run.ps1 index bf206bbd..437d538d 100644 --- a/build/run.ps1 +++ b/build/run.ps1 @@ -1,6 +1,6 @@ -$ErrorActionPreference = "Stop"; - $ScriptDir = Split-Path $MyInvocation.MyCommand.Path -Parent Set-Location "$ScriptDir\.." dotnet run --project "$ScriptDir\..\src\Build" -- $args + +exit $LASTEXITCODE diff --git a/docs/_config.yml b/docs/_config.yml deleted file mode 100644 index 6adcae98..00000000 --- a/docs/_config.yml +++ /dev/null @@ -1,6 +0,0 @@ -theme: jekyll-theme-architect -markdown: kramdown -highlighter: rouge - -title: Create & Fake -description: Mocking and data generation for testing. diff --git a/docs/_includes/nav.html b/docs/_includes/nav.html deleted file mode 100644 index f558963d..00000000 --- a/docs/_includes/nav.html +++ /dev/null @@ -1,38 +0,0 @@ -

General:

- -

Design:

- -

Tools:

- diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html deleted file mode 100644 index cfee0fe2..00000000 --- a/docs/_layouts/default.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - {% seo %} - - - -
-
- -

{{ site.title | default: site.github.repository_name }}

-
-

{{ site.description | default: site.github.project_tagline }}

- - View project on GitHub - -
-
- -
-
-
- {{ content }} -
- - -
-
- - - \ No newline at end of file diff --git a/nuget.config b/nuget.config index 591ef03c..089f2cf2 100644 --- a/nuget.config +++ b/nuget.config @@ -1,6 +1,6 @@ - + - \ No newline at end of file + diff --git a/site/docfx.json b/site/docfx.json new file mode 100644 index 00000000..59724310 --- /dev/null +++ b/site/docfx.json @@ -0,0 +1,65 @@ +{ + "$schema": "https://raw.githubusercontent.com/dotnet/docfx/main/schemas/docfx.schema.json", + "metadata": [ + { + "src": [ + { + "src": "../src", + "files": [ + "**/*.csproj" + ], + "exclude": [ + "Build/*.csproj", + "Samples/*.csproj" + ] + } + ], + "output": "../artifacts/api", + "properties": { + "TargetFramework": "net10" + }, + "noRestore": true, + "namespaceLayout": "flattened", + "memberLayout": "separatePages" + } + ], + "build": { + "content": [ + { + "files": [ + "**/*.{md,yml}" + ] + }, + { + "src": "../artifacts", + "files": [ + "api/**" + ] + } + ], + "resource": [ + { + "files": [ + "images/**" + ] + } + ], + "output": "../artifacts/site", + "template": [ + "default", + "modern", + "template" + ], + "globalMetadata": { + "_appName": "Create & Fake", + "_appTitle": "Create & Fake", + "_enableSearch": true, + "_disableContribution": true, + "pdf": false + }, + "sitemap": { + "baseUrl": "https://werecodent.github.io/CreateAndFake", + "changefreq": "monthly" + } + } +} \ No newline at end of file diff --git a/docs/pages/Design-IRandom.md b/site/docs/Design-IRandom.md similarity index 100% rename from docs/pages/Design-IRandom.md rename to site/docs/Design-IRandom.md diff --git a/docs/pages/Design-Limiter.md b/site/docs/Design-Limiter.md similarity index 100% rename from docs/pages/Design-Limiter.md rename to site/docs/Design-Limiter.md diff --git a/docs/pages/General-ExampleScenario.md b/site/docs/General-ExampleScenario.md similarity index 100% rename from docs/pages/General-ExampleScenario.md rename to site/docs/General-ExampleScenario.md diff --git a/docs/pages/General-TestAttributes.md b/site/docs/General-TestAttributes.md similarity index 80% rename from docs/pages/General-TestAttributes.md rename to site/docs/General-TestAttributes.md index 6954cf55..e9e87299 100644 --- a/docs/pages/General-TestAttributes.md +++ b/site/docs/General-TestAttributes.md @@ -5,11 +5,11 @@ For many test frameworks, attributes can create parameter data for test methods. ```c# /// Verifies the option works. [Theory, RandomData] -public static void Min_Works(int value) +public static void AtLeast_Works(int value) { - Tools.Asserter.Is(false, Times.Min(value).IsInRange(value - 1)); - Tools.Asserter.Is(true, Times.Min(value).IsInRange(value)); - Tools.Asserter.Is(true, Times.Min(value).IsInRange(value + 1)); + Tools.Asserter.Is(false, Times.AtLeast(value).IsInRange(value - 1)); + Tools.Asserter.Is(true, Times.AtLeast(value).IsInRange(value)); + Tools.Asserter.Is(true, Times.AtLeast(value).IsInRange(value + 1)); } ``` diff --git a/site/docs/General-V2Migration.md b/site/docs/General-V2Migration.md new file mode 100644 index 00000000..d5f46b0e --- /dev/null +++ b/site/docs/General-V2Migration.md @@ -0,0 +1,20 @@ +# Migrating v1 -> v2 + +This doc details the changes necessary to migrate a code base using 1.x.x versions to version 2.0.0. + +No changes are needed if the code base compiles. Changes are mainly required for code customizing the tools instead of using the default set with their default configurations. + +## Why + +In general, backwards compatibility is a high priority for normal releases. This leads to wanting new behavior be customizable and restricted to changes not breaking the existing API. Tools are highly configurable, but the methodology was found to be lacking especially when only wanting a change on a case by case basis. Using configuration records with optional fluent per method customization resolves these issues. + +## Randomizer Changes + +```c# +/// Test that will fail. +[Theory, RandomData] +public void Tools_DataSampleExample(DataSample original) +{ + Tools.Asserter.Is(original, Tools.Mutator.Variant(original)); +} +``` diff --git a/docs/pages/Tools-Asserter.md b/site/docs/Tools-Asserter.md similarity index 90% rename from docs/pages/Tools-Asserter.md rename to site/docs/Tools-Asserter.md index e46437db..763e49ae 100644 --- a/docs/pages/Tools-Asserter.md +++ b/site/docs/Tools-Asserter.md @@ -30,9 +30,9 @@ Which gives the following message detailing the differences: ``` Result Message: -Test method CreateAndFakeTests.ToolsTests.Tools_DataSampleExample threw +Test method Werecodent.CreateAndFake.Tests.ToolsTests.Tools_DataSampleExample threw exception: -CreateAndFake.Toolbox.AsserterTool.AssertException: Value equality failed +CreateAndFake.AsserterTool.AssertException: Value equality failed for type 'DataSample'. Content: .NestedValue.StringValue -> Expected:, Actual:<0RIXwSBI> diff --git a/docs/pages/Tools-Duplicator.md b/site/docs/Tools-Duplicator.md similarity index 100% rename from docs/pages/Tools-Duplicator.md rename to site/docs/Tools-Duplicator.md diff --git a/docs/pages/Tools-Faker.md b/site/docs/Tools-Faker.md similarity index 89% rename from docs/pages/Tools-Faker.md rename to site/docs/Tools-Faker.md index 80161d2e..32d21e92 100644 --- a/docs/pages/Tools-Faker.md +++ b/site/docs/Tools-Faker.md @@ -32,7 +32,7 @@ public void Setup_ObjectEquality() Tools.Asserter.Is(false, fake.Dummy.Equals(new object())); Tools.Asserter.Is(true, fake.Dummy.Equals(data)); - fake.VerifyAll(Times.Exactly(2)); + fake.Verify(Times.Exactly(2)); } ``` @@ -50,8 +50,8 @@ The `Faker` requires a `Valuer` to be given at creation, which controls value eq There are a variety of options to verify methods were called as expected: -* `Fake.VerifyAll()` - Automatically checks methods based upon `Times` in each Behavior. -* `Fake.VerifyAll(Times)` - Does the above and that the total matches the provided `Times`. +* `Fake.Verify()` - Automatically checks methods based upon `Times` in each Behavior. +* `Fake.Verify(Times)` - Does the above and that the total matches the provided `Times`. * `Fake.Verify(Times, delegate)` - Verifies the given delegate was called the given `Times`. * `Fake.VerifyTotalCalls(Times)` - Only verifies the total number of calls made. @@ -67,7 +67,7 @@ There are two special useful types provided: The assembly containing the internals to fake needs to grant visibility to the dynamic assembly by adding somewhere (typically AssemblyInfo.cs): ```c# -[assembly: InternalsVisibleTo("FakerTypes")] +[assembly: InternalsVisibleTo("Werecodent.CreateAndFake.FakerTypes")] ``` ## Faking Protected @@ -84,10 +84,10 @@ public void GetHashCode_ValidHint() Fake hint = Tools.Faker.Mock(); hint.Setup("Supports", - new[] { data, data, Arg.LambdaAny() }, + new[] { data, data, Arg.LambdaAny() }, Behavior.Returns(true, Times.Once)); hint.Setup("GetHashCode", - new[] { data, Arg.LambdaAny() }, + new[] { data, Arg.LambdaAny() }, Behavior.Returns(result, Times.Once)); Tools.Asserter.Is(result, new Valuer(false, hint.Dummy).GetHashCode(data)); diff --git a/docs/pages/Tools-Mutator.md b/site/docs/Tools-Mutator.md similarity index 100% rename from docs/pages/Tools-Mutator.md rename to site/docs/Tools-Mutator.md diff --git a/docs/pages/Tools-Randomizer.md b/site/docs/Tools-Randomizer.md similarity index 100% rename from docs/pages/Tools-Randomizer.md rename to site/docs/Tools-Randomizer.md diff --git a/docs/pages/Tools-Tester.md b/site/docs/Tools-Tester.md similarity index 87% rename from docs/pages/Tools-Tester.md rename to site/docs/Tools-Tester.md index b4fadf52..60562640 100644 --- a/docs/pages/Tools-Tester.md +++ b/site/docs/Tools-Tester.md @@ -14,9 +14,9 @@ Simply create a test method and call the `Tester` case: ```c# /// Verifies null reference exceptions are prevented. [Fact] -public void ValueRandom_GuardsNulls() +public Task ValueRandom_GuardsNulls() { - Tools.Tester.PreventsNullRefException(); + return Tools.Tester.PreventsNullRefException(); } ``` diff --git a/docs/pages/Tools-Valuer.md b/site/docs/Tools-Valuer.md similarity index 100% rename from docs/pages/Tools-Valuer.md rename to site/docs/Tools-Valuer.md diff --git a/site/docs/toc.yml b/site/docs/toc.yml new file mode 100644 index 00000000..c420f374 --- /dev/null +++ b/site/docs/toc.yml @@ -0,0 +1,20 @@ +- name: Introduction +- href: ../index.md + +- name: General +- href: General-ExampleScenario.md +- href: General-TestAttributes.md +- href: General-V2Migration.md + +- name: Design +- href: Design-IRandom.md +- href: Design-Limiter.md + +- name: Tools +- href: Tools-Asserter.md +- href: Tools-Duplicator.md +- href: Tools-Faker.md +- href: Tools-Mutator.md +- href: Tools-Randomizer.md +- href: Tools-Tester.md +- href: Tools-Valuer.md diff --git a/docs/index.md b/site/index.md similarity index 100% rename from docs/index.md rename to site/index.md diff --git a/site/template/public/main.css b/site/template/public/main.css new file mode 100644 index 00000000..273c2bb5 --- /dev/null +++ b/site/template/public/main.css @@ -0,0 +1,7 @@ +.typelist.extensionMethods { + display: none; +} + +footer { + display: none; +} \ No newline at end of file diff --git a/site/template/public/main.js b/site/template/public/main.js new file mode 100644 index 00000000..d0ac0378 --- /dev/null +++ b/site/template/public/main.js @@ -0,0 +1,10 @@ +export default { + /** A list of icons to show in the header next to the theme picker */ + iconLinks: [ + { + icon: 'github', + href: 'https://github.com/Werecodent/CreateAndFake', + title: 'GitHub' + } + ] +} diff --git a/site/template/toc.extension.js b/site/template/toc.extension.js new file mode 100644 index 00000000..0b98697e --- /dev/null +++ b/site/template/toc.extension.js @@ -0,0 +1,28 @@ +/** + * This method will be called at the start of exports.transform in toc.html.js and toc.json.js + */ +exports.preTransform = function (model) { + simplifyTocNamespaces(model); + return model; + + /** + * Cleans up titles in the table of contents by removing the common project namespace. + * @param {*} item Model with a potential title name to clean. + */ + function simplifyTocNamespaces(item) { + if (item.name) { + if (item.name == "Werecodent.CreateAndFake") { + item.name = "CreateAndFake"; + } else { + item.name = item.name.replace("Werecodent.CreateAndFake.", ''); + } + } + + if (item.items) { + var length = item.items.length; + for (var i = 0; i < length; i++) { + simplifyTocNamespaces(item.items[i]); + }; + } + } +} diff --git a/site/toc.yml b/site/toc.yml new file mode 100644 index 00000000..954ce4da --- /dev/null +++ b/site/toc.yml @@ -0,0 +1,4 @@ +- name: Docs + href: docs/ +- name: API + href: ../artifacts/api/ diff --git a/src/.csharpierignore b/src/.csharpierignore new file mode 100644 index 00000000..50005146 --- /dev/null +++ b/src/.csharpierignore @@ -0,0 +1,2 @@ +**/*.csproj +**/Directory.Build.props diff --git a/src/.editorconfig b/src/.editorconfig index 644bc334..f71ae8dc 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -1,42 +1,18 @@ [*.cs] -# Default severity for all analyzer diagnostics -dotnet_analyzer_diagnostic.severity = warning +# Not supported in all .NET versions. +dotnet_diagnostic.CA1847.severity = None -# CA1000:DoNotDeclareStaticMembersOnGenericTypes -# Per generic static behavior is a valuable tool that can reduce complexity. -dotnet_diagnostic.CA1000.severity = none +# Requiring message based constructors are unnecessary and hinders design. +dotnet_diagnostic.CA1032.severity = None +dotnet_diagnostic.RCS1194.severity = None -# CA1032: Implement standard exception constructors -# Message based constructors unnecessary and hurts design. -dotnet_diagnostic.CA1032.severity = none - -# CA1805: Do not initialize unnecessarily -# Important for clarity and understanding intention. -dotnet_diagnostic.CA1805.severity = none - -# CA1812:AvoidUninstantiatedInternalClasses -# For testing, called via Activator/library dynamically. -dotnet_diagnostic.CA1812.severity = none - -# IDE0045: 'if' statement can be simplified -# IDE0046: Convert to conditional expression -# Choice should be left to developer to maximize readability. -dotnet_diagnostic.IDE0045.severity = none -dotnet_diagnostic.IDE0046.severity = none - -# IDE0048: Add parentheses for clarity -# Unneeded parentheses can hurt readability. -dotnet_diagnostic.IDE0048.severity = none - -# IDE0057: Substring can be simplified -# No support in legacy frameworks. -dotnet_diagnostic.IDE0057.severity = none +# False positive when adding a tag while also using tag. +dotnet_diagnostic.CS1573.severity = None -# IDE0130: Namespace does not match folder structure -# More important to provide a good public surface and backwards compatibility. -dotnet_diagnostic.IDE0130.severity = none +# Bad rules that advocate for less maintainable documentation. +dotnet_diagnostic.MA0197.severity = None +dotnet_diagnostic.MA0203.severity = None -# CS1573: Parameter has no matching param tag in the XML comment (but other parameters do) -# False positive when adding a tag while also using tag. -dotnet_diagnostic.CS1573.severity = none +# Doesn't account for overloads. +dotnet_diagnostic.CA1019.severity = None diff --git a/src/Build/.editorconfig b/src/Build/.editorconfig index e78b3296..36a08a7d 100644 --- a/src/Build/.editorconfig +++ b/src/Build/.editorconfig @@ -1,5 +1,4 @@ [*.cs] -# CA2007: Consider calling ConfigureAwait on the awaited task # Not needed for the build project. -dotnet_diagnostic.CA2007.severity = none +dotnet_diagnostic.CA2007.severity = None diff --git a/src/Build/Build.csproj b/src/Build/Build.csproj index fe1ee1ec..2d68f427 100644 --- a/src/Build/Build.csproj +++ b/src/Build/Build.csproj @@ -1,16 +1,15 @@ - net8.0 - enable - Exe + net10.0 + exe false + $(MSBuildProjectName) - - - + + - \ No newline at end of file + diff --git a/src/Build/Program.cs b/src/Build/Program.cs index 87f8a711..72c3158b 100644 --- a/src/Build/Program.cs +++ b/src/Build/Program.cs @@ -1,102 +1,189 @@ -using static Bullseye.Targets; -using static SimpleExec.Command; - -namespace Build; - -/// Manages build behavior for the solution. -public static class Program -{ - /// Base directory for all output. - private static readonly string _ArtifactDir = Path.Combine(Directory.GetCurrentDirectory(), "artifacts"); - - /// Console application entry point. - /// Command-line arguments. - public static async Task Main(string[] args) - { - Target("default", DependsOn("coverage")); - Target("restore", Restore); - Target("compile", DependsOn("restore"), Compile); - Target("test", DependsOn("compile"), Test); - Target("coverage", DependsOn("compile"), Coverage); - Target("pack", DependsOn("compile"), Pack); - await RunTargetsAndExitAsync(args); - } - - /// Downloads all packages for the solution. - private static Task Restore() - { - return RunAsync("dotnet", "restore"); - } - - /// Builds the solution. - private static async Task Compile() - { - await RunAsync($"dotnet", $"build --no-restore --configuration Debug"); - await RunAsync($"dotnet", $"build --no-restore --configuration Release"); - } - - /// Tests the solution. - private static async Task Test() - { - string testArgs = "test --no-restore --no-build "; - - await RunAsync("dotnet", testArgs + "--configuration Debug"); - await RunAsync("dotnet", testArgs + "--configuration Release"); - } - - /// Tests and analyzes test code coverage. - private static async Task Coverage() - { - string prefix = "coverage"; - string postfix = ".cobertura.xml"; - - string toolsDir = Path.Combine(_ArtifactDir, "tools"); - string coverageDir = Path.Combine(_ArtifactDir, "coverage"); - string testDir = Path.Combine(coverageDir, "testResults"); - string reportDir = Path.Combine(coverageDir, "report"); - - EnsureEmpty(coverageDir); - - await RunAsync("dotnet", string.Join(' ', - "test", - "--no-build", - "--no-restore", - "--configuration Debug", - "--collect:\"XPlat Code Coverage\"", - $"--results-directory \"{testDir}\"")); - - int count = 0; - foreach (string result in Directory.GetFiles(testDir, $"{prefix}{postfix}", SearchOption.AllDirectories)) - { - File.Copy(result, Path.Combine(coverageDir, $"{prefix}{count++}{postfix}")); - } - - await RunAsync("dotnet", $"tool update dotnet-reportgenerator-globaltool --tool-path {toolsDir}"); - await RunAsync($"{toolsDir}/reportgenerator", $"-reports:{coverageDir}/*.xml -targetdir:{reportDir}"); - } - - /// Packs the solution. - private static Task Pack() - { - string releaseDir = Path.Combine(_ArtifactDir, "releases"); - EnsureEmpty(releaseDir); - - return RunAsync("dotnet", string.Join(' ', - "pack", - "--no-build", - "--no-restore", - "--configuration Release", - $"--output \"{releaseDir}\"")); - } - - /// Deletes and creates a directory. - /// Directory to empty. - private static void EnsureEmpty(string dir) - { - if (Directory.Exists(dir)) - { - Directory.Delete(dir, true); - } - _ = Directory.CreateDirectory(dir); - } -} \ No newline at end of file +using static Bullseye.Targets; +using static SimpleExec.Command; + +namespace Build; + +/// Manages build behavior for the solution. +/// Do not add this project to the solution file. +internal static class Program +{ + /// Base directory for all output. + private static readonly string _ArtifactDir = Path.Combine( + Directory.GetCurrentDirectory(), + "artifacts" + ); + + /// Base directory for build tools. + private static readonly string _ToolsDir = Path.Combine(_ArtifactDir, "tools"); + + /// Console application entry point. + /// Command-line arguments. + public static Task Main(string[] args) + { + string[] configurations = ["Debug", "Release"]; + Target("default", dependsOn: ["test"]); + Target("restore", RestoreAsync); + Target("compile", dependsOn: ["restore"], forEach: configurations, CompileAsync); + Target("test", dependsOn: ["compile"], forEach: configurations, TestAsync); + Target("coverage", dependsOn: ["compile"], CoverageAsync); + Target("pack", dependsOn: ["compile"], PackAsync); + Target("debugCrash", dependsOn: ["compile"], DebugCrashAsync); + Target("buildSite", BuildSiteAsync); + Target("serveSite", dependsOn: ["buildSite"], ServeSiteAsync); + return RunTargetsAndExitAsync(args); + } + + /// Downloads all packages for the solution. + /// A that represents the asynchronous operation. + private static async Task RestoreAsync() + { + await RunAsync("dotnet", "tool update -g csharpier").ConfigureAwait(false); + await RunAsync("dotnet", "restore").ConfigureAwait(false); + } + + /// Builds the solution. + /// Build configuration to use. + /// A that represents the asynchronous operation. + private static Task CompileAsync(string configuration) + { + return RunAsync("dotnet", $"build --no-restore --configuration {configuration}"); + } + + /// Tests the solution. + /// Build configuration to use. + /// A that represents the asynchronous operation. + private static Task TestAsync(string configuration) + { + return RunAsync("dotnet", $"test --no-restore --no-build --configuration {configuration}"); + } + + /// Tests the solution with file logging. + /// For debugging test harness crashes. + /// A that represents the asynchronous operation. + private static Task DebugCrashAsync() + { + string logDir = Path.Combine(_ArtifactDir, "logs"); + EnsureEmpty(logDir); + + string logFile = Path.Combine(logDir, "test.txt"); + string testArgs = $"test --no-restore --no-build --diag:{logFile} "; + + return RunAsync("dotnet", testArgs + "--configuration Debug"); + } + + /// Builds the documentation and site. + /// A that represents the asynchronous operation. + private static async Task BuildSiteAsync() + { + string siteDir = Path.Combine(_ArtifactDir, "site"); + string apiDir = Path.Combine(_ArtifactDir, "api"); + EnsureEmpty(siteDir); + EnsureEmpty(apiDir); + + await RunAsync("dotnet", $"tool update docfx --tool-path {_ToolsDir}") + .ConfigureAwait(false); + + await RunAsync("dotnet", "restore -p:TargetFramework=net10.0").ConfigureAwait(false); + + await RunAsync( + $"{_ToolsDir}/docfx", + "metadata site/docfx.json --property \"TargetFramework=net10.0;Configuration=Release\"" + ) + .ConfigureAwait(false); + + await RunAsync($"{_ToolsDir}/docfx", "build site/docfx.json").ConfigureAwait(false); + } + + /// Builds the documentation and site. + /// A that represents the asynchronous operation. + private static Task ServeSiteAsync() + { + string siteDir = Path.Combine(_ArtifactDir, "site"); + + return RunAsync($"{_ToolsDir}/docfx", $"serve {siteDir}"); + } + + /// Tests and analyzes test code coverage. + /// A that represents the asynchronous operation. + private static async Task CoverageAsync() + { + const string prefix = "coverage"; + const string postfix = ".cobertura.xml"; + + string coverageDir = Path.Combine(_ArtifactDir, "coverage"); + string testDir = Path.Combine(coverageDir, "testResults"); + string reportDir = Path.Combine(coverageDir, "report"); + + EnsureEmpty(coverageDir); + + await RunAsync( + "dotnet", + string.Join( + ' ', + "test", + "--no-build", + "--no-restore", + "--configuration Debug", + "--collect:\"XPlat Code Coverage\"", + "--test-adapter-path:\"$(Pkgcoverlet_collector)\\build\\netstandard1.0\"", + $"--results-directory \"{testDir}\"" + ) + ) + .ConfigureAwait(false); + + int count = 0; + foreach ( + string result in Directory.GetFiles( + testDir, + prefix + postfix, + SearchOption.AllDirectories + ) + ) + { + File.Copy(result, Path.Combine(coverageDir, $"{prefix}{count++}{postfix}")); + } + + await RunAsync( + "dotnet", + $"tool update dotnet-reportgenerator-globaltool --tool-path {_ToolsDir}" + ) + .ConfigureAwait(false); + await RunAsync( + $"{_ToolsDir}/reportgenerator", + $"-reports:{coverageDir}/*.xml -targetdir:{reportDir}" + ) + .ConfigureAwait(false); + } + + /// Packs the solution for release. + /// A that represents the asynchronous operation. + private static Task PackAsync() + { + string releaseDir = Path.Combine(_ArtifactDir, "releases"); + EnsureEmpty(releaseDir); + + return RunAsync( + "dotnet", + string.Join( + ' ', + "pack", + "--no-build", + "--no-restore", + "--configuration Release", + $"--output \"{releaseDir}\"" + ) + ); + } + + /// Enforces that exists and is empty. + /// Directory to empty/create. + /// Any existing contents are deleted. + private static void EnsureEmpty(string dir) + { + if (Directory.Exists(dir)) + { + Directory.Delete(dir, true); + } + _ = Directory.CreateDirectory(dir); + } +} diff --git a/src/Build/Properties/AssemblyInfo.cs b/src/Build/Properties/AssemblyInfo.cs index 95465252..c0d560ec 100644 --- a/src/Build/Properties/AssemblyInfo.cs +++ b/src/Build/Properties/AssemblyInfo.cs @@ -1 +1 @@ -[assembly: CLSCompliant(true)] \ No newline at end of file +[assembly: CLSCompliant(true)] diff --git a/src/CreateAndFake/Attributes/FakeAttribute.cs b/src/CreateAndFake/Attributes/FakeAttribute.cs deleted file mode 100644 index 530e9ab8..00000000 --- a/src/CreateAndFake/Attributes/FakeAttribute.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace CreateAndFake; - -/// Flag to create the attached object as a stub with injected random behavior. -/// -/// -/// -[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] -public sealed class FakeAttribute : Attribute { } \ No newline at end of file diff --git a/src/CreateAndFake/Attributes/RandomDataAttribute.cs b/src/CreateAndFake/Attributes/RandomDataAttribute.cs deleted file mode 100644 index 718d2fe0..00000000 --- a/src/CreateAndFake/Attributes/RandomDataAttribute.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Reflection; -using CreateAndFake.Fluent; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using Xunit.Sdk; - -namespace CreateAndFake; - -/// Populates data with random values. -/// Only available when using xUnit. -/// -[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] -public sealed class RandomDataAttribute : DataAttribute -{ - /// Number of times to test the method. - public int Trials { get; set; } = 1; - - /// Generates data for a test. - /// Method details this is attached to. - /// The generated data to run the test with. - public override IEnumerable GetData(MethodInfo testMethod) - { - return Enumerable - .Range(0, Math.Max(0, Trials)) - .Select(_ => Tools.Randomizer.CreateFor(testMethod).Args.Select(FixArg).ToArray()); - } - - /// Fixes to be suitable for Xunit. - /// Instance to fix. - /// modified (if necessary) for Xunit. - private object? FixArg(object? arg) - { - if (arg is IFaked and Type type) - { - type.UnderlyingSystemType.SetupReturn(typeof(Type).UnderlyingSystemType); - type.FullName.SetupReturn(typeof(Type).FullName); - type.IsArray.SetupReturn(typeof(Type).IsArray); - } - return arg; - } -} diff --git a/src/CreateAndFake/Attributes/SizeAttribute.cs b/src/CreateAndFake/Attributes/SizeAttribute.cs deleted file mode 100644 index d9fd9e7d..00000000 --- a/src/CreateAndFake/Attributes/SizeAttribute.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace CreateAndFake; - -/// Flag to create the attached collection with items. -/// -/// -/// -[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] -public sealed class SizeAttribute(int count) : Attribute -{ - /// Number of items to generate and populate the attached collection with. - public int Count { get; } = count; -} \ No newline at end of file diff --git a/src/CreateAndFake/Attributes/StubAttribute.cs b/src/CreateAndFake/Attributes/StubAttribute.cs deleted file mode 100644 index 841571c5..00000000 --- a/src/CreateAndFake/Attributes/StubAttribute.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace CreateAndFake; - -/// Flag to create the attached object as a stub. -/// -/// -[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] -public sealed class StubAttribute : Attribute { } \ No newline at end of file diff --git a/src/CreateAndFake/CreateAndFake.csproj b/src/CreateAndFake/CreateAndFake.csproj deleted file mode 100644 index b05dc0dc..00000000 --- a/src/CreateAndFake/CreateAndFake.csproj +++ /dev/null @@ -1,36 +0,0 @@ - - - - net8.0;netstandard2.0 - enable - v - - - - LEGACY - - - - CreateAndFake Contributors - A C# class library that handles mocking, test data generation, and validation. - MPL-2.0 - https://createandfake.github.io/CreateAndFake/ - https://github.com/CreateAndFake/CreateAndFake - https://github.com/CreateAndFake/CreateAndFake/releases/ - Github - create, fake, tdd, agile, testing, tests, stubs, mocking, mocks, mock, data, random, cloning, clones, clone - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/CreateAndFake/Design/ArgumentGuard.cs b/src/CreateAndFake/Design/ArgumentGuard.cs deleted file mode 100644 index 38816fde..00000000 --- a/src/CreateAndFake/Design/ArgumentGuard.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFake.Design; - -/// Handles common argument exception cases. -internal static class ArgumentGuard -{ - /// Prevents further execution if the parameter is null. - /// Passed parameter value. - /// Name of the parameter. - /// If is null. - internal static void ThrowIfNull([NotNull] object? value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - } -} diff --git a/src/CreateAndFake/Design/Content/Disposer.cs b/src/CreateAndFake/Design/Content/Disposer.cs deleted file mode 100644 index 0df765c7..00000000 --- a/src/CreateAndFake/Design/Content/Disposer.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace CreateAndFake.Design.Content; - -/// Disposes generated objects. -internal static class Disposer -{ - /// Tries to dispose . - /// Potential disposables to clean up. - internal static void Cleanup(params object?[]? items) - { - foreach (object? item in items ?? Enumerable.Empty()) - { - (item as IDisposable)?.Dispose(); - _ = (item as IAsyncDisposable)?.DisposeAsync().Preserve(); - } - } -} \ No newline at end of file diff --git a/src/CreateAndFake/Design/Content/IDeepCloneable.cs b/src/CreateAndFake/Design/Content/IDeepCloneable.cs deleted file mode 100644 index 24a90c83..00000000 --- a/src/CreateAndFake/Design/Content/IDeepCloneable.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace CreateAndFake.Design.Content; - -/// Provides self copy-by-value functionality. -public interface IDeepCloneable -{ - /// - /// Creates a clone where any mutation to this or the - /// created copy only affects that object and not the other. - /// - /// The created clone that is equal by value to this. - IDeepCloneable DeepClone(); -} diff --git a/src/CreateAndFake/Design/Content/IValueEquatable.cs b/src/CreateAndFake/Design/Content/IValueEquatable.cs deleted file mode 100644 index 4a4dcf40..00000000 --- a/src/CreateAndFake/Design/Content/IValueEquatable.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace CreateAndFake.Design.Content; - -/// Provides value equality without changing the default reference equality. -public interface IValueEquatable -{ - /// Compares this to by value. - /// Instance to compare this with. - /// - /// true if this is equal to by value; - /// false otherwise. - /// - bool ValuesEqual(object? other); - - /// Computes an identifying hash code for this based upon value. - /// The value computed hash code for this. - int GetValueHash(); -} diff --git a/src/CreateAndFake/Design/Content/ValueComparer.cs b/src/CreateAndFake/Design/Content/ValueComparer.cs deleted file mode 100644 index b7e7f28f..00000000 --- a/src/CreateAndFake/Design/Content/ValueComparer.cs +++ /dev/null @@ -1,252 +0,0 @@ -using System.Collections; - -namespace CreateAndFake.Design.Content; - -/// Compares objects/collections by value via if possible. -public sealed class ValueComparer : - IComparer, - IComparer, - IComparer, - IComparer, - IComparer, - IEqualityComparer, - IEqualityComparer, - IEqualityComparer, - IEqualityComparer, - IEqualityComparer -{ - /// Hash used for null values. - public static int NullHash { get; } = 0; - - /// Starting hash value. - public static int BaseHash { get; } = 1009; - - /// Multiplier for computing hashes. - public static int HashMultiplier { get; } = 92821; - - /// Default instance to use for comparing objects by value. - public static ValueComparer Use { get; } = new ValueComparer(); - - /// Determines if equals by value. - /// Object to compare with . - /// Object to compare with . - /// - /// true if equals by value; false otherwise. - /// - public new bool Equals(object? x, object? y) - { - if (ReferenceEquals(x, y)) - { - return true; - } - else if (x is null || y is null) - { - return false; - } - else if (x is IValueEquatable asValue) - { - return Equals(asValue, y as IValueEquatable); - } - else if (x is IEnumerable asEnum) - { - return Equals(asEnum, y as IEnumerable); - } - else - { - return x.Equals(y); - } - } - - /// - public bool Equals(IValueEquatable? x, IValueEquatable? y) - { - return x?.ValuesEqual(y) ?? y?.ValuesEqual(x) ?? true; - } - - /// - public bool Equals(IEnumerable? x, IEnumerable? y) - { - if (ReferenceEquals(x, y)) - { - return true; - } - else if (x is null || y is null) - { - return false; - } - else if (x is IDictionary asDict) - { - return Equals(asDict, y as IDictionary); - } - else - { - return EqualsBySequence(x, y); - } - } - - /// - private bool EqualsBySequence(IEnumerable x, IEnumerable y) - { - if (x is string) - { - return x.Equals(y); - } - else - { - IEnumerator xGen = x.GetEnumerator(); - IEnumerator yGen = y.GetEnumerator(); - - while (xGen.MoveNext()) - { - if (!yGen.MoveNext() || !Equals(xGen.Current, yGen.Current)) - { - return false; - } - } - return !yGen.MoveNext(); - } - } - - /// - public bool Equals(IDictionary? x, IDictionary? y) - { - if (ReferenceEquals(x, y)) - { - return true; - } - else if (x is null || y is null) - { - return false; - } - else if (x.Count != y.Count) - { - return false; - } - else - { - foreach (DictionaryEntry entry in x) - { - if (!y.Contains(entry.Key) || !Equals(entry.Value, y[entry.Key])) - { - return false; - } - } - return true; - } - } - - /// Computes an identifying hash code for based upon value. - /// Bundled objects to generate a single value hash code for. - /// The value computed hash code for . - public int GetHashCode(params object?[]? items) - { - return GetHashCode((IEnumerable?)items); - } - - /// Computes an identifying hash code for based upon value. - /// Object to generate a hash code for. - /// The value computed hash code for . - public int GetHashCode(object? obj) - { - if (obj is null) - { - return NullHash; - } - else if (obj is IValueEquatable asValue) - { - return GetHashCode(asValue); - } - else if (obj is IEnumerable asEnum) - { - return GetHashCode(asEnum); - } - else - { - return obj.GetHashCode(); - } - } - - /// - public int GetHashCode(IValueEquatable? obj) - { - return obj?.GetValueHash() ?? NullHash; - } - - /// - public int GetHashCode(IEnumerable? obj) - { - if (obj is null) - { - return NullHash; - } - else if (obj is string) - { - return obj.GetHashCode(); - } - else if (obj is IDictionary asDict) - { - return GetHashCode(asDict); - } - else - { - int hash = BaseHash; - foreach (object item in obj) - { - hash = hash * HashMultiplier + GetHashCode(item); - } - return hash; - } - } - - /// - public int GetHashCode(IDictionary? obj) - { - if (obj is null) - { - return NullHash; - } - else - { - int hash = BaseHash; - foreach (DictionaryEntry item in obj) - { - hash += GetHashCode(item.Key); - hash += GetHashCode(item.Value); - } - return hash; - } - } - - /// - /// Compares and by their value hash for sorting. - /// - /// Object to compare with . - /// Object to compare with . - /// - /// Positive value if > . - /// Zero if = . - /// Negative value if < . - /// - public int Compare(object? x, object? y) - { - return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); - } - - /// - public int Compare(IValueEquatable? x, IValueEquatable? y) - { - return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); - } - - /// - public int Compare(IEnumerable? x, IEnumerable? y) - { - return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); - } - - /// - public int Compare(IDictionary? x, IDictionary? y) - { - return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); - } -} diff --git a/src/CreateAndFake/Design/Content/ValueComparer[T].cs b/src/CreateAndFake/Design/Content/ValueComparer[T].cs deleted file mode 100644 index 86b0e3cd..00000000 --- a/src/CreateAndFake/Design/Content/ValueComparer[T].cs +++ /dev/null @@ -1,68 +0,0 @@ -namespace CreateAndFake.Design.Content; - -/// Compares objects/collections of Type by value. -/// Type of the objects to compare. -public sealed class ValueComparer : - IComparer, - IComparer>, - IEqualityComparer, - IEqualityComparer> - where T : IValueEquatable -{ - /// - public static ValueComparer Use { get; } = new ValueComparer(); - - /// - public bool Equals(T? x, T? y) - { - return ValueComparer.Use.Equals(x, y); - } - - /// - public bool Equals(IEnumerable? x, IEnumerable? y) - { - return ValueComparer.Use.Equals(x, y); - } - - /// - public bool Equals(IDictionary? x, IDictionary? y) - { - return ValueComparer.Use.Equals(x, y); - } - - /// - public int GetHashCode(T? obj) - { - return ValueComparer.Use.GetHashCode(obj); - } - - /// - public int GetHashCode(IEnumerable? obj) - { - return ValueComparer.Use.GetHashCode(obj); - } - - /// - public int GetHashCode(IDictionary? obj) - { - return ValueComparer.Use.GetHashCode(obj); - } - - /// - public int Compare(T? x, T? y) - { - return ValueComparer.Use.Compare(x, y); - } - - /// - public int Compare(IEnumerable? x, IEnumerable? y) - { - return ValueComparer.Use.Compare(x, y); - } - - /// - public int Compare(IDictionary? x, IDictionary? y) - { - return ValueComparer.Use.Compare(x, y); - } -} diff --git a/src/CreateAndFake/Design/Context/BaseDataContext.cs b/src/CreateAndFake/Design/Context/BaseDataContext.cs deleted file mode 100644 index 42d10c8e..00000000 --- a/src/CreateAndFake/Design/Context/BaseDataContext.cs +++ /dev/null @@ -1,17 +0,0 @@ -using CreateAndFake.Design.Randomization; - -namespace CreateAndFake.Design.Context; - -/// Bundles associated random values from data pools. -public abstract class BaseDataContext -{ - /// - protected IRandom Gen { get; } - - /// - /// - internal BaseDataContext(IRandom gen) - { - Gen = gen ?? throw new ArgumentNullException(nameof(gen)); - } -} \ No newline at end of file diff --git a/src/CreateAndFake/Design/Context/PersonContext.cs b/src/CreateAndFake/Design/Context/PersonContext.cs deleted file mode 100644 index 4089007c..00000000 --- a/src/CreateAndFake/Design/Context/PersonContext.cs +++ /dev/null @@ -1,35 +0,0 @@ -using CreateAndFake.Design.Data; -using CreateAndFake.Design.Randomization; - -namespace CreateAndFake.Design.Context; - -/// Bundled random values for a person. -public sealed class PersonContext : BaseDataContext -{ - /// Name fragment. - private readonly Lazy _firstName, _middleName, _lastName; - - /// - /// - internal PersonContext(IRandom gen) : base(gen) - { - _firstName = new(() => Gen.NextItem(NameData.Values)); - _middleName = new(() => Gen.NextItem(NameData.Values)); - _lastName = new(() => Gen.NextItem(NameData.Values)); - } - - /// First name for the person. - public string FirstName => _firstName.Value; - - /// Middle name for the person. - public string MiddleName => _middleName.Value; - - /// Last name for the person. - public string LastName => _lastName.Value; - - /// First and last name for the person. - public string FullName => $"{FirstName} {LastName}"; - - /// Initials for the person's name. - public string Initials => $"{FirstName[0]}{MiddleName[0]}{LastName[0]}"; -} diff --git a/src/CreateAndFake/Design/Limiter.cs b/src/CreateAndFake/Design/Limiter.cs deleted file mode 100644 index 8bd1aaa6..00000000 --- a/src/CreateAndFake/Design/Limiter.cs +++ /dev/null @@ -1,403 +0,0 @@ -using System.Diagnostics; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Design; - -/// Provides the core functionality for repetition. -/// -/// -/// -public sealed class Limiter(TimeSpan timeout, int tries, TimeSpan? delay = null) : IEquatable -{ - /// Instance that defaults to a single attempt. - public static Limiter Once { get; } = new Limiter(1); - - /// Instance that defaults to five attempts. - public static Limiter Few { get; } = new Limiter(5); - - /// Instance that defaults to a dozen attempts. - public static Limiter Dozen { get; } = new Limiter(12); - - /// Instance that defaults to a hundred attempts. - public static Limiter Hundred { get; } = new Limiter(100); - - /// Instance that defaults to a thousand attempts. - public static Limiter Myriad { get; } = new Limiter(1000); - - /// Instance that defaults to half a second with a small delay. - public static Limiter Quick { get; } = new Limiter( - new TimeSpan(0, 0, 0, 0, 500), new TimeSpan(0, 0, 0, 0, 20)); - - /// Instance that defaults to five seconds with a large delay. - public static Limiter Slow { get; } = new Limiter( - new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 0, 0, 200)); - - /// Maximum attempts to try. - private readonly int _tries = tries; - - /// Maximum duration to attempt for. - private readonly TimeSpan _timeout = timeout; - - /// Delay between attempts. - private readonly TimeSpan _delay = delay ?? TimeSpan.Zero; - - /// - public Limiter(int tries, TimeSpan? delay = null) - : this(TimeSpan.MaxValue, tries, delay) { } - - /// - public Limiter(TimeSpan timeout, TimeSpan? delay = null) - : this(timeout, int.MaxValue, delay) { } - - /// Awaitable Task handling the repetitions. - /// - public Task Repeat(string message, Action? behavior, CancellationToken? canceler = null) - { - return Repeat(message, () => { behavior?.Invoke(); return true; }, canceler); - } - - /// Repeats . - /// Type returned from . - /// Details to include upon a . - /// Behavior to repeatably do. - /// Token to potentially cancel the attempts. - /// Results from all calls. - public async Task> Repeat( - string message, Func behavior, CancellationToken? canceler = null) - { - ArgumentGuard.ThrowIfNull(behavior, nameof(behavior)); - - List results = []; - - Stopwatch watch = Stopwatch.StartNew(); - int attempt = 0; - do - { - results.Add(behavior.Invoke()); - } while (await DelayIfNotDone(message, watch.Elapsed, ++attempt, canceler).ConfigureAwait(false)); - - return results.AsReadOnly(); - } - - /// Retries until it returns true. - /// - public Task StallUntil(string message, Func behavior, CancellationToken? canceler = null) - { - return StallUntil(message, null, behavior, canceler); - } - - /// Awaitable Task handling the repetitions. - /// - public Task StallUntil(string message, Action? behavior, Func checkState, CancellationToken? canceler = null) - { - return StallUntil(message, () => { behavior?.Invoke(); return true; }, checkState, canceler); - } - - /// - public Task> StallUntil( - string message, Func behavior, Func checkState, CancellationToken? canceler = null) - { - return StallUntil(message, behavior, (T _) => checkState.Invoke(), canceler); - } - - /// Retries until . - /// Result Type returned from . - /// Details to include upon a . - /// Behavior to repeatably attempt. - /// Polls if the behavior was successful. - /// Token to potentially cancel the attempts. - /// Results from all calls. - /// If an attempt limit is reached. - /// Beware infinite loops in . - public async Task> StallUntil( - string message, Func behavior, Func checkState, CancellationToken? canceler = null) - { - ArgumentGuard.ThrowIfNull(behavior, nameof(behavior)); - ArgumentGuard.ThrowIfNull(checkState, nameof(checkState)); - - List results = []; - - Stopwatch watch = Stopwatch.StartNew(); - for (int i = 1; true; i++) - { - T result = behavior.Invoke(); - - results.Add(result); - if (checkState.Invoke(result)) - { - break; - } - else - { - await DelayOrFault(message, watch.Elapsed, i, canceler).ConfigureAwait(false); - } - } - - return results.AsReadOnly(); - } - - /// - public Task Retry(string message, Action behavior, CancellationToken? canceler = null) - { - return Retry(message, behavior, null, canceler); - } - - /// - public Task Retry(string message, Action behavior, Action resetState, CancellationToken? canceler = null) - { - return Retry(message, behavior, resetState, canceler); - } - - /// - public Task Retry(string message, Action behavior, CancellationToken? canceler = null) - where TException : Exception - { - return Retry(message, behavior, null, canceler); - } - - /// Awaitable Task handling the repetitions. - /// - public Task Retry( - string message, Action behavior, Action? resetState, CancellationToken? canceler = null) - where TException : Exception - { - return Retry(message, () => { behavior?.Invoke(); return true; }, resetState, canceler); - } - - /// - public Task Retry(string message, Func behavior, CancellationToken? canceler = null) - { - return Retry(message, behavior, null, canceler); - } - - /// - public Task Retry( - string message, Func behavior, Action resetState, CancellationToken? canceler = null) - { - return Retry(message, behavior, resetState, canceler); - } - - /// - public Task Retry( - string message, Func behavior, CancellationToken? canceler = null) - where TException : Exception - { - return Retry(message, behavior, null, canceler); - } - - /// Result of the successful attempt. - /// If an attempt limit is reached. - /// - public async Task Retry( - string message, Func behavior, Action? resetState, CancellationToken? canceler = null) - where TException : Exception - { - ArgumentGuard.ThrowIfNull(behavior, nameof(behavior)); - - Stopwatch watch = Stopwatch.StartNew(); - for (int i = 1; true; i++) - { - TException lastError; - try - { - return behavior.Invoke(); - } - catch (TException error) - { - lastError = error; - } - resetState?.Invoke(); - await DelayOrFault(message, watch.Elapsed, i, canceler, lastError).ConfigureAwait(false); - } - } - - /// - public Task Attempt(string message, Action behavior, CancellationToken? canceler = null) - { - return Attempt(message, behavior, null, canceler); - } - - /// - public Task Attempt(string message, Action behavior, Action resetState, CancellationToken? canceler = null) - { - return Attempt(message, behavior, resetState, canceler); - } - - /// - public Task Attempt(string message, Action behavior, CancellationToken? canceler = null) - where TException : Exception - { - return Attempt(message, behavior, null, canceler); - } - - /// Awaitable task handling the repetitions. - /// - public Task Attempt( - string message, Action? behavior, Action? resetState, CancellationToken? canceler = null) - where TException : Exception - { - return Attempt(message, () => { behavior?.Invoke(); return true; }, resetState, canceler); - } - - /// - public Task Attempt(string message, Func behavior, CancellationToken? canceler = null) - { - return Attempt(message, behavior, null, canceler); - } - - /// - public Task Attempt( - string message, Func behavior, Action resetState, CancellationToken? canceler = null) - { - return Attempt(message, behavior, resetState, canceler); - } - - /// - public Task Attempt( - string message, Func behavior, CancellationToken? canceler = null) - where TException : Exception - { - return Attempt(message, behavior, null, canceler); - } - - /// - /// Retries when encountering - /// exceptions of Type . - /// - /// - /// Exception Type to ignore and retry if encountered. - /// - /// Result Type returned from . - /// Details to include upon a . - /// Behavior to repeatably attempt. - /// Behavior to reset state before next attempt. - /// Token to potentially cancel the attempts. - /// - /// Result of the successful attempt or default if limit reached. - /// - /// If an attempt limit is reached. - /// Beware infinite loops in . - public async Task Attempt( - string message, Func behavior, Action? resetState, CancellationToken? canceler = null) - where TException : Exception - { - ArgumentGuard.ThrowIfNull(behavior, nameof(behavior)); - - Stopwatch watch = Stopwatch.StartNew(); - int i = 0; - do - { - try - { - return behavior.Invoke(); - } - catch (TException) { } - - resetState?.Invoke(); - } while (await DelayIfNotDone(message, watch.Elapsed, ++i, canceler).ConfigureAwait(false)); - - return default; - } - - /// Delays if terminal condition not reached. - /// Details to include upon a . - /// Current amount of time that has elapsed. - /// Current number of attempts. - /// Token to potentially cancel the attempts. - /// true if terminal condition not reached; false otherwise. - private async Task DelayIfNotDone(string message, TimeSpan elapsed, int tries, CancellationToken? canceler) - { - if (tries < _tries && elapsed < _timeout) - { - await DelayOrCancel(message, canceler).ConfigureAwait(false); - return true; - } - else - { - return false; - } - } - - /// Faults if terminal condition reached; delays otherwise. - /// Details to include upon a timeout exception. - /// Current amount of time that has elapsed. - /// Current number of attempts. - /// Token to potentially cancel the attempts. - /// Current exception if present. - /// Awaitable Task handling the delay. - /// If an attempt limit is reached. - private async Task DelayOrFault( - string message, TimeSpan elapsed, int tries, CancellationToken? canceler, Exception? ex = null) - { - string details = string.IsNullOrWhiteSpace(message) ? "." : $": {message}"; - if (tries >= _tries) - { - throw new TimeoutException($"Reached max attempts of '{_tries}'{details}", ex); - } - else if (elapsed >= _timeout) - { - throw new TimeoutException($"Reached timeout of '{_timeout}'{details}", ex); - } - else - { - await DelayOrCancel(message, canceler).ConfigureAwait(false); - } - } - - /// Faults if behavior has been canceled; delays otherwise. - /// Details to include upon a timeout exception. - /// Token to potentially cancel the attempts. - /// Awaitable Task handling the delay. - private async Task DelayOrCancel(string message, CancellationToken? canceler) - { - CancellationToken token = canceler ?? CancellationToken.None; - try - { - if (_delay > TimeSpan.Zero) - { - await Task.Delay(_delay, token).ConfigureAwait(false); - } - else - { - token.ThrowIfCancellationRequested(); - } - } - catch (OperationCanceledException e) - { - string details = string.IsNullOrWhiteSpace(message) ? "." : $": {message}"; - throw new OperationCanceledException($"Operation canceled via token{details}", e, token); - } - } - - /// Compares this to by value. - /// Instance to compare this with. - /// - /// true if this is equal to by value; false otherwise. - /// - public override bool Equals(object? obj) - { - return Equals(obj as Limiter); - } - - /// - public bool Equals(Limiter? other) - { - return other != null - && other._delay == _delay - && other._tries == _tries - && other._timeout == _timeout; - } - - /// - public override int GetHashCode() - { - return ValueComparer.Use.GetHashCode(_tries, _timeout, _delay); - } - - /// Converts this to a string. - /// string representation of this. - public override string ToString() - { - return $"{_tries}-{_timeout}-{_delay}"; - } -} diff --git a/src/CreateAndFake/Design/Nullable/MaybeNullAttribute.cs b/src/CreateAndFake/Design/Nullable/MaybeNullAttribute.cs deleted file mode 100644 index 7dabed4b..00000000 --- a/src/CreateAndFake/Design/Nullable/MaybeNullAttribute.cs +++ /dev/null @@ -1,11 +0,0 @@ -#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 - -namespace System.Diagnostics.CodeAnalysis; - -/// Specifies the attached data may actually be null. -[ExcludeFromCodeCoverage, AttributeUsage( - AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.ReturnValue, - Inherited = false)] -internal sealed class MaybeNullAttribute : Attribute { } - -#endif diff --git a/src/CreateAndFake/Design/Nullable/NotNullAttribute.cs b/src/CreateAndFake/Design/Nullable/NotNullAttribute.cs deleted file mode 100644 index bbaded38..00000000 --- a/src/CreateAndFake/Design/Nullable/NotNullAttribute.cs +++ /dev/null @@ -1,11 +0,0 @@ -#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 - -namespace System.Diagnostics.CodeAnalysis; - -/// Specifies the attached data will not be null when the call returns. -[ExcludeFromCodeCoverage, AttributeUsage( - AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.ReturnValue, - Inherited = false)] -internal sealed class NotNullAttribute : Attribute { } - -#endif \ No newline at end of file diff --git a/src/CreateAndFake/Design/Nullable/NotNullIfNotNullAttribute.cs b/src/CreateAndFake/Design/Nullable/NotNullIfNotNullAttribute.cs deleted file mode 100644 index bbaa86b5..00000000 --- a/src/CreateAndFake/Design/Nullable/NotNullIfNotNullAttribute.cs +++ /dev/null @@ -1,19 +0,0 @@ -#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 - -namespace System.Diagnostics.CodeAnalysis; - -/// -/// Specifies the attached data will not be null when is not null. -/// -/// -[ExcludeFromCodeCoverage, AttributeUsage( - AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, - AllowMultiple = true, - Inherited = false)] -internal sealed class NotNullIfNotNullAttribute(string parameterName) : Attribute -{ - /// Name of the associated parameter that matches nullability. - public string ParameterName { get; } = parameterName; -} - -#endif diff --git a/src/CreateAndFake/Design/Nullable/NotNullWhenAttribute.cs b/src/CreateAndFake/Design/Nullable/NotNullWhenAttribute.cs deleted file mode 100644 index a04a7dec..00000000 --- a/src/CreateAndFake/Design/Nullable/NotNullWhenAttribute.cs +++ /dev/null @@ -1,16 +0,0 @@ -#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 - -namespace System.Diagnostics.CodeAnalysis; - -/// -/// Specifies the attached data will not be null when the call returns with . -/// -/// -[ExcludeFromCodeCoverage, AttributeUsage(AttributeTargets.Parameter, Inherited = false)] -internal sealed class NotNullWhenAttribute(bool returnValue) : Attribute -{ - /// Result when the attached data will not be null. - public bool ReturnValue { get; } = returnValue; -} - -#endif \ No newline at end of file diff --git a/src/CreateAndFake/Design/Randomization/DataRandom.cs b/src/CreateAndFake/Design/Randomization/DataRandom.cs deleted file mode 100644 index 30c11ccf..00000000 --- a/src/CreateAndFake/Design/Randomization/DataRandom.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Text; -using CreateAndFake.Design.Context; - -namespace CreateAndFake.Design.Randomization; - -/// Collects random predefined values to use for data generation. -public sealed class DataRandom -{ - /// Supported searchable property names for values. - private static readonly Dictionary> _Matcher = new() - { - { "FIRSTNAME", gen => gen.Person.FirstName }, - { "MIDDLENAME", gen => gen.Person.MiddleName }, - { "LASTNAME", gen => gen.Person.LastName }, - { "FULLNAME", gen => gen.Person.FullName }, - { "INITIALS", gen => gen.Person.Initials } - }; - - /// All searchable names. - internal static ICollection SupportedProperties => _Matcher.Keys; - - /// - private readonly IRandom _gen; - - /// - private readonly Lazy _person; - - /// - public PersonContext Person => _person.Value; - - /// - /// - internal DataRandom(IRandom gen) - { - _gen = gen ?? throw new ArgumentNullException(nameof(gen)); - _person = new(() => new PersonContext(_gen)); - } - - /// Searches for a value representing the identifying . - /// Name to match a value with. - /// The value representing if found; null otherwise. - public string? Find(string? name) - { - return _Matcher.TryGetValue(ToUpperOnly(name), out Func? finder) - ? finder.Invoke(this) - : null; - } - - /// Converts to uppercase letters only. - /// Text to convert. - /// The uppercase converted text. - private static string ToUpperOnly(string? value) - { - StringBuilder result = new(); - foreach (char c in value?.ToUpperInvariant() ?? "") - { - if (c is >= 'A' and <= 'Z') - { - _ = result.Append(c); - } - } - return result.ToString(); - } -} diff --git a/src/CreateAndFake/Design/Randomization/FastRandom.cs b/src/CreateAndFake/Design/Randomization/FastRandom.cs deleted file mode 100644 index 0dd5231a..00000000 --- a/src/CreateAndFake/Design/Randomization/FastRandom.cs +++ /dev/null @@ -1,27 +0,0 @@ -#pragma warning disable CA5394 // Do not use insecure randomness: Valid option and secure alternative provided. - -namespace CreateAndFake.Design.Randomization; - -/// For quickly generating cryptographically insecure random values. -/// -public sealed class FastRandom(bool onlyValidValues = true) : ValueRandom(onlyValidValues) -{ - /// - public override int? InitialSeed { get; } = null; - - /// Source generator used for random bytes. - private static readonly Random _Gen = new(); - - /// - protected override byte[] NextBytes(short length) - { - byte[] buffer = new byte[length]; - lock (_Gen) - { - _Gen.NextBytes(buffer); - } - return buffer; - } -} - -#pragma warning restore CA5394 // Do not use insecure randomness diff --git a/src/CreateAndFake/Design/Randomization/IRandom.cs b/src/CreateAndFake/Design/Randomization/IRandom.cs deleted file mode 100644 index 2c263c04..00000000 --- a/src/CreateAndFake/Design/Randomization/IRandom.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFake.Design.Randomization; - -/// Provides the core functionality for generic randomization. -[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", - MessageId = "Next", Justification = "Matches the Random convention.")] -public interface IRandom -{ - /// Initial seed used to begin generating values. - int? InitialSeed { get; } - - /// Checks if can be used for . - /// Type to determine randomization support for. - /// true if is supported; false otherwise. - bool Supports() where T : struct, IComparable, IComparable, IEquatable; - - /// Checks if can be used for . - /// Type to determine randomization support for. - /// true if is supported; false otherwise. - bool Supports([NotNullWhen(true)] Type? type); - - /// Generates a random value. - /// Value type to generate. - /// The generated value. - /// If isn't supported. - T Next() where T : struct, IComparable, IComparable, IEquatable; - - /// Generates a random value. - /// Value type to generate. - /// The generated value. - /// If isn't supported. - object Next(Type valueType); - - /// Generates a positive constrained value. - /// Value type to generate. - /// Positive exclusive upper boundary for the value. - /// The generated value < . - /// If isn't supported. - /// If < 0. - T Next(T max) where T : struct, IComparable, IComparable, IEquatable; - - /// Generates a constrained value. - /// Value type to generate. - /// Inclusive lower boundary for the value. - /// Exclusive upper boundary for the value. - /// - /// The generated value >= and < . - /// - /// If isn't supported. - /// - /// If < . - /// - T Next(T min, T max) where T : struct, IComparable, IComparable, IEquatable; - - /// Picks a random item from . - /// Type of items being picked from. - /// Collection of items to pick from. - /// The picked item from . - /// If is null or empty. - T NextItem(IEnumerable items); - - /// - /// The picked item from if any; default for the type otherwise. - [return: MaybeNull, NotNullIfNotNull(nameof(items))] - T NextItemOrDefault(IEnumerable? items); - - /// Generates a group of random predefined data.> - /// The generated group of random predefined data. - DataRandom NextData(); -} diff --git a/src/CreateAndFake/Design/Randomization/SecureRandom.cs b/src/CreateAndFake/Design/Randomization/SecureRandom.cs deleted file mode 100644 index ec07f13d..00000000 --- a/src/CreateAndFake/Design/Randomization/SecureRandom.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Security.Cryptography; - -namespace CreateAndFake.Design.Randomization; - -/// For slowly generating cryptographically secure random values. -/// -public sealed class SecureRandom(bool onlyValidValues = true) : ValueRandom(onlyValidValues) -{ - /// - public override int? InitialSeed { get; } = null; - - /// Source generator used for random bytes. - private static readonly RandomNumberGenerator _Gen = RandomNumberGenerator.Create(); - - /// - protected override byte[] NextBytes(short length) - { - byte[] buffer = new byte[length]; - _Gen.GetBytes(buffer); - return buffer; - } -} diff --git a/src/CreateAndFake/Design/Randomization/SeededRandom.cs b/src/CreateAndFake/Design/Randomization/SeededRandom.cs deleted file mode 100644 index f0af0f51..00000000 --- a/src/CreateAndFake/Design/Randomization/SeededRandom.cs +++ /dev/null @@ -1,51 +0,0 @@ -#pragma warning disable CA5394 // Do not use insecure randomness: Valid option and secure alternative provided. - -namespace CreateAndFake.Design.Randomization; - -/// For generating deterministic random values. -public sealed class SeededRandom : ValueRandom -{ - /// Lock to prevent thread collision with seeds. - private readonly object _lock = new(); - - /// Current seed to be used for the next randomized value. - private int _seed; - - /// - public int Seed - { - get { lock (_lock) { return _seed; } } - } - - /// - public override int? InitialSeed { get; } - - /// - public SeededRandom(int? seed = null) : this(true, seed) { } - - /// - /// - /// - public SeededRandom(bool onlyValidValues, int? seed = null) : base(onlyValidValues) - { - InitialSeed = seed ?? Environment.TickCount; - _seed = InitialSeed.Value; - } - - /// - protected override byte[] NextBytes(short length) - { - Random gen; - lock (_lock) - { - gen = new Random(_seed); - _seed = gen.Next(); - } - - byte[] buffer = new byte[length]; - gen.NextBytes(buffer); - return buffer; - } -} - -#pragma warning restore CA5394 // Do not use insecure randomness diff --git a/src/CreateAndFake/Design/Randomization/ValueRandom.cs b/src/CreateAndFake/Design/Randomization/ValueRandom.cs deleted file mode 100644 index 1fa28e82..00000000 --- a/src/CreateAndFake/Design/Randomization/ValueRandom.cs +++ /dev/null @@ -1,211 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFake.Design.Randomization; - -/// -/// -public abstract class ValueRandom(bool onlyValidValues) : IRandom -{ - /// Supported types paired with the method used to generate them. - private static readonly Dictionary> _Gens = new() - { - { typeof(double), gen => Create(gen, BitConverter.ToDouble, 8, - double.NaN, double.NegativeInfinity, double.PositiveInfinity) }, - { typeof(float), gen => Create(gen, BitConverter.ToSingle, 4, - float.NaN, float.NegativeInfinity, float.PositiveInfinity) }, - - { typeof(ushort), gen => Create(gen, BitConverter.ToUInt16, 2) }, - { typeof(ulong), gen => Create(gen, BitConverter.ToUInt64, 8) }, - { typeof(short), gen => Create(gen, BitConverter.ToInt16, 2) }, - { typeof(uint), gen => Create(gen, BitConverter.ToUInt32, 4) }, - { typeof(long), gen => Create(gen, BitConverter.ToInt64, 8) }, - { typeof(char), gen => Create(gen, BitConverter.ToChar, 2) }, - { typeof(int), gen => Create(gen, BitConverter.ToInt32, 4) }, - - { typeof(byte), gen => gen.NextBytes(1)[0] }, - { typeof(sbyte), gen => (sbyte)gen.Next() }, - { typeof(bool), gen => gen.Next() > byte.MaxValue / 2 }, - - { typeof(decimal), gen => new decimal( - gen.Next(), gen.Next(), gen.Next(), gen.Next(), gen.Next(29)) } - }; - - /// Generates a random value using random bytes. - /// Type to create. - /// Instance generating the random bytes. - /// Behavior used to convert the bytes to . - /// Number of bytes required to generate . - /// Special invalid values for the type. - /// The generated value. - private static T Create(ValueRandom gen, Func converter, short size, params T[] invalids) - { - T value; - do - { - value = converter.Invoke(gen.NextBytes(size), 0); - } while (gen.OnlyValidValues && invalids.Any(v => Equals(v, value))); - return value; - } - - /// All supported value types. - public static ICollection ValueTypes => _Gens.Keys; - - /// Flag to prevent generating invalid values (NaN, -∞ and +∞). - public bool OnlyValidValues { get; set; } = onlyValidValues; - - /// - public abstract int? InitialSeed { get; } - - /// Generates a byte array filled with random bytes. - /// Length of the byte array to generate. - /// The generated byte array. - protected abstract byte[] NextBytes(short length); - - /// - public bool Supports() where T : struct, IComparable, IComparable, IEquatable - { - return Supports(typeof(T)); - } - - /// - public bool Supports([NotNullWhen(true)] Type? type) - { - return (type != null) && _Gens.ContainsKey(type); - } - - /// - public T Next() where T : struct, IComparable, IComparable, IEquatable - { - return (T)Next(typeof(T)); - } - - /// - public object Next(Type valueType) - { - if (valueType != null && _Gens.TryGetValue(valueType, out Func? gen)) - { - return gen.Invoke(this); - } - else - { - throw new NotSupportedException($"Type '{valueType?.Name}' not supported."); - } - } - - /// - public T Next(T max) where T : struct, IComparable, IComparable, IEquatable - { - return Next(default, max); - } - - /// - public T Next(T min, T max) where T : struct, IComparable, IComparable, IEquatable - { - if (!Supports()) - { - throw new NotSupportedException($"Type '{typeof(T).Name}' not supported."); - } - else if (min.Equals(max)) - { - return min; - } - else if (min.CompareTo(max) >= 0) - { - throw new ArgumentOutOfRangeException(nameof(max), max, - $"Value must be greater than given min: '{min}'."); - } - else if (typeof(T) == typeof(bool)) - { - return default; - } - else - { - try - { - return CalcNext(min, max); - } - catch (ArithmeticException) - { - return StumbleNext(min, max); - } - } - } - - /// Uses an algorithm to generate the next value. - /// - private T CalcNext(T min, T max) where T : struct, IComparable, IComparable, IEquatable - { - dynamic percent; - - // Creates a number in the range of 0.0 to 1.0. - if (typeof(T) != typeof(decimal)) - { - percent = (double)Next() / uint.MaxValue; - } - else - { - percent = (decimal)Next() / uint.MaxValue; - } - - checked - { - T value = (T)(percent * ((dynamic)max - min) + min); - - // Prevent any issues stemming from imprecision. - return (value.CompareTo(max) < 0) ? value : min; - } - } - - /// Randoms until acceptable for the next value. - /// - private T StumbleNext(T min, T max) where T : struct, IComparable, IComparable, IEquatable - { - T value; - do - { - value = Next(); - } while (value.CompareTo(min) < 0 || value.CompareTo(max) >= 0); - return value; - } - - /// - public T NextItem(IEnumerable items) - { - if (items == null) - { - throw new InvalidOperationException("The source sequence is empty."); - } - else if (items is ICollection collection && collection.Count > 0) - { - return collection.ElementAt(Next(collection.Count)); - } - else - { - return items.OrderBy(i => Next()).First(); - } - } - - /// - [return: MaybeNull, NotNullIfNotNull(nameof(items))] - public T NextItemOrDefault(IEnumerable? items) - { - if (items == null) - { - return default; - } - else if (items is ICollection collection && collection.Count > 0) - { - return collection.ElementAt(Next(collection.Count))!; - } - else - { - return items.OrderBy(i => Next()).FirstOrDefault()!; - } - } - - /// - public DataRandom NextData() - { - return new(this); - } -} diff --git a/src/CreateAndFake/Extensions/AssertExtensions.cs b/src/CreateAndFake/Extensions/AssertExtensions.cs deleted file mode 100644 index 10ddca4a..00000000 --- a/src/CreateAndFake/Extensions/AssertExtensions.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.AsserterTool.Fluent; - -namespace CreateAndFake.Fluent; - -/// Provides fluent assertions. -public static class AssertExtensions -{ - /// - /// - /// Asserter to test with. - public static AssertObject Assert(this object? actual) - { - return new AssertObject(Tools.Gen, Tools.Valuer, actual); - } - - /// - /// - /// Asserter to test with. - public static AssertGroup Assert(this IEnumerable? collection) - { - return new AssertGroup(Tools.Gen, Tools.Valuer, collection); - } - - /// - /// - /// Asserter to test with. - public static AssertText Assert(this string? text) - { - return new AssertText(Tools.Gen, Tools.Valuer, text); - } - - /// - /// - /// Asserter to test with. - public static AssertComparable Assert(this IComparable? value) - { - return new AssertComparable(Tools.Gen, Tools.Valuer, value); - } - - /// - /// - /// Asserter to test with. - public static AssertType Assert(this Type? type) - { - return new AssertType(Tools.Gen, Tools.Valuer, type); - } - - /// - /// - /// Asserter to test with. - public static AssertError Assert(this Exception? error) - { - return new AssertError(Tools.Gen, Tools.Valuer, error); - } - - /// - /// - /// Asserter to test with. - public static AssertBehavior Assert(this Action? behavior) - { - return new AssertBehavior(Tools.Gen, Tools.Valuer, behavior); - } - - /// - /// Return Type of . - /// - /// Asserter to test with. - public static AssertBehavior Assert(this Func? behavior) - { - return new AssertBehavior(Tools.Gen, Tools.Valuer, behavior); - } - - /// Handles assertion calls for runtime . - /// Type of . - /// Object with to test. - /// Delegate on to test. - /// Asserter to test with. - /// Primarily useful for exception testing. - public static AssertBehavior Assert(this T origin, Action behavior) - { - return Assert(() => behavior.Invoke(origin)); - } - - /// - public static AssertBehavior Assert(this T origin, Func behavior) - { - return Assert(() => behavior.Invoke(origin)); - } -} diff --git a/src/CreateAndFake/Extensions/CreateExtensions.cs b/src/CreateAndFake/Extensions/CreateExtensions.cs deleted file mode 100644 index 691e5aa6..00000000 --- a/src/CreateAndFake/Extensions/CreateExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.MutatorTool; -using CreateAndFake.Toolbox.RandomizerTool; - -namespace CreateAndFake.Fluent; - -/// Provides fluent randomization options. -public static class CreateExtensions -{ - /// - [return: NotNullIfNotNull(nameof(source))] - public static T CreateDeepClone(this T source) - { - return Tools.Duplicator.Copy(source); - } - - /// - public static T CreateVariant(this T source) - { - return Tools.Mutator.Variant(source); - } - - /// - public static T CreateUnique(this T source) - { - return Tools.Mutator.Unique(source); - } - - /// - public static object CreateRandomInstance(this Type type) - { - return Tools.Randomizer.Create(type); - } -} diff --git a/src/CreateAndFake/Extensions/FakeExtensions.cs b/src/CreateAndFake/Extensions/FakeExtensions.cs deleted file mode 100644 index 0d69b3a3..00000000 --- a/src/CreateAndFake/Extensions/FakeExtensions.cs +++ /dev/null @@ -1,119 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.AsserterTool.Fluent; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -#pragma warning disable IDE0060 // Remove unused parameter: Provides fluent attachment. - -namespace CreateAndFake.Fluent; - -/// Provides fluent handling of fakes. -public static class FakeExtensions -{ - /// Ties a method call to fake behavior. - /// Result from the fake method to setup. - /// Value to set the call behavior with. - /// Expected number of calls for the behavior. - /// For use on stubs from the tool only. - /// - /// - /// T db = Tools.Faker.Stub{T}().Dummy; - /// db.Find(id).SetupReturn(data); - /// - /// - public static void SetupReturn(this T fakeCallResult, T returnValue, Times? times = null) - { - SetupCall(fakeCallResult, Behavior.Returns(returnValue, times)); - } - - /// Ties a method call to . - /// Result from the fake method to setup. - /// Behavior to set the call behavior with. - /// For use on stubs from the tool only. - public static void SetupCall(this T fakeCallResult, Behavior behavior) - { - FakeMetaProvider.SetLastCallBehavior(behavior); - } - - /// Accesses the raw fake wrapper. - /// Faked type. - /// Fake instance to wrap. - /// Fake to test with. - /// For use on stubs from the tool only. - public static Fake ToFake(this T fakeDummy) - { - return new((IFaked)fakeDummy!); - } - - /// Accesses the raw fake wrapper. - /// Faked type to cast to. - /// Fake instance to wrap. - /// Fake to test with. - /// For use on stubs from the tool only. - public static Fake ToFake(this object fakeDummy) - { - return new((IFaked)fakeDummy); - } - - /// Verifies all behaviors with associated times were called as expected. - /// Fake instance with behavior set. - /// Expected total number of calls to test as well. - /// - /// For use on stubs from the tool only. - /// When specifying , be aware of test framework calls for info/display. - /// - public static void VerifyAllCalls(this object fake, Times? total = null) - { - new Fake((IFaked)fake).VerifyAll(total); - } - - /// Asserter testing a method call using fakes. - /// Fake instance with behavior set. - /// Expected total number of calls to test as well. - /// - public static AssertChainer Called(this AssertObject asserter, object fake, Times? total = null) - { - ArgumentGuard.ThrowIfNull(asserter, nameof(asserter)); - - VerifyAllCalls(fake, total); - return asserter.ToChainer(); - } - - /// - public static AssertChainer Called(this AssertGroup asserter, object fake, Times? total = null) - { - ArgumentGuard.ThrowIfNull(asserter, nameof(asserter)); - - VerifyAllCalls(fake, total); - return asserter.ToChainer(); - } - - /// - public static AssertChainer Called(this AssertBehavior asserter, object fake, Times? total = null) - { - ArgumentGuard.ThrowIfNull(asserter, nameof(asserter)); - - VerifyAllCalls(fake, total); - return asserter.ToChainer(); - } - - /// - public static AssertChainer Called(this AssertText asserter, object fake, Times? total = null) - { - ArgumentGuard.ThrowIfNull(asserter, nameof(asserter)); - - VerifyAllCalls(fake, total); - return asserter.ToChainer(); - } - - /// - public static AssertChainer Called(this AssertComparable asserter, object fake, Times? total = null) - { - ArgumentGuard.ThrowIfNull(asserter, nameof(asserter)); - - VerifyAllCalls(fake, total); - return asserter.ToChainer(); - } -} - -#pragma warning restore IDE0060 // Remove unused parameter diff --git a/src/CreateAndFake/Extensions/TypeExtensions.cs b/src/CreateAndFake/Extensions/TypeExtensions.cs deleted file mode 100644 index a52b8526..00000000 --- a/src/CreateAndFake/Extensions/TypeExtensions.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using System.Runtime.CompilerServices; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox; - -/// Extensions for types. -public static class TypeExtensions -{ - /// Keeps track of type inheritance. - private static readonly Dictionary> _InheritCache = []; - - /// Finds subclasses of in the 's assembly. - /// to locate subclasses for. - /// The found creatable subclasses for . - public static IEnumerable FindLocalSubclasses(this Type type) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - return type.Assembly.GetTypes() - .Where(t => !t.IsAbstract) - .Where(t => t.Inherits(type)) - .Where(t => IsVisibleTo(t, Assembly.GetCallingAssembly().GetName())); - } - - /// Finds subclasses of in all loaded assemblies. - /// to locate subclasses for. - /// The found creatable subclasses for . - public static IEnumerable FindLoadedSubclasses(this Type type) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - return AppDomain.CurrentDomain.GetAssemblies() - .Where(a => !a.ReflectionOnly) - .Where(a => !a.IsDynamic) - .SelectMany(FindLoadedTypes) - .Where(t => !t.IsAbstract) - .Where(t => t.Inherits(type)) - .Where(t => IsVisibleTo(t, Assembly.GetCallingAssembly().GetName())); - } - - /// Finds all types in . - /// to load types from. - /// The found types if can load; none otherwise. - internal static Type[] FindLoadedTypes(Assembly? assembly) - { - try - { - return assembly?.GetTypes() ?? Type.EmptyTypes; - } - catch (FileNotFoundException) - { - return Type.EmptyTypes; - } - catch (ReflectionTypeLoadException) - { - return Type.EmptyTypes; - } - } - - /// Determines if is visible to . - /// to check. - /// Name of the . - /// - /// true if is visible to - /// ; false otherwise. - /// - public static bool IsVisibleTo([NotNullWhen(true)] this Type? type, AssemblyName assembly) - { - ArgumentGuard.ThrowIfNull(assembly, nameof(assembly)); - - return type != null && (type.IsVisible || type.Assembly - .GetCustomAttributes() - .Any(a => a.AssemblyName == assembly.Name)); - } - - /// Attempts to get the root generic type of . - /// to cast. - /// The casted if generic; null otherwise. - public static Type? AsGenericType(this Type? type) - { - return type != null && type.IsGenericType - ? type.GetGenericTypeDefinition() - : null; - } - - /// Checks if inherits . - /// Potential child of . - /// Potential parent of . - /// - /// true if inherits ; false otherwise. - /// - public static bool Inherits([NotNullWhen(true)] this Type? parent) - { - return Inherits(parent, typeof(T)); - } - - /// Checks if inherits . - /// Potential parent of . - /// Potential child of . - /// - /// true if inherits ; false otherwise. - /// - public static bool Inherits([NotNullWhen(true)] this Type? parent, [NotNullWhen(true)] Type? child) - { - return IsInheritedBy(child, parent); - } - - /// Checks if inherits . - /// Potential parent of . - /// Potential child of . - /// - /// true if inherits ; false otherwise. - /// - public static bool IsInheritedBy([NotNullWhen(true)] this Type? child) - { - return IsInheritedBy(child, typeof(T)); - } - - /// - public static bool IsInheritedBy([NotNullWhen(true)] this Type? child, [NotNullWhen(true)] Type? parent) - { - if (child == null || parent == null) - { - return false; - } - - HashSet? children; - lock (_InheritCache) - { - if (!_InheritCache.TryGetValue(parent, out children)) - { - _InheritCache[parent] = children = new HashSet(FindInheritance(parent).Distinct()); - } - } - - return children.Contains(Nullable.GetUnderlyingType(child) ?? child); - } - - /// Finds all types inherits. - /// to check. - /// The found types inherited by . - private static IEnumerable FindInheritance(Type? type) - { - if (type == null) - { - yield break; - } - - yield return type; - - if (type.IsGenericType) - { - yield return type.GetGenericTypeDefinition(); - } - - foreach (Type child in type.GetInterfaces().SelectMany(FindInheritance)) - { - yield return child; - } - - foreach (Type child in FindInheritance(type.BaseType)) - { - yield return child; - } - } -} diff --git a/src/CreateAndFake/Properties/AssemblyInfo.cs b/src/CreateAndFake/Properties/AssemblyInfo.cs deleted file mode 100644 index 966021f6..00000000 --- a/src/CreateAndFake/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,5 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: CLSCompliant(true)] -[assembly: InternalsVisibleTo("FakerTypes")] -[assembly: InternalsVisibleTo("CreateAndFakeTests")] diff --git a/src/CreateAndFake/Toolbox/AsserterTool/AssertException.cs b/src/CreateAndFake/Toolbox/AsserterTool/AssertException.cs deleted file mode 100644 index f783f15b..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/AssertException.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Runtime.Serialization; - -namespace CreateAndFake.Toolbox.AsserterTool; - -/// Exception for a failed case. -[Serializable, KnownType(typeof(Exception)), KnownType(typeof(Exception[]))] -public sealed class AssertException : Exception -{ - /// - /// Serialization constructor. - private AssertException() : base() { } - - /// - /// Reason for the exception. - /// Optional fail details. - /// Seed used for data generation. - /// Optional related content. - public AssertException(string? message, string? details, int? seed, string? content = null) - : base(BuildMessage(message, details, seed, content)) { } - - /// - /// Reason for the exception. - /// Optional fail details. - /// Seed used for data generation. - /// Inner exception that occurred. - public AssertException(string? message, string? details, int? seed, Exception innerException) - : base(BuildMessage(message, details, seed), innerException) { } - - /// - /// Reason for the exception. - /// Optional fail details. - /// Seed used for data generation. - /// Optional related content. - /// Inner exception that occurred. - public AssertException(string? message, string? details, int? seed, string? content, Exception innerException) - : base(BuildMessage(message, details, seed, content), innerException) { } - - /// - /// Object data. - /// Additional info. - /// Serialization constructor. -#if NET5_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private AssertException(SerializationInfo info, StreamingContext context) : base(info, context) { } - - /// Integrates the details into the message. - /// Starting message. - /// Details to integrate. - /// Seed used for data generation. - /// Content to integrate. - /// Message to use for the exception. - private static string BuildMessage(string? message, string? details, int? seed, string? content = null) - { - string nl = Environment.NewLine; - - return (message ?? "Unknown assert failure.") + - ((details != null) ? $"{nl}Details: {details}" : "") + - (seed.HasValue ? $"{nl}Seed: {seed.Value}" : "") + - ((content != null) ? $"{nl}Content: {nl}{content}" : ""); - } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Asserter.cs b/src/CreateAndFake/Toolbox/AsserterTool/Asserter.cs deleted file mode 100644 index 82bb9a0b..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Asserter.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System.Collections; -using System.Diagnostics.CodeAnalysis; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.AsserterTool.Fluent; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool; - -/// Handles common test scenarios. -/// -/// -/// If given a null parameter. -public class Asserter(IRandom gen, IValuer valuer) -{ - /// Core randomizer with a potential seed for logging. - protected IRandom Gen { get; } = gen ?? throw new ArgumentNullException(nameof(gen)); - - /// Handles comparisons for assertion checks. - protected IValuer Valuer { get; } = valuer ?? throw new ArgumentNullException(nameof(valuer)); - - /// Runs each case and aggregates exceptions. - /// Assert cases. - [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Rethrows all at end.")] - public virtual void CheckAll(params Action[] cases) - { - if (cases == null) - { - return; - } - - Exception?[] errors = new Exception[cases.Length]; - for (int i = 0; i < errors.Length; i++) - { - try - { - cases[i].Invoke(); - errors[i] = null; - } - catch (Exception e) - { - errors[i] = e; - } - } - - if (errors.Any(e => e != null)) - { - throw new AggregateException("Cases failed: " + - string.Join(", ", Enumerable.Range(0, errors.Length).Where(i => errors[i] != null)) + " -", - errors.Where(e => e != null).Select(e => e!)); - } - } - - /// - public virtual void Fail(string? details = null) - { - throw new AssertException("Test failed.", details, Gen.InitialSeed); - } - - /// Throws an assert exception. - /// Exception that occurred. - /// Optional failure details to include. - public virtual void Fail(Exception exception, string? details = null) - { - throw new AssertException("Test failed.", details, Gen.InitialSeed, exception); - } - - /// - /// - /// - public void Is(object? expected, object? actual, string? details = null) - { - _ = new AssertObject(Gen, Valuer, actual).Is(expected, details); - } - - /// - /// - /// - public void IsNot(object? expected, object? actual, string? details = null) - { - _ = new AssertObject(Gen, Valuer, actual).IsNot(expected, details); - } - - /// - /// - /// - public virtual void IsEmpty(IEnumerable? collection, string? details = null) - { - _ = new AssertGroup(Gen, Valuer, collection).IsEmpty(details); - } - - /// - /// - /// - public virtual void IsNotEmpty(IEnumerable? collection, string? details = null) - { - _ = new AssertGroup(Gen, Valuer, collection).IsNotEmpty(details); - } - - /// - /// - /// - public virtual void HasCount(int count, IEnumerable? collection, string? details = null) - { - _ = new AssertGroup(Gen, Valuer, collection).HasCount(count, details); - } - - /// - /// - /// - public virtual void ReferenceEqual(object? expected, object? actual, string? details = null) - { - _ = new AssertObject(Gen, Valuer, actual).ReferenceEqual(expected, details); - } - - /// - /// - /// - public virtual void ReferenceNotEqual(object? expected, object? actual, string? details = null) - { - _ = new AssertObject(Gen, Valuer, actual).ReferenceNotEqual(expected, details); - } - - /// - /// - /// - public virtual void ValuesEqual(object? expected, object? actual, string? details = null) - { - _ = new AssertObject(Gen, Valuer, actual).ValuesEqual(expected, details); - } - - /// - /// - /// - public virtual void ValuesNotEqual(object? expected, object? actual, string? details = null) - { - _ = new AssertObject(Gen, Valuer, actual).ValuesNotEqual(expected, details); - } - - /// - /// - /// - public virtual void AreUnique(object? expected, object? actual, string? details = null) - { - _ = new AssertObject(Gen, Valuer, actual).UniqueFrom(expected, details); - } - - /// - /// - public virtual T Throws(Action? behavior, string? details = null) where T : Exception - { - return new AssertBehavior(Gen, Valuer, behavior).Throws(details); - } - - /// - /// - public virtual T Throws(Func? behavior, string? details = null) where T : Exception - { - return new AssertBehavior(Gen, Valuer, behavior).Throws(details); - } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertBehavior.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertBehavior.cs deleted file mode 100644 index 956043ae..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertBehavior.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// -public sealed class AssertBehavior : AssertBehaviorBase -{ - /// - internal AssertBehavior(IRandom gen, IValuer valuer, Delegate? behavior) : base(gen, valuer, behavior) { } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertBehaviorBase.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertBehaviorBase.cs deleted file mode 100644 index fdedb9ad..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertBehaviorBase.cs +++ /dev/null @@ -1,79 +0,0 @@ -using CreateAndFake.Design.Content; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// Handles assertion calls for delegates. -/// Core value random handler. -/// Handles comparisons. -/// Delegate to check. -public abstract class AssertBehaviorBase(IRandom gen, IValuer valuer, Delegate? behavior) - : AssertObjectBase(gen, valuer, behavior) where T : AssertBehaviorBase -{ - /// Delegate to check. - protected Delegate? Behavior { get; } = behavior; - - /// Verifies behavior throws an exception. - /// Exception type expected. - /// Optional failure details to include. - /// If the expected behavior doesn't happen. - public virtual TException Throws(string? details = null) where TException : Exception - { - string errorMessage = $"Expected exception of type '{typeof(TException).FullName}'."; - try - { - if (Behavior is Action action) - { - action.Invoke(); - } - else - { - Disposer.Cleanup(((dynamic?)Behavior)?.Invoke()); - } - } - catch (TException e) - { - return e; - } - catch (AggregateException e) - { - if (e.InnerExceptions.Count == 1 && e.InnerExceptions[0] is TException actual) - { - return actual; - } - else - { - throw new AssertException(errorMessage, details, Gen.InitialSeed, e); - } - } - catch (Exception e) - { - throw new AssertException(errorMessage, details, Gen.InitialSeed, e); - } - - throw new AssertException(errorMessage, details, Gen.InitialSeed); - } - - /// Verifies behavior does not throw an exception. - /// Optional failure details to include. - /// If the expected behavior doesn't happen. - public virtual void ThrowsNoException(string? details = null) - { - try - { - if (Behavior is Action action) - { - action.Invoke(); - } - else - { - Disposer.Cleanup(((dynamic?)Behavior)?.Invoke()); - } - } - catch (Exception e) - { - throw new AssertException("Expected no exception.", details, Gen.InitialSeed, e); - } - } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertChainer.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertChainer.cs deleted file mode 100644 index 772a1f60..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertChainer.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Collections; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// Allows assertion calls to be chained fluently. -/// Assertion base Type to chain. -/// Assertion base instance to chain. -/// Core randomizer with a potential seed for logging. -/// Handles comparisons for assertion checks. -public sealed class AssertChainer(T chain, IRandom gen, IValuer valuer) -{ - /// Includes another assertion on the instance to test. - public T And { get; } = chain; - - /// Specifies a different instance to test. - /// - /// Asserter to test with. - public AssertObject Also(object? actual) - { - return new AssertObject(gen, valuer, actual); - } - - /// - /// Asserter to test with. - /// - public AssertGroup Also(IEnumerable? collection) - { - return new AssertGroup(gen, valuer, collection); - } - - /// - /// Asserter to test with. - /// - public AssertText Also(string? text) - { - return new AssertText(Tools.Gen, Tools.Valuer, text); - } - - /// - /// Asserter to test with. - /// - public AssertComparable Also(IComparable? value) - { - return new AssertComparable(Tools.Gen, Tools.Valuer, value); - } - - /// - /// Asserter to test with. - /// - public AssertType Also(Type? type) - { - return new AssertType(Tools.Gen, Tools.Valuer, type); - } - - /// - /// Asserter to test with. - /// - public AssertError Also(Exception? error) - { - return new AssertError(Tools.Gen, Tools.Valuer, error); - } - - /// - /// Asserter to test with. - /// - public AssertBehavior Also(Action? behavior) - { - return new AssertBehavior(Tools.Gen, Tools.Valuer, behavior); - } - - /// Return Type of . - /// - /// Asserter to test with. - /// - public AssertBehavior Also(Func? behavior) - { - return new AssertBehavior(Tools.Gen, Tools.Valuer, behavior); - } - - /// Handles assertion calls for runtime . - /// Type of . - /// Object with to test. - /// Delegate on to test. - /// Asserter to test with. - /// Primarily useful for exception testing. - public AssertBehavior Also(TOrigin origin, Action behavior) - { - return Also(() => behavior.Invoke(origin)); - } - - /// - public AssertBehavior Also(TOrigin origin, Func behavior) - { - return Also(() => behavior.Invoke(origin)); - } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertComparable.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertComparable.cs deleted file mode 100644 index fd92304a..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertComparable.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// -public sealed class AssertComparable : AssertComparableBase -{ - /// - internal AssertComparable(IRandom gen, IValuer valuer, IComparable? value) : base(gen, valuer, value) { } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertComparableBase.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertComparableBase.cs deleted file mode 100644 index 46d5c9ee..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertComparableBase.cs +++ /dev/null @@ -1,124 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// Handles common comparables assertion calls. -/// -/// -public abstract class AssertComparableBase(IRandom gen, IValuer valuer, IComparable? value) - : AssertObjectBase(gen, valuer, value) where T : AssertComparableBase -{ - /// Value to run assertion checks with. - protected IComparable? Value { get; } = value; - - /// Verifies value > . - /// - public virtual AssertChainer GreaterThan(IComparable expected, string? details = null) - { - return HandleMathCheck(() => Value!.CompareTo(expected) > 0, "greater than", expected, details); - } - - /// Verifies value >= . - /// - public virtual AssertChainer GreaterThanOrEqualTo(IComparable expected, string? details = null) - { - return HandleMathCheck(() => Value!.CompareTo(expected) >= 0, "greater than or equal to", expected, details); - } - - /// Verifies value > or equals by value. - /// - public virtual AssertChainer GreaterThanOrIs(IComparable expected, string? details = null) - { - return Valuer.Equals(Value, expected) - ? ToChainer() - : GreaterThanOrEqualTo(expected, details); - } - - /// Verifies value < . - /// - public virtual AssertChainer LessThan(IComparable expected, string? details = null) - { - return HandleMathCheck(() => Value!.CompareTo(expected) < 0, "less than", expected, details); - } - - /// Verifies value is <= . - /// - public virtual AssertChainer LessThanOrEqualTo(IComparable expected, string? details = null) - { - return HandleMathCheck(() => Value!.CompareTo(expected) <= 0, "less than or equal to", expected, details); - } - - /// Verifies value < or equals by value. - /// - public virtual AssertChainer LessThanOrIs(IComparable expected, string? details = null) - { - return Valuer.Equals(Value, expected) - ? ToChainer() - : LessThanOrEqualTo(expected, details); - } - - /// Verifies <= value <= . - /// Inclusive lower bound. - /// Inclusive upper bound. - /// Optional failure details to include. - /// Chainer to make additional assertions with. - public virtual AssertChainer InRange(IComparable min, IComparable max, string? details = null) - { - if (Value == null) - { - throw new AssertException( - $"Value was null and not in range [{min}, {max}].", - details, Gen.InitialSeed); - } - else if (min == null || max == null) - { - throw new AssertException( - $"Min {min} or max {max} was null and not valid for math comparison check.", - details, Gen.InitialSeed, Value.ToString()); - } - else if (Value.CompareTo(min) < 0 || Value.CompareTo(max) > 0) - { - throw new AssertException( - $"Value was not in range [{min}, {max}].", - details, Gen.InitialSeed, Value.ToString()); - } - else - { - return ToChainer(); - } - } - - /// Verifies value matches the . - /// Math used to check the value. - /// Math description to use for error message. - /// Value to compare with. - /// Optional failure details to include. - /// Chainer to make additional assertions with. - /// If value does not match . - private AssertChainer HandleMathCheck(Func math, string description, IComparable expected, string? details) - { - if (Value == null) - { - throw new AssertException( - $"Value was null and not {description} '{expected}'.", - details, Gen.InitialSeed); - } - else if (expected == null) - { - throw new AssertException( - $"Expected was null and not valid for math comparison check.", - details, Gen.InitialSeed, Value.ToString()); - } - else if (!math()) - { - throw new AssertException( - $"Value was not {description} '{expected}'.", - details, Gen.InitialSeed, Value.ToString()); - } - else - { - return ToChainer(); - } - } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertError.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertError.cs deleted file mode 100644 index 36e1fc57..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertError.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// -public sealed class AssertError : AssertErrorBase -{ - /// - internal AssertError(IRandom gen, IValuer valuer, Exception? error) : base(gen, valuer, error) { } -} - diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertErrorBase.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertErrorBase.cs deleted file mode 100644 index 0f89c481..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertErrorBase.cs +++ /dev/null @@ -1,27 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// Handles common assertion calls. -/// -/// -public abstract class AssertErrorBase(IRandom gen, IValuer valuer, Exception? error) - : AssertObjectBase(gen, valuer, error) where T : AssertErrorBase -{ - /// Exception to run assertion checks with. - protected Exception? Error { get; } = error; - - /// - public override void Fail(string? details = null) - { - if (Error != null) - { - throw new AssertException("Test failed.", details, Gen.InitialSeed, Error); - } - else - { - throw new AssertException("Test failed.", details, Gen.InitialSeed); - } - } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertGroup.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertGroup.cs deleted file mode 100644 index 86bfb813..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertGroup.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// -public sealed class AssertGroup : AssertGroupBase -{ - /// - internal AssertGroup(IRandom gen, IValuer valuer, IEnumerable? collection) : base(gen, valuer, collection) { } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertGroupBase.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertGroupBase.cs deleted file mode 100644 index 77c789b5..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertGroupBase.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System.Collections; -using System.Text; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// Handles common collection assertion calls. -/// -/// -public abstract class AssertGroupBase(IRandom gen, IValuer valuer, IEnumerable? collection) - : AssertObjectBase(gen, valuer, collection) where T : AssertGroupBase -{ - /// Collection to run assertion checks with. - protected IEnumerable? Collection { get; } = collection; - - /// Verifies collection is empty. - /// Optional failure details to include. - /// Chainer to make additional assertions with. - /// If collection fails to match the expected behavior. - public virtual AssertChainer IsEmpty(string? details = null) - { - return HasCount(0, details); - } - - /// Verifies collection is not empty. - /// - public virtual AssertChainer IsNotEmpty(string? details = null) - { - if (Collection == null) - { - throw new AssertException( - $"Expected collection with elements, but was 'null'.", details, Gen.InitialSeed); - } - else if (!Collection.GetEnumerator().MoveNext()) - { - throw new AssertException( - "Expected collection with elements, but was empty.", details, Gen.InitialSeed); - } - else - { - return ToChainer(); - } - } - - /// Verifies collection has elements. - /// Size that the collection should be. - /// - public virtual AssertChainer HasCount(int count, string? details = null) - { - if (Collection == null) - { - throw new AssertException( - $"Expected collection of '{count}' elements, but was 'null'.", details, Gen.InitialSeed); - } - - int i = 0; - StringBuilder contents = new(); - for (IEnumerator data = Collection.GetEnumerator(); data.MoveNext(); i++) - { - _ = contents.Append('[').Append(i).Append("]:").Append(data.Current).AppendLine(); - } - - if (i != count) - { - throw new AssertException( - $"Expected collection of '{count}' elements, but was '{i}'.", - details, Gen.InitialSeed, contents.ToString()); - } - - return ToChainer(); - } - - /// Verifies collection contains an element equal to by value. - /// Potential element to check for. - /// - public virtual AssertChainer Contains(object? content, string? details = null) - { - if (Collection == null) - { - throw new AssertException( - $"Expected collection to contain '{content}', but was 'null'.", details, Gen.InitialSeed); - } - - int i = 0; - bool success = false; - StringBuilder contents = new(); - for (IEnumerator data = Collection.GetEnumerator(); data.MoveNext(); i++) - { - success = success || Valuer.Equals(content, data.Current); - - _ = contents.Append('[').Append(i).Append("]:").Append(data.Current).AppendLine(); - } - - if (!success) - { - throw new AssertException( - $"Expected collection to contain '{content}' but didn't.", - details, Gen.InitialSeed, contents.ToString()); - } - - return ToChainer(); - } - - /// - /// Verifies collection contains an element unequal to by value. - /// - /// Potential element to check for. - /// - public virtual AssertChainer ContainsNot(object? content, string? details = null) - { - if (Collection == null) - { - throw new AssertException( - $"Expected collection to contain '{content}', but was 'null'.", details, Gen.InitialSeed); - } - - int i = 0; - bool success = true; - StringBuilder contents = new(); - for (IEnumerator data = Collection.GetEnumerator(); data.MoveNext(); i++) - { - success &= !Valuer.Equals(content, data.Current); - - _ = contents.Append('[').Append(i).Append("]:").Append(data.Current).AppendLine(); - } - - if (!success) - { - throw new AssertException( - $"Expected collection to contain '{content}' but didn't.", - details, Gen.InitialSeed, contents.ToString()); - } - - return ToChainer(); - } - - /// - public override void Fail(string? details = null) - { - if (Collection == null) - { - throw new AssertException($"Test failed.", details, Gen.InitialSeed, (string?)null); - } - - int i = 0; - StringBuilder contents = new(); - for (IEnumerator data = Collection.GetEnumerator(); data.MoveNext(); i++) - { - _ = contents.Append('[').Append(i).Append("]:").Append(data.Current).AppendLine(); - } - - throw new AssertException("Test failed.", details, Gen.InitialSeed, contents.ToString()); - } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertObject.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertObject.cs deleted file mode 100644 index c634f0ad..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertObject.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// -public sealed class AssertObject : AssertObjectBase -{ - /// - internal AssertObject(IRandom gen, IValuer valuer, object? actual) : base(gen, valuer, actual) { } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertObjectBase.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertObjectBase.cs deleted file mode 100644 index 0d69572a..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertObjectBase.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System.Text; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.MutatorTool; -using CreateAndFake.Toolbox.ValuerTool; - -#pragma warning disable CA1307 // Specify StringComparison for clarity: Not available for all versions. - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// Handles common assertion calls. -/// -/// -/// -public abstract class AssertObjectBase(IRandom gen, IValuer valuer, object? actual) where T : AssertObjectBase -{ - /// Core randomizer with a potential seed for logging. - protected IRandom Gen { get; } = gen ?? throw new ArgumentNullException(nameof(gen)); - - /// Handles comparisons for assertion checks. - protected IValuer Valuer { get; } = valuer ?? throw new ArgumentNullException(nameof(valuer)); - - /// Instance to run assertion checks with. - protected object? Actual { get; } = actual; - - /// Verifies actual equals by value. - /// Instance to compare against. - /// Optional failure details to include. - /// Chainer to make additional assertions with. - /// If the comparison fails to match the expected behavior. - public AssertChainer Is(object? expected, string? details = null) - { - return ValuesEqual(expected, details); - } - - /// Verifies actual unequals by value. - /// - public AssertChainer IsNot(object? expected, string? details = null) - { - return ValuesNotEqual(expected, details); - } - - /// Verifies actual equals by reference. - /// - public virtual AssertChainer ReferenceEqual(object? expected, string? details = null) - { - if (!ReferenceEquals(expected, Actual)) - { - throw new AssertException("References failed to equal.", details, Gen.InitialSeed); - } - return ToChainer(); - } - - /// Verifies actual unequals by reference. - /// - public virtual AssertChainer ReferenceNotEqual(object? expected, string? details = null) - { - if (ReferenceEquals(expected, Actual)) - { - throw new AssertException("References failed to not equal.", details, Gen.InitialSeed); - } - return ToChainer(); - } - - /// - public virtual AssertChainer ValuesEqual(object? expected, string? details = null) - { - Difference[] differences = Valuer.Compare(expected, Actual).ToArray(); - if (differences.Length > 0) - { - throw new AssertException($"Value equality failed for type '{GetTypeName(expected)}'.", - details, Gen.InitialSeed, string.Join(Environment.NewLine, differences)); - } - return ToChainer(); - } - - /// - public virtual AssertChainer ValuesNotEqual(object? expected, string? details = null) - { - if (!Valuer.Compare(expected, Actual).Any()) - { - throw new AssertException( - $"Value inequality failed for type '{GetTypeName(expected)}'.", - details, Gen.InitialSeed, expected?.ToString()); - } - return ToChainer(); - } - - /// Verifies actual shares no data with . - /// Instance to compare against. - /// Optional failure details to include. - /// Chainer to make additional assertions with. - /// If the comparison fails to match the expected behavior. - /// Ignores types with too small of range for unique randomization. - public virtual AssertChainer UniqueFrom(object? expected, string? details = null) - { - _ = ReferenceNotEqual(expected, details); - - int i = 0; - StringBuilder contents = new(); - foreach (object value in ContentMap.Extract(Actual).FindSharedContent(Valuer, ContentMap.Extract(expected))) - { - _ = contents.Append('#').Append(i++).Append(':').Append(value).AppendLine(); - } - - if (i != 0) - { - throw new AssertException( - $"Expected no shared content, but had '{i}' shared items.", - details, Gen.InitialSeed, contents.ToString()); - } - - return ToChainer(); - } - - /// Throws an assert exception. - /// Optional failure details to include. - public virtual void Fail(string? details = null) - { - throw new AssertException("Test failed.", details, Gen.InitialSeed, Actual?.ToString()); - } - - /// Stipulates the test is successful if it reaches this point. - public virtual void Pass() { } - - /// Finds a suitable Type name to use for assertion messages. - /// Instance being compared to actual. - /// The Type name to use if found; null otherwise. - protected string? GetTypeName(object? expected) - { - return ExpandTypeName((expected ?? Actual)?.GetType()); - } - - /// Builds Type name with generic argument names. - /// Type to describe. - /// The built name. - protected static string? ExpandTypeName(Type? type) - { - if (type != null && type.IsGenericType) - { - return string.Concat( - type.Name.Substring(0, type.Name.IndexOf('`')), - "<", - string.Join(",", type.GetGenericArguments().Select(ExpandTypeName)), - ">"); - } - else - { - return type?.Name; - } - } - - /// Converts this to a chainer for additional assertions on actual. - /// The created chainer. - protected internal AssertChainer ToChainer() - { - return new AssertChainer((T)this, Gen, Valuer); - } -} - -#pragma warning restore CA1307 // Specify StringComparison for clarity diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertText.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertText.cs deleted file mode 100644 index 5b681300..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertText.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// -public sealed class AssertText : AssertTextBase -{ - /// - internal AssertText(IRandom gen, IValuer valuer, string? text) : base(gen, valuer, text) { } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertTextBase.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertTextBase.cs deleted file mode 100644 index cb892bf5..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertTextBase.cs +++ /dev/null @@ -1,89 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -#pragma warning disable CA1307 // Specify StringComparison for clarity: Not available for all versions. -#pragma warning disable CA1310 // Specify StringComparison for correctness: Not available for all versions. - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// Handles common assertion calls. -/// -/// -public abstract class AssertTextBase(IRandom gen, IValuer valuer, string? text) - : AssertGroupBase(gen, valuer, text) where T : AssertTextBase -{ - /// Text to run assertion checks with. - protected string? Text { get; } = text; - - /// Verifies text contains . - /// Potential internal text to check for. - /// Optional failure details to include. - /// Chainer to make additional assertions with. - /// If text fails to match the expected behavior. - public virtual AssertChainer Contains(string content, string? details = null) - { - if (Text == null || !Text.Contains(content)) - { - throw new AssertException($"Text was missing '{content}'.", details, Gen.InitialSeed, Text); - } - return ToChainer(); - } - - /// Verifies text does not contain . - /// - public virtual AssertChainer ContainsNot(string content, string? details = null) - { - if (Text != null && Text.Contains(content)) - { - throw new AssertException($"Text contained '{content}'.", details, Gen.InitialSeed, Text); - } - return ToChainer(); - } - - /// Verifies text starts with . - /// - public virtual AssertChainer StartsWith(string content, string? details = null) - { - if (Text == null || !Text.StartsWith(content)) - { - throw new AssertException($"Text did not start with '{content}'.", details, Gen.InitialSeed, Text); - } - return ToChainer(); - } - - /// Verifies text does not start with . - /// - public virtual AssertChainer StartsNotWith(string content, string? details = null) - { - if (Text != null && Text.StartsWith(content)) - { - throw new AssertException($"Text started with '{content}'.", details, Gen.InitialSeed, Text); - } - return ToChainer(); - } - - /// Verifies text ends with . - /// - public virtual AssertChainer EndsWith(string content, string? details = null) - { - if (Text == null || !Text.EndsWith(content)) - { - throw new AssertException($"Text did not end with '{content}'.", details, Gen.InitialSeed, Text); - } - return ToChainer(); - } - - /// Verifies text does not end with . - /// - public virtual AssertChainer EndsNotWith(string content, string? details = null) - { - if (Text != null && Text.EndsWith(content)) - { - throw new AssertException($"Text ended with '{content}'.", details, Gen.InitialSeed, Text); - } - return ToChainer(); - } -} - -#pragma warning restore CA1307 // Specify StringComparison for clarity -#pragma warning restore CA1310 // Specify StringComparison for correctness diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertType.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertType.cs deleted file mode 100644 index db590e82..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertType.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// -public sealed class AssertType : AssertTypeBase -{ - /// - internal AssertType(IRandom gen, IValuer valuer, Type? type) : base(gen, valuer, type) { } -} diff --git a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertTypeBase.cs b/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertTypeBase.cs deleted file mode 100644 index 99cbc2f4..00000000 --- a/src/CreateAndFake/Toolbox/AsserterTool/Fluent/AssertTypeBase.cs +++ /dev/null @@ -1,80 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.ValuerTool; - -#pragma warning disable CA1716 // Rename conflicting virtual/interface member: Overriding here should be a rarity. - -namespace CreateAndFake.Toolbox.AsserterTool.Fluent; - -/// Handles common assertion calls. -/// -/// -public abstract class AssertTypeBase(IRandom gen, IValuer valuer, Type? type) - : AssertObjectBase(gen, valuer, type) where T : AssertTypeBase -{ - /// Type to run assertion checks with. - protected Type? Type { get; } = type; - - /// Verifies Type inherits . - /// Potential child of Type. - /// Optional failure details to include. - /// Chainer to make additional assertions with. - /// If Type fails to match the expected behavior. - public virtual AssertChainer Inherits(string? details = null) - { - if (!Type.Inherits()) - { - throw new AssertException( - $"'{ExpandTypeName(Type)}' does not inherit '{ExpandTypeName(typeof(TChild))}'.", - details, - Gen.InitialSeed); - } - return ToChainer(); - } - - /// Verifies Type inherits . - /// Potential child of Type. - /// - public virtual AssertChainer Inherits(Type? child, string? details = null) - { - if (!Type.Inherits(child)) - { - throw new AssertException( - $"'{ExpandTypeName(Type)}' does not inherit '{ExpandTypeName(child)}'.", - details, - Gen.InitialSeed); - } - return ToChainer(); - } - - /// Verifies inherits Type. - /// Potential parent of Type. - /// - public virtual AssertChainer InheritedBy(string? details = null) - { - if (!Type.IsInheritedBy()) - { - throw new AssertException( - $"'{ExpandTypeName(typeof(TParent))}' does not inherit '{ExpandTypeName(Type)}'.", - details, - Gen.InitialSeed); - } - return ToChainer(); - } - - /// Verifies inherits Type. - /// Potential parent of Type. - /// - public virtual AssertChainer InheritedBy(Type? parent, string? details = null) - { - if (!Type.IsInheritedBy(parent)) - { - throw new AssertException( - $"'{ExpandTypeName(parent)}' does not inherit '{ExpandTypeName(Type)}'.", - details, - Gen.InitialSeed); - } - return ToChainer(); - } -} - -#pragma warning restore CA1716 // Rename conflicting virtual/interface member diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHint.cs deleted file mode 100644 index bd4e52b1..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHint.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace CreateAndFake.Toolbox.DuplicatorTool; - -/// Handles cloning specific types for . -public abstract class CopyHint -{ - /// Tries to deep clone . - /// Object to clone. - /// Handles cloning child values. - /// - /// (true, clone of ) if successful; - /// (false, null) otherwise. - /// - protected internal abstract (bool, object?) TryCopy(object source, DuplicatorChainer duplicator); -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHint[T].cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHint[T].cs deleted file mode 100644 index 299b66cb..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHint[T].cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace CreateAndFake.Toolbox.DuplicatorTool; - -/// Type being supported for cloning. -/// -public abstract class CopyHint : CopyHint -{ - /// - protected internal sealed override (bool, object?) TryCopy(object source, DuplicatorChainer duplicator) - { - if (source is T data) - { - return (true, Copy(data, duplicator)); - } - else - { - return (false, null); - } - } - - /// Deep clones . - /// Object to clone. - /// Handles cloning child values. - /// Clone of . - protected abstract T Copy(T source, DuplicatorChainer duplicator); -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/AsyncCollectionCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/AsyncCollectionCopyHint.cs deleted file mode 100644 index 8102fa7c..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/AsyncCollectionCopyHint.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning collections for . -public sealed class AsyncCollectionCopyHint : CopyHint -{ - /// - protected internal override (bool, object?) TryCopy(object source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(source, nameof(source)); - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - if (source.GetType().Inherits(typeof(IAsyncEnumerable<>))) - { - return (true, typeof(AsyncCollectionCopyHint) - .GetMethod(nameof(CopyAsync), BindingFlags.Static | BindingFlags.NonPublic)! - .MakeGenericMethod(source.GetType().GetGenericArguments().Single()) - .Invoke(null, [source, duplicator])); - } - else - { - return (false, null); - } - } - - /// Deep clones . - /// Item type being copied. - /// Object to clone. - /// Handles callback behavior for child values. - /// Clone of . - private static async IAsyncEnumerable CopyAsync(IAsyncEnumerable source, DuplicatorChainer duplicator) - { - await foreach (T item in source) - { - yield return duplicator.Copy(item); - } - } -} \ No newline at end of file diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/BasicCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/BasicCopyHint.cs deleted file mode 100644 index 08f762b7..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/BasicCopyHint.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Runtime.Serialization; -using CreateAndFake.Design; -using CreateAndFake.Design.Randomization; - -#pragma warning disable SYSLIB0050 // 'IObjectReference' is obsolete: Still needed for compatibility. - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning basic types for . -public sealed class BasicCopyHint : CopyHint -{ - /// Specific types to control via this hint. - private static readonly HashSet _SupportedTypes = [typeof(string), typeof(object)]; - - /// - protected internal sealed override (bool, object?) TryCopy(object source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(source, nameof(source)); - - Type type = source.GetType(); - if (type.IsPrimitive - || type.IsEnum - || ValueRandom.ValueTypes.Contains(type) - || _SupportedTypes.Contains(type) - || type.Inherits()) - { - return (true, source); - } - else - { - return (false, null); - } - } -} - -#pragma warning restore SYSLIB0050 // 'IObjectReference' is obsolete diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CloneableCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CloneableCopyHint.cs deleted file mode 100644 index bd9fb916..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CloneableCopyHint.cs +++ /dev/null @@ -1,15 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning instances for . -public sealed class CloneableCopyHint : CopyHint -{ - /// - protected override ICloneable Copy(ICloneable source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(source, nameof(source)); - - return (ICloneable)source.Clone(); - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CollectionCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CollectionCopyHint.cs deleted file mode 100644 index d6c677ad..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CollectionCopyHint.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System.Collections; -using System.Collections.Concurrent; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning collections for . - -public sealed class CollectionCopyHint : CopyHint -{ - /// Special cases where the data needs to be reversed. - private static readonly Type[] _ReverseCases = - [ - typeof(ConcurrentStack<>), - typeof(Stack<>), - typeof(Stack) - ]; - - /// - protected override IEnumerable Copy(IEnumerable source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(source, nameof(source)); - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - if (source.GetType().IsArray) - { - return CopyContents(source, duplicator); - } -#if LEGACY // Constructor missing in .NET full. - else if (source.GetType().AsGenericType() == typeof(Dictionary<,>)) - { - dynamic result = Activator.CreateInstance(source.GetType()); - foreach (dynamic item in CopyContents(source, duplicator)) - { - result.Add(item.Key, item.Value); - } - return result; - } -#endif - else - { - return (IEnumerable)Activator.CreateInstance(source.GetType(), CopyContents(source, duplicator))!; - } - } - - /// Copies the contents of . - /// Collection with contents to copy. - /// Handles callback behavior for child values. - /// Clone of 's elements. - private static IEnumerable CopyContents(IEnumerable source, DuplicatorChainer duplicator) - { - Type type = source.GetType(); - Type? genericType = type.AsGenericType(); - - object?[] data = CopyContentsHelper(source, duplicator, - _ReverseCases.Contains(genericType ?? type)); - - if (genericType != null) - { - Type[] args = type.GetGenericArguments(); - Type itemType = (args.Length != 1) - ? typeof(KeyValuePair<,>).MakeGenericType(args) - : args.Single(); - - return ArrayCast(itemType, data); - } - else if (type.IsArray) - { - return ArrayCast(type.GetElementType()!, data); - } - else - { - return data; - } - } - - /// Convert to array. - /// Array type to create. - /// Array to convert. - /// The converted array. - private static Array ArrayCast(Type elementType, object?[] data) - { - Array result = Array.CreateInstance(elementType, data.Length); - for (int i = 0; i < data.Length; i++) - { - result.SetValue(data[i], i); - } - return result; - } - - /// Copies the contents of . - /// Collection with contents to copy. - /// Handles callback behavior for child values. - /// If the copy process should reverse the order of items from the enumerator. - /// The duplicate object. - private static object?[] CopyContentsHelper(IEnumerable source, DuplicatorChainer duplicator, bool reverse) - { - List copy = []; - - IEnumerator enumerator = source.GetEnumerator(); - while (enumerator.MoveNext()) - { - copy.Add(duplicator.Copy(enumerator.Current)); - } - - if (reverse) - { - copy.Reverse(); - } - - return [.. copy]; - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CommonSystemCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CommonSystemCopyHint.cs deleted file mode 100644 index bd64eb41..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/CommonSystemCopyHint.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning common types for . -public sealed class CommonSystemCopyHint : CopyHint -{ - /// - protected internal sealed override (bool, object?) TryCopy(object source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - if (source is TimeSpan span) - { - return (true, new TimeSpan(duplicator.Copy(span.Ticks))); - } - else if (source is Uri link) - { - return (true, new Uri(link.OriginalString)); - } - else if (source is WeakReference reference) - { - return (true, new WeakReference(reference.Target, reference.TrackResurrection)); - } - else if (source is MemberInfo member) - { - return (true, member); - } - else - { - return (false, null); - } - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/DeepCloneableCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/DeepCloneableCopyHint.cs deleted file mode 100644 index 68fcc9c0..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/DeepCloneableCopyHint.cs +++ /dev/null @@ -1,16 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning instances for . -public sealed class DeepCloneableCopyHint : CopyHint -{ - /// - protected override IDeepCloneable Copy(IDeepCloneable source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(source, "source"); - - return source.DeepClone(); - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/DuplicatableCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/DuplicatableCopyHint.cs deleted file mode 100644 index 5d23e352..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/DuplicatableCopyHint.cs +++ /dev/null @@ -1,16 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning instances for . -public sealed class DuplicatableCopyHint : CopyHint -{ - /// - protected override IDuplicatable Copy(IDuplicatable source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(source, nameof(source)); - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - return source.DeepClone(duplicator.Duplicator); - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/LegacyCollectionCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/LegacyCollectionCopyHint.cs deleted file mode 100644 index bfc2f8c6..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/LegacyCollectionCopyHint.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System.Collections; -using System.Collections.Specialized; -using CreateAndFake.Design; - -#pragma warning disable IDE0058 // Expression value is never used: Return not available on all versions. - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning legacy collections for . -public sealed class LegacyCollectionCopyHint : CopyHint -{ - /// Supported types and the methods used to generate them. - private static readonly Dictionary> _Copiers = new() - { - { typeof(Hashtable), CreateAndCopy }, - { typeof(SortedList), CreateAndCopy }, - { typeof(ListDictionary), CreateAndCopy }, - { typeof(HybridDictionary), CreateAndCopy }, - { typeof(OrderedDictionary), CreateAndCopy }, - - { typeof(BitArray), (data, cloner) => new BitArray((BitArray)data) }, - { typeof(NameValueCollection), (data, cloner) => new NameValueCollection((NameValueCollection)data) }, - - { typeof(StringCollection), (data, cloner) => - { - StringCollection result = [.. (StringCollection)data]; - return result; - } - }, - { typeof(StringDictionary), (data, cloner) => - { - StringDictionary result = []; - foreach (DictionaryEntry entry in (StringDictionary)data) - { - result.Add((string)entry.Key, (string?)entry.Value); - } - return result; - } - } - }; - - /// - protected internal sealed override (bool, object?) TryCopy(object source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(source, nameof(source)); - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - if (_Copiers.TryGetValue(source.GetType(), out Func? copier)) - { - return (true, copier.Invoke(source, duplicator)); - } - else - { - return (false, null); - } - } - - /// Clones . - /// Collection type being cloned. - /// Collection to clone. - /// Handles callback behavior for child values. - /// Clone of . - private static T CreateAndCopy(object source, DuplicatorChainer duplicator) where T : IDictionary, new() - { - T result = new(); - foreach (DictionaryEntry entry in (T)source) - { - result.Add(duplicator.Copy(entry.Key)!, duplicator.Copy(entry.Value)); - } - return result; - } -} - -#pragma warning restore IDE0058 // Expression value is never used diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/ObjectCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/ObjectCopyHint.cs deleted file mode 100644 index 37e1d0f0..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/ObjectCopyHint.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning objects for . -public sealed class ObjectCopyHint : CopyHint -{ - /// Flags used to identify members. - private const BindingFlags _MemberFlags = BindingFlags.Public - | BindingFlags.NonPublic | BindingFlags.Instance; - - /// - protected internal sealed override (bool, object?) TryCopy(object source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(source, nameof(source)); - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - object? result = Copy(source, duplicator); - return (result != null, result); - } - - /// - private static object? Copy(object source, DuplicatorChainer duplicator) - { - object? dupe = CreateNew(source, duplicator); - if (dupe == null) - { - return dupe; - } - duplicator.AddToHistory(source, dupe); - - foreach (FieldInfo field in source.GetType() - .GetFields(BindingFlags.Instance | BindingFlags.Public) - .Where(f => !f.IsInitOnly && !f.IsLiteral)) - { - field.SetValue(dupe, duplicator.Copy(field.GetValue(source))); - } - - foreach (PropertyInfo property in source.GetType() - .GetProperties(BindingFlags.Instance | BindingFlags.Public) - .Where(p => p.CanRead && p.CanWrite)) - { - property.SetValue(dupe, duplicator.Copy(property.GetValue(source))); - } - - return dupe; - } - - /// Creates an instance of 's . - /// Object whose is to be created. - /// Handles callback behavior for child values. - /// The created instance. - private static object? CreateNew(object source, DuplicatorChainer duplicator) - { - Type type = source.GetType(); - - if (type.GetConstructor(Type.EmptyTypes) != null) - { - return Activator.CreateInstance(type); - } - else - { - PropertyInfo[] props = type.GetProperties(_MemberFlags).Where(p => p.CanRead).ToArray(); - FieldInfo[] fields = [.. type.GetFields(_MemberFlags)]; - - return type.GetConstructors(_MemberFlags) - .Where(c => !c.IsPrivate) - .OrderByDescending(c => c.GetParameters().Length) - .Select(c => TryCreate(source, duplicator, c, props, fields)) - .FirstOrDefault(o => o != null); - } - } - - /// Attempts to create an instance using a . - /// Object being cloned. - /// Handles callback behavior for child values. - /// Constructor on to use. - /// Properties on . - /// Fields on . - /// Null if failed; created instance otherwise. - private static object? TryCreate(object source, DuplicatorChainer duplicator, - ConstructorInfo constructor, IEnumerable props, IEnumerable fields) - { - List propList = props.ToList(); - List fieldList = fields.ToList(); - - // Attempts to match members with parameters in the constructor. - List matchedMembers = []; - foreach (ParameterInfo param in constructor.GetParameters()) - { - PropertyInfo[] potentialProps = propList - .Where(p => p.PropertyType.Inherits(param.ParameterType)) - .ToArray(); - if (potentialProps.Length != 0) - { - PropertyInfo? directPropMatch = potentialProps.FirstOrDefault( - p => p.Name.Equals(param.Name, StringComparison.OrdinalIgnoreCase)); - if (directPropMatch != null) - { - _ = propList.Remove(directPropMatch); - matchedMembers.Add(directPropMatch); - } - else - { - _ = propList.Remove(potentialProps.First()); - matchedMembers.Add(potentialProps.First()); - } - continue; - } - - FieldInfo[] potentialFields = fieldList - .Where(f => f.FieldType.Inherits(param.ParameterType)) - .ToArray(); - if (potentialFields.Length != 0) - { - FieldInfo? directFieldMatch = potentialFields.FirstOrDefault( - f => f.Name.Equals(param.Name, StringComparison.OrdinalIgnoreCase)); - if (directFieldMatch != null) - { - _ = fieldList.Remove(directFieldMatch); - matchedMembers.Add(directFieldMatch); - } - else - { - _ = fieldList.Remove(potentialFields.First()); - matchedMembers.Add(potentialFields.First()); - } - continue; - } - - return null; - } - - return constructor.Invoke(matchedMembers.Select(m => CopyMember(m, source, duplicator)).ToArray()); - } - - /// Copies the value of on . - /// Property or field to copy. - /// Instance containing the member. - /// Duplicator handling the cloning. - /// The duplicate object. - private static object? CopyMember(MemberInfo member, object source, DuplicatorChainer duplicator) - { - if (member is PropertyInfo prop) - { - return duplicator.Copy(prop.GetValue(source)); - } - else - { - return duplicator.Copy(((FieldInfo)member).GetValue(source)); - } - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/SerializableCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/SerializableCopyHint.cs deleted file mode 100644 index 8d5585f4..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/SerializableCopyHint.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Collections; -using System.Reflection; -using System.Runtime.Serialization; -#if !NET5_0_OR_GREATER -using System.Runtime.Serialization.Formatters.Binary; -#endif - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning instances for . -public sealed class SerializableCopyHint : CopyHint -{ - /// Scope used to search for inner types. - private const BindingFlags _Scope - = BindingFlags.Public - | BindingFlags.NonPublic - | BindingFlags.Instance; - - /// - protected internal override (bool, object?) TryCopy(object source, DuplicatorChainer duplicator) - { - if (source is ISerializable) - { -#if !NET5_0_OR_GREATER // Backwards compatibility. - BinaryFormatter binary = new(); - using MemoryStream memory = new(); - - binary.Serialize(memory, source); - _ = memory.Seek(0, SeekOrigin.Begin); - return (true, binary.Deserialize(memory)); -#else - HashSet knownData = []; - FlattenData(source, knownData); - - DataContractSerializer serializer = new(source.GetType(), knownData.Select(d => d.GetType()).Distinct()); - - using MemoryStream stream = new(); - - serializer.WriteObject(stream, source); - _ = stream.Seek(0, SeekOrigin.Begin); - return (true, serializer.ReadObject(stream)); -#endif - } - else - { - return (false, null); - } - } - - /// Finds data associated with - /// Instance being serialized. - /// Set to populate with found data. - private static void FlattenData(object? source, HashSet foundData) - { - if (source != null && foundData.Add(source) && !source.GetType().Inherits()) - { - FlattenComplexData(source, foundData); - } - } - - /// Finds nested data associated with . - /// Instance being serialized. - /// Set to populate with found data. - private static void FlattenComplexData(object source, HashSet foundData) - { - if (source is IDictionary map) - { - foreach (DictionaryEntry item in map) - { - FlattenData(item.Key, foundData); - FlattenData(item.Value, foundData); - } - } - else if (source is IEnumerable values) - { - IEnumerator gen = values.GetEnumerator(); - while (gen.MoveNext()) - { - FlattenData(gen.Current, foundData); - } - } - else if (!source.GetType().IsValueType) - { - FlattenInnerData(source, foundData); - } - } - - /// Finds member data inside . - /// Instance being serialized. - /// Set to populate with found data. - private static void FlattenInnerData(object source, HashSet foundData) - { - Type type = source.GetType(); - - foreach (PropertyInfo property in type.GetProperties(_Scope).Where(p => p.CanRead)) - { - FlattenData(property.GetValue(source), foundData); - } - - foreach (FieldInfo field in type.GetFields(_Scope)) - { - FlattenData(field.GetValue(source), foundData); - } - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/TaskCopyHint.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/TaskCopyHint.cs deleted file mode 100644 index fcb99bfa..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/CopyHints/TaskCopyHint.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -/// Handles cloning instances for . -public sealed class TaskCopyHint : CopyHint -{ - /// - protected internal sealed override (bool, object?) TryCopy(object source, DuplicatorChainer duplicator) - { - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - if (source is Task task && task.GetType().IsGenericType) - { - return (true, Copy(task, duplicator)); - } - else - { - return (false, null); - } - } - - /// - private static object Copy(Task source, DuplicatorChainer duplicator) - { - PropertyInfo resultHolder = source.GetType().GetProperty(nameof(Task.Result))!; - - return typeof(TaskCopyHint) - .GetMethod(nameof(NewInstanceFromResult), BindingFlags.NonPublic | BindingFlags.Static)! - .MakeGenericMethod(resultHolder.PropertyType) - .Invoke(null, [duplicator.Copy(resultHolder.GetValue(source))])!; - } - - /// Forces a Task instance that isn't cached. - /// Task result type. - /// value to return from the Task. - /// The created Task. - private static Task NewInstanceFromResult(T result) - { - TaskCompletionSource wrapper = new(); - _ = wrapper.TrySetResult(result); - return wrapper.Task; - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/Duplicator.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/Duplicator.cs deleted file mode 100644 index 7e9abc0a..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/Duplicator.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -namespace CreateAndFake.Toolbox.DuplicatorTool; - -/// -/// -/// If the default set of hints should be added. -/// -public sealed class Duplicator(Asserter asserter, bool includeDefaultHints = true, params CopyHint[]? hints) : IDuplicator, IDuplicatable -{ - /// Default set of hints to use for copying. - private static readonly CopyHint[] _DefaultHints = - [ - new CommonSystemCopyHint(), - new TaskCopyHint(), - new DeepCloneableCopyHint(), - new DuplicatableCopyHint(), - new BasicCopyHint(), - new AsyncCollectionCopyHint(), - new LegacyCollectionCopyHint(), - new CollectionCopyHint(), - new CloneableCopyHint(), - new SerializableCopyHint(), - new ObjectCopyHint() - ]; - - /// Verifies duplicates are valid. - private readonly Asserter _asserter = asserter ?? throw new ArgumentNullException(nameof(asserter)); - - /// Hints used to copy specific types. - private readonly List _hints = (hints ?? Enumerable.Empty()) - .Concat(includeDefaultHints ? _DefaultHints : []) - .ToList(); - - /// - [return: NotNullIfNotNull(nameof(source))] - public T Copy(T source) - { - try - { - T result = Copy(source, new DuplicatorChainer(this, Copy)); - _asserter.ValuesEqual(source, result, - $"Type '{source?.GetType()}' did not clone properly. " + - "Verify/create a hint to generate the type and pass it to the duplicator."); - return result; - } - catch (InsufficientExecutionStackException) - { - throw new InsufficientExecutionStackException( - $"Ran into infinite generation trying to duplicate type '{source!.GetType().Name}'."); - } - } - - /// Handles cloning child values. - /// - [return: NotNullIfNotNull(nameof(source))] - private T Copy(T source, DuplicatorChainer chainer) - { - if (source == null) - { - return default!; - } - (bool, object?) result = _hints - .Select(h => h.TryCopy(source, chainer)) - .FirstOrDefault(r => r.Item1); - - if (!result.Equals(default)) - { - return (T)result.Item2!; - } - else - { - throw new NotSupportedException( - $"Type '{source.GetType().FullName}' not supported by the duplicator. " + - "Create a hint to generate the type and pass it to the duplicator."); - } - } - - /// - public IDuplicatable DeepClone(IDuplicator duplicator) - { - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - return new Duplicator(duplicator.Copy(_asserter)!, false, [.. duplicator.Copy(_hints)]); - } - - /// - public void AddHint(CopyHint hint) - { - _hints.Insert(0, hint ?? throw new ArgumentNullException(nameof(hint))); - } -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/DuplicatorChainer.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/DuplicatorChainer.cs deleted file mode 100644 index fa71f4e4..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/DuplicatorChainer.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -#pragma warning disable IDE0028 // Collection initialization can be simplified: Invalid because it's not constructible. - -namespace CreateAndFake.Toolbox.DuplicatorTool; - -/// Provides a callback into to create child values. -/// -/// -public sealed class DuplicatorChainer(IDuplicator duplicator, Func callback) -{ - /// Reference to the actual duplicator. - internal IDuplicator Duplicator { get; } = duplicator - ?? throw new ArgumentNullException(nameof(duplicator)); - - /// Callback to the duplicator to handle child values. - private readonly Func _callback = callback - ?? throw new ArgumentNullException(nameof(callback)); - - /// History of clones to match up references. - private readonly ConditionalWeakTable _history = new(); - - /// Adds successful clone details to history. - /// Object cloned. - /// The clone. - public void AddToHistory(object source, object clone) - { - if (CanTrack(source)) - { - _history.Add(source, clone); - } - } - - /// Type being cloned. - /// - public T? Copy(T? source) - { - return (T?)Copy((object?)source); - } - - /// Deep clones . - /// Object to clone. - /// Clone of . - /// If no hint supports cloning . - public object? Copy(object? source) - { - RuntimeHelpers.EnsureSufficientExecutionStack(); - if (!CanTrack(source)) - { - return _callback.Invoke(source, this); - } - - if (_history.TryGetValue(source, out object? clone)) - { - return clone; - } - - object? result = _callback.Invoke(source, this); - if (!_history.TryGetValue(source, out _)) - { - _history.Add(source, result); - } - return result; - } - - /// If can be tracked in history. - /// Item to check. - /// true if possible; false otherwise. - private static bool CanTrack([NotNullWhen(true)] object? source) - { - return !(source == null || source is IFaked || source.GetType().IsValueType); - } -} - -#pragma warning restore IDE0028 // Collection initialization can be simplified diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/IDuplicatable.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/IDuplicatable.cs deleted file mode 100644 index 9bde4789..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/IDuplicatable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace CreateAndFake.Toolbox.DuplicatorTool; - -/// Enables deep copies with the aid of the duplicator. -public interface IDuplicatable -{ - /// - /// Makes a clone such that any mutation to the source - /// or copy only affects that object and not the other. - /// - /// Duplicator to clone child values. - /// Created clone that is equal in value to the instance. - IDuplicatable DeepClone(IDuplicator duplicator); -} diff --git a/src/CreateAndFake/Toolbox/DuplicatorTool/IDuplicator.cs b/src/CreateAndFake/Toolbox/DuplicatorTool/IDuplicator.cs deleted file mode 100644 index c991cd80..00000000 --- a/src/CreateAndFake/Toolbox/DuplicatorTool/IDuplicator.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFake.Toolbox.DuplicatorTool; - -/// Deep clones objects. -public interface IDuplicator -{ - /// Deep clones . - /// Type being cloned. - /// Object to clone. - /// Clone of . - /// If no hint supports cloning . - /// If infinite recursion occurs. - [return: NotNullIfNotNull(nameof(source))] - T Copy(T source); - - /// Adds to be used for cloning. Last added takes precedence. - /// Hint to add. - /// Should only be modified in module initializers. - void AddHint(CopyHint hint); -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Behavior.cs b/src/CreateAndFake/Toolbox/FakerTool/Behavior.cs deleted file mode 100644 index 6356d920..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Behavior.cs +++ /dev/null @@ -1,437 +0,0 @@ -using System.Reflection; -using System.Runtime.ExceptionServices; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// Mock behavior for fakes. -/// -/// -/// Starting number of calls. -public abstract class Behavior(Delegate implementation, Times? times, int calls) : IDeepCloneable -{ - /// Set behavior to run. - protected Delegate Implementation { get; } = implementation; - - /// Behavior call limit. - protected Times Limit { get; } = times ?? Times.Min(1); - - /// Times the fake behavior was called. - protected internal int Calls { get; private set; } = calls; - - /// Triggers calling the base method of the given type instead. - public Type? BaseCallType { get; private set; } = null; - - /// - public abstract IDeepCloneable DeepClone(); - - /// Runs the behavior. - /// Expected args for the behavior. - /// Result of the call. - internal object? Invoke(object[] args) - { - return Invoke(Implementation, args); - } - - /// Runs the behavior. - /// Delegate to run. - /// Expected args for the behavior. - /// Result of the call. - internal object? Invoke(Delegate implementation, object[] args) - { - Calls++; - try - { - if (implementation.Method.GetParameters().Length == 0) - { - return implementation.DynamicInvoke(); - } - else - { - return implementation.DynamicInvoke(args); - } - } - catch (Exception e) - { - ExceptionDispatchInfo? info = (e is TargetInvocationException) - ? ExceptionDispatchInfo.Capture(e.InnerException!) - : null; - - info?.Throw(); - throw; - } - } - - /// Checks if call count is in expected range. - /// true if in range; false otherwise. - internal bool HasExpectedCalls() - { - return Limit.IsInRange(Calls); - } - - /// Text representation of expected calls. - internal string ToExpectedCalls() - { - return Limit.ToString(); - } - - /// Specifies no behavior for a fake. - /// Behavior call limit. - public static Behavior None(Times? times = null) - { - return Set(() => { }, times); - } - - /// Specifies exception behavior for a fake. - /// Behavior call limit. - public static Behavior Error(Times? times = null) - { - return Throw(times); - } - - /// Specifies behavior returning null for a fake. - /// Null type to return. - /// Behavior call limit. - /// Instance to set up the mock with. - public static Behavior Null(Times? times = null) - { - return Returns(default(T), times); - } - - /// Specifies behavior returning the default for a fake. - /// Default value type to return. - /// Behavior call limit. - /// Instance to set up the mock with. - public static Behavior Default(Times? times = null) - { - return Returns(default(T), times); - } - - /// - public static Behavior Base(Times? times = null) - { - return Base(times); - } - - /// Specifies behavior calling the base implementation. - /// Type with the base method to call. - /// Expected value type to return. - /// Behavior call limit. - /// Instance to set up the mock with. - public static Behavior Base(Times? times = null) - { - Behavior result = Default(times); - result.BaseCallType = typeof(TBase); - return result; - } - - /// - public static Behavior Throw(Times? times = null) where T : Exception, new() - { - return Throw(new T(), times); - } - - /// Specifies a specific exception behavior for a fake. - /// Exception type to throw if called. - /// Exception to throw. - /// Behavior call limit. - /// Instance to set up the mock with. - public static Behavior Throw(T exception, Times? times = null) where T : Exception - { - return Set(() => throw exception, times); - } - - /// Specifies behavior returning a value for a fake. - /// Value type to return. - /// Value to return. - /// Behavior call limit. - /// Instance to set up the mock with. - public static Behavior Returns(T? value, Times? times = null) - { - return Set(() => value, times); - } - - /// Specifies behavior returning values for a fake. - /// Value type to return. - /// Value to return first. - /// Following sequential values to return. - /// Instance to set up the mock with. - public static Behavior Series(T value, params T[] values) - { - int counter = -2; - return Set(() => - { - counter++; - if (counter == -1) - { - return value; - } - else if (counter < values?.Length) - { - return values[counter]; - } - else - { - return default; - } - }); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Action implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } - - /// Specifies mock behavior of for a fake. - /// Type for parameter 1. - /// Type for parameter 2. - /// Type for parameter 3. - /// Type for parameter 4. - /// Type for parameter 5. - /// Type for parameter 6. - /// Type for parameter 7. - /// Type for parameter 8. - /// Type for parameter 9. - /// Type for parameter 10. - /// Type for parameter 11. - /// Type for parameter 12. - /// Type for parameter 13. - /// Type for parameter 14. - /// Type for parameter 15. - /// Type for parameter 16. - /// Type for the return value of . - /// Behavior to invoke for calls. - /// Behavior call limit. - /// Instance to set up the mock with. - public static Behavior Set( - Func implementation, Times? times = null) - { - return new Behavior(implementation, times); - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Behavior[T].cs b/src/CreateAndFake/Toolbox/FakerTool/Behavior[T].cs deleted file mode 100644 index 4931b421..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Behavior[T].cs +++ /dev/null @@ -1,43 +0,0 @@ -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// -/// Return type. -public sealed class Behavior : Behavior -{ - /// > - public Behavior(Delegate implementation, Times? times = null) : base(implementation, times, 0) { } - - /// - private Behavior(Delegate implementation, Times times, int calls) : base(implementation, times, calls) { } - - /// - public override IDeepCloneable DeepClone() - { - return new Behavior(Implementation, Limit, Calls); - } - - /// Specifies exception behavior for a fake. - /// Behavior call limit. - public static new Behavior Error(Times? times = null) - { - return Throw(times); - } - - /// - public static new Behavior Throw(Times? times = null) where TException : Exception, new() - { - return Throw(new TException(), times); - } - - /// Specifies a specific exception behavior for a fake. - /// Exception type to throw if called. - /// Exception to throw. - /// Behavior call limit. - /// Instance to set up the mock with. - public static new Behavior Throw(TException exception, Times? times = null) where TException : Exception - { - return Set(() => throw exception, times); - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/FakeExtensions.cs b/src/CreateAndFake/Toolbox/FakerTool/FakeExtensions.cs deleted file mode 100644 index 11331831..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/FakeExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace CreateAndFake.Toolbox.FakerTool; - -/// Niceties for fakes. -public static class FakeExtensions -{ - /// Switches the fake to a different type. - /// Alternative base to cast to. - /// Created fake with the extra type. - /// Fake to test with. - public static Fake ToFake(this Fake baseFake) - { - if (baseFake is Fake fake) - { - return fake; - } - else - { - return new Fake(baseFake); - } - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Fake[T].cs b/src/CreateAndFake/Toolbox/FakerTool/Fake[T].cs deleted file mode 100644 index 615a9a08..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Fake[T].cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Linq.Expressions; -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// Type being faked. -/// -public sealed class Fake : Fake -{ - /// - public new T Dummy => (T)base.Dummy; - - /// - public Fake(IFaked fake) : base(fake) { } - - /// - /// Switches the fake to a different type. - public Fake(Fake baseFake) : base(baseFake?.Dummy ?? throw new ArgumentNullException(nameof(baseFake))) - { - _ = (T)base.Dummy; - } - - /// Ties a set method call to fake behavior. - /// Property type. - /// Expression of property to setup. - /// Set value to match from the call. - /// Fake behavior to invoke. - /// Representation of the call. - public void SetupSet(Expression> method, TResult value, Behavior callback) - { - (MethodInfo, Type[], object?[]) call = ExtractCall(method, true); - Setup(call.Item1.Name, call.Item2, [value], callback); - } - - /// Ties a set method call to fake behavior. - /// Property type. - /// Expression of property to setup. - /// Arg expression to match from the call. - /// Fake behavior to invoke. - /// Representation of the call. - public void SetupSet(Expression> method, Arg value, Behavior callback) - { - (MethodInfo, Type[], object?[]) call = ExtractCall(method, true); - Setup(call.Item1.Name, call.Item2, [value], callback); - } - - /// Ties a method call to fake behavior. - /// Expression of method to setup. - /// Fake behavior to invoke. - /// Representation of the call. - public void Setup(Expression> method, Behavior callback) - { - (MethodInfo, Type[], object?[]) call = ExtractCall(method, false); - Setup(call.Item1.Name, call.Item2, call.Item3, callback); - } - - /// Ties a method call to fake behavior. - /// Method return type. - /// Expression of method to setup. - /// Fake behavior to invoke. - /// Representation of the call. - public void Setup(Expression> method, Behavior callback) - { - (MethodInfo, Type[], object?[]) call = ExtractCall(method, false); - Setup(call.Item1.Name, call.Item2, call.Item3, callback); - } - - /// Verifies the number of calls made to the setter. - /// Expected number of calls. - /// Setter to verify. - /// Set value to match from the call. - public void VerifySet(Times times, Expression> method, TResult value) - { - (MethodInfo, Type[], object?[]) call = ExtractCall(method, true); - Verify(times, call.Item1.Name, call.Item2, [value]); - } - - /// Verifies the number of calls made to the setter. - /// Expected number of calls. - /// Setter to verify. - /// Arg expression to match from the call. - public void VerifySet(Times times, Expression> method, Arg value) - { - (MethodInfo, Type[], object?[]) call = ExtractCall(method, true); - Verify(times, call.Item1.Name, call.Item2, [value]); - } - - /// Verifies the number of calls made to . - /// Expected number of calls. - /// Method to verify. - public void Verify(Times times, Expression> method) - { - (MethodInfo, Type[], object?[]) call = ExtractCall(method, false); - Verify(times, call.Item1.Name, call.Item2, call.Item3); - } - - /// Verifies the number of calls made to . - /// Expected number of calls. - /// Method to verify. - public void Verify(Times times, Expression> method) - { - (MethodInfo, Type[], object?[]) call = ExtractCall(method, false); - Verify(times, call.Item1.Name, call.Item2, call.Item3); - } - - /// Changes expression to call data. - /// Expression to convert. - /// If only setter is allowed. - /// Method name, generics, and args. - private static (MethodInfo, Type[], object?[]) ExtractCall(LambdaExpression method, bool onlySetter) - { - ArgumentGuard.ThrowIfNull(method, nameof(method)); - - if (!onlySetter && method.Body is MethodCallExpression methodCall) - { - if (methodCall.Method.IsStatic) - { - throw new NotSupportedException( - $"Method '{methodCall.Method.Name}' is static and not an actual member of '{typeof(T).Name}'."); - } - - Type[] generics = methodCall.Method.IsGenericMethod - ? methodCall.Method.GetGenericArguments() - : Type.EmptyTypes; - - return (methodCall.Method, generics, methodCall.Arguments.Select(ConvertArg).ToArray()); - } - else if (method.Body is MemberExpression memberExpression) - { - PropertyInfo info = (PropertyInfo)memberExpression.Member; - return onlySetter - ? (info.GetSetMethod()!, Type.EmptyTypes, []) - : (info.GetGetMethod()!, Type.EmptyTypes, []); - } - else - { - throw new InvalidOperationException($"Unexpected expression type: {method}"); - } - } - - /// Converts arg expressions to actual values. - /// Arg to convert. - /// Value to pass to the call. - private static object? ConvertArg(Expression arg) - { - if (arg is MemberExpression memberExpression - && memberExpression.Member.Name == nameof(OutRef.Var)) - { - return ConvertArg(memberExpression.Expression!); - } - - MethodCallExpression? call = arg as MethodCallExpression - ?? (arg as UnaryExpression)?.Operand as MethodCallExpression; - if (call?.Method.DeclaringType == typeof(Arg) && call.Method.ReturnType != typeof(Arg)) - { - return ResolveArgLambda(call); - } - else - { - return Expression.Lambda(arg).Compile().DynamicInvoke(); - } - } - - /// Converts an lambda arg expression to its actual value. - /// Expression of the arg to convert. - /// Value to pass to the call. - [SuppressMessage("Microsoft.Style", "IDE0200:PreferMethodGroupConversion", Justification = "Code coverage issue.")] - private static object ResolveArgLambda(MethodCallExpression call) - { - Type innerType = (call.Method.ReturnType.AsGenericType() == typeof(OutRef<>)) - ? call.Method.ReturnType.GetGenericArguments().Single() - : call.Method.ReturnType; - - return typeof(Arg) - .GetMethod("Lambda" + call.Method.Name)! - .MakeGenericMethod(innerType) - .Invoke(null, call.Arguments.Select(x => ConvertArg(x)).ToArray())!; - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Faker.cs b/src/CreateAndFake/Toolbox/FakerTool/Faker.cs deleted file mode 100644 index 48927fb4..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Faker.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// -/// Handles comparisons. -public sealed class Faker(IValuer valuer) : IFaker -{ - /// - public bool Supports() - { - return Subclasser.Supports(); - } - - /// - public bool Supports(Type type) - { - return Subclasser.Supports(type); - } - - /// - public Fake Mock(params Type[] interfaces) - { - IFaked provider = Subclasser.Create(typeof(T), interfaces); - provider.FakeMeta.Valuer = valuer; - return new Fake(provider); - } - - /// - public Fake Mock(Type parent, params Type[] interfaces) - { - IFaked provider = Subclasser.Create(parent, interfaces); - provider.FakeMeta.Valuer = valuer; - return new Fake(provider); - } - - /// - public Fake Stub(params Type[] interfaces) - { - Fake fake = Mock(interfaces); - fake.ThrowByDefault = false; - return fake; - } - - /// - public Fake Stub(Type parent, params Type[] interfaces) - { - Fake fake = Mock(parent, interfaces); - fake.ThrowByDefault = false; - return fake; - } - - /// - public Injected InjectMocks(params object[] values) - { - return Inject(values ?? [], (Type t) => Mock(t)); - } - - /// - public Injected InjectStubs(params object[] values) - { - return Inject(values ?? [], (Type t) => Stub(t)); - } - - /// Creates an instance injected with fakes. - /// Instance to be created. - /// Values to inject instead where possible. - /// Fake creation method to use. - /// The created instance with its fakes. - private Injected Inject(object[] values, Func subclasser) - { - Type[] startingTypes = values - .Where(v => v != null) - .Select(v => (v is Fake fake) ? fake.Dummy : v) - .Select(v => v.GetType()) - .ToArray(); - - ConstructorInfo? maker = FindBestConstructor(startingTypes); - if (maker != null) - { - object?[] args = CreateInjectArgs(maker, values, subclasser); - - return new Injected((T)maker.Invoke(args - .Select(v => (v is Fake fake) ? fake.Dummy : v) - .ToArray()), args.OfType()); - } - else - { - throw new InvalidOperationException($"No constructors found on type '{typeof(T).Name}'."); - } - } - - /// Creates the args to inject an instance with. - /// Constructor to use. - /// Values to inject instead where possible. - /// Fake creation method to use. - /// The created args to inject an instance with. - private object?[] CreateInjectArgs(ConstructorInfo maker, object[] values, Func subclasser) - { - List> data = values - .Where(v => v != null) - .Select(v => Tuple.Create((v is Fake fake) ? fake.Dummy.GetType() : v.GetType(), v)) - .ToList(); - - ParameterInfo[] info = maker.GetParameters(); - object?[] args = new object[info.Length]; - - for (int i = 0; i < args.Length; i++) - { - Tuple? match = data.FirstOrDefault(t => t.Item1.Inherits(info[i].ParameterType)); - if (match != default) - { - args[i] = match.Item2; - _ = data.Remove(match); - } - else if (Supports(info[i].ParameterType)) - { - args[i] = subclasser.Invoke(info[i].ParameterType); - } - else - { - args[i] = null; - } - } - return args; - } - - /// Finds the constructor with the most matches then by most parameters. - /// Type to search. - /// Argument types to search on. - /// The constructor best fitted to the types. - private static ConstructorInfo? FindBestConstructor(Type[] startingTypes) - { - return typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.Public) - .GroupBy(c => c.GetParameters().Count(p => startingTypes.Any(t => t.Inherits(p.ParameterType)))) - .OrderByDescending(g => g.Key) - .FirstOrDefault() - ?.OrderByDescending(c => c.GetParameters()) - .FirstOrDefault(); - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/IFaker.cs b/src/CreateAndFake/Toolbox/FakerTool/IFaker.cs deleted file mode 100644 index 1772d0da..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/IFaker.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace CreateAndFake.Toolbox.FakerTool; - -/// Creates fake objects. -public interface IFaker -{ - /// Determines if type can be faked. - /// Type to check. - /// true if possible; false otherwise. - bool Supports(); - - /// Determines if can be faked. - /// Type to check. - /// true if possible; false otherwise. - bool Supports(Type type); - - /// Type being faked. - /// - Fake Mock(params Type[] interfaces); - - /// Creates a strict fake where calls fail unless set up. - /// Type being faked. - /// Extra interfaces to implement. - /// Handler for fake behavior. - Fake Mock(Type parent, params Type[] interfaces); - - /// Type being faked. - /// - Fake Stub(params Type[] interfaces); - - /// Creates a loose fake with a base default implementation. - /// Type being faked. - /// Extra interfaces to implement. - /// Handler for the fake behavior. - Fake Stub(Type parent, params Type[] interfaces); - - /// Creates an instance injected with mocks. - /// - Injected InjectMocks(params object[] values); - - /// Creates an instance injected with stubs. - /// Instance type to be created. - /// Values to inject instead where possible. - /// The created instance with its fakes. - Injected InjectStubs(params object[] values); -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Injected.cs b/src/CreateAndFake/Toolbox/FakerTool/Injected.cs deleted file mode 100644 index 5291b404..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Injected.cs +++ /dev/null @@ -1,62 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// Instance with dynamically injected fakes. -/// Type being injected by fakes. -public sealed class Injected -{ - /// Faked implementation. - public T Dummy { get; } - - /// Fakes injected into the dummy. - public IEnumerable Fakes { get; } - - /// - /// Faked implementation. - /// Fakes injected into the dummy. - public Injected(T dummy, IEnumerable fakes) - { - ArgumentGuard.ThrowIfNull(dummy, nameof(dummy)); - ArgumentGuard.ThrowIfNull(fakes, nameof(fakes)); - - Dummy = dummy; - Fakes = fakes.ToArray(); - } - - /// Finds the fake. - /// Type of fake to look for. - /// How many fakes of the to ignore first. - /// The found fake. - public Fake Fake(int skip = 0) - { - Fake? direct = Fakes - .OfType>() - .Skip(skip) - .FirstOrDefault(); - - return direct ?? Fakes - .Where(f => f.Dummy.GetType().Inherits()) - .Skip(skip) - .First() - .ToFake(); - } - - /// Finds the fake owner of the given dummy. - /// Type of fake to look for. - /// Dummy of a fake to search on. - /// The found fake. - public Fake Fake(TInject dummy) - { - return Fakes.First(f => ReferenceEquals(f.Dummy, dummy)).ToFake(); - } - - /// Verifies all behaviors in all fakes were called as expected. - public void VerifyAll() - { - foreach (Fake fake in Fakes) - { - fake.VerifyAll(); - } - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/OutRef.cs b/src/CreateAndFake/Toolbox/FakerTool/OutRef.cs deleted file mode 100644 index 5271842d..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/OutRef.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// For matching out and ref arguments. -/// Argument Type to match. -public sealed class OutRef : IOutRef -{ - /// Used as the out/ref argument. - [SuppressMessage("Microsoft.Design", - "CA1051:DoNotDeclareVisibleInstanceFields", - Justification = "Required to match out/ref.")] - public T? Var = default; -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Proxy/CallData.cs b/src/CreateAndFake/Toolbox/FakerTool/Proxy/CallData.cs deleted file mode 100644 index 878aca21..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Proxy/CallData.cs +++ /dev/null @@ -1,115 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.FakerTool.Proxy; - -/// Method call details. -/// -/// -/// -/// -internal sealed class CallData(string methodName, Type[] generics, object?[] args, IValuer? valuer) : IDuplicatable -{ - /// Name tied to the call. - private readonly string _methodName = methodName ?? throw new ArgumentNullException(nameof(methodName)); - - /// Generics tied to the call. - private readonly Type[] _generics = generics ?? throw new ArgumentNullException(nameof(generics)); - - /// Args tied to the call. - private readonly object?[] _args = args ?? throw new ArgumentNullException(nameof(args)); - - /// How to compare call data. - private readonly IValuer? _valuer = valuer; - - /// Converts arg values to designated Arg matchers. - /// Created Args to substitute on the given values. - internal void ConvertArgs(Tuple[] argChanges) - { - ArgumentGuard.ThrowIfNull(argChanges, nameof(argChanges)); - - List> changes = [.. argChanges]; - for (int i = 0; i < _args.Length; i++) - { - Tuple? change = changes.FirstOrDefault(c => Equals(c.Item2, _args[i])); - if (change != default) - { - _args[i] = change.Item1; - _ = changes.Remove(change); - } - } - } - - /// - public IDuplicatable DeepClone(IDuplicator duplicator) - { - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - return new CallData(_methodName, [.. _generics], duplicator.Copy(_args)!, duplicator.Copy(_valuer)); - } - - /// Determines if behavior is intended for a call. - /// Details of the call. - /// true if matched; false otherwise. - internal bool MatchesCall(CallData input) - { - ArgumentGuard.ThrowIfNull(input, nameof(input)); - - return (_methodName == input._methodName) - && GenericsMatch(input._generics) - && ArgsMatch(input._args); - } - - /// Determines if the call generics match the expected ones. - /// Generics used in the call. - /// true if matched; false otherwise. - private bool GenericsMatch(Type[] inputGenerics) - { - bool matches = inputGenerics.Length == _generics.Length; - - for (int i = 0; matches && i < inputGenerics.Length; i++) - { - if (_generics[i] != typeof(AnyGeneric)) - { - matches &= _generics[i] == inputGenerics[i]; - } - } - return matches; - } - - /// Determines if the call args match the expected ones. - /// Args used in the call. - /// true if matched; false otherwise. - private bool ArgsMatch(object?[] inputArgs) - { - bool matches = inputArgs.Length == _args.Length; - - for (int i = 0; matches && i < inputArgs.Length; i++) - { - if (_args[i] is Arg exp) - { - matches &= exp.Matches(inputArgs[i]); - } - else if (_valuer != null) - { - matches &= _valuer.Equals(inputArgs[i], _args[i]); - } - else - { - matches &= Equals(inputArgs[i], _args[i]); - } - } - return matches; - } - - /// Converts this to a string. - /// string representation of this. - public override string ToString() - { - string gen = _generics.Length != 0 - ? "<" + string.Join(", ", _generics.Select(g => g.Name)) + ">" - : ""; - return _methodName + gen + "(" + string.Join(", ", _args.Select(i => i ?? "'null'")) + ")"; - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Proxy/Emitter.cs b/src/CreateAndFake/Toolbox/FakerTool/Proxy/Emitter.cs deleted file mode 100644 index de331947..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Proxy/Emitter.cs +++ /dev/null @@ -1,301 +0,0 @@ -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; - -namespace CreateAndFake.Toolbox.FakerTool.Proxy; - -/// Creates dynamic subclasses by IL code. -internal static class Emitter -{ - /// Assembly used to contain the dynamic types. - internal static AssemblyName AssemblyName { get; } = new AssemblyName("FakerTypes"); - - /// Underlying type managing implementation details. - internal static Type FakeType { get; } = typeof(IFaked); - - /// Underlying type managing implementation details. - internal static Type MetaType { get; } = typeof(FakeMetaProvider); - - /// Flags used to find members to implement. - private const BindingFlags _MemberFinder = BindingFlags.FlattenHierarchy | - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - - /// Methods called to chain fake calls. - private static readonly MethodInfo - _VoidChainer = MetaType.GetMethod( - nameof(FakeMetaProvider.CallVoid), - BindingFlags.Instance | BindingFlags.NonPublic)!, - _ResultChainer = MetaType.GetMethod( - nameof(FakeMetaProvider.CallRet), - BindingFlags.Instance | BindingFlags.NonPublic)!, - _TypeResolver = typeof(Type).GetMethod( - nameof(Type.GetTypeFromHandle), - BindingFlags.Static | BindingFlags.Public)!; - - /// Module storing the faked types. - private static readonly ModuleBuilder _Module = AssemblyBuilder - .DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess.RunAndCollect) - .DefineDynamicModule("FakerTypesModule"); - - /// Creates a type with the given inheritance. - /// Base class inheriting from. - /// Additional interfaces to inherit. - /// Dynamic type with behavior faked. - internal static TypeInfo BuildType(Type parent, Type[] interfaces) - { - TypeBuilder newType = _Module.DefineType( - "Fake_" + string.Join("|", interfaces.Prepend(parent).Select(i => i.Name)) + "_" + Guid.NewGuid(), - TypeAttributes.NotPublic | TypeAttributes.Sealed, parent, interfaces); - - MethodInfo metaGetter = SetupFakeMetaProvider(newType, SetupConstructor(newType, parent)); - - (PropertyInfo, PropertyBuilder)[] props = - FindImplementableProperties(interfaces.Prepend(parent)) - .Select(p => (p, newType.DefineProperty( - p.DeclaringType!.Name + "." + p.Name, - p.Attributes, - p.PropertyType, - Type.EmptyTypes))) - .ToArray(); - - foreach (MethodInfo method in FindImplementableMethods(interfaces.Prepend(parent))) - { - MethodBuilder fakedMethod = newType.DefineMethod( - method.DeclaringType!.Name + "." + method.Name, - method.Attributes & ~MethodAttributes.Abstract, - method.ReturnType, - method.GetParameters().Select(p => p.ParameterType).ToArray()); - - if (method.IsGenericMethod) - { - _ = fakedMethod.DefineGenericParameters(method.GetGenericArguments().Select(a => a.Name).ToArray()); - } - ImplementFakeBehavior(fakedMethod.GetILGenerator(), method, metaGetter); - newType.DefineMethodOverride(fakedMethod, method); - - foreach ((PropertyInfo, PropertyBuilder) prop in props) - { - if (prop.Item1.GetMethod == method) - { - prop.Item2.SetGetMethod(fakedMethod); - } - else if (prop.Item1.SetMethod == method) - { - prop.Item2.SetSetMethod(fakedMethod); - } - } - } - - return newType.CreateTypeInfo()!; - } - - /// Finds all properties to generate for a type implementing the given interfaces. - /// Interfaces to inherit. - /// Properties to implement for the faked type. - private static IEnumerable FindImplementableProperties(IEnumerable interfaces) - { - return interfaces - .Where(t => t != typeof(IFaked)) - .SelectMany(i => i - .GetProperties(_MemberFinder) - .Where(p => IsVisible(p.GetMethod)) - .Concat(FindImplementableProperties(i.GetInterfaces()))) - .Distinct(); - } - - /// Finds all methods to generate for a type implementing the given interfaces. - /// Interfaces to inherit. - /// Methods to implement for the faked type. - private static IEnumerable FindImplementableMethods(IEnumerable interfaces) - { - return interfaces - .Where(t => t != typeof(IFaked)) - .SelectMany(i => i - .GetMethods(_MemberFinder) - .Where(m => m.IsAbstract || (m.IsVirtual && !m.IsFinal)) - .Where(m => IsVisible(m)) - .Where(m => m.Name != "Finalize") - .Concat(FindImplementableMethods(i.GetInterfaces()))) - .Distinct(); - } - - /// Determines if the method is visible for faking. - /// Method to check. - /// True if visible; false otherwise. - private static bool IsVisible(MethodInfo? method) - { - if (method == null) - { - return true; - } - - return !method.IsPrivate - && (!(method.IsAssembly || method.IsFamilyAndAssembly) - || method.Module.Assembly.GetCustomAttributes() - .Any(a => a.AssemblyName == AssemblyName.Name)); - } - - /// Chains the call for a method. - /// Generator for the fake method. - /// Method being implemented. - /// Hook for the meta provider to chain with. - private static void ImplementFakeBehavior(ILGenerator gen, MethodInfo method, MethodInfo metaGetter) - { - ParameterInfo[] argInfos = method.GetParameters(); - Type[] generics = method.GetGenericArguments(); - - // object[] args = new object[params.Length]; - LocalBuilder args = gen.DeclareLocal(typeof(object[])); - gen.Emit(OpCodes.Ldc_I4, argInfos.Length); - gen.Emit(OpCodes.Newarr, typeof(object)); - gen.Emit(OpCodes.Stloc, args); - - // args[0..x] = params[0..x]; - for (int i = 0; i < argInfos.Length; i++) - { - gen.Emit(OpCodes.Ldloc, args); - gen.Emit(OpCodes.Ldc_I4, i); - if (!argInfos[i].ParameterType.IsByRef) - { - gen.Emit(OpCodes.Ldarg, i + 1); - gen.Emit(OpCodes.Box, argInfos[i].ParameterType); - gen.Emit(OpCodes.Stelem_Ref); - } - else - { - // args[i] = new OutRef(); - Type outRef = typeof(OutRef<>).MakeGenericType(argInfos[i].ParameterType.GetElementType()!); - gen.Emit(OpCodes.Newobj, outRef.GetConstructor(Type.EmptyTypes)!); - gen.Emit(OpCodes.Stelem_Ref); - if (!argInfos[i].IsOut) - { - // ((OutRef)args[i].Var) = params[i]; - gen.Emit(OpCodes.Ldloc, args); - gen.Emit(OpCodes.Ldc_I4, i); - gen.Emit(OpCodes.Ldelem_Ref); - gen.Emit(OpCodes.Castclass, outRef); - gen.Emit(OpCodes.Ldarg, i + 1); - gen.Emit(OpCodes.Ldind_Ref); - gen.Emit(OpCodes.Stfld, outRef.GetField(nameof(OutRef.Var))!); - } - } - } - - // Type[] types = new Type[generics.Length]; - LocalBuilder types = gen.DeclareLocal(typeof(Type[])); - gen.Emit(OpCodes.Ldc_I4, generics.Length); - gen.Emit(OpCodes.Newarr, typeof(Type)); - gen.Emit(OpCodes.Stloc, types); - - // types[0..x] = typeof(generics[0..x]); - for (int i = 0; i < generics.Length; i++) - { - gen.Emit(OpCodes.Ldloc, types); - gen.Emit(OpCodes.Ldc_I4, i); - gen.Emit(OpCodes.Ldtoken, generics[i]); - gen.Emit(OpCodes.Call, _TypeResolver); - gen.Emit(OpCodes.Stelem_Ref); - } - - // this.FakeMeta.Call(this, 'method.Name', types, args); - gen.Emit(OpCodes.Ldarg_0); - gen.Emit(OpCodes.Callvirt, metaGetter); - gen.Emit(OpCodes.Ldarg_0); - gen.Emit(OpCodes.Ldstr, method.Name); - gen.Emit(OpCodes.Ldloc, types); - gen.Emit(OpCodes.Ldloc, args); - if (method.ReturnType != typeof(void)) - { - gen.Emit(OpCodes.Callvirt, _ResultChainer.MakeGenericMethod(method.ReturnType)); - } - else - { - gen.Emit(OpCodes.Callvirt, _VoidChainer); - } - - // params[0..x] = ((OutRef)args[0..x]).Var; - for (int i = 0; i < argInfos.Length; i++) - { - if (argInfos[i].ParameterType.IsByRef) - { - Type outRef = typeof(OutRef<>).MakeGenericType(argInfos[i].ParameterType.GetElementType()!); - - gen.Emit(OpCodes.Ldarg, i + 1); - gen.Emit(OpCodes.Ldloc, args); - gen.Emit(OpCodes.Ldc_I4, i); - gen.Emit(OpCodes.Ldelem_Ref); - gen.Emit(OpCodes.Castclass, outRef); - gen.Emit(OpCodes.Ldfld, outRef.GetField(nameof(OutRef.Var))!); - gen.Emit(OpCodes.Stind_Ref); - } - } - - gen.Emit(OpCodes.Ret); - } - - /// Creates the constructor with the backing field for the meta provider. - /// Dynamic type being created. - /// Base class inheriting from. - /// Info for the meta provider field. - private static FieldBuilder SetupConstructor(TypeBuilder newType, Type parent) - { - ConstructorInfo? baseConstructor = parent - .GetConstructors(_MemberFinder) - .SingleOrDefault(c => c.GetParameters().Length == 0); - - FieldBuilder backingField = newType.DefineField( - "_" + nameof(IFaked.FakeMeta), MetaType, - FieldAttributes.Private | FieldAttributes.InitOnly); - - ConstructorBuilder constructor = newType.DefineConstructor( - MethodAttributes.Public, - CallingConventions.HasThis, - [MetaType]); - { - // base(); - ILGenerator gen = constructor.GetILGenerator(); - if (baseConstructor != null) - { - gen.Emit(OpCodes.Ldarg_0); - gen.Emit(OpCodes.Call, baseConstructor); - } - - // this.m_FakeMeta = params[0]; - gen.Emit(OpCodes.Ldarg_0); - gen.Emit(OpCodes.Ldarg_1); - gen.Emit(OpCodes.Stfld, backingField); - gen.Emit(OpCodes.Ret); - } - - return backingField; - } - - /// Hooks up the fake behavior mechanism for the new type. - /// Dynamic type being created. - /// Field holding the meta provider. - /// Info for the meta provider get hook. - private static MethodInfo SetupFakeMetaProvider(TypeBuilder newType, FieldInfo backingField) - { - PropertyInfo propInfo = FakeType.GetProperty(nameof(IFaked.FakeMeta))!; - MethodInfo getterInfo = propInfo.GetGetMethod()!; - - MethodBuilder getMetaMethod = newType.DefineMethod( - nameof(IFaked) + "." + getterInfo.Name, - getterInfo.Attributes & ~MethodAttributes.Abstract, - MetaType, - Type.EmptyTypes); - { - // return this._FakeMeta; - ILGenerator gen = getMetaMethod.GetILGenerator(); - gen.Emit(OpCodes.Ldarg_0); - gen.Emit(OpCodes.Ldfld, backingField); - gen.Emit(OpCodes.Ret); - } - - newType.DefineProperty(nameof(IFaked) + "." + propInfo.Name, - propInfo.Attributes, MetaType, Type.EmptyTypes).SetGetMethod(getMetaMethod); - - newType.DefineMethodOverride(getMetaMethod, getterInfo); - return getterInfo; - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeCallException.cs b/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeCallException.cs deleted file mode 100644 index 0c34aeca..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeCallException.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Runtime.Serialization; - -namespace CreateAndFake.Toolbox.FakerTool.Proxy; - -/// Exception for a call lacking behavior. -[Serializable, KnownType(typeof(Exception))] -public sealed class FakeCallException : Exception -{ - /// - /// Serialization constructor. - private FakeCallException() : base() { } - - /// - /// Associated call data. - /// Call data with behavior. - internal FakeCallException(CallData data, IEnumerable setup) : base(BuildMessage(data, setup)) { } - - /// - /// Object data. - /// Additional info. - /// Serialization constructor. -#if NET5_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private FakeCallException(SerializationInfo info, StreamingContext context) : base(info, context) { } - - /// Integrates the details into the message. - /// Associated call data. - /// Call data with behavior. - /// Message to use for the exception. - private static string BuildMessage(CallData data, IEnumerable setup) - { - string nl = Environment.NewLine; - - return "Method called without matched behavior." + - ((data == null) ? "" : $"{nl}Call: {data}") + - ((setup == null) ? "" : $"{nl}Calls with behavior set: {BuildMessage(setup)}"); - } - - /// - private static string BuildMessage(IEnumerable setup) - { - return Environment.NewLine + string.Join(Environment.NewLine, setup); - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeMetaProvider.cs b/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeMetaProvider.cs deleted file mode 100644 index 1aca1307..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeMetaProvider.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System.Linq.Expressions; -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.FakerTool.Proxy; - -/// Internal mechanism for faked object behavior. -public sealed class FakeMetaProvider : IDuplicatable -{ - /// Last called method. - [ThreadStatic] - private static Tuple? _LastCall; - - /// Faked behavior. - private readonly Stack<(CallData, Behavior)> _behavior = new(); - - /// Record of calls made. - private readonly List _log = []; - - /// Number of calls made with no associated behavior. - private int _defaultCalls = 0; - - /// Mutatable for value tooling. - public int Identifier { get; set; } - - /// Determines behavior when missing set behavior for a call. - public bool ThrowByDefault { get; set; } = true; - - /// - internal IValuer? Valuer { get; set; } - - /// - public FakeMetaProvider() { } - - /// - /// Behavior to pass in. - /// Record of calls to pass in. - /// Copy constructor. - internal FakeMetaProvider(IEnumerable<(CallData, Behavior)> behavior, IEnumerable log) - { - ArgumentGuard.ThrowIfNull(behavior, nameof(log)); - ArgumentGuard.ThrowIfNull(log, nameof(log)); - - foreach ((CallData, Behavior) set in behavior) - { - _behavior.Push(set); - } - foreach (CallData data in log) - { - _log.Add(data); - } - } - - /// - public IDuplicatable DeepClone(IDuplicator duplicator) - { - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - return new FakeMetaProvider( - _behavior.Reverse().Select(t => duplicator.Copy(t)), - _log.Select(t => duplicator.Copy(t)!)) - { - Valuer = duplicator.Copy(Valuer), - Identifier = Identifier, - ThrowByDefault = ThrowByDefault, - _defaultCalls = _defaultCalls - }; - } - - /// Sets up behavior for the fake method last called. - /// Behavior to tie to the call. - internal static void SetLastCallBehavior(Behavior behavior) - { - if (_LastCall == null) - { - throw new InvalidOperationException( - "Faked method never called to set behavior for. Verify instance is a [Fake] stub, and method is abstract."); - } - - _ = _LastCall.Item1._log.Remove(_LastCall.Item2); - _LastCall.Item1.SetCallBehavior(_LastCall.Item2, behavior); - _LastCall.Item2.ConvertArgs(Arg.CaptureSetArgs()); - _LastCall = null; - } - - /// Sets up behavior for the fake. - /// Call to set behavior for. - /// Behavior to tie to the call. - internal void SetCallBehavior(CallData callData, Behavior behavior) - { - ArgumentGuard.ThrowIfNull(callData, nameof(callData)); - ArgumentGuard.ThrowIfNull(behavior, nameof(behavior)); - - _behavior.Push((callData, behavior)); - } - - /// Verifies behavior with associated times were called as expected. - internal void Verify() - { - (CallData, Behavior)[] invalids = _behavior.Where(t => !t.Item2.HasExpectedCalls()).ToArray(); - if (invalids.Length != 0) - { - throw new FakeVerifyException(invalids, _log); - } - } - - /// Verifies the number of calls made. - /// Expected number of calls. - /// Call to verify. - internal void Verify(Times times, CallData callData) - { - ArgumentGuard.ThrowIfNull(times, nameof(times)); - ArgumentGuard.ThrowIfNull(callData, nameof(callData)); - - IEnumerable calls = _log.Where(callData.MatchesCall).ToArray(); - if (!times.IsInRange(calls.Count())) - { - throw new FakeVerifyException(callData, times, calls.Count(), _log); - } - } - - /// Verifies the total number of calls made. - /// Expected total. - internal void VerifyTotalCalls(Times times) - { - ArgumentGuard.ThrowIfNull(times, nameof(times)); - - if (!times.IsInRange(_log.Count)) - { - throw new FakeVerifyException(times, _log); - } - } - - /// Manager for all action calls. - /// The faked object. - /// Name of the method being called. - /// Generics tied to the call. - /// Provided args to the call. - internal void CallVoid(object instance, string name, Type[] generics, object[] args) - { - object? result = CallRet(instance, name, generics, args); - if (result != null) - { - throw new InvalidOperationException( - $"Method '{name}' expected void but instead returned '{result}'."); - } - } - - /// Manager for all func calls. - /// Return type. - /// The faked object. - /// Name of the method being called. - /// Generics tied to the call. - /// Provided args to the call. - /// Faked result previously set up. - internal T? CallRet(object instance, string name, Type[] generics, object[] args) - { - CallData data = new(name, generics, args, Valuer); - _log.Add(data); - _LastCall = Tuple.Create(this, data); - - (CallData, Behavior) match = _behavior.FirstOrDefault(t => t.Item1.MatchesCall(data)); - if (match.Equals(default)) - { - _defaultCalls++; - if (ThrowByDefault) - { - throw new FakeCallException(data, _behavior.Select(b => b.Item1)); - } - else - { - return default; - } - } - - if (match.Item2.BaseCallType != null) - { - return CallBase(instance, name, match, args); - } - else - { - return (T?)match.Item2.Invoke(args); - } - } - - /// Calls the base method for a behavior. - /// Return type. - /// The faked object. - /// Name of the method being called. - /// Behavior details. - /// Provided args to the call. - /// Base method result. - private static T? CallBase(object instance, string name, (CallData, Behavior) match, object[] args) - { - MethodInfo? method = match.Item2.BaseCallType!.GetMethod(name); - if (method == null) - { - throw new MissingMethodException($"Method '{name}' does not exist on '{match.Item2.BaseCallType}'"); - } - else if (method.IsAbstract) - { - throw new InvalidOperationException($"Cannot call base '{name}' as it's abstract."); - } - else - { - Delegate caller = (Delegate)Activator.CreateInstance( - FindDelegateType(method), instance, method.MethodHandle.GetFunctionPointer())!; - - return (T?)match.Item2.Invoke(caller, args); - } - } - - /// Matches a delegate to the method. - /// Method to call. - /// Found delegate type. - private static Type FindDelegateType(MethodInfo methodInfo) - { - IEnumerable args = methodInfo.GetParameters().Select(p => p.ParameterType); - - return (methodInfo.ReturnType == typeof(void)) - ? Expression.GetActionType(args.ToArray()) - : Expression.GetFuncType(args.Concat([methodInfo.ReturnType]).ToArray()); - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeVerifyException.cs b/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeVerifyException.cs deleted file mode 100644 index 93c75dd8..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Proxy/FakeVerifyException.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Runtime.Serialization; - -namespace CreateAndFake.Toolbox.FakerTool.Proxy; - -/// Exception for call counts not matching expectations. -[Serializable, KnownType(typeof(Exception))] -public sealed class FakeVerifyException : Exception -{ - /// - /// Serialization constructor. - private FakeVerifyException() : base() { } - - /// - /// Associated call data. - /// Expected number of calls. - /// Actual number of calls. - /// Log of all made calls. - internal FakeVerifyException(CallData data, Times expected, int actual, IEnumerable log) - : base(BuildMessage(data, expected.ToString(), actual, log)) { } - - /// - /// Expected number of calls. - /// Log of all made calls. - internal FakeVerifyException(Times expected, IEnumerable log) - : base(BuildMessage(null, expected.ToString(), log.Count(), log)) { } - - /// - /// Call data with behavior that aren't valid. - /// Log of all made calls. - internal FakeVerifyException(IEnumerable<(CallData, Behavior)> invalid, IEnumerable log) - : base(string.Join(Environment.NewLine, invalid - .Select(i => BuildMessage(i.Item1, i.Item2.ToExpectedCalls(), i.Item2.Calls, null)) - .Append(BuildMessage(log)))) - { } - - /// - /// Object data. - /// Additional info. - /// Serialization constructor. -#if NET5_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private FakeVerifyException(SerializationInfo info, StreamingContext context) : base(info, context) { } - - /// Integrates the details into the message. - /// Associated call data. - /// Expected number of calls. - /// Actual number of calls. - /// Log of all made calls. - /// Message to use for the exception. - private static string BuildMessage(CallData? source, string expected, int actual, IEnumerable? log) - { - string nl = Environment.NewLine; - - return $"Expected '{expected}', but had '{actual}' calls." + - ((source == null) ? "" : $"{nl}Call: {source}") + - ((log == null) ? "" : $"{nl}Log: {BuildMessage(log)}"); - } - - /// Integrates the details into the message. - /// Log of all made calls. - /// Message to use for the exception. - private static string BuildMessage(IEnumerable log) - { - return Environment.NewLine + string.Join(Environment.NewLine, log); - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Proxy/IOutRef.cs b/src/CreateAndFake/Toolbox/FakerTool/Proxy/IOutRef.cs deleted file mode 100644 index 91c16fe7..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Proxy/IOutRef.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFake.Toolbox.FakerTool.Proxy; - -/// Marker for OutRef. -[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", - Justification = "For matching any OutRef in mock behavior.")] -public interface IOutRef { } diff --git a/src/CreateAndFake/Toolbox/FakerTool/Proxy/Subclasser.cs b/src/CreateAndFake/Toolbox/FakerTool/Proxy/Subclasser.cs deleted file mode 100644 index 2f3fff51..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Proxy/Subclasser.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System.Reflection; - -namespace CreateAndFake.Toolbox.FakerTool.Proxy; - -/// Creates dynamic subclasses. -public static class Subclasser -{ - /// Assembly used to contain the dynamic types. - public static AssemblyName AssemblyName => Emitter.AssemblyName; - - /// Cache of already created types. - private static readonly Dictionary _TypeCache = []; - - /// Determines if the type can be faked. - /// Type to check. - /// True if possible; false otherwise. - public static bool Supports() - { - return Supports(typeof(T)); - } - - /// Determines if the type can be faked. - /// Type to check. - /// True if possible; false otherwise. - public static bool Supports(Type type) - { - return CanBeSubclassed(type).Item1; - } - - /// Creates a subclass of the given type. - /// Parent type to inherit from. - /// Extra interfaces to implement. - /// An instance of the created child type. - public static T Create(params Type[] interfaces) - { - return (T)Create(typeof(T), interfaces); - } - - /// Creates a subclass of the given type. - /// Parent type to inherit from. - /// Extra interfaces to implement. - /// An instance of the created child type. - public static IFaked Create(Type parent, params Type[] interfaces) - { - return (IFaked)CreateInfo(parent, interfaces).AsType() - .GetConstructor([Emitter.MetaType])! - .Invoke([new FakeMetaProvider()]); - } - - /// Creates a subclass of the given type. - /// Parent type to inherit from. - /// Extra interfaces to implement. - /// The created child type. - internal static TypeInfo CreateInfo(Type parent, params Type[] interfaces) - { - List allInterfaces = interfaces?.ToList() ?? []; - allInterfaces.Add(Emitter.FakeType); - - Type realParent = parent ?? typeof(object); - if (realParent.IsInterface) - { - allInterfaces.Add(realParent); - realParent = typeof(object); - } - - (bool, Exception?) possible = CanBeSubclassed(realParent); - if (!possible.Item1) - { - throw possible.Item2!; - } - - IEnumerable invalidInterfaces = allInterfaces.Where(t => !t.IsInterface); - if (invalidInterfaces.Any()) - { - throw new ArgumentException("Given interfaces not actually interfaces: '" + - string.Join("', '", invalidInterfaces.Select(t => t.Name)) + "'."); - } - - return FindOrBuildType(realParent, allInterfaces.Distinct().ToArray()); - } - - /// Determines if type can be subclassed. - /// Type to check. - /// True if possible; false if not with exception to throw. - private static (bool, Exception?) CanBeSubclassed(Type parent) - { - if (parent == null) - { - return (true, null); - } - else if (parent.IsSealed) - { - return (false, new ArgumentException($"Cannot subclass the sealed type '{parent.Name}'.")); - } - else if (parent.IsPointer) - { - return (false, new ArgumentException($"Cannot subclass the pointer '{parent.Name}'.")); - } - else if (parent.ContainsGenericParameters) - { - return (false, new ArgumentException($"Cannot subclass with unspecified generics '{parent.Name}'.")); - } - else if (!parent.IsVisibleTo(AssemblyName)) - { - return (false, new ArgumentException($"Cannot subclass with nonpublic type '{parent.Name}'. " - + $"Think about adding 'InternalsVisibleTo(\"{AssemblyName.Name}\")' to the type's assembly.")); - } - else if (parent == typeof(Array)) - { - return (false, new ArgumentException($"Cannot subclass system reserved '{nameof(Array)}' type.")); - } - else - { - return (true, null); - } - } - - /// Finds or creates a type with the given hierarchy. - /// Parent type to inherit from. - /// Extra interfaces to implement. - /// The cached or created child type. - private static TypeInfo FindOrBuildType(Type parent, Type[] interfaces) - { - lock (_TypeCache) - { - TypeInfo cachedType = _TypeCache - .Where(t => t.Key.BaseType == parent) - .SingleOrDefault(t => !t.Value - .Except(interfaces) - .Union(interfaces - .Except(t.Value)) - .Any()).Key; - - if (cachedType != null) - { - return cachedType; - } - else - { - TypeInfo newType = Emitter.BuildType(parent, interfaces); - _TypeCache.Add(newType, interfaces); - return newType; - } - } - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Times.cs b/src/CreateAndFake/Toolbox/FakerTool/Times.cs deleted file mode 100644 index fec3e356..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/Times.cs +++ /dev/null @@ -1,135 +0,0 @@ -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// Tracks number of calls. -public sealed class Times : IEquatable, IDeepCloneable -{ - /// Expected bounds. - private readonly int _min, _max; - - /// - /// Upper and lower bound. - /// Sets the expected bounds to a single value. - private Times(int count) : this(count, count) { } - - /// - /// Lower bound. - /// Upper bound. - private Times(int min, int max) - { - _min = min; - _max = max; - } - - /// - public IDeepCloneable DeepClone() - { - return new Times(_min, _max); - } - - /// Checks if is in the expected range. - /// Value to verify. - /// true if is in range; false otherwise. - internal bool IsInRange(int count) - { - return _min <= count && count <= _max; - } - - /// Compares this to by value. - /// Instance to compare this with. - /// - /// true if this is equal to by value; false otherwise. - /// - public override bool Equals(object? obj) - { - return Equals(obj as Times); - } - - /// - public bool Equals(Times? other) - { - return other != null - && _min == other._min - && _max == other._max; - } - - /// Computes an identifying hash code based upon value. - /// The computed hash code. - public override int GetHashCode() - { - return ValueComparer.Use.GetHashCode(_min, _max); - } - - /// Converts this to a string. - /// string representation of this. - public override string ToString() - { - string maxValue = (_max != int.MaxValue) - ? $"{_max}" - : "*"; - return (_min != _max) - ? $"[{_min}-{maxValue}]" - : maxValue; - } - - /// Sets the expected bounds to a single value. - /// Upper and lower bound. - public static implicit operator Times(int count) - { - return ToTimes(count); - } - - /// Sets the expected bounds to a single value. - /// Upper and lower bound. - public static Times ToTimes(int count) - { - return new Times(count); - } - - /// Represents 0 allowed calls. - public static Times Never { get; } = Exactly(0); - - /// Represents 1 allowed calls. - public static Times Once { get; } = Exactly(1); - - /// Sets the expected bounds to exactly . - /// Upper and lower bound. - /// Representation of the bounds. - public static Times Exactly(int count) - { - return new Times(count); - } - - /// Sets the bounds to and . - /// Lower bound. - /// Upper bound. - /// Representation of the bounds. - public static Times Between(int min, int max) - { - return new Times(min, max); - } - - /// Sets the expected bounds to anything above . - /// Lower bound. - /// Representation of the bounds. - public static Times Min(int count) - { - return Between(count, int.MaxValue); - } - - /// Sets the expected bounds to anything below . - /// Upper bound. - /// Representation of the bounds. - public static Times Max(int count) - { - return Between(0, count); - } - - /// Sets the expected bounds to any number. - /// Representation of the bounds. - public static Times Any() - { - return Min(0); - } -} diff --git a/src/CreateAndFake/Toolbox/FakerTool/VoidType.cs b/src/CreateAndFake/Toolbox/FakerTool/VoidType.cs deleted file mode 100644 index d16855ea..00000000 --- a/src/CreateAndFake/Toolbox/FakerTool/VoidType.cs +++ /dev/null @@ -1,10 +0,0 @@ - -namespace CreateAndFake.Toolbox.FakerTool; - -/// Represents void type for behaviors. -public sealed class VoidType -{ - /// - /// Prevents instantiation. - private VoidType() { } -} diff --git a/src/CreateAndFake/Toolbox/MutatorTool/ContentMap.cs b/src/CreateAndFake/Toolbox/MutatorTool/ContentMap.cs deleted file mode 100644 index 98143b43..00000000 --- a/src/CreateAndFake/Toolbox/MutatorTool/ContentMap.cs +++ /dev/null @@ -1,203 +0,0 @@ -using System.Collections; -using System.Reflection; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.MutatorTool; - -/// Extracted content of an object. -/// -public sealed class ContentMap(IDictionary> content) -{ - /// Scope used to search for inner types. - private const BindingFlags _Scope - = BindingFlags.Public - | BindingFlags.NonPublic - | BindingFlags.Instance; - - /// Types with too small of range for unique randomization. - private static readonly HashSet _SmallTypes = [ - typeof(bool), - typeof(char), - typeof(byte)]; - - /// Flattened object data. - private readonly IDictionary> _content = content - ?? throw new ArgumentNullException(nameof(content)); - - /// Iterates all the extracted contents. - /// The extracted contents. - public IEnumerable AllContent() - { - return _content.Values.SelectMany(x => x); - } - - /// Determines if the map has in it. - /// Comparison tool determining equality. - /// Content to check for. - /// true if this has the item; false otherwise. - public bool HasContent(IValuer valuer, object? item) - { - if (item == null) - { - return false; - } - - Type itemType = item.GetType(); - - return itemType.IsValueType || itemType == typeof(string) - ? _content.Values - .Any(p => p.Contains(item)) - : _content.Keys - .Where(k => k.Inherits(itemType)) - .SelectMany(k => _content[k]) - .Any(i => valuer.Equals(item, i)); - } - - /// Determines if this has any content from in it. - /// Comparison tool determining equality. - /// Content to compare this with. - /// true if this has content from ; false otherwise. - /// Ignores types with too small of range for unique randomization. - public bool HasSharedContent(IValuer valuer, params ContentMap[] maps) - { - return FindSharedContent(valuer, maps).Any(); - } - - /// Finds content this shares with . - /// Comparison tool determining equality. - /// Content to compare this with. - /// All shared content found. - /// Ignores types with too small of range for unique randomization. - public IEnumerable FindSharedContent(IValuer valuer, params ContentMap[] maps) - { - return maps - .SelectMany(m => m.AllContent()) - .Intersect(AllContent(), valuer) - .Where(d => !_SmallTypes.Contains(d.GetType())) - .Where(d => !d.GetType().IsEnum) - .Where(d => !(d is IEnumerable series && !series.GetEnumerator().MoveNext())); - } - - /// Returns all possible instances. - /// Content type to find. - /// All instances (including subclasses). - public IEnumerable FindAll() - { - return _content.Keys - .Where(t => t.Inherits(typeof(T))) - .SelectMany(t => _content[t]) - .OfType(); - } - - /// Returns all possible instances. - /// Content type to find. - /// All instances (including subclasses). - public IEnumerable FindAll(Type type) - { - return _content.Keys - .Where(t => t.Inherits(type)) - .SelectMany(t => _content[t]) - .Where(t => t.GetType().Inherits(type)); - } - - /// - /// Extracted content of . - public static ContentMap Extract(object? source) - { - Dictionary> data = []; - FlattenData(null, source, data); - return new ContentMap(data); - } - - /// Finds data associated with - /// Field/Property type the is assigned to. - /// Instance being deconstructed. - /// Collection to populate with found data. - private static void FlattenData(Type? memberType, object? source, IDictionary> foundData) - { - if (source != null) - { - Type keyType = memberType ?? source.GetType(); - - if (!foundData.TryGetValue(keyType, out ISet? data)) - { - data = new HashSet(); - foundData.Add(keyType, data); - } - - if (data.Add(source) && source.GetType() != typeof(string)) - { - FlattenComplexData(source, foundData); - } - } - } - - /// Finds nested data associated with . - /// - private static void FlattenComplexData(object source, IDictionary> foundData) - { - if (source is IDictionary map) - { - FlattenDictionaryData(map, foundData); - } - else if (source is IEnumerable values) - { - FlattenEnumerableData(values, foundData); - } - else if (!source.GetType().IsValueType) - { - FlattenInnerData(source, foundData); - } - } - - /// - private static void FlattenDictionaryData(IDictionary source, IDictionary> foundData) - { - Type type = source.GetType(); - - Type[] mapArgs = type.IsGenericType - ? type.GetGenericArguments() - : [typeof(object), typeof(object)]; - - foreach (DictionaryEntry item in source) - { - FlattenData(mapArgs[0], item.Key, foundData); - FlattenData(mapArgs[1], item.Value, foundData); - } - } - - /// - private static void FlattenEnumerableData(IEnumerable source, IDictionary> foundData) - { - Type type = source.GetType(); - - Type? arrayType = type.IsArray - ? type.GetElementType() - : type.IsGenericType - ? type.GetGenericArguments()[0] - : typeof(object); - - IEnumerator gen = source.GetEnumerator(); - while (gen.MoveNext()) - { - FlattenData(arrayType, gen.Current, foundData); - } - } - - /// Finds member data inside . - /// - private static void FlattenInnerData(object source, IDictionary> foundData) - { - Type type = source.GetType(); - - foreach (PropertyInfo property in type.GetProperties(_Scope).Where(p => p.CanRead)) - { - FlattenData(property.PropertyType, property.GetValue(source), foundData); - } - - foreach (FieldInfo field in type.GetFields(_Scope)) - { - FlattenData(field.FieldType, field.GetValue(source), foundData); - } - } -} diff --git a/src/CreateAndFake/Toolbox/MutatorTool/IMutator.cs b/src/CreateAndFake/Toolbox/MutatorTool/IMutator.cs deleted file mode 100644 index c732558d..00000000 --- a/src/CreateAndFake/Toolbox/MutatorTool/IMutator.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace CreateAndFake.Toolbox.MutatorTool; - -/// Changes the value of objects or creates alternatives. -public interface IMutator -{ - /// Type to create. - /// - T Variant(T instance, params T?[]? extraInstances); - - /// Creates an object with different values. - /// Type to create. - /// Object to diverge from. - /// Extra objects to diverge from. - /// - /// The created object that differs from and . - /// - object Variant(Type type, object? instance, params object?[]? extraInstances); - - /// Type to create. - /// - T Unique(T instance, params T?[]? extraInstances); - - /// Creates an object with completely different values. - /// Type to create. - /// Object to diverge from. - /// Extra objects to diverge from. - /// - /// The created object that differs from and . - /// - /// Ignores types with too small of range for unique randomization. - object Unique(Type type, object? instance, params object?[]? extraInstances); - - /// Attempts to mutate an object. - /// Object to modify. - /// true if has been modified; false otherwise. - bool Modify(object? instance); -} diff --git a/src/CreateAndFake/Toolbox/MutatorTool/Mutator.cs b/src/CreateAndFake/Toolbox/MutatorTool/Mutator.cs deleted file mode 100644 index d01f9aad..00000000 --- a/src/CreateAndFake/Toolbox/MutatorTool/Mutator.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.MutatorTool; - -/// -/// -/// -/// -public sealed class Mutator(IRandomizer randomizer, IValuer valuer, Limiter limiter) : IMutator -{ - /// Handles randomization. - private readonly IRandomizer _randomizer = randomizer ?? throw new ArgumentNullException(nameof(randomizer)); - - /// Ensures object variance. - private readonly IValuer _valuer = valuer ?? throw new ArgumentNullException(nameof(valuer)); - - /// Limits attempts at creating variants. - private readonly Limiter _limiter = limiter ?? throw new ArgumentNullException(nameof(limiter)); - - /// - public T Variant(T instance, params T?[]? extraInstances) - { - return (T)Variant(typeof(T), instance, extraInstances?.Cast().ToArray()); - } - - /// - public object Variant(Type type, object? instance, params object?[]? extraInstances) - { - IEnumerable values = (extraInstances ?? Enumerable.Empty()).Prepend(instance); - try - { - return _limiter.StallUntil( - $"Create variant of type '{type}'", - () => _randomizer.Create(type), - result => - { - if (values.All(o => !_valuer.Equals(result, o))) - { - return true; - } - else - { - Disposer.Cleanup(result); - return false; - } - }).Result.Last(); - } - catch (AggregateException e) - { - throw new TimeoutException($"Could not create different instance of type '{type}'.", e); - } - } - - /// - public T Unique(T instance, params T?[]? extraInstances) - { - return (T)Unique(typeof(T), instance, extraInstances); - } - - /// - public object Unique(Type type, object? instance, params object?[]? extraInstances) - { - ContentMap[] maps = (extraInstances ?? []) - .Prepend(instance) - .Where(e => e != null) - .Select(ContentMap.Extract) - .ToArray(); - - try - { - return _limiter.StallUntil( - $"Create unique of type '{type}'", - () => _randomizer.Create(type), - result => - { - if (!ContentMap.Extract(result).HasSharedContent(valuer, maps)) - { - return true; - } - else - { - Disposer.Cleanup(result); - return false; - } - }).Result.Last(); - } - catch (AggregateException e) - { - throw new TimeoutException($"Could not create unique instance of type '{type}'.", e); - } - } - - /// - public bool Modify(object? instance) - { - if (instance == null) - { - return false; - } - - bool modified = false; - - Type type = instance.GetType(); - foreach (FieldInfo field in type.GetFields(BindingFlags.Instance | BindingFlags.Public)) - { - field.SetValue(instance, Variant(field.FieldType, field.GetValue(instance))); - modified = true; - } - foreach (PropertyInfo property in type - .GetProperties(BindingFlags.Instance | BindingFlags.Public) - .Where(p => p.CanWrite && p.CanRead) - .Where(p => p.GetGetMethod() != null) - .Where(p => p.GetSetMethod() != null)) - { - property.SetValue(instance, Variant(property.PropertyType, property.GetValue(instance))); - modified = true; - } - - return modified; - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateCollectionHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateCollectionHint.cs deleted file mode 100644 index e2ad5909..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateCollectionHint.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace CreateAndFake.Toolbox.RandomizerTool; - -/// Handles randomizing specific collections for . -public abstract class CreateCollectionHint : CreateHint -{ - /// Number of items to generate. - /// - protected internal abstract (bool, object?) TryCreate(Type type, int size, RandomizerChainer randomizer); -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHint.cs deleted file mode 100644 index 2381c38f..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHint.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace CreateAndFake.Toolbox.RandomizerTool; - -/// Handles randomizing specific types for . -public abstract class CreateHint -{ - /// Tries to create a random instance of the given . - /// Type to generate. - /// Handles randomizing child values. - /// - /// (true, created instance) if successful; - /// (false, null) otherwise. - /// - protected internal abstract (bool, object?) TryCreate(Type type, RandomizerChainer randomizer); -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHint[T].cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHint[T].cs deleted file mode 100644 index 002d5791..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHint[T].cs +++ /dev/null @@ -1,30 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.RandomizerTool; - -/// Type being supported for randomization. -/// -public abstract class CreateHint : CreateHint -{ - /// - protected internal sealed override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type.IsInheritedBy() - && (type != typeof(object) || typeof(T) == typeof(object)) - && !randomizer.AlreadyCreated()) - { - return (true, Create(randomizer)); - } - else - { - return (false, null); - } - } - - /// Creates a random instance. - /// Handles randomizing child values. - /// The created instance. - protected abstract T Create(RandomizerChainer randomizer); -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/AsyncCollectionCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/AsyncCollectionCreateHint.cs deleted file mode 100644 index 30b4e2f7..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/AsyncCollectionCreateHint.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Reflection; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing collections for . -/// Handles creating internal representations. -public sealed class AsyncCollectionCreateHint(CollectionCreateHint listHint) : CreateCollectionHint -{ - /// - /// - public AsyncCollectionCreateHint(int minSize = 1, int range = 3) - : this(new CollectionCreateHint(minSize, range)) { } - - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - return TryCreate(type, () => listHint.TryCreate( - typeof(List<>).MakeGenericType(type.GetGenericArguments().Single()), randomizer).Item2); - } - - /// - protected internal override (bool, object?) TryCreate(Type type, int size, RandomizerChainer randomizer) - { - return TryCreate(type, () => listHint.TryCreate( - typeof(List<>).MakeGenericType(type.GetGenericArguments().Single()), size, randomizer).Item2); - } - - /// Creates the backing data. - /// - private (bool, object?) TryCreate(Type type, Func listMaker) - { - if (type.Inherits(typeof(IAsyncEnumerable<>))) - { - return (true, GetType() - .GetMethod(nameof(GetItems), BindingFlags.Static | BindingFlags.NonPublic)! - .MakeGenericMethod(type.GetGenericArguments().Single()) - .Invoke(null, [listMaker()])); - } - else - { - return (false, null); - } - } - - /// Supplies collection items asynchronously. - /// Item Type to supply. - /// Collection items to supply. - /// The collection made from . - private static async IAsyncEnumerable GetItems(List backing) - { - for (int i = 0; i < backing.Count; i++) - { - await Task.Delay(0).ConfigureAwait(false); - yield return backing[i]; - } - } -} \ No newline at end of file diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/CollectionCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/CollectionCreateHint.cs deleted file mode 100644 index e50b3125..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/CollectionCreateHint.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Collections; -using System.Collections.Concurrent; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing collections for . -/// Min size for created collections. -/// Size variance for created collections. -/// Specifies the size of generated collections. -public sealed class CollectionCreateHint(int minSize = 1, int range = 3) : CreateCollectionHint -{ - /// Collections able to be randomized. - private static readonly Type[] _Collections = - [ - typeof(List<>), - typeof(Dictionary<,>), - - typeof(Queue<>), - typeof(Stack<>), - typeof(HashSet<>), - typeof(LinkedList<>), - typeof(ArraySegment<>), - typeof(ConcurrentQueue<>), - typeof(ConcurrentStack<>), - typeof(ConcurrentDictionary<,>) - ]; - - /// Collections that the hint can create. - internal static IEnumerable PotentialCollections => _Collections.Select(i => i); - - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer? randomizer) - { - return TryCreate(type, minSize + randomizer?.Gen.Next(range) ?? 0, randomizer); - } - - /// - protected internal override (bool, object?) TryCreate(Type type, int size, RandomizerChainer? randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - if (type == null) - { - return (false, null); - } - - Type? itemType = GetItemType(type); - if (itemType != null && FindMatches(type, itemType).Any()) - { - return (true, Create(type, size, itemType, randomizer)); - } - else - { - return (false, null); - } - } - - /// Number of items to generate. - /// Item Type to be contained in the collection. - /// The randomized instance. - /// - private static object? Create(Type type, int size, Type itemType, RandomizerChainer randomizer) - { - Type collection = randomizer.Gen.NextItem(FindMatches(type, itemType)); - Type newType = MakeNewType(collection, itemType); - - Array internalData = CreateInternalData(itemType, size, - t => randomizer.Create(t, randomizer.Parent)); - - if (newType == typeof(Array) || newType == internalData.GetType()) - { - return internalData; - } -#if LEGACY // Constructor missing in .NET full. - else if (newType.AsGenericType() == typeof(Dictionary<,>)) - { - dynamic result = Activator.CreateInstance(newType); - foreach (dynamic item in internalData) - { - result.Add(item.Key, item.Value); - } - return result; - } -#endif - else - { - return Activator.CreateInstance(newType, internalData); - } - } - - /// Finds the Type to be contained by a created collection. - /// Collection Type being created.. - /// null if not logical; Type for the collection otherwise. - private static Type? GetItemType(Type type) - { - Type[] args = type.IsGenericType - ? type.GetGenericArguments() - : []; - - if (type.IsArray) - { - return type.GetElementType(); - } - else if (type.IsGenericTypeDefinition) - { - return null; - } - else if (args.Length == 1) - { - return args[0]; - } - else if (args.Length == 2) - { - return typeof(KeyValuePair<,>).MakeGenericType(args[0], args[1]); - } - else - { - return null; - } - } - - /// Finds potential collection matches for . - /// Type to find matches for. - /// Item Type to be contained in the collection. - /// All possible matches. - private static IEnumerable FindMatches(Type type, Type itemType) - { - Type typeAsGeneric = type.IsGenericType - ? type.GetGenericTypeDefinition() - : type; - - if (type.IsArray - || typeAsGeneric.IsInheritedBy(typeof(IList<>)) - || typeAsGeneric.IsInheritedBy(typeof(IList))) - { - yield return typeof(Array); - } - - foreach (Type match in _Collections.Where(typeAsGeneric.IsInheritedBy)) - { - if (!match.Inherits() || itemType.Inherits(typeof(KeyValuePair<,>))) - { - yield return match; - } - } - } - - /// Creates basic structures for . - /// Item Type to be contained in the collection. - /// Number of items to generate. - /// Handles randomizing child values. - /// Data populated with random values. - private static Array CreateInternalData(Type itemType, int size, Func randomizer) - { - Array data = Array.CreateInstance(itemType, size); - for (int i = 0; i < data.Length; i++) - { - data.SetValue(randomizer.Invoke(itemType), i); - } - return data; - } - - /// Constructs the new Type to make for the collection. - /// Matching collection Type with details. - /// Item Type to be contained in the collection. - /// Type to create. - private static Type MakeNewType(Type collection, Type itemType) - { - if (!collection.IsGenericType) - { - return collection; - } - else if (collection.Inherits()) - { - return collection.MakeGenericType(itemType.GetGenericArguments()); - } - else - { - return collection.MakeGenericType(itemType); - } - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/CommonSystemCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/CommonSystemCreateHint.cs deleted file mode 100644 index 0a96a77a..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/CommonSystemCreateHint.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System.Globalization; -using System.Reflection; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing common instances for . -public sealed class CommonSystemCreateHint : CreateHint -{ - /// Supported types and the methods used to generate them. - private static readonly Dictionary> _Gens = new() - { - { typeof(CultureInfo), rand => rand.Gen.NextItem(CultureInfo.GetCultures(CultureTypes.AllCultures)) }, - { typeof(TimeSpan), rand => new TimeSpan(rand.Gen.Next()) }, - { typeof(DateTime), rand => new DateTime(rand.Gen.Next(DateTime.MinValue.Ticks, DateTime.MaxValue.Ticks)) }, - { typeof(DateTimeOffset), rand => new DateTimeOffset(rand.Create()) }, - { typeof(Guid), rand => new Guid(Enumerable.Range(0, 16).Select(i => rand.Create()).ToArray()) }, - - { typeof(Assembly), rand => rand.Gen.NextItem(AppDomain.CurrentDomain.GetAssemblies()) }, - { typeof(AssemblyName), rand => rand.Create()!.GetName() }, - { typeof(Type).GetType(), rand => rand.Create()! }, - { typeof(Type), rand => rand.Gen.NextItem(Assembly.GetExecutingAssembly().GetTypes()) }, - - { typeof(Uri), rand => rand.Create()!.Uri }, - { typeof(UriBuilder), rand => new UriBuilder( - rand.Create() ? "http" : "https", rand.Create(), rand.Gen.Next(-1, 65535)) }, - - { typeof(ConstructorInfo), rand => FindTypeInfo(rand, t => t.GetConstructors()) }, - { typeof(PropertyInfo), rand => FindTypeInfo(rand, t => t.GetProperties()) }, - { typeof(MethodInfo), rand => FindTypeInfo(rand, t => t.GetMethods()) }, - { typeof(MemberInfo), rand => FindTypeInfo(rand, t => t.GetMembers()) }, - { typeof(FieldInfo), rand => FindTypeInfo(rand, t => t.GetFields()) }, - { typeof(ParameterInfo), rand => FindTypeInfo(rand, - t => t.GetMethods().SelectMany(m => m.GetParameters()).ToArray()) }, - { typeof(MethodBase), rand => FindTypeInfo(rand, - t => t.GetConstructors().Cast().Concat(t.GetMethods()).ToArray()) }, - }; - - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type != null && _Gens.TryGetValue(type, out Func? gen)) - { - return (true, gen.Invoke(randomizer)); - } - else - { - return (false, null); - } - } - - /// Finds a random member info. - /// Type being found. - /// Handles randomizing child values. - /// How members are found on a Type. - /// The found member. - private static T FindTypeInfo(RandomizerChainer randomizer, Func grabber) - { - T[] result; - do - { - result = grabber.Invoke((Type)_Gens[typeof(Type)].Invoke(randomizer)); - } while (result.Length == 0); - - return randomizer.Gen.NextItem(result); - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/DelegateCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/DelegateCreateHint.cs deleted file mode 100644 index 19a47fb5..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/DelegateCreateHint.cs +++ /dev/null @@ -1,383 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing instances for . -public sealed class DelegateCreateHint : CreateHint -{ - /// Methods used to match delegates. - private static readonly MethodInfo[] _Delegators = typeof(Delegator) - .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) - .Where(m => m.Name == "AutoDelegate") - .ToArray(); - - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type == typeof(Delegate)) - { - return (true, Create(typeof(Action), randomizer)); - } - else if (type.Inherits()) - { - return (true, Create(type, randomizer)); - } - else - { - return (false, null); - } - } - - /// The randomized instance. - /// - private static object Create(Type type, RandomizerChainer randomizer) - { - Delegator delegator = new(randomizer); - - MethodInfo info = type.GetMethod("Invoke")!; - bool hasReturn = info.ReturnType != typeof(void); - - MethodInfo match = _Delegators - .Where(m => m.GetParameters().Length == info.GetParameters().Length) - .Single(m => m.ReturnType != typeof(void) == hasReturn); - - IEnumerable generics = info.GetParameters().Select(p => p.ParameterType); - if (!match.IsGenericMethod) - { - return Delegate.CreateDelegate(type, delegator, match); - } - else if (hasReturn) - { - return Delegate.CreateDelegate(type, delegator, - match.MakeGenericMethod(generics.Append(info.ReturnType).ToArray())); - } - else - { - return Delegate.CreateDelegate(type, delegator, - match.MakeGenericMethod(generics.ToArray())); - } - } - - /// Provides delegate implementations. - private sealed class Delegator - { - /// Creates random results. - private readonly RandomizerChainer _randomizer; - - /// Sets up the randomization. - /// - internal Delegator(RandomizerChainer randomizer) - { - _randomizer = randomizer; - } - - /// Randomizes any inputs. - /// Inputs for the delegate. - private void HandleIn(params object?[] inputs) - { - foreach (object? outRef in inputs) - { - if (outRef != null) - { - Type inputType = outRef.GetType(); - if (inputType.Inherits()) - { - FieldInfo valueField = inputType.GetField(nameof(OutRef.Var))!; - valueField.SetValue(outRef, _randomizer.Create(valueField.FieldType, _randomizer.Parent)); - } - } - } - } - - /// Randomizes any OutRef inputs and the return. - /// Return Type for the delegate. - /// Inputs for the delegate. - /// Generated output for the delegate. - private T? HandleInAndOut(params object?[] inputs) - { - HandleIn(inputs); - return (T?)_randomizer.Create(typeof(T), _randomizer.Parent); - } - - /// - internal void AutoDelegate() - { - HandleIn(); - } - - /// - internal void AutoDelegate(T1? in1) - { - HandleIn(in1); - } - - /// - internal void AutoDelegate(T1? in1, T2? in2) - { - HandleIn(in1, in2); - } - - /// - internal void AutoDelegate(T1? in1, T2? in2, T3? in3) - { - HandleIn(in1, in2, in3); - } - - /// - internal void AutoDelegate(T1? in1, T2? in2, T3? in3, T4? in4) - { - HandleIn(in1, in2, in3, in4); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5) - { - HandleIn(in1, in2, in3, in4, in5); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6) - { - HandleIn(in1, in2, in3, in4, in5, in6); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12, T13? in13) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12, T13? in13, T14? in14) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13, in14); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12, T13? in13, T14? in14, T15? in15) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13, in14, in15); - } - - /// - internal void AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12, T13? in13, T14? in14, T15? in15, T16? in16) - { - HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13, in14, in15, in16); - } - - /// - internal TOut? AutoDelegate() - { - return HandleInAndOut(); - } - - /// - internal TOut? AutoDelegate(T1 in1) - { - return HandleInAndOut(in1); - } - - /// - internal TOut? AutoDelegate(T1? in1, T2? in2) - { - return HandleInAndOut(in1, in2); - } - - /// - internal TOut? AutoDelegate(T1? in1, T2? in2, T3? in3) - { - return HandleInAndOut(in1, in2, in3); - } - - /// - internal TOut? AutoDelegate(T1? in1, T2? in2, T3? in3, T4? in4) - { - return HandleInAndOut(in1, in2, in3, in4); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5) - { - return HandleInAndOut(in1, in2, in3, in4, in5); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12, T13? in13) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12, T13? in13, T14? in14) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13, in14); - } - - /// - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12, T13? in13, T14? in14, T15? in15) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13, in14, in15); - } - - /// Matches to delegate with same number of inputs and output. - /// Type for parameter 1. - /// Type for parameter 2. - /// Type for parameter 3. - /// Type for parameter 4. - /// Type for parameter 5. - /// Type for parameter 6. - /// Type for parameter 7. - /// Type for parameter 8. - /// Type for parameter 9. - /// Type for parameter 10. - /// Type for parameter 11. - /// Type for parameter 12. - /// Type for parameter 13. - /// Type for parameter 14. - /// Type for parameter 15. - /// Type for parameter 16. - /// Type for the return value. - /// Matches input parameter 1. - /// Matches input parameter 2. - /// Matches input parameter 3. - /// Matches input parameter 4. - /// Matches input parameter 5. - /// Matches input parameter 6. - /// Matches input parameter 7. - /// Matches input parameter 8. - /// Matches input parameter 9. - /// Matches input parameter 10. - /// Matches input parameter 11. - /// Matches input parameter 12. - /// Matches input parameter 13. - /// Matches input parameter 14. - /// Matches input parameter 15. - /// Matches input parameter 16. - /// Nothing if void; otherwise random data. - internal TOut? AutoDelegate( - T1? in1, T2? in2, T3? in3, T4? in4, T5? in5, T6? in6, T7? in7, T8? in8, T9? in9, - T10? in10, T11? in11, T12? in12, T13? in13, T14? in14, T15? in15, T16? in16) - { - return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13, in14, in15, in16); - } - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/EnumCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/EnumCreateHint.cs deleted file mode 100644 index 71e8b691..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/EnumCreateHint.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing Enum values for . -public sealed class EnumCreateHint : CreateHint -{ - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type?.IsEnum ?? false) - { - return (true, randomizer.Gen.NextItem(Enum.GetValues(type).Cast())); - } - else - { - return (false, null); - } - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ExceptionCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ExceptionCreateHint.cs deleted file mode 100644 index 66dfccb0..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ExceptionCreateHint.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; - -#pragma warning disable SYSLIB0050 // 'Type.IsSerializable' is obsolete: Needed for backwards compatibility. - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing instances for . -public sealed class ExceptionCreateHint : CreateHint -{ - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (!type.Inherits()) - { - return (false, null); - } - - ConstructorInfo[] options = type.FindLocalSubclasses() - .Where(t => t.IsVisible) - .Where(t => t.IsSerializable) -#if LEGACY // Security exceptions don't work with default serialization in .NET full. - .Where(t => !t.Namespace.StartsWith("System.Security", StringComparison.Ordinal)) -#endif - .Select(t => t.GetConstructor([typeof(string)])) - .Where(c => c != null) - .Select(c => c!) - .ToArray(); - - return (options.Length != 0) - ? (true, randomizer.Gen.NextItem(options).Invoke([randomizer.Create()])) - : (false, null); - } -} - -#pragma warning restore SYSLIB0050 // 'Type.IsSerializable' is obsolete diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/FakeCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/FakeCreateHint.cs deleted file mode 100644 index 25bf29b8..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/FakeCreateHint.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing instances for . -public sealed class FakeCreateHint : CreateHint -{ - /// Possible action types to use. - private static readonly Type[] _ActionTypes = - [ - typeof(Action), - typeof(Action<>), - typeof(Action<,>), - typeof(Action<,,>), - typeof(Action<,,,>), - typeof(Action<,,,,>), - typeof(Action<,,,,,>), - typeof(Action<,,,,,,>), - typeof(Action<,,,,,,,>), - typeof(Action<,,,,,,,,>), - typeof(Action<,,,,,,,,,>), - typeof(Action<,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,,,,,>) - ]; - - /// Possible func types to use. - private static readonly Type?[] _FuncTypes = - [ - null, - typeof(Func<>), - typeof(Func<,>), - typeof(Func<,,>), - typeof(Func<,,,>), - typeof(Func<,,,,>), - typeof(Func<,,,,,>), - typeof(Func<,,,,,,>), - typeof(Func<,,,,,,,>), - typeof(Func<,,,,,,,,>), - typeof(Func<,,,,,,,,,>), - typeof(Func<,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,,,,,>) - ]; - - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type.Inherits(typeof(Fake<>))) - { - return (true, Create(type, randomizer)); - } - else - { - return (false, null); - } - } - - /// The randomized instance. - /// - private static Fake Create(Type type, RandomizerChainer randomizer) - { - Type target = type.GetGenericArguments().Single(); - - Fake mock = randomizer.Stub(target); - mock.Dummy.FakeMeta.Identifier = randomizer.Create(); - - // Generic returns have to just use stub behavior. - foreach (MethodInfo method in target - .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) - .Where(m => m.IsAbstract || (m.IsVirtual && !m.IsFinal)) - .Where(m => !m.IsPrivate) - .Where(m => !m.ReturnType.IsGenericParameter) - .Where(m => !m.ReturnType.ContainsGenericParameters) - .Where(m => m.Name != "Finalize")) - { - Type[] generics = method.IsGenericMethod - ? method.GetGenericArguments().Select(a => typeof(AnyGeneric)).ToArray() - : []; - - mock.Setup(method.Name, generics, - method.GetParameters().Select(a => SetupMatch(a.ParameterType)).ToArray(), - MakeBehavior(method, randomizer)); - } - - return (Fake)type.GetConstructor([typeof(Fake)])!.Invoke([mock]); - } - - /// Sets up the random fake behavior for the method. - /// Method to fake. - /// Handles randomizing child values. - /// Behavior for the fake. - private static Behavior MakeBehavior(MethodInfo method, RandomizerChainer randomizer) - { - Type[] args = method.GetParameters().Select(p => SetupArg(p.ParameterType)).ToArray(); - - if (method.ReturnType != typeof(void)) - { - Type[] withOut = [.. args, .. new[] { method.ReturnType }]; - - return (Behavior)typeof(Behavior<>) - .MakeGenericType(method.ReturnType) - .GetConstructor([typeof(Delegate), typeof(Times)])! - .Invoke([randomizer.Create(_FuncTypes[withOut.Length]!.MakeGenericType(withOut)), Times.Any()]); - } - else if (args.Length != 0) - { - return new Behavior((Delegate)randomizer - .Create(_ActionTypes[args.Length].MakeGenericType(args))!, Times.Any()); - } - else - { - return Behavior.None(Times.Any()); - } - } - - /// Sets up arg types for the fake behavior. - /// Type of the method to convert. - /// Type to use for the fake behavior delegate. - private static Type SetupArg(Type type) - { - if (type.IsByRef) - { - return typeof(IOutRef); - } - else if (type.IsGenericParameter) - { - return typeof(object); - } - else - { - return type; - } - } - - /// Sets up the arg matcher for a parameter. - /// Parameter Type to allow. - /// Arg to use for setting up the mock. - private static object SetupMatch(Type type) - { - if (type.IsByRef) - { - return Arg.LambdaAny(); - } - else if (type.IsGenericParameter) - { - return Arg.LambdaAny(); - } - else - { - return typeof(Arg) - .GetMethod(nameof(Arg.LambdaAny), BindingFlags.Static | BindingFlags.Public)! - .MakeGenericMethod(type) - .Invoke(null, [])!; - } - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/FakedCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/FakedCreateHint.cs deleted file mode 100644 index d034e7ce..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/FakedCreateHint.cs +++ /dev/null @@ -1,19 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing instances for . -public sealed class FakedCreateHint : CreateHint -{ - /// - protected override IFaked Create(RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - Fake stub = randomizer.Stub(typeof(object)); - stub.Dummy.FakeMeta.Identifier = randomizer.Create(); - return stub.Dummy; - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/GenericCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/GenericCreateHint.cs deleted file mode 100644 index dd836174..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/GenericCreateHint.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; -using CreateAndFake.Design.Randomization; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing generic types for . -public sealed class GenericCreateHint : CreateHint -{ - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type?.IsGenericTypeDefinition ?? false) - { - return (true, Create(type, randomizer)); - } - else - { - return (false, null); - } - } - - /// The randomized instance. - /// - private static object Create(Type type, RandomizerChainer randomizer) - { - return randomizer.Create(type.MakeGenericType(type - .GetGenericArguments() - .Select(a => CreateArg(a, type, randomizer)) - .ToArray()), type); - } - - /// Creates a concrete arg type from the given generic arg. - /// Generic arg to create. - /// Base Type being created. - /// Handles randomizing child values. - /// Created arg Type. - internal static Type CreateArg(Type type, Type parent, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - bool newNeeded = type.GenericParameterAttributes.HasFlag( - GenericParameterAttributes.DefaultConstructorConstraint); - - Type arg; - if (type.GenericParameterAttributes.HasFlag( - GenericParameterAttributes.NotNullableValueTypeConstraint)) - { - arg = randomizer.Gen.NextItem(ValueRandom.ValueTypes); - } - else if (newNeeded) - { - arg = typeof(object); - } - else - { - arg = typeof(string); - } - - Type[] constraints = type - .GetGenericParameterConstraints() - .Select(t => t.ContainsGenericParameters ? t.GetGenericTypeDefinition() : t) - .ToArray(); - - bool isValidArg() - { - return constraints.All(c => arg.Inherits(c) || (arg.IsValueType && c == typeof(ValueType))) - && (!newNeeded || arg.GetConstructor(Type.EmptyTypes) != null || arg.IsValueType); - } - - if (!isValidArg()) - { - Limiter.Few.Retry( - $"Creating generic arguments of type '{type}' for type '{parent}' [Retry]", - () => Limiter.Few.StallUntil($"Trying arguments of type '{type}' for type '{parent}' [Stall]", () => - { - arg = CreateArgViaConstraint(constraints, parent, randomizer); - }, isValidArg).Wait()).Wait(); - } - - return arg; - } - - /// Creates an arg type from the given constraints. - /// Constraints limiting the arg type. - /// Base Type being created. - /// Handles randomizing child values. - /// Created arg Type. - private static Type CreateArgViaConstraint(Type[] constraints, Type parent, RandomizerChainer randomizer) - { - Type constraint = randomizer.Gen.NextItem(constraints); - if (parent == constraint) - { - return randomizer.Gen.NextItemOrDefault(parent.FindLoadedSubclasses()) - ?? throw new InvalidOperationException( - $"Cannot create '{parent}' due to self-reference and no visible subclasses."); - } - else - { - object sample = randomizer.Create(constraint); - Type result = sample.GetType(); - Disposer.Cleanup(sample); - return result; - } - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/InjectedCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/InjectedCreateHint.cs deleted file mode 100644 index baeca819..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/InjectedCreateHint.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing injected dummies for . -public sealed class InjectedCreateHint : CreateHint -{ - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type.Inherits(typeof(Injected<>))) - { - return (true, Create(type, randomizer)); - } - else - { - return (false, null); - } - } - - /// The randomized instance. - /// - private static object Create(Type type, RandomizerChainer randomizer) - { - Type target = type.GetGenericArguments().Single(); - - ConstructorInfo? maker = FindConstructor(target, randomizer, BindingFlags.Public) - ?? FindConstructor(target, randomizer, BindingFlags.NonPublic); - - if (maker != null) - { - ParameterInfo[] info = maker.GetParameters(); - object?[] args = new object[info.Length]; - for (int i = 0; i < args.Length; i++) - { - args[i] = randomizer.FakerSupports(info[i].ParameterType) - ? randomizer.Create(typeof(Fake<>).MakeGenericType(info[i].ParameterType)) - : randomizer.Create(info[i].ParameterType); - } - - return type - .GetConstructor([target, typeof(IEnumerable)])! - .Invoke( - [ - maker.Invoke(args.Select(v => (v is Fake fake) ? fake.Dummy : v).ToArray()), - args.OfType() - ]); - } - else - { - throw new InvalidOperationException($"No constructors found on type '{target}'."); - } - } - - /// Finds the constructor with the most class references then by fewest parameters. - /// Type to find a constructor for. - /// Handles randomizing child values. - /// Scope of constructors to find. - /// Constructor if found; null otherwise. - private static ConstructorInfo? FindConstructor(Type target, RandomizerChainer randomizer, BindingFlags scope) - { - return target.GetConstructors(BindingFlags.Instance | scope) - .GroupBy(c => c.GetParameters().Count(p => randomizer.FakerSupports(p.ParameterType))) - .OrderByDescending(g => g.Key) - .FirstOrDefault() - ?.OrderBy(c => c.GetParameters()) - .FirstOrDefault(); - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/LegacyCollectionCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/LegacyCollectionCreateHint.cs deleted file mode 100644 index 308ad9c9..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/LegacyCollectionCreateHint.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System.Collections; -using System.Collections.Specialized; -using CreateAndFake.Design; - -#pragma warning disable IDE0058 // Expression value is never used: Return isn't present on all versions. - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing legacy collections for . -/// -public sealed class LegacyCollectionCreateHint(int minSize = 1, int range = 3) : CreateCollectionHint -{ - /// Supported types and the methods used to generate them. - private static readonly (Type, Func)[] _Creators - = - [ - (typeof(Hashtable), CreateDict), - (typeof(SortedList), CreateDict), - (typeof(ListDictionary), CreateDict), - (typeof(HybridDictionary), CreateDict), - (typeof(StringDictionary), CreateDict), - (typeof(OrderedDictionary), CreateDict), - (typeof(NameValueCollection), CreateDict), - - (typeof(Array), (data, gen) => data), - (typeof(Stack), (data, gen) => new Stack(data)), - (typeof(Queue), (data, gen) => new Queue(data)), - (typeof(ArrayList), (data, gen) => new ArrayList(data)), - (typeof(BitArray), (data, gen) => new BitArray(data.Select(d => gen.Create()).ToArray())), - - (typeof(StringCollection), (data, gen) => - { - StringCollection result = [.. data]; - return result; - } - ), - ]; - - /// Collections that the hint will create. - internal static IEnumerable PotentialCollections => _Creators.Select(i => i.Item1); - - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer? randomizer) - { - return TryCreate(type, minSize + randomizer?.Gen.Next(range) ?? 0, randomizer); - } - - /// - protected internal override (bool, object?) TryCreate(Type type, int size, RandomizerChainer? randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type.Inherits() && FindMatches(type).Any()) - { - return (true, randomizer.Gen.NextItem(FindMatches(type)).Item2 - .Invoke(CreateInternalData(size, randomizer), randomizer)); - } - else - { - return (false, null); - } - } - - /// Finds potential collection matches for . - /// Type to find matches for. - /// All possible matches. - private static IEnumerable<(Type, Func)> FindMatches(Type type) - { - return _Creators.Where(m => type.IsInheritedBy(m.Item1)); - } - - /// Creates the and populates it with data. - /// Type to create. - /// Keys to create in the . - /// Handles randomizing child values. - /// The created instance. - private static TDict CreateDict(string[] keys, RandomizerChainer gen) - { - dynamic data = Activator.CreateInstance()!; - for (int i = 0; i < keys.Length; i++) - { - data.Add(keys[i], gen.Create()); - } - return data; - } - - /// Creates populated collection of data to use. - /// Number of items to generate. - /// Handles randomizing child values. - /// Data populated with random values. - private static string[] CreateInternalData(int size, RandomizerChainer randomizer) - { - string[] data = new string[size]; - for (int i = 0; i < data.Length; i++) - { - data.SetValue(randomizer.Create(), i); - } - return data; - } -} - -#pragma warning restore IDE0058 // Expression value is never used diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ObjectCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ObjectCreateHint.cs deleted file mode 100644 index 1c19c05d..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ObjectCreateHint.cs +++ /dev/null @@ -1,265 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing objects in general for . -public sealed class ObjectCreateHint : CreateHint -{ - /// Caches found subclasses for types. - private static readonly Dictionary _SubclassCache = new() - { - { typeof(object), new[] { typeof(object) } } - }; - - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - object? result = (type == null) ? null : Limiter - .Dozen - .Attempt($"Create object of type '{type}'", - () => Create(FindTypeToCreate(type, randomizer), type, randomizer)) - .Result; - - return (result != null, result); - } - - /// Original Type being generated. - /// The randomized instance. - /// - private static object? Create(Type type, Type rootType, RandomizerChainer randomizer) - { - if (type != rootType) - { - return randomizer.Create(type); - } - - DataRandom smartData = randomizer.Gen.NextData(); - object? data = CreateNew(type, randomizer, smartData); - if (data == null) - { - return data; - } - - try - { - Populate(data, smartData, randomizer); - } - catch - { - Disposer.Cleanup(data); - throw; - } - - return data; - } - - /// Sets member data for a newly created instance. - /// Instance to populate. - /// Smart data currently being utilized. - /// Handles randomizing child values. - private static void Populate(object data, DataRandom smartData, RandomizerChainer randomizer) - { - Type dataType = data.GetType(); - - foreach (FieldInfo field in dataType.GetFields(BindingFlags.Instance | BindingFlags.Public) - .Where(f => !f.IsInitOnly && !f.IsLiteral)) - { - string? smartValue = (field.FieldType == typeof(string)) - ? smartData.Find(field.Name) - : null; - field.SetValue(data, smartValue ?? randomizer.Create(field.FieldType, data)); - } - foreach (PropertyInfo property in dataType.GetProperties(BindingFlags.Instance | BindingFlags.Public) - .Where(p => p.CanWrite) - .Where(p => p.GetSetMethod() != null)) - { - string? smartValue = (property.PropertyType == typeof(string)) - ? smartData.Find(property.Name) - : null; - property.SetValue(data, smartValue ?? randomizer.Create(property.PropertyType, data)); - } - } - - /// Creates a new instance of . - /// Type to generate. - /// Handles randomizing child values. - /// Predefined random data. - /// The created instance. - private static object? CreateNew(Type type, RandomizerChainer randomizer, DataRandom smartData) - { - /* - * Order of preference: - * 1) Default constructor. - * 2) Public constructor. - * 3) Public factory. - * 4) Internal factory. - * 5) Internal constructor. - * 6) Stub. - */ - - ConstructorInfo? defaultConstructor = type.GetConstructor(Type.EmptyTypes); - if (type == typeof(object)) - { - IFaked fake = randomizer.Stub().Dummy; - fake.FakeMeta.Identifier = randomizer.Create(); - return fake; - } - else if (defaultConstructor != null) - { - return defaultConstructor.Invoke(null); - } - else if (FindConstructors(type, BindingFlags.Public, randomizer).Any()) - { - return CreateFrom(randomizer, smartData, (c, d) => c.Invoke(d), - FindConstructors(type, BindingFlags.Public, randomizer)); - } - else if (FindFactories(type, BindingFlags.Public, randomizer).Any()) - { - return CreateFrom(randomizer, smartData, (c, d) => c.Invoke(null, d)!, - FindFactories(type, BindingFlags.Public, randomizer)); - } - else if (FindFactories(type, BindingFlags.NonPublic, randomizer).Any()) - { - return CreateFrom(randomizer, smartData, (c, d) => c.Invoke(null, d)!, - FindFactories(type, BindingFlags.NonPublic, randomizer)); - } - else if (FindConstructors(type, BindingFlags.NonPublic, randomizer).Any()) - { - return CreateFrom(randomizer, smartData, (c, d) => c.Invoke(d), - FindConstructors(type, BindingFlags.NonPublic, randomizer)); - } - else if (randomizer.FakerSupports(type)) - { - return randomizer.Stub(type).Dummy; - } - else - { - return null; - } - } - - /// Creates a instance. - /// Creation method Type. - /// Handles randomizing child values. - /// Predefined random data. - /// How to create the Type from the creation method. - /// Possible creation methods. - /// The created instance. - private static object CreateFrom(RandomizerChainer randomizer, DataRandom smartData, - Func invoker, IEnumerable creators) where T : MethodBase - { - T creator = randomizer.Gen.NextItem(creators); - - if (creator is MethodInfo method && method.IsGenericMethodDefinition) - { - creator = (T)(object)method.MakeGenericMethod(method - .GetGenericArguments() - .Select(a => GenericCreateHint.CreateArg(a, method.ReturnType, randomizer)) - .ToArray()); - } - - return invoker.Invoke(creator, creator.GetParameters() - .Select(p => - { - string? smartValue = (p.ParameterType == typeof(string)) - ? smartData.Find(p.Name) - : null; - return smartValue ?? randomizer.Create(p.ParameterType, randomizer.Parent); - }) - .ToArray()); - } - - /// Finds a creatable Type of . - /// Parent Type being created. - /// Handles randomizing child values. - /// Type to use. - private static Type FindTypeToCreate(Type type, RandomizerChainer randomizer) - { - Type[]? subclasses; - lock (_SubclassCache) - { - if (!_SubclassCache.TryGetValue(type, out subclasses)) - { - subclasses = FindSelfAndSubclasses(type); - _SubclassCache.Add(type, subclasses); - } - } - - return randomizer.Gen.NextItemOrDefault(subclasses.Where(t => !randomizer.AlreadyCreated(t))) ?? type; - } - - /// Finds subclasses of . - /// Parent Type. - /// Found subclasses. - private static Type[] FindSelfAndSubclasses(Type type) - { - BindingFlags anyScope = BindingFlags.Public | BindingFlags.NonPublic; - - Type[] subclasses = type.FindLocalSubclasses() - .Prepend(type) - .Where(t => FindConstructors(t, anyScope).Any() || FindFactories(t, anyScope).Any()) - .Where(t => !t.IsNestedPrivate) - .ToArray(); - - if (subclasses.Length != 0) - { - return subclasses; - } - else - { - return type.FindLoadedSubclasses() - .Prepend(type) - .Where(t => FindConstructors(t, anyScope).Any() || FindFactories(t, anyScope).Any()) - .Where(t => !t.IsNestedPrivate) - .ToArray(); - } - } - - /// Finds public or internal constructors. - /// Type to search for. - /// Scope of constructors to look for. - /// Handles randomizing child values. - /// Found constructors. - private static IEnumerable FindConstructors(Type type, - BindingFlags scope, RandomizerChainer? randomizer = null) - { - return type - .GetConstructors(BindingFlags.Instance | scope) - .Where(c => c.IsPublic || c.IsAssembly) - .Where(c => randomizer == null - || c.GetParameters().All(p => !randomizer.AlreadyCreated(p.ParameterType))); - } - - /// Finds static methods that create . - /// Type to search for. - /// Scope of constructors to look for. - /// Handles randomizing child values. - /// Found factory methods. - private static IEnumerable FindFactories(Type type, - BindingFlags scope, RandomizerChainer? randomizer = null) - { - MethodInfo[] factories = type - .GetMethods(BindingFlags.Static | scope) - .Where(m => m.IsPublic || m.IsAssembly) - .Where(m => m.ReturnType.Inherits(type)) - .Where(c => randomizer == null - || c.GetParameters().All(p => !randomizer.AlreadyCreated(p.ParameterType))) - .ToArray(); - - IEnumerable nonGenericFactories = factories.Where(m => !m.ContainsGenericParameters).ToArray(); - if (nonGenericFactories.Any()) - { - return nonGenericFactories; - } - else - { - return factories; - } - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/StringCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/StringCreateHint.cs deleted file mode 100644 index 5fd4d8f4..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/StringCreateHint.cs +++ /dev/null @@ -1,32 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing collections for . -/// -/// -public sealed class StringCreateHint(int minSize = 7, int range = 5, IEnumerable? charSet = null) - : CreateHint -{ - /// Default characters to include in random strings. - private static readonly char[] _DefaultCharSet = - @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); - - /// Characters to include in random strings. - private readonly char[] _charSet = (charSet?.Any() ?? false) - ? charSet.ToArray() - : _DefaultCharSet; - - /// - protected override string Create(RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - char[] data = new char[minSize + randomizer.Gen.Next(range)]; - for (int i = 0; i < data.Length; i++) - { - data[i] = randomizer.Gen.NextItem(_charSet); - } - return new string(data); - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/TaskCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/TaskCreateHint.cs deleted file mode 100644 index 14ee4761..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/TaskCreateHint.cs +++ /dev/null @@ -1,41 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing instances for . -public sealed class TaskCreateHint : CreateHint -{ - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (type.Inherits() || typeof(TaskCompletionSource<>).IsInheritedBy(type)) - { - return (true, Create(type, randomizer)); - } - else - { - return (false, null); - } - } - - /// The randomized instance. - /// - private static object? Create(Type type, RandomizerChainer randomizer) - { - if (type.IsGenericType) - { - Type content = type.GetGenericArguments().Single(); - - return typeof(Task) - .GetMethod(nameof(Task.FromResult))! - .MakeGenericMethod(content) - .Invoke(null, [randomizer.Create(content, randomizer.Parent)]); - } - else - { - return Task.FromResult(randomizer.Create()); - } - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ValueCreateHint.cs b/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ValueCreateHint.cs deleted file mode 100644 index 3eec2cc5..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/CreateHints/ValueCreateHint.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -/// Handles randomizing values for . -public sealed class ValueCreateHint : CreateHint -{ - /// - protected internal override (bool, object?) TryCreate(Type type, RandomizerChainer randomizer) - { - ArgumentGuard.ThrowIfNull(randomizer, nameof(randomizer)); - - if (randomizer.Gen.Supports(type)) - { - return (true, randomizer.Gen.Next(type)); - } - else - { - return (false, null); - } - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/IRandomizer.cs b/src/CreateAndFake/Toolbox/RandomizerTool/IRandomizer.cs deleted file mode 100644 index 04191dac..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/IRandomizer.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Reflection; - -namespace CreateAndFake.Toolbox.RandomizerTool; - -/// Creates objects and populates them with random values. -public interface IRandomizer -{ - /// Creates a randomized instance. - /// Type to create. - /// Optional condition for the instance to match. - /// The created instance. - /// If no hint supports generating the type. - /// If an instance couldn't be created to match the condition. - /// If infinite recursion occurs. - T Create(Func? condition = null); - - /// Creates a randomized instance. - /// Optional condition for the instance to match. - /// Type to create. - /// The created instance. - /// If no hint supports generating the type. - /// If an instance couldn't be created to match the condition. - /// If infinite recursion occurs. - object Create(Type type, Func? condition = null); - - /// - /// Creates a randomized collection of size. - /// - /// Collection type to create. - /// Number of items to generate. - /// The created collection with items. - /// If no hint supports generating the type. - /// If infinite recursion occurs. - T CreateSized(int count); - - /// Creates a randomized collection of size. - /// Collection type to create. - /// Number of items to generate. - /// The created collection with items. - /// If no hint supports generating the type. - /// If infinite recursion occurs. - object CreateSized(Type type, int count); - - /// - /// Constructs the parameters for . - /// Randomizes types by default. - /// Earlier types will be used to construct later types if possible. - /// - /// Method to create parameters for. - /// Starting values to inject into instances. - /// Parameter arguments for in order. - MethodCallWrapper CreateFor(MethodBase method, params object?[]? values); - - /// - /// Creates a instance using or random data as needed. - /// - /// Type to create. - /// Values to inject into the instance. - /// The created instance. - T Inject(params object?[]? values); - - /// Creates an instance using or random data as needed. - /// Type to create. - /// Values to inject into the instance. - /// The created instance. - object Inject(Type type, params object?[]? values); - - /// Adds to be used for randomization. Last added takes precedence. - /// Hint to add. - /// Should only be modified in module initializers. - void AddHint(CreateHint hint); -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/InfiniteLoopException.cs b/src/CreateAndFake/Toolbox/RandomizerTool/InfiniteLoopException.cs deleted file mode 100644 index de6255ba..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/InfiniteLoopException.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Runtime.Serialization; - -namespace CreateAndFake.Toolbox.RandomizerTool; - -/// Exception when encountering infinite loops. -[Serializable, KnownType(typeof(Exception)), KnownType(typeof(Exception[]))] -public sealed class InfiniteLoopException : Exception -{ - /// - /// Serialization constructor. - private InfiniteLoopException() : base() { } - - /// - /// Last Type attempted to be created. - /// Stack of created parents. - public InfiniteLoopException(Type lastType, IEnumerable history) : base( - $"Already created type '{lastType?.FullName}'. History:" - + Environment.NewLine - + string.Join(Environment.NewLine, history.Select(t => t.FullName))) - { } - - /// - /// Object data. - /// Additional info. - /// Serialization constructor. -#if NET5_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private InfiniteLoopException(SerializationInfo info, StreamingContext context) : base(info, context) { } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/MethodCallWrapper.cs b/src/CreateAndFake/Toolbox/RandomizerTool/MethodCallWrapper.cs deleted file mode 100644 index e6d92861..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/MethodCallWrapper.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.DuplicatorTool; - -namespace CreateAndFake.Toolbox.RandomizerTool; - -/// Holds parameter data for a method. -public sealed class MethodCallWrapper : IDuplicatable -{ - /// Associated method. - private readonly MethodBase _method; - - /// Ordered parameter names. - private readonly IEnumerable _names; - - /// Parameter names with associated data to pass. - private readonly Dictionary _args; - - /// Parameter data for the method. - public IEnumerable Args => _names.Select(n => _args[n]).ToArray(); - - /// - /// - /// - public MethodCallWrapper(MethodBase method, IEnumerable> args) - { - ArgumentGuard.ThrowIfNull(args, nameof(args)); - - _method = method ?? throw new ArgumentNullException(nameof(method)); - _args = []; - - List names = []; - foreach (Tuple arg in args) - { - names.Add(arg.Item1); - _args.Add(arg.Item1, arg.Item2); - } - _names = names; - } - - /// Sets parameter named to . - /// Name for the parameter to modify. - /// New value to use. - public void ModifyArg(string name, object value) - { - if (_args.ContainsKey(name)) - { - _args[name] = value; - } - else - { - throw new KeyNotFoundException($"Parameter '{name}' not on method '{_method.Name}'."); - } - } - - /// Invokes the method on . - /// Instance to call the method with the data on. - /// Results from the call. - public object? InvokeOn(object instance) - { - return _method.Invoke(instance, Args.ToArray()); - } - - /// - public IDuplicatable DeepClone(IDuplicator duplicator) - { - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - return new MethodCallWrapper(duplicator.Copy(_method)!, - duplicator.Copy(_names.Select(n => Tuple.Create(n, _args[n])).ToArray())!); - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/Randomizer.cs b/src/CreateAndFake/Toolbox/RandomizerTool/Randomizer.cs deleted file mode 100644 index 83ca1cbb..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/Randomizer.cs +++ /dev/null @@ -1,331 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; - -namespace CreateAndFake.Toolbox.RandomizerTool; - -/// -/// -/// -/// -/// If the default set of hints should be added. -/// -public sealed class Randomizer( - IFaker faker, - IRandom gen, - Limiter limiter, - bool includeDefaultHints = true, - params CreateHint[] hints) - : IRandomizer, IDuplicatable -{ - /// Default set of hints to use for randomization. - private static readonly CreateHint[] _DefaultHints = - [ - new ValueCreateHint(), - new EnumCreateHint(), - new GenericCreateHint(), - new AsyncCollectionCreateHint(), - new CollectionCreateHint(), - new LegacyCollectionCreateHint(), - new StringCreateHint(), - new DelegateCreateHint(), - new TaskCreateHint(), - new CommonSystemCreateHint(), - new InjectedCreateHint(), - new FakeCreateHint(), - new FakedCreateHint(), - new ExceptionCreateHint(), - new ObjectCreateHint() - ]; - - /// Provides stubs. - private readonly IFaker _faker = faker ?? throw new ArgumentNullException(nameof(faker)); - - /// Value generator used for base randomization. - private readonly IRandom _gen = gen ?? throw new ArgumentNullException(nameof(gen)); - - /// Limits attempts at matching conditions. - private readonly Limiter _limiter = limiter ?? throw new ArgumentNullException(nameof(limiter)); - - /// Generators used to randomize specific types. - private readonly List _hints = (hints ?? Enumerable.Empty()) - .Concat(includeDefaultHints ? _DefaultHints : []) - .ToList(); - - /// - public T Create(Func? condition = null) - { - return (T)Create(typeof(T), o => condition?.Invoke((T)o) ?? true); - } - - /// - public object Create(Type type, Func? condition = null) - { - try - { - return _limiter.StallUntil( - $"Trying to create instance of '{type}'", - () => Create(type, new RandomizerChainer(_faker, _gen, Create)), - result => - { - if (condition?.Invoke(result!) ?? true) - { - return true; - } - else - { - Disposer.Cleanup(result); - return false; - } - }).Result.Last()!; - } - catch (AggregateException e) - { - if (e.InnerException is InsufficientExecutionStackException) - { - throw new InsufficientExecutionStackException( - $"Ran into infinite generation trying to randomize type '{type}'."); - } - else if (e.InnerException is TimeoutException) - { - throw new TimeoutException( - $"Could not create instance of type '{type}' matching condition.", e); - } - else if (e.InnerException is NotSupportedException) - { - throw e.InnerException; - } - else - { - throw new InvalidOperationException( - $"Encountered issue creating instance of type '{type}'.", e); - } - } - } - - /// Type to create. - /// Handles callback behavior for child values. - /// - private object Create(Type type, RandomizerChainer chainer) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - (bool, object?) result = _hints - .Select(h => h.TryCreate(type, chainer)) - .FirstOrDefault(r => r.Item1); - - if (!result.Equals(default)) - { - return result.Item2!; - } - else - { - throw new NotSupportedException( - $"Type '{type.FullName}' not supported by the randomizer. " + - "Create a hint to generate the type and pass it to the randomizer."); - } - } - - /// - public T CreateSized(int count) - { - return (T)CreateSized(typeof(T), count); - } - - /// - public object CreateSized(Type type, int count) - { - try - { - return CreateSized(type, count, new RandomizerChainer(_faker, _gen, Create)); - } - catch (InsufficientExecutionStackException) - { - throw new InsufficientExecutionStackException( - $"Ran into infinite generation trying to randomize type '{type}'."); - } - catch (Exception e) when (e is not NotSupportedException) - { - throw new InvalidOperationException( - $"Encountered issue creating instance of type '{type}'.", e); - } - } - - /// Type to create. - /// Number of items to generate. - /// Handles callback behavior for child values. - /// - private object CreateSized(Type type, int count, RandomizerChainer chainer) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - (bool, object?) result = _hints - .OfType() - .Select(h => h.TryCreate(type, count, chainer)) - .FirstOrDefault(r => r.Item1); - - if (!result.Equals(default)) - { - return result.Item2!; - } - else - { - throw new NotSupportedException( - $"Collection type '{type.FullName}' not supported by the randomizer. " + - "Create a collection hint to generate the type and pass it to the randomizer."); - } - } - - /// - public MethodCallWrapper CreateFor(MethodBase method, params object?[]? values) - { - ArgumentGuard.ThrowIfNull(method, nameof(method)); - - List> data = (values ?? []) - .Where(v => v != null) - .Select(v => (v is Fake fake) ? fake.Dummy : v) - .Where(v => v != null) - .Select(v => Tuple.Create(v!.GetType(), v)) - .ToList(); - - List> args = new(method.GetParameters().Length); - - foreach (ParameterInfo param in method.GetParameters()) - { - args.Add(Tuple.Create(param.Name ?? $"{args.Count}", ExtractArg(param, data, args))); - } - - return new MethodCallWrapper(method, args); - } - - /// Randomizes an instance to fill a parameter. - /// Parameter to fill. - /// Canned data to prefer. - /// Already created parameter data. - /// The created arg to fill the parameter with. - private object? ExtractArg(ParameterInfo param, List> data, List> args) - { - Tuple match = data.FirstOrDefault(t => t.Item1.Inherits(param.ParameterType))!; - if (param.IsOut) - { - return null; - } - else if (param.GetCustomAttributes().Any()) - { - return ((Fake)Create(typeof(Fake<>).MakeGenericType(param.ParameterType))!).Dummy; - } - else if (param.GetCustomAttributes().Any()) - { - return _faker.Stub(param.ParameterType).Dummy; - } - else if (param.GetCustomAttributes().Any()) - { - return CreateSized(param.ParameterType, param.GetCustomAttribute()!.Count); - } - else if (match != default) - { - _ = data.Remove(match); - return match.Item2; - } - else - { - return Inject(param.ParameterType, args - .Select(a => a.Item2) - .Where(a => a is Fake or IFaked) - .Reverse() - .ToArray()); - } - } - - /// - public T Inject(params object?[]? values) - { - return (T)Inject(typeof(T), values); - } - - /// - public object Inject(Type type, params object?[]? values) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - List> data = (values ?? []) - .Where(v => v != null) - .Select(v => (v is Fake fake) ? fake.Dummy : v) - .Where(v => v != null) - .Select(v => Tuple.Create(v!.GetType(), v)) - .ToList(); - - ConstructorInfo? maker = FindConstructor(type, data, BindingFlags.Public) - ?? FindConstructor(type, data, BindingFlags.NonPublic); - - if (maker != null && !type.Inherits() && !type.Inherits(typeof(Injected<>))) - { - return maker.Invoke(CreateInjectArgs(maker, data)); - } - else - { - return Create(type); - } - } - - /// Creates the args to inject an instance with. - /// Constructor to use. - /// Canned data to prefer. - /// The created args to inject an instance with. - private object?[] CreateInjectArgs(ConstructorInfo maker, List> data) - { - ParameterInfo[] info = maker.GetParameters(); - object?[] args = new object[info.Length]; - - for (int i = 0; i < args.Length; i++) - { - Tuple? match = data.FirstOrDefault(t => t.Item1.Inherits(info[i].ParameterType)); - if (match != default) - { - args[i] = match.Item2; - _ = data.Remove(match); - } - else - { - args[i] = Create(info[i].ParameterType); - } - } - return args; - } - - /// Finds the constructor with the most matches then by fewest parameters. - /// Type to find a constructor for. - /// Injection data to use. - /// Scope of constructors to find. - /// Constructor if found; null otherwise. - private static ConstructorInfo? FindConstructor(Type type, List> data, BindingFlags scope) - { - return type.GetConstructors(BindingFlags.Instance | scope) - .GroupBy(c => c.GetParameters().Count(p => data.Any(t => t.Item1.Inherits(p.ParameterType)))) - .Where(g => g.Key > 0) - .OrderByDescending(g => g.Key) - .FirstOrDefault() - ?.OrderBy(c => c.GetParameters()) - .FirstOrDefault(); - } - - /// - public IDuplicatable DeepClone(IDuplicator duplicator) - { - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - return new Randomizer(duplicator.Copy(_faker)!, duplicator.Copy(_gen)!, - duplicator.Copy(_limiter)!, false, [.. duplicator.Copy(_hints)]); - } - - /// - public void AddHint(CreateHint hint) - { - _hints.Insert(0, hint ?? throw new ArgumentNullException(nameof(hint))); - } -} diff --git a/src/CreateAndFake/Toolbox/RandomizerTool/RandomizerChainer.cs b/src/CreateAndFake/Toolbox/RandomizerTool/RandomizerChainer.cs deleted file mode 100644 index 4fcb8fe4..00000000 --- a/src/CreateAndFake/Toolbox/RandomizerTool/RandomizerChainer.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System.Runtime.CompilerServices; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFake.Toolbox.RandomizerTool; - -/// Provides a callback into to create child values. -public sealed class RandomizerChainer -{ - /// Callback to to randomize child values. - private readonly Func _randomizer; - - /// Types not to create as to prevent infinite recursion. - private readonly IDictionary _history; - - /// Provides stubs. - private readonly IFaker _faker; - - /// Value generator to use for base randomization. - public IRandom Gen { get; } - - /// Container of the instance to create. - public object? Parent { get; } - - /// - /// - /// - /// - public RandomizerChainer(IFaker faker, IRandom gen, Func randomizer) - { - _faker = faker ?? throw new ArgumentNullException(nameof(faker)); - Gen = gen ?? throw new ArgumentNullException(nameof(gen)); - _randomizer = randomizer ?? throw new ArgumentNullException(nameof(randomizer)); - - _history = new Dictionary(); - Parent = null; - } - - /// - /// Previous chainer to build upon. - /// - private RandomizerChainer(RandomizerChainer prevChainer, object? parent) - { - Parent = parent; - Gen = prevChainer.Gen; - _faker = prevChainer._faker; - _randomizer = prevChainer._randomizer; - - if (parent != null) - { - _history = prevChainer._history - .Append(new KeyValuePair(parent.GetType(), parent)) - .ToDictionary(p => p.Key, p => p.Value); - } - else - { - _history = prevChainer._history; - } - } - - /// Checks if has already been created by the randomizer. - /// Type to check. - /// true if already created; false otherwise. - public bool AlreadyCreated() - { - return AlreadyCreated(typeof(T)); - } - - /// Checks if has already been created by the randomizer. - /// Type to check. - /// true if already created; false otherwise. - public bool AlreadyCreated(Type type) - { - return _history.ContainsKey(type); - } - - /// Calls the randomizer to create a random instance. - /// Type to create. - /// The created instance. - public T Create() - { - return (T)Create(typeof(T), null); - } - - /// Calls the randomizer to create a random instance of the given . - /// Type to create. - /// - /// The created instance. - public object Create(Type type, object? parent = null) - { - if (parent != null) - { - if (AlreadyCreated(type)) - { - return _history[type]; - } - else if (parent.GetType() == type) - { - return parent; - } - } - else if (AlreadyCreated(type)) - { - throw new InfiniteLoopException(type, _history.Keys); - } - - RuntimeHelpers.EnsureSufficientExecutionStack(); - return _randomizer.Invoke(type, new RandomizerChainer(this, (parent != Parent) ? parent : null)); - } - - /// - public Fake Stub(params Type[] interfaces) - { - return _faker.Stub(interfaces); - } - - /// - public Fake Stub(Type parent, params Type[] interfaces) - { - return _faker.Stub(parent, interfaces); - } - - /// - public bool FakerSupports() - { - return _faker.Supports(); - } - - /// - public bool FakerSupports(Type type) - { - return _faker.Supports(type); - } -} diff --git a/src/CreateAndFake/Toolbox/TesterTool/BaseGuarder.cs b/src/CreateAndFake/Toolbox/TesterTool/BaseGuarder.cs deleted file mode 100644 index c4d5b9c2..00000000 --- a/src/CreateAndFake/Toolbox/TesterTool/BaseGuarder.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System.Collections; -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.RandomizerTool; - -#pragma warning disable CA1822 // Member does not access instance data and can be marked static - -namespace CreateAndFake.Toolbox.TesterTool; - -/// Automates checks. -/// Handles generic resolution. -/// Creates objects and populates them with random values. -/// How long to wait for methods to complete. -internal abstract class BaseGuarder(GenericFixer fixer, IRandomizer randomizer, TimeSpan timeout) -{ - /// Handles generic resolution. - protected GenericFixer Fixer { get; } = fixer ?? throw new ArgumentNullException(nameof(fixer)); - - /// Creates objects and populates them with random values. - protected IRandomizer Randomizer { get; } = randomizer ?? throw new ArgumentNullException(nameof(randomizer)); - - /// How long to wait for methods to complete. - protected TimeSpan Timeout { get; } = (timeout.TotalMilliseconds is >= -1 and <= int.MaxValue) - ? timeout - : TimeSpan.FromMilliseconds(-1); - - /// Gets all testable constructors on a type. - /// Type with the constructors to test. - /// Found constructors. - protected static IEnumerable FindAllConstructors(Type type) - { - return type - .GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) - .Where(c => c.IsPublic || c.IsAssembly || c.IsFamilyOrAssembly) - .Where(c => !c.IsPrivate); - } - - /// Gets all testable methods on a type. - /// Type with the methods to test. - /// Instance, static, or both. - /// Found methods. - protected static IEnumerable FindAllMethods(Type type, BindingFlags kind) - { - return type - .GetMethods(kind | BindingFlags.Public | BindingFlags.NonPublic) - .Where(m => m.IsPublic || m.IsAssembly || m.IsFamily || m.IsFamilyOrAssembly) - .Where(m => m.DeclaringType == type || m.DeclaringType!.IsAbstract) - .Where(m => !m.IsPrivate); - } - - /// Calls all methods to test parameter being set to null. - /// Method under test. - /// Parameter being set to null. - /// Instance whose methods to test. - /// Values to inject into the method. - protected void CallAllMethods(MethodBase? testOrigin, - ParameterInfo? testParam, object instance, object?[]? injectionValues) - { - ArgumentGuard.ThrowIfNull(instance, nameof(instance)); - - foreach (MethodInfo method in FindAllMethods(instance.GetType(), BindingFlags.Instance) - .Where(m => m.Name is not "Finalize" and not "Dispose") - .Where(m => !m.IsFamily) - .Select(Fixer.FixMethod)) - { - object?[] data = Randomizer.CreateFor(method, injectionValues).Args.ToArray(); - try - { - Disposer.Cleanup(RunCheck(testOrigin ?? method, testParam, () => method.Invoke(instance, data)!)); - } - finally - { - DisposeAllButInjected(injectionValues, data); - } - } - } - - /// Runs the check. - /// Method under test. - /// Parameter being set to null. - /// Call to invoke and test. - /// Returned result from the call. - protected object? RunCheck(MethodBase testOrigin, ParameterInfo? testParam, Func call) - { - ArgumentGuard.ThrowIfNull(testOrigin, nameof(testOrigin)); - ArgumentGuard.ThrowIfNull(call, nameof(call)); - try - { - Task task = Task.Run(() => - { - object result = call.Invoke(); - if (result is IEnumerable collection) - { - // Required to run through yield return methods. - return collection.OfType().ToArray(); - } - else - { - return result; - } - }); - if (!task.Wait(Timeout)) - { - throw new TimeoutException($"Attempting to run method '{testOrigin.Name}' timed out."); - } - return task.Result; - } - catch (AggregateException taskException) when (taskException.InnerExceptions.Count == 1) - { - Exception actual = taskException.InnerExceptions.Single(); - if (actual is TargetInvocationException ex) - { - actual = ex.InnerException!; - } - - HandleCheckException(testOrigin, testParam, actual); - return null; - } - } - - /// Checks data for disposables and disposes them. - /// Injected values to ignore. - /// Data to check and dispose. - protected void DisposeAllButInjected(object?[]? injectedValues, params object?[]? data) - { - foreach (object? item in data ?? []) - { - if (item is object?[] nested) - { - DisposeAllButInjected(injectedValues, nested); - } - else if (!(injectedValues?.Any(v => ReferenceEquals(item, v)) ?? false)) - { - Disposer.Cleanup(item); - } - } - } - - /// Handles exceptions encountered by the check. - /// Method under test. - /// Parameter being set to null. - /// Exception encountered. - protected abstract void HandleCheckException(MethodBase testOrigin, - ParameterInfo? testParam, Exception taskException); -} - -#pragma warning restore CA1822 // Member does not access instance data and can be marked static diff --git a/src/CreateAndFake/Toolbox/TesterTool/ExceptionGuarder.cs b/src/CreateAndFake/Toolbox/TesterTool/ExceptionGuarder.cs deleted file mode 100644 index f9fb6de4..00000000 --- a/src/CreateAndFake/Toolbox/TesterTool/ExceptionGuarder.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.RandomizerTool; - -namespace CreateAndFake.Toolbox.TesterTool; - -/// Automates basic layer passthrough checks. -internal sealed class ExceptionGuarder : BaseGuarder -{ - /// Handles common test scenarios. - private readonly Asserter _asserter; - - /// Initializes a new instance of the class. - /// Handles generic resolution. - /// Creates objects and populates them with random values. - /// Handles common test scenarios. - /// How long to wait for methods to complete. - internal ExceptionGuarder(GenericFixer fixer, IRandomizer randomizer, Asserter asserter, TimeSpan timeout) - : base(fixer, randomizer, timeout) - { - _asserter = asserter ?? throw new ArgumentNullException(nameof(asserter)); - } - - /// - internal void CallAllMethods(object instance, params object[] injectionValues) - { - base.CallAllMethods(null, null, instance, injectionValues); - } - - /// - protected override void HandleCheckException(MethodBase testOrigin, ParameterInfo? testParam, Exception taskException) - { - ArgumentGuard.ThrowIfNull(testOrigin, nameof(testOrigin)); - ArgumentGuard.ThrowIfNull(taskException, nameof(taskException)); - - _asserter.Fail(taskException, $"Exception encountered on method '{testOrigin.Name}'."); - } -} diff --git a/src/CreateAndFake/Toolbox/TesterTool/GenericFixer.cs b/src/CreateAndFake/Toolbox/TesterTool/GenericFixer.cs deleted file mode 100644 index eafb607a..00000000 --- a/src/CreateAndFake/Toolbox/TesterTool/GenericFixer.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.RandomizerTool; - -namespace CreateAndFake.Toolbox.TesterTool; - -/// Handles generic resolution. -internal sealed class GenericFixer -{ - /// Core value random handler. - private readonly IRandom _gen; - - /// Creates objects and populates them with random values. - private readonly IRandomizer _randomizer; - - /// Initializes a new instance of the class. - /// Core value random handler. - /// Creates objects and populates them with random values. - internal GenericFixer(IRandom gen, IRandomizer randomizer) - { - _gen = gen ?? throw new ArgumentNullException(nameof(gen)); - _randomizer = randomizer ?? throw new ArgumentNullException(nameof(randomizer)); - } - - /// Defines any generics in a method. - /// Method to fix. - /// Method with all generics defined. - internal MethodInfo FixMethod(MethodInfo method) - { - ArgumentGuard.ThrowIfNull(method, nameof(method)); - - return method.ContainsGenericParameters - ? method.MakeGenericMethod(method.GetGenericArguments().Select(CreateArg).ToArray()) - : method; - } - - /// Creates a concrete arg type from the given generic arg. - /// Generic arg to create. - /// Created arg type. - private Type CreateArg(Type type) - { - bool newNeeded = type.GenericParameterAttributes.HasFlag( - GenericParameterAttributes.DefaultConstructorConstraint); - - Type arg; - if (type.GenericParameterAttributes.HasFlag( - GenericParameterAttributes.NotNullableValueTypeConstraint)) - { - arg = _gen.NextItem(ValueRandom.ValueTypes); - } - else if (newNeeded) - { - arg = typeof(object); - } - else - { - arg = typeof(string); - } - - Type[] constraints = type.GetGenericParameterConstraints(); - - Limiter.Dozen.Repeat( - $"Creating generic argument of type '{type}'", - () => - { - while (!constraints.All(c => arg.Inherits(c)) - && (!newNeeded || arg.GetConstructor(Type.EmptyTypes) != null)) - { - object? constraint = _randomizer.Create(_gen.NextItem(constraints)); - if (constraint != null) - { - arg = constraint.GetType(); - } - Disposer.Cleanup(constraint); - } - }).Wait(); - - return arg; - } -} diff --git a/src/CreateAndFake/Toolbox/TesterTool/MutationGuarder.cs b/src/CreateAndFake/Toolbox/TesterTool/MutationGuarder.cs deleted file mode 100644 index ccf3bbb5..00000000 --- a/src/CreateAndFake/Toolbox/TesterTool/MutationGuarder.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.RandomizerTool; - -namespace CreateAndFake.Toolbox.TesterTool; - -/// Automates parameter mutation checks. -internal sealed class MutationGuarder : BaseGuarder -{ - /// Deep clones objects. - private readonly IDuplicator _duplicator; - - /// Handles common test scenarios. - private readonly Asserter _asserter; - - /// Initializes a new instance of the class. - /// Handles generic resolution. - /// Creates objects and populates them with random values. - /// Deep clones objects. - /// Handles common test scenarios. - /// How long to wait for methods to complete. - internal MutationGuarder(GenericFixer fixer, IRandomizer randomizer, - IDuplicator duplicator, Asserter asserter, TimeSpan timeout) - : base(fixer, randomizer, timeout) - { - _duplicator = duplicator ?? throw new ArgumentNullException(nameof(duplicator)); - _asserter = asserter ?? throw new ArgumentNullException(nameof(asserter)); - } - - /// Verifies mutations are prevented on constructors. - /// Type to verify. - /// Run instance methods to validate constructor parameters. - /// Values to inject into the method. - internal void PreventsMutationOnConstructors(Type type, bool callAllMethods, params object[] injectionValues) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - foreach (ConstructorInfo constructor in FindAllConstructors(type)) - { - PreventsMutation(null, constructor, callAllMethods, injectionValues); - } - } - - /// Verifies mutations are prevented on methods. - /// Instance to test the methods on. - /// Values to inject into the method. - internal void PreventsMutationOnMethods(object instance, params object?[]? injectionValues) - { - ArgumentGuard.ThrowIfNull(instance, nameof(instance)); - - foreach (MethodInfo method in FindAllMethods(instance.GetType(), BindingFlags.Instance) - .Where(m => m.Name is not "Finalize" and not "Dispose")) - { - PreventsMutation(instance, Fixer.FixMethod(method), false, injectionValues); - } - } - - /// Verifies mutations are prevented on methods. - /// Type to verify. - /// Run instance methods to validate factory parameters. - /// Values to inject into the method. - internal void PreventsMutationOnStatics(Type type, bool callAllMethods, params object[] injectionValues) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - foreach (MethodInfo method in FindAllMethods(type, BindingFlags.Static)) - { - PreventsMutation(null, Fixer.FixMethod(method), - callAllMethods && method.ReturnType.Inherits(type), injectionValues); - } - } - - /// Verifies mutations are prevented on a method. - /// Instance with the method under test. - /// Method under test. - /// If all instance methods should be called after the method. - /// Values to inject into the method. - private void PreventsMutation(object? instance, - MethodBase method, bool callAllMethods, object?[]? injectionValues) - { - object?[]? data = null; - object?[]? copy = null; - object? result = null; - try - { - data = Randomizer.CreateFor(method, injectionValues).Args.ToArray(); - copy = _duplicator.Copy(data); - - result = (instance == null && method is ConstructorInfo builder) - ? RunCheck(method, null, () => builder.Invoke(data)) - : RunCheck(method, null, () => method.Invoke(instance, data!)!); - - if (result != null && callAllMethods) - { - CallAllMethods(method, null, result, injectionValues); - } - - _asserter.ValuesEqual(copy, data, $"Parameter data was mutated when testing '{method.Name}'."); - } - finally - { - DisposeAllButInjected(injectionValues, data, copy, result); - } - } - - /// - protected override void HandleCheckException(MethodBase testOrigin, - ParameterInfo? testParam, Exception taskException) - { } -} diff --git a/src/CreateAndFake/Toolbox/TesterTool/NullGuarder.cs b/src/CreateAndFake/Toolbox/TesterTool/NullGuarder.cs deleted file mode 100644 index 5f066a25..00000000 --- a/src/CreateAndFake/Toolbox/TesterTool/NullGuarder.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.RandomizerTool; - -namespace CreateAndFake.Toolbox.TesterTool; - -/// Automates null reference guard checks. -internal sealed class NullGuarder : BaseGuarder -{ - /// Handles common test scenarios. - private readonly Asserter _asserter; - - /// Initializes a new instance of the class. - /// Handles generic resolution. - /// Creates objects and populates them with random values. - /// Handles common test scenarios. - /// How long to wait for methods to complete. - internal NullGuarder(GenericFixer fixer, IRandomizer randomizer, Asserter asserter, TimeSpan timeout) - : base(fixer, randomizer, timeout) - { - _asserter = asserter ?? throw new ArgumentNullException(nameof(asserter)); - } - - /// - /// Verifies nulls are guarded on constructors. - /// Tests each nullable parameter possible with null. - /// Ignores any exception besides NullReferenceException and moves on. - /// - /// Type to verify. - /// Run instance methods to validate constructor parameters. - /// Values to inject into the method. - internal void PreventsNullRefExceptionOnConstructors( - Type type, bool callAllMethods, params object[] injectionValues) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - foreach (ConstructorInfo constructor in FindAllConstructors(type)) - { - PreventsNullRefException(null, constructor, callAllMethods, injectionValues); - } - } - - /// - /// Verifies nulls are guarded on methods. - /// Tests each nullable parameter possible with null. - /// Ignores any exception besides NullReferenceException and moves on. - /// - /// Instance to test the methods on. - /// Values to inject into the method. - internal void PreventsNullRefExceptionOnMethods(object instance, params object?[]? injectionValues) - { - ArgumentGuard.ThrowIfNull(instance, nameof(instance)); - - foreach (MethodInfo method in FindAllMethods(instance.GetType(), BindingFlags.Instance) - .Where(m => m.Name is not "Finalize" and not "Dispose")) - { - PreventsNullRefException(instance, Fixer.FixMethod(method), false, injectionValues); - } - } - - /// - /// Verifies nulls are guarded on methods. - /// Tests each nullable parameter possible with null. - /// Ignores any exception besides NullReferenceException and moves on. - /// - /// Type to verify. - /// Run instance methods to validate factory parameters. - /// Values to inject into the method. - internal void PreventsNullRefExceptionOnStatics( - Type type, bool callAllMethods, params object[] injectionValues) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - foreach (MethodInfo method in FindAllMethods(type, BindingFlags.Static)) - { - PreventsNullRefException(null, Fixer.FixMethod(method), - callAllMethods && method.ReturnType.Inherits(type), injectionValues); - } - } - - /// Verifies nulls are guarded on a method. - /// Instance with the method under test. - /// Method under test. - /// If all instance methods should be called after the method. - /// Values to inject into the method. - private void PreventsNullRefException(object? instance, - MethodBase method, bool callAllMethods, object?[]? injectionValues) - { - object?[]? data = null; - object? result = null; - try - { - data = Randomizer.CreateFor(method, injectionValues).Args.ToArray(); - - for (int i = 0; i < data.Length; i++) - { - ParameterInfo param = method.GetParameters()[i]; - if (param.ParameterType.IsValueType - && Nullable.GetUnderlyingType(param.ParameterType) == null) - { - continue; - } - - object? original = data[i]; - data[i] = null; - try - { - result = (instance == null && method is ConstructorInfo builder) - ? RunCheck(method, param, () => builder.Invoke(data)) - : RunCheck(method, param, () => method.Invoke(instance, data)!); - - if (result != null && callAllMethods) - { - CallAllMethods(method, param, result, injectionValues); - } - } - finally - { - data[i] = original; - } - } - } - finally - { - DisposeAllButInjected(injectionValues, data, result); - } - } - - /// - protected override void HandleCheckException(MethodBase testOrigin, - ParameterInfo? testParam, Exception taskException) - { - ArgumentGuard.ThrowIfNull(testOrigin, nameof(testOrigin)); - ArgumentGuard.ThrowIfNull(testParam, nameof(testParam)); - ArgumentGuard.ThrowIfNull(taskException, nameof(taskException)); - - string details = $"on method '{testOrigin.Name}' with parameter '{testParam.Name}'"; - - _asserter.Is(false, taskException is NullReferenceException, - $"Null reference exception encountered {details}."); - } -} diff --git a/src/CreateAndFake/Toolbox/TesterTool/Tester.cs b/src/CreateAndFake/Toolbox/TesterTool/Tester.cs deleted file mode 100644 index daad121e..00000000 --- a/src/CreateAndFake/Toolbox/TesterTool/Tester.cs +++ /dev/null @@ -1,204 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Design.Content; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.RandomizerTool; - -namespace CreateAndFake.Toolbox.TesterTool; - -/// Automates common tests. -/// Core value random handler. -/// Creates objects and populates them with random values. -/// Deep clones objects. -/// Handles common test scenarios. -/// How long to wait for tests to complete. -/// If given nulls. -public class Tester(IRandom gen, IRandomizer randomizer, - IDuplicator duplicator, Asserter asserter, TimeSpan? timeout = null) -{ - /// Retries tests if timeout is reached. - private static readonly Limiter _Limiter = Limiter.Few; - - /// Core value random handler. - protected IRandom Gen { get; } = gen ?? throw new ArgumentNullException(nameof(gen)); - - /// Creates objects and populates them with random values. - protected IRandomizer Randomizer { get; } = randomizer ?? throw new ArgumentNullException(nameof(randomizer)); - - /// Deep clones objects. - protected IDuplicator Duplicator { get; } = duplicator ?? throw new ArgumentNullException(nameof(duplicator)); - - /// Handles common test scenarios. - protected Asserter Asserter { get; } = asserter ?? throw new ArgumentNullException(nameof(asserter)); - - /// How long to wait for tests to complete. - private readonly TimeSpan _timeout = timeout ?? new(0, 0, 3); - - /// - /// Verifies nulls are guarded on the type. - /// Tests each nullable parameter possible with null. - /// Constructor and factory parameters are additionally tested by running all methods. - /// Ignores any exception besides NullReferenceException and moves on. - /// - /// Type to verify. - /// Values to inject into the method. - public virtual void PreventsNullRefException(params object[] injectionValues) - { - PreventsNullRefException(typeof(T), injectionValues); - } - - /// - /// Verifies nulls are guarded on the type. - /// Tests each nullable parameter possible with null. - /// Constructor and factory parameters are additionally tested by running all methods. - /// Ignores any exception besides NullReferenceException and moves on. - /// - /// Type to verify. - /// Values to inject into the method. - public virtual void PreventsNullRefException(Type type, params object[] injectionValues) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - NullGuarder checker = new(new GenericFixer(Gen, Randomizer), Randomizer, Asserter, _timeout); - - _Limiter.Retry($"Null reference check on constructors for type '{type}'", - () => checker.PreventsNullRefExceptionOnConstructors(type, true, injectionValues)).Wait(); - - if (!(type.IsAbstract && type.IsSealed)) - { - _Limiter.Retry( - $"Null reference check on methods for type '{type}'", - () => - { - object? instance = (injectionValues?.Length > 0) - ? Randomizer.Inject(type, injectionValues) - : Randomizer.Create(type); - try - { - checker.PreventsNullRefExceptionOnMethods(instance!, injectionValues); - } - finally - { - Disposer.Cleanup(instance); - } - }).Wait(); - } - - _Limiter.Retry($"Null reference check on static methods for type '{type}'", - () => checker.PreventsNullRefExceptionOnStatics(type, true, injectionValues)).Wait(); - } - - /// - /// Verifies nulls are guarded on the type. - /// Tests each parameter possible with null. - /// Constructor and factory parameters are not tested by running all methods. - /// Ignores any exception besides NullReferenceException and moves on. - /// - /// Type to verify. - /// Instance to test the methods on. - /// Values to inject into the method. - public virtual void PreventsNullRefException(T instance, params object[] injectionValues) - { - NullGuarder checker = new(new GenericFixer(Gen, Randomizer), Randomizer, Asserter, _timeout); - - _Limiter.Retry($"Null reference check on constructors for type '{typeof(T).Name}'", - () => checker.PreventsNullRefExceptionOnConstructors(typeof(T), false, injectionValues)).Wait(); - _Limiter.Retry($"Null reference check on methods for type '{typeof(T).Name}'", - () => checker.PreventsNullRefExceptionOnMethods(instance!, injectionValues)).Wait(); - _Limiter.Retry($"Null reference check on static methods for type '{typeof(T).Name}'", - () => checker.PreventsNullRefExceptionOnStatics(typeof(T), false, injectionValues)).Wait(); - } - - /// - /// Verifies mutations are prevented on the type. - /// Constructor and factory parameters are additionally tested by running all methods. - /// Ignores any exception and moves on. - /// - /// Type to verify. - /// Values to inject into the method. - public virtual void PreventsParameterMutation(params object[] injectionValues) - { - PreventsParameterMutation(typeof(T), injectionValues); - } - - /// - /// Verifies mutations are prevented on the type. - /// Constructor and factory parameters are additionally tested by running all methods. - /// Ignores any exception and moves on. - /// - /// Type to verify. - /// Values to inject into the method. - public virtual void PreventsParameterMutation(Type type, params object[] injectionValues) - { - ArgumentGuard.ThrowIfNull(type, nameof(type)); - - MutationGuarder checker = new(new GenericFixer(Gen, Randomizer), - Randomizer, Duplicator, Asserter, _timeout); - - _Limiter.Retry($"Parameter mutation check on constructors for type '{type}'", - () => checker.PreventsMutationOnConstructors(type, true, injectionValues)).Wait(); - - if (!(type.IsAbstract && type.IsSealed)) - { - _Limiter.Retry( - $"Parameter mutation check on methods for type '{type}'", - () => - { - object? instance = (injectionValues?.Length > 0) - ? Randomizer.Inject(type, injectionValues) - : Randomizer.Create(type); - try - { - checker.PreventsMutationOnMethods(instance!, injectionValues); - } - finally - { - Disposer.Cleanup(instance); - } - }).Wait(); - } - - _Limiter.Retry($"Parameter mutation check on static methods for type '{type}'", - () => checker.PreventsMutationOnStatics(type, true, injectionValues)).Wait(); - } - - /// - /// Verifies mutations are prevented on the type. - /// Constructor and factory parameters are not tested by running all methods. - /// Ignores any exception and moves on. - /// - /// Type to verify. - /// Instance to test the methods on. - /// Values to inject into the method. - public virtual void PreventsParameterMutation(T instance, params object[] injectionValues) - { - MutationGuarder checker = new(new GenericFixer(Gen, Randomizer), - Randomizer, Duplicator, Asserter, _timeout); - - _Limiter.Retry($"Parameter mutation check on constructors for type '{typeof(T).Name}'", - () => checker.PreventsMutationOnConstructors(typeof(T), false, injectionValues)).Wait(); - _Limiter.Retry($"Parameter mutation check on methods for type '{typeof(T).Name}'", - () => checker.PreventsMutationOnMethods(instance!, injectionValues)).Wait(); - _Limiter.Retry($"Parameter mutation check on static methods for type '{typeof(T).Name}'", - () => checker.PreventsMutationOnStatics(typeof(T), false, injectionValues)).Wait(); - } - - /// Verifies no exceptions are thrown on any method when using injection and random data. - /// Type to verify. - /// Values to inject into called methods. - public virtual void PassthroughWithNoExceptions(params object[] injectionValues) - { - PassthroughWithNoExceptions(Randomizer.Create>()!.Dummy!, injectionValues); - } - - /// Verifies no exceptions are thrown on any method. - /// Instance to test the methods on. - /// Values to inject into called methods. - public virtual void PassthroughWithNoExceptions(object instance, params object[] injectionValues) - { - new ExceptionGuarder(new GenericFixer(Gen, Randomizer), Randomizer, Asserter, _timeout) - .CallAllMethods(instance, injectionValues); - } -} diff --git a/src/CreateAndFake/Toolbox/ToolSet.cs b/src/CreateAndFake/Toolbox/ToolSet.cs deleted file mode 100644 index cd164a7b..00000000 --- a/src/CreateAndFake/Toolbox/ToolSet.cs +++ /dev/null @@ -1,75 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.MutatorTool; -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFake.Toolbox.TesterTool; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake; - -/// Holds implementations of all reflection tools. -/// -/// -/// -/// -/// -/// -/// -/// -public sealed class ToolSet( - IRandom gen, - IValuer valuer, - IFaker faker, - IRandomizer randomizer, - IMutator mutator, - Asserter asserter, - IDuplicator duplicator, - Tester tester) -{ - /// Default tools to use. - public static ToolSet DefaultSet { get; } = CreateViaSeed(Environment.TickCount); - - /// Creates all the reflection tools using . - /// - /// The created reflection tools. - public static ToolSet CreateViaSeed(int seed) - { - IRandom gen = new SeededRandom(seed); - IValuer valuer = new Valuer(); - IFaker faker = new Faker(valuer); - IRandomizer randomizer = new Randomizer(faker, gen, Limiter.Dozen); - IMutator mutator = new Mutator(randomizer, valuer, Limiter.Dozen); - Asserter asserter = new(gen, valuer); - IDuplicator duplicator = new Duplicator(asserter); - Tester tester = new(gen, randomizer, duplicator, asserter); - - return new ToolSet(gen, valuer, faker, randomizer, mutator, asserter, duplicator, tester); - } - - /// - public IRandom Gen { get; } = gen; - - /// - public IValuer Valuer { get; } = valuer; - - /// - public IFaker Faker { get; } = faker; - - /// - public IRandomizer Randomizer { get; } = randomizer; - - /// - public IMutator Mutator { get; } = mutator; - - /// - public Asserter Asserter { get; } = asserter; - - /// - public IDuplicator Duplicator { get; } = duplicator; - - /// - public Tester Tester { get; } = tester; -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHint.cs deleted file mode 100644 index 05ec2600..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHint.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace CreateAndFake.Toolbox.ValuerTool; - -/// Handles comparing specific types for . -public abstract class CompareHint -{ - /// - /// Tries to find the differences between and . - /// - /// Object to compare with . - /// Potentially different object to compare against . - /// Handles comparing child values. - /// - /// (true, found differences) if successful; - /// (false, null) otherwise. - /// - internal (bool, IEnumerable?) TryCompare(object? expected, object? actual, ValuerChainer valuer) - { - if (Supports(expected, actual, valuer)) - { - return (true, Compare(expected, actual, valuer)); - } - else - { - return (false, null); - } - } - - /// Tries to compute an identifying hash code for based upon value. - /// Object to generate a hash code for. - /// Handles hashing behavior for child values. - /// - /// (true, value computed hash code) if successful; - /// (false, 0) otherwise. - /// - internal (bool, int) TryGetHashCode(object? item, ValuerChainer valuer) - { - if (Supports(item, item, valuer)) - { - return (true, GetHashCode(item, valuer)); - } - else - { - return (false, default); - } - } - - /// - /// Determines if or are supported by the hint. - /// - /// true if the objects can be compared; false otherwise. - /// - protected abstract bool Supports(object? expected, object? actual, ValuerChainer valuer); - - /// Finds the differences between and . - /// The found differences between and . - /// - protected abstract IEnumerable Compare(object? expected, object? actual, ValuerChainer valuer); - - /// Computes an identifying hash code for based upon value. - /// The value computed hash code for . - /// - protected abstract int GetHashCode(object? item, ValuerChainer valuer); -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHint[T].cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHint[T].cs deleted file mode 100644 index 23ca575a..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHint[T].cs +++ /dev/null @@ -1,34 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.ValuerTool; - -/// Type being supported for comparisons. -/// -public abstract class CompareHint : CompareHint -{ - /// - protected sealed override bool Supports(object? expected, object? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(expected, nameof(expected)); - - return expected is T && actual is T; - } - - /// - protected sealed override IEnumerable Compare(object? expected, object? actual, ValuerChainer valuer) - { - return Compare((T?)expected, (T?)actual, valuer); - } - - /// - protected abstract IEnumerable Compare(T? expected, T? actual, ValuerChainer valuer); - - /// - protected sealed override int GetHashCode(object? item, ValuerChainer valuer) - { - return GetHashCode((T?)item, valuer); - } - - /// - protected abstract int GetHashCode(T? item, ValuerChainer valuer); -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/AsyncEnumerableCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/AsyncEnumerableCompareHint.cs deleted file mode 100644 index 95ebb408..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/AsyncEnumerableCompareHint.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing collections for . -public sealed class AsyncEnumerableCompareHint : CompareHint -{ - /// - protected override bool Supports(object? expected, object? actual, ValuerChainer valuer) - { - return (expected?.GetType()).Inherits(typeof(IAsyncEnumerable<>)) - && (actual?.GetType()).Inherits(typeof(IAsyncEnumerable<>)); - } - - /// - protected override IEnumerable Compare( - object? expected, object? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(expected, nameof(expected)); - ArgumentGuard.ThrowIfNull(actual, nameof(actual)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return Task.Run(() => (Task>)GetType() - .GetMethod(nameof(CompareAsync), BindingFlags.Static | BindingFlags.NonPublic)! - .MakeGenericMethod(expected.GetType().GetGenericArguments().Single()) - .Invoke(null, [expected, actual, valuer])!).Result; - } - - /// - /// Item Type being compared. - private static async Task> CompareAsync( - IAsyncEnumerable expected, IAsyncEnumerable actual, ValuerChainer valuer) - { - List differences = []; - - IAsyncEnumerator expectedEnumerator = expected.GetAsyncEnumerator(); - IAsyncEnumerator actualEnumerator = actual.GetAsyncEnumerator(); - await using (expectedEnumerator.ConfigureAwait(false)) - await using (actualEnumerator.ConfigureAwait(false)) - { - int index = 0; - while (await expectedEnumerator.MoveNextAsync().ConfigureAwait(false)) - { - if (await actualEnumerator.MoveNextAsync().ConfigureAwait(false)) - { - differences.AddRange(valuer - .Compare(expectedEnumerator.Current, actualEnumerator.Current) - .Select(diff => new Difference(index, diff))); - } - else - { - differences.Add(new Difference(index, new Difference(expectedEnumerator.Current, "'outofbounds'"))); - } - index++; - } - while (await actualEnumerator.MoveNextAsync().ConfigureAwait(false)) - { - differences.Add(new Difference(index++, new Difference("'outofbounds'", actualEnumerator.Current))); - } - } - - return differences; - } - - /// - protected override int GetHashCode(object? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(item, nameof(item)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return Task.Run(() => (Task)GetType() - .GetMethod(nameof(GetHashCodeAsync), BindingFlags.Static | BindingFlags.NonPublic)! - .MakeGenericMethod(item.GetType().GetGenericArguments().Single()) - .Invoke(null, [item, valuer])!).Result; - } - - /// - /// Item Type being compared. - private static async Task GetHashCodeAsync(IAsyncEnumerable item, ValuerChainer valuer) - { - int hash = ValueComparer.BaseHash; - await foreach (T current in item) - { - hash = hash * ValueComparer.HashMultiplier + valuer.GetHashCode(current); - } - return hash; - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/DictionaryCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/DictionaryCompareHint.cs deleted file mode 100644 index b22e60ff..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/DictionaryCompareHint.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System.Collections; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing collections for . -public sealed class DictionaryCompareHint : CompareHint -{ - /// - protected override IEnumerable Compare( - IDictionary? expected, IDictionary? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(expected, nameof(expected)); - ArgumentGuard.ThrowIfNull(actual, nameof(actual)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return LazyCompare(expected, actual, valuer); - } - - /// - private static IEnumerable LazyCompare( - IDictionary expected, IDictionary actual, ValuerChainer valuer) - { - object[] expectedKeys = expected.Keys.Cast().ToArray(); - object[] actualKeys = actual.Keys.Cast().ToArray(); - - foreach (object key in expectedKeys) - { - object? match = actualKeys.FirstOrDefault(k => valuer.Equals(key, k)); - if (match != null) - { - foreach (Difference diff in valuer.Compare(expected[key], actual[match])) - { - yield return new Difference($"[{key}]", diff); - } - } - else - { - yield return new Difference($"[{key}]", new Difference(expected[key], "'null'")); - } - } - - foreach (object key in actualKeys) - { - if (!expectedKeys.Any(k => valuer.Equals(key, k))) - { - yield return new Difference($"[{key}]", new Difference("'null'", actual[key])); - } - } - } - - /// - protected override int GetHashCode(IDictionary? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(item, nameof(item)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - int hash = ValueComparer.BaseHash; - foreach (DictionaryEntry entry in item) - { - hash += valuer.GetHashCode(entry.Key, entry.Value); - } - return hash; - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EarlyFailCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EarlyFailCompareHint.cs deleted file mode 100644 index 66394e28..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EarlyFailCompareHint.cs +++ /dev/null @@ -1,58 +0,0 @@ -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles basic Type compare issues for . -public sealed class EarlyFailCompareHint : CompareHint -{ - /// Specific types to control via this hint. - private static readonly HashSet _SupportedTypes = [typeof(string), typeof(object)]; - - /// - protected override bool Supports(object? expected, object? actual, ValuerChainer valuer) - { - return expected == null - || actual == null - || Supports(expected.GetType(), actual.GetType()) - || expected is Delegate - || expected is Type; - } - - /// - private static bool Supports(Type expected, Type actual) - { - return (expected != actual - && !(expected.Inherits(typeof(IAsyncEnumerable<>)) && actual.Inherits(typeof(IAsyncEnumerable<>))) - && !(expected.Inherits(typeof(IEnumerable<>)) && actual.Inherits(typeof(IEnumerable<>)))) - || expected.IsPrimitive - || expected.IsEnum - || _SupportedTypes.Contains(expected); - } - - /// - protected override IEnumerable Compare(object? expected, object? actual, ValuerChainer valuer) - { - if (expected == null && actual == null) - { - yield break; - } - else if (expected == null || actual == null) - { - yield return new Difference(expected, actual); - } - else if (expected.GetType() != actual.GetType()) - { - yield return new Difference(expected.GetType(), actual.GetType()); - } - else if (!expected.Equals(actual)) - { - yield return new Difference(expected, actual); - } - } - - /// - protected override int GetHashCode(object? item, ValuerChainer valuer) - { - return ValueComparer.Use.GetHashCode(item); - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EnumerableCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EnumerableCompareHint.cs deleted file mode 100644 index 2ca9213c..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EnumerableCompareHint.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Collections; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing collections for . -public sealed class EnumerableCompareHint : CompareHint -{ - /// - protected override IEnumerable Compare( - IEnumerable? expected, IEnumerable? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(expected, nameof(expected)); - ArgumentGuard.ThrowIfNull(actual, nameof(actual)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return LazyCompare(expected, actual, valuer); - } - - /// - private static IEnumerable LazyCompare( - IEnumerable expected, IEnumerable actual, ValuerChainer valuer) - { - IEnumerator expectedEnumerator = expected.GetEnumerator(); - IEnumerator actualEnumerator = actual.GetEnumerator(); - int index = 0; - - while (expectedEnumerator.MoveNext()) - { - if (actualEnumerator.MoveNext()) - { - foreach (Difference diff in valuer.Compare(expectedEnumerator.Current, actualEnumerator.Current)) - { - yield return new Difference(index, diff); - } - } - else - { - yield return new Difference(index, new Difference(expectedEnumerator.Current, "'outofbounds'")); - } - index++; - } - while (actualEnumerator.MoveNext()) - { - yield return new Difference(index++, new Difference("'outofbounds'", actualEnumerator.Current)); - } - } - - /// - protected override int GetHashCode(IEnumerable? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(item, nameof(item)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - int hash = ValueComparer.BaseHash; - foreach (object value in item) - { - hash = hash * ValueComparer.HashMultiplier + valuer.GetHashCode(value); - } - return hash; - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EquatableCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EquatableCompareHint.cs deleted file mode 100644 index 76493c50..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/EquatableCompareHint.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Collections; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing instances for . -public sealed class EquatableCompareHint : CompareHint -{ - /// - protected override bool Supports(object? expected, object? actual, ValuerChainer valuer) - { - return expected != null - && expected.GetType().Inherits(typeof(IEquatable<>).MakeGenericType(expected.GetType())) - && expected is not IStructuralEquatable; - } - - /// - protected override IEnumerable Compare(object? expected, object? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(expected, nameof(expected)); - - if (!expected.Equals(actual)) - { - return [new Difference(expected, actual)]; - } - else - { - return []; - } - } - - /// - protected override int GetHashCode(object? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(item, nameof(item)); - - return item.GetHashCode(); - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/FakedCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/FakedCompareHint.cs deleted file mode 100644 index 1e49be40..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/FakedCompareHint.cs +++ /dev/null @@ -1,24 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing instances for . -public sealed class FakedCompareHint : CompareHint -{ - /// - protected override IEnumerable Compare(IFaked? expected, IFaked? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return valuer.Compare(expected?.FakeMeta, actual?.FakeMeta); - } - - /// - protected override int GetHashCode(IFaked? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return valuer.GetHashCode(item?.FakeMeta); - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ObjectCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ObjectCompareHint.cs deleted file mode 100644 index a6f55366..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ObjectCompareHint.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing objects for . -/// Flags used to find properties and fields. -public sealed class ObjectCompareHint(BindingFlags scope) : CompareHint -{ - /// - protected override bool Supports(object? expected, object? actual, ValuerChainer valuer) - { - if (expected == null || actual == null) - { - return false; - } - - Type type = expected.GetType(); - return type.GetProperties(scope).Any(p => p.CanRead) - || type.GetFields(scope).Length != 0; - } - - /// - protected override IEnumerable Compare(object? expected, object? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(expected, nameof(expected)); - ArgumentGuard.ThrowIfNull(actual, nameof(actual)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return LazyCompare(expected, actual, valuer); - } - - /// - private IEnumerable LazyCompare(object expected, object actual, ValuerChainer valuer) - { - Type type = expected.GetType(); - - foreach (PropertyInfo property in type.GetProperties(scope).Where(p => p.CanRead)) - { - foreach (Difference diff in valuer.Compare(property.GetValue(expected), property.GetValue(actual))) - { - yield return new Difference(property, diff); - } - } - - foreach (FieldInfo field in expected.GetType().GetFields(scope)) - { - foreach (Difference diff in valuer.Compare(field.GetValue(expected), field.GetValue(actual))) - { - yield return new Difference(field, diff); - } - } - } - - /// - protected override int GetHashCode(object? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(item, nameof(item)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - Type type = item.GetType(); - int hash = ValueComparer.BaseHash + type.GetHashCode(); - - foreach (PropertyInfo property in type.GetProperties(scope).Where(p => p.CanRead)) - { - hash = hash * ValueComparer.HashMultiplier + valuer.GetHashCode(property.GetValue(item)); - } - - foreach (FieldInfo field in type.GetFields(scope)) - { - hash = hash * ValueComparer.HashMultiplier + valuer.GetHashCode(field.GetValue(item)); - } - - return hash; - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/StatelessCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/StatelessCompareHint.cs deleted file mode 100644 index 4b46d723..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/StatelessCompareHint.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing stateless objects for . -public sealed class StatelessCompareHint : CompareHint -{ - /// Flags used to find properties and fields. - private const BindingFlags _Scope = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - - /// - protected override bool Supports(object? expected, object? actual, ValuerChainer valuer) - { - if (expected == null || actual == null) - { - return false; - } - - Type type = expected.GetType(); - return !type.GetProperties(_Scope).Any(p => p.CanRead) - && type.GetFields(_Scope).Length == 0; - } - - /// - protected override IEnumerable Compare(object? expected, object? actual, ValuerChainer valuer) - { - return []; - } - - /// - protected override int GetHashCode(object? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(item, nameof(item)); - - return item.GetType().GetHashCode(); - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/StringDictionaryCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/StringDictionaryCompareHint.cs deleted file mode 100644 index 00e0b5de..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/StringDictionaryCompareHint.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections; -using System.Collections.Specialized; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing collections for . -public sealed class StringDictionaryCompareHint : CompareHint -{ - /// - protected override IEnumerable Compare( - StringDictionary? expected, StringDictionary? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return valuer.Compare(Convert(expected), Convert(actual)); - } - - /// - protected override int GetHashCode(StringDictionary? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return valuer.GetHashCode(Convert(item)); - } - - /// Handles changing string dictionaries to dictionaries. - /// Dictionary to convert. - /// The converted dictionary. - private static Dictionary Convert(StringDictionary? dict) - { - ArgumentGuard.ThrowIfNull(dict, nameof(dict)); - - return dict.Cast().ToDictionary(e => (string)e.Key, e => (string?)e.Value); - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/TaskCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/TaskCompareHint.cs deleted file mode 100644 index 1fc7a64c..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/TaskCompareHint.cs +++ /dev/null @@ -1,45 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing instances for . -public sealed class TaskCompareHint : CompareHint -{ - /// - protected override IEnumerable Compare(Task? expected, Task? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return valuer.Compare(ExtractResult(expected), ExtractResult(actual)); - } - - /// - protected override int GetHashCode(Task? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return valuer.GetHashCode(ExtractResult(item)); - } - - /// Retrieves the result from a task. - /// Given task. - /// Result if possible; status otherwise. - private static object? ExtractResult(Task? item) - { - if (item == null) - { - return null; - } - else if (item.GetType().IsGenericType) - { - return item - .GetType() - .GetProperty(nameof(Task.Result))! - .GetValue(item); - } - else - { - return (item.Status, item.Exception); - } - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ValueEquatableCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ValueEquatableCompareHint.cs deleted file mode 100644 index 96f18e80..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ValueEquatableCompareHint.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing instances for . -public sealed class ValueEquatableCompareHint : CompareHint -{ - /// Compares equatables by value as well. - private static readonly ObjectCompareHint _NestedHint - = new(BindingFlags.Public | BindingFlags.Instance); - - /// - protected override IEnumerable Compare( - IValueEquatable? expected, IValueEquatable? actual, ValuerChainer valuer) - { - return LazyCompare(expected, actual, valuer); - } - - /// - private static IEnumerable LazyCompare( - IValueEquatable? expected, IValueEquatable? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(expected, nameof(expected)); - - if (!expected.ValuesEqual(actual)) - { - yield return new Difference(".ValuesEqual", new Difference(true, false)); - - (bool, IEnumerable?) byValues = _NestedHint.TryCompare(expected, actual, valuer); - if (byValues.Item1) - { - foreach (Difference difference in byValues.Item2!) - { - yield return difference; - } - } - } - } - - /// - protected override int GetHashCode(IValueEquatable? item, ValuerChainer valuer) - { - return ValueComparer.Use.GetHashCode(item); - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ValuerEquatableCompareHint.cs b/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ValuerEquatableCompareHint.cs deleted file mode 100644 index 9a9cd9ba..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/CompareHints/ValuerEquatableCompareHint.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; - -namespace CreateAndFake.Toolbox.ValuerTool.CompareHints; - -/// Handles comparing instances for . -public sealed class ValuerEquatableCompareHint : CompareHint -{ - /// Compares equatables by value as well. - private static readonly ObjectCompareHint _NestedHint - = new(BindingFlags.Public | BindingFlags.Instance); - - /// - protected override IEnumerable Compare( - IValuerEquatable? expected, IValuerEquatable? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return LazyCompare(expected, actual, valuer); - } - - /// - private static IEnumerable LazyCompare( - IValuerEquatable? expected, IValuerEquatable? actual, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(expected, nameof(expected)); - - if (!expected.ValuesEqual(actual, valuer.Valuer)) - { - yield return new Difference(".ValuesEqual", new Difference(true, false)); - - (bool, IEnumerable?) byValues = _NestedHint.TryCompare(expected, actual, valuer); - if (byValues.Item1) - { - foreach (Difference difference in byValues.Item2!) - { - yield return difference; - } - } - } - } - - /// - protected override int GetHashCode(IValuerEquatable? item, ValuerChainer valuer) - { - ArgumentGuard.ThrowIfNull(item, nameof(item)); - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return item.GetValueHash(valuer.Valuer); - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/Difference.cs b/src/CreateAndFake/Toolbox/ValuerTool/Difference.cs deleted file mode 100644 index 009678c3..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/Difference.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.ValuerTool; - -/// Expresses a value difference between two objects. -public sealed class Difference : IValueEquatable, IDeepCloneable -{ - /// Message stating the difference. - private readonly Lazy _message; - - /// - /// Type of the compared expected object. - /// Type of the compared actual object. - public Difference(Type expectedType, Type actualType) - { - _message = new Lazy( - () => $" -> Expected type:<{expectedType}>, Actual type:<{actualType}>"); - } - - /// - /// Object compared with . - /// Object compared against . - public Difference(object? expected, object? actual) - { - _message = new Lazy(() => $" -> Expected:<{expected}>, Actual:<{actual}>"); - } - - /// - /// Member where the compared objects differed. - /// Found difference for the compared objects. - public Difference(MemberInfo member, Difference difference) - : this("." + member?.Name, difference) - { - ArgumentGuard.ThrowIfNull(member, nameof(member)); - } - - /// - /// Index where the compared objects differed. - /// Found difference for the compared objects. - public Difference(int index, Difference difference) - : this($"[{index}]", difference) { } - - /// - /// Access method where the compared objects differed. - /// Found difference for the compared objects. - public Difference(string access, Difference difference) - { - ArgumentGuard.ThrowIfNull(access, nameof(access)); - ArgumentGuard.ThrowIfNull(difference, nameof(difference)); - - _message = new Lazy(() => access + difference.ToString()); - } - - /// - /// - public Difference(string message) - { - _message = new Lazy(() => message); - } - - /// - public IDeepCloneable DeepClone() - { - return new Difference(_message.Value); - } - - /// - public bool ValuesEqual(object? other) - { - return other != null - && GetType() == other.GetType() - && _message.Value == ((Difference)other)._message.Value; - } - - /// - public int GetValueHash() - { - return ValueComparer.Use.GetHashCode(_message.Value); - } - - /// Converts this to a string. - /// string representation of this. - public override string ToString() - { - return _message.Value; - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/IValuer.cs b/src/CreateAndFake/Toolbox/ValuerTool/IValuer.cs deleted file mode 100644 index 267db985..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/IValuer.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Collections; - -namespace CreateAndFake.Toolbox.ValuerTool; - -/// Compares objects by value via reflection if needed. -public interface IValuer : IEqualityComparer, IEqualityComparer -{ - /// Finds the differences between and . - /// Object to compare with . - /// Potentially different object to compare against . - /// Found differences between and . - /// If no hint supports comparing the objects. - /// If infinite recursion occurs. - IEnumerable Compare(object? expected, object? actual); - - /// Determines if equals by value. - /// Object to compare with . - /// Object to compare with . - /// - /// true if equals by value; false otherwise. - /// - /// If no hint supports comparing the objects. - /// If infinite recursion occurs. - new bool Equals(object? x, object? y); - - /// Computes an identifying hash code for based upon value. - /// Object to generate a hash code for. - /// The value computed hash code for . - /// If no hint supports hashing the object. - /// If infinite recursion occurs. - new int GetHashCode(object? item); - - /// Computes an identifying hash code for based upon value. - /// Bundled objects to generate a single value hash code for. - /// The value computed hash code for . - /// If no hint supports hashing an object. - /// If infinite recursion occurs. - int GetHashCode(params object?[]? items); - - /// Adds to be used for comparisons. Last added takes precedence. - /// Hint to add. - /// Should only be modified in module initializers. - void AddHint(CompareHint hint); -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/Valuer.cs b/src/CreateAndFake/Toolbox/ValuerTool/Valuer.cs deleted file mode 100644 index bab370bd..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/Valuer.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; - -namespace CreateAndFake.Toolbox.ValuerTool; - -/// -/// If the default set of hints should be used. -/// -public sealed class Valuer(bool includeDefaultHints = true, params CompareHint[]? hints) : IValuer, IDuplicatable -{ - /// Default set of hints to use for comparisons. - private static readonly CompareHint[] _DefaultHints = - [ - new EarlyFailCompareHint(), - new FakedCompareHint(), - new TaskCompareHint(), - new ValueEquatableCompareHint(), - new ValuerEquatableCompareHint(), - new EquatableCompareHint(), - new AsyncEnumerableCompareHint(), - new StringDictionaryCompareHint(), - new DictionaryCompareHint(), - new EnumerableCompareHint(), - new ObjectCompareHint(BindingFlags.Public | BindingFlags.Instance), - new ObjectCompareHint(BindingFlags.NonPublic | BindingFlags.Instance), - new StatelessCompareHint() - ]; - - /// Hints used to compare specific types. - private readonly List _hints = (hints ?? Enumerable.Empty()) - .Concat(includeDefaultHints ? _DefaultHints : []) - .ToList(); - - /// - public new bool Equals(object? x, object? y) - { - return !Compare(x, y).Any(); - } - - /// - [SuppressMessage("Microsoft.Design", - "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", - Justification = "Forwarded.")] - public int GetHashCode(object? item) - { - string? typeName = item?.GetType().Name; - try - { - return GetHashCode(item, new ValuerChainer(this, GetHashCode, Compare)); - } - catch (InsufficientExecutionStackException) - { - throw new InsufficientExecutionStackException( - $"Ran into infinite generation trying to hash type '{typeName}'."); - } - } - - /// Handles callback behavior for child values. - /// - private int GetHashCode(object? item, ValuerChainer chainer) - { - (bool, int) result = _hints - .Select(h => h.TryGetHashCode(item, chainer)) - .FirstOrDefault(r => r.Item1); - - if (!result.Equals(default)) - { - return result.Item2; - } - else - { - throw new NotSupportedException( - $"Type '{item?.GetType().FullName}' not supported by the valuer. " + - "Create a hint to generate the type and pass it to the valuer."); - } - } - - /// - public int GetHashCode(params object?[]? items) - { - return GetHashCode((object?)items); - } - - /// - public IEnumerable Compare(object? expected, object? actual) - { - string? typeName = (expected ?? actual)?.GetType().Name; - try - { - return Compare(expected, actual, new ValuerChainer(this, GetHashCode, Compare)); - } - catch (InsufficientExecutionStackException) - { - throw new InsufficientExecutionStackException( - $"Ran into infinite generation trying to compare type '{typeName}'."); - } - } - - /// Handles callback behavior for child values. - /// - private IEnumerable Compare(object? expected, object? actual, ValuerChainer chainer) - { - if (ReferenceEquals(expected, actual)) - { - return []; - } - - (bool, IEnumerable?) result = _hints - .Select(h => h.TryCompare(expected, actual, chainer)) - .FirstOrDefault(r => r.Item1); - - if (!result.Equals(default)) - { - return result.Item2!; - } - else - { - throw new NotSupportedException( - $"Type '{expected?.GetType().FullName}' not supported by the valuer. " + - "Create a hint to generate the type and pass it to the valuer."); - } - } - - /// - public IDuplicatable DeepClone(IDuplicator duplicator) - { - ArgumentGuard.ThrowIfNull(duplicator, nameof(duplicator)); - - return new Valuer(false, [.. duplicator.Copy(_hints)]); - } - - /// - public void AddHint(CompareHint hint) - { - _hints.Insert(0, hint ?? throw new ArgumentNullException(nameof(hint))); - } -} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/ValuerChainer.cs b/src/CreateAndFake/Toolbox/ValuerTool/ValuerChainer.cs deleted file mode 100644 index e29a137b..00000000 --- a/src/CreateAndFake/Toolbox/ValuerTool/ValuerChainer.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFake.Toolbox.ValuerTool; - -/// Provides a callback into to create child values. -/// -/// -/// -public sealed class ValuerChainer( - IValuer valuer, - Func hasher, - Func> comparer) -{ - /// Callback to to handle child hashes. - private readonly Func _hasher - = hasher ?? throw new ArgumentNullException(nameof(hasher)); - - /// Callback to to handle child comparisons. - private readonly Func> _comparer - = comparer ?? throw new ArgumentNullException(nameof(comparer)); - - /// History of hashes to match up references. - private readonly Dictionary _hashHistory = []; - - /// History of comparisons to match up references. - private readonly HashSet<(int, int)> _compareHistory = []; - - /// Reference to the actual source valuer. - internal IValuer Valuer { get; } = valuer ?? throw new ArgumentNullException(nameof(valuer)); - - /// - public IEnumerable Compare(object? expected, object? actual) - { - RuntimeHelpers.EnsureSufficientExecutionStack(); - if (CanTrack(expected) && CanTrack(actual)) - { - (int, int) refHash = (RuntimeHelpers.GetHashCode(expected), RuntimeHelpers.GetHashCode(actual)); - - return _compareHistory.Add(refHash) - ? _comparer.Invoke(expected, actual, this) - : []; - } - else - { - return _comparer.Invoke(expected, actual, this); - } - } - - /// - public new bool Equals(object? x, object? y) - { - return !Compare(x, y).Any(); - } - - /// - public int GetHashCode(object? item) - { - RuntimeHelpers.EnsureSufficientExecutionStack(); - if (!CanTrack(item)) - { - return _hasher.Invoke(item, this); - } - - int refHash = RuntimeHelpers.GetHashCode(item); - if (_hashHistory.TryGetValue(refHash, out object? stored) && ReferenceEquals(item, stored)) - { - return 0; - } - - _hashHistory[refHash] = item; - try - { - return _hasher.Invoke(item, this); - } - finally - { - _ = _hashHistory.Remove(refHash); - } - } - - /// - public int GetHashCode(params object?[]? items) - { - return GetHashCode((object?)items); - } - - /// If can be tracked in history. - /// Item to check. - /// true if tracking is possible; false otherwise. - private static bool CanTrack([NotNullWhen(true)] object? item) - { - return !(item == null || item is IFaked || item.GetType().IsValueType); - } -} diff --git a/src/CreateAndFake/Tools.cs b/src/CreateAndFake/Tools.cs deleted file mode 100644 index 79ba3b3b..00000000 --- a/src/CreateAndFake/Tools.cs +++ /dev/null @@ -1,42 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.MutatorTool; -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFake.Toolbox.TesterTool; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake; - -/// Manages implementations of all reflection tools. -public static class Tools -{ - /// Manages currently used tools globally. - /// Should only be modified in module initializer once. - public static ToolSet Source { get; set; } = ToolSet.DefaultSet; - - /// - public static IRandom Gen => Source.Gen; - - /// - public static IValuer Valuer => Source.Valuer; - - /// - public static IFaker Faker => Source.Faker; - - /// - public static IRandomizer Randomizer => Source.Randomizer; - - /// - public static IMutator Mutator => Source.Mutator; - - /// - public static Asserter Asserter => Source.Asserter; - - /// - public static IDuplicator Duplicator => Source.Duplicator; - - /// - public static Tester Tester => Source.Tester; -} diff --git a/src/Design/ArgumentGuard.cs b/src/Design/ArgumentGuard.cs new file mode 100644 index 00000000..275017bd --- /dev/null +++ b/src/Design/ArgumentGuard.cs @@ -0,0 +1,277 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Extensions; +using Werecodent.CreateAndFake.Design.Properties; + +namespace Werecodent.CreateAndFake.Design; + +#pragma warning disable RCS1256 // False positive. + +/// Handles common argument cases. +public static class ArgumentGuard +{ + /// Prevents further execution if is . + /// Passed parameter value. + /// Name of the parameter. + /// If is null. + [DebuggerStepThrough] + public static void ThrowIfNull( + [NotNull] object? value, + [CallerArgumentExpression(nameof(value))] string? name = null + ) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + /// Prevents further execution if any of the values are . + /// First passed parameter value. + /// Second passed parameter value. + /// Parameter name for . + /// Parameter name for . + /// If any value is null. + [DebuggerStepThrough] + public static void ThrowIfNull( + [NotNull] object? valueA, + [NotNull] object? valueB, + [CallerArgumentExpression(nameof(valueA))] string? nameA = null, + [CallerArgumentExpression(nameof(valueB))] string? nameB = null + ) + { + ThrowIfNull(valueA, nameA); + ThrowIfNull(valueB, nameB); + } + + /// + /// Third passed parameter value. + /// Parameter name for . + [DebuggerStepThrough] + public static void ThrowIfNull( + [NotNull] object? valueA, + [NotNull] object? valueB, + [NotNull] object? valueC, + [CallerArgumentExpression(nameof(valueA))] string? nameA = null, + [CallerArgumentExpression(nameof(valueB))] string? nameB = null, + [CallerArgumentExpression(nameof(valueC))] string? nameC = null + ) + { + ThrowIfNull(valueA, nameA); + ThrowIfNull(valueB, nameB); + ThrowIfNull(valueC, nameC); + } + + /// + /// Fourth passed parameter value. + /// Parameter name for . + [DebuggerStepThrough] + public static void ThrowIfNull( + [NotNull] object? valueA, + [NotNull] object? valueB, + [NotNull] object? valueC, + [NotNull] object? valueD, + [CallerArgumentExpression(nameof(valueA))] string? nameA = null, + [CallerArgumentExpression(nameof(valueB))] string? nameB = null, + [CallerArgumentExpression(nameof(valueC))] string? nameC = null, + [CallerArgumentExpression(nameof(valueD))] string? nameD = null + ) + { + ThrowIfNull(valueA, nameA); + ThrowIfNull(valueB, nameB); + ThrowIfNull(valueC, nameC); + ThrowIfNull(valueD, nameD); + } + + /// + /// Fifth passed parameter value. + /// Parameter name for . + [DebuggerStepThrough] + public static void ThrowIfNull( + [NotNull] object? valueA, + [NotNull] object? valueB, + [NotNull] object? valueC, + [NotNull] object? valueD, + [NotNull] object? valueE, + [CallerArgumentExpression(nameof(valueA))] string? nameA = null, + [CallerArgumentExpression(nameof(valueB))] string? nameB = null, + [CallerArgumentExpression(nameof(valueC))] string? nameC = null, + [CallerArgumentExpression(nameof(valueD))] string? nameD = null, + [CallerArgumentExpression(nameof(valueE))] string? nameE = null + ) + { + ThrowIfNull(valueA, nameA); + ThrowIfNull(valueB, nameB); + ThrowIfNull(valueC, nameC); + ThrowIfNull(valueD, nameD); + ThrowIfNull(valueE, nameE); + } + + /// + /// Sixth passed parameter value. + /// Parameter name for . + [DebuggerStepThrough] + public static void ThrowIfNull( + [NotNull] object? valueA, + [NotNull] object? valueB, + [NotNull] object? valueC, + [NotNull] object? valueD, + [NotNull] object? valueE, + [NotNull] object? valueF, + [CallerArgumentExpression(nameof(valueA))] string? nameA = null, + [CallerArgumentExpression(nameof(valueB))] string? nameB = null, + [CallerArgumentExpression(nameof(valueC))] string? nameC = null, + [CallerArgumentExpression(nameof(valueD))] string? nameD = null, + [CallerArgumentExpression(nameof(valueE))] string? nameE = null, + [CallerArgumentExpression(nameof(valueF))] string? nameF = null + ) + { + ThrowIfNull(valueA, nameA); + ThrowIfNull(valueB, nameB); + ThrowIfNull(valueC, nameC); + ThrowIfNull(valueD, nameD); + ThrowIfNull(valueE, nameE); + ThrowIfNull(valueF, nameF); + } + + /// + /// Seventh passed parameter value. + /// Parameter name for . + [DebuggerStepThrough] + public static void ThrowIfNull( + [NotNull] object? valueA, + [NotNull] object? valueB, + [NotNull] object? valueC, + [NotNull] object? valueD, + [NotNull] object? valueE, + [NotNull] object? valueF, + [NotNull] object? valueG, + [CallerArgumentExpression(nameof(valueA))] string? nameA = null, + [CallerArgumentExpression(nameof(valueB))] string? nameB = null, + [CallerArgumentExpression(nameof(valueC))] string? nameC = null, + [CallerArgumentExpression(nameof(valueD))] string? nameD = null, + [CallerArgumentExpression(nameof(valueE))] string? nameE = null, + [CallerArgumentExpression(nameof(valueF))] string? nameF = null, + [CallerArgumentExpression(nameof(valueG))] string? nameG = null + ) + { + ThrowIfNull(valueA, nameA); + ThrowIfNull(valueB, nameB); + ThrowIfNull(valueC, nameC); + ThrowIfNull(valueD, nameD); + ThrowIfNull(valueE, nameE); + ThrowIfNull(valueF, nameF); + ThrowIfNull(valueG, nameG); + } + + /// + /// Eighth passed parameter value. + /// Parameter name for . + [DebuggerStepThrough] + public static void ThrowIfNull( + [NotNull] object? valueA, + [NotNull] object? valueB, + [NotNull] object? valueC, + [NotNull] object? valueD, + [NotNull] object? valueE, + [NotNull] object? valueF, + [NotNull] object? valueG, + [NotNull] object? valueH, + [CallerArgumentExpression(nameof(valueA))] string? nameA = null, + [CallerArgumentExpression(nameof(valueB))] string? nameB = null, + [CallerArgumentExpression(nameof(valueC))] string? nameC = null, + [CallerArgumentExpression(nameof(valueD))] string? nameD = null, + [CallerArgumentExpression(nameof(valueE))] string? nameE = null, + [CallerArgumentExpression(nameof(valueF))] string? nameF = null, + [CallerArgumentExpression(nameof(valueG))] string? nameG = null, + [CallerArgumentExpression(nameof(valueH))] string? nameH = null + ) + { + ThrowIfNull(valueA, nameA); + ThrowIfNull(valueB, nameB); + ThrowIfNull(valueC, nameC); + ThrowIfNull(valueD, nameD); + ThrowIfNull(valueE, nameE); + ThrowIfNull(valueF, nameF); + ThrowIfNull(valueG, nameG); + ThrowIfNull(valueH, nameH); + } + + /// Checks if is an asynchronous . + /// Passed parameter value. + public static bool IsAsynchronous(object? value) + { + if (value == null) + { + return false; + } + + if (value is Task task && !task.IsCompleted) + { + return true; + } + + Type type = value as Type ?? value.GetType(); + + return type.Inherits(typeof(IAsyncEnumerable<>)); + } + + /// Prevents further execution if is an asynchronous . + /// Passed parameter value. + /// Error details for the potential . + /// + /// If is an asynchronous . + /// + [DebuggerStepThrough] + public static void ThrowIfAsynchronous(object? value, string message) + { + if (IsAsynchronous(value)) + { + throw new AsynchronousAccessException(value, message); + } + } + + /// + /// Prevents further execution if the + /// has exceeded the . + /// + /// Current iteration count. + /// If index >= DesignDefaults.IterationLimit. + [DebuggerStepThrough] + public static void ThrowUponIterationLimit(int index) + { + if (index >= DesignDefaults.IterationLimit) + { + throw new IterationLimitException( + DesignDefaults.IterationLimit, + $"Index {index} surpassed max iteration limit." + ); + } + } + + /// + /// Prevents further execution if the + /// has exceeded the . + /// + /// Current iteration count. + /// Max allowable index. + /// If index >= iterationLimit. + [DebuggerStepThrough] + public static void ThrowUponIterationLimit(int index, int iterationLimit) + { + if (index >= iterationLimit) + { + throw new IterationLimitException( + iterationLimit, + $"Index {index} surpassed max iteration limit. Increase via 'Design.IterationLimit'." + ); + } + } +} + +#pragma warning restore diff --git a/src/Design/Comparisons/IAsyncEqualityComparer.cs b/src/Design/Comparisons/IAsyncEqualityComparer.cs new file mode 100644 index 00000000..e3e09d78 --- /dev/null +++ b/src/Design/Comparisons/IAsyncEqualityComparer.cs @@ -0,0 +1,22 @@ +namespace Werecodent.CreateAndFake.Design.Comparisons; + +/// Checks if two s are equal with compatibility. +/// Supported for comparisons. +public interface IAsyncEqualityComparer +{ + /// Determines if equals by value. + /// Instance to compare with . + /// Instance to compare with . + /// Aborts execution if triggered. + /// + /// if equals by value, + /// otherwise. + /// + Task EqualsAsync(T? x, T? y, CancellationToken canceler); + + /// Computes an identifying hash code for based upon value. + /// Instance to generate a hash code for. + /// Aborts execution if triggered. + /// The value computed hash code for . + Task GetHashCodeAsync(T? obj, CancellationToken canceler); +} diff --git a/src/Design/Comparisons/IDeepCloneable.cs b/src/Design/Comparisons/IDeepCloneable.cs new file mode 100644 index 00000000..082f1320 --- /dev/null +++ b/src/Design/Comparisons/IDeepCloneable.cs @@ -0,0 +1,15 @@ +namespace Werecodent.CreateAndFake.Design.Comparisons; + +/// Provides self copy-by-value functionality. +/// Self-reference . +/// Should only be inherited by s. +public interface IDeepCloneable + where T : IDeepCloneable +{ + /// + /// Creates a clone where any mutation to + /// or the returned copy only alters that instance and not the other. + /// + /// The created clone that is equal by value to . + T DeepClone(); +} diff --git a/src/Design/Comparisons/IExtractable.cs b/src/Design/Comparisons/IExtractable.cs new file mode 100644 index 00000000..24c5bfa6 --- /dev/null +++ b/src/Design/Comparisons/IExtractable.cs @@ -0,0 +1,9 @@ +namespace Werecodent.CreateAndFake.Design.Comparisons; + +/// Provides identifiable content extraction. +public interface IExtractable +{ + /// Finds all identifiable data contained by . + /// The identifiable data. + IEnumerable ExtractContents(); +} diff --git a/src/Design/Comparisons/IValueEquatable.cs b/src/Design/Comparisons/IValueEquatable.cs new file mode 100644 index 00000000..d1fcef62 --- /dev/null +++ b/src/Design/Comparisons/IValueEquatable.cs @@ -0,0 +1,17 @@ +namespace Werecodent.CreateAndFake.Design.Comparisons; + +/// Provides value equality without changing the default reference equality. +public interface IValueEquatable +{ + /// Compares to by value. + /// Instance to compare with. + /// + /// if is equal to + /// by value, otherwise. + /// + bool ValuesEqual(object? other); + + /// Computes an identifying hash code for based upon value. + /// The value computed hash code for . + int GetValueHash(); +} diff --git a/src/Design/Comparisons/ReferenceComparer.cs b/src/Design/Comparisons/ReferenceComparer.cs new file mode 100644 index 00000000..619255ea --- /dev/null +++ b/src/Design/Comparisons/ReferenceComparer.cs @@ -0,0 +1,49 @@ +using System.Collections; +using System.Runtime.CompilerServices; + +namespace Werecodent.CreateAndFake.Design.Comparisons; + +/// Compares s by reference. +/// Ignores overrides to and . +public sealed class ReferenceComparer + : IComparer, + IComparer, + IEqualityComparer, + IEqualityComparer +{ + /// Default instance to use for comparing by reference. + public static ReferenceComparer Use { get; } = new(); + + /// Determines if equals by reference. + /// Instance to compare with . + /// Instance to compare with . + /// + /// if equals + /// by reference, otherwise. + /// + public new bool Equals(object? x, object? y) + { + return ReferenceEquals(x, y); + } + + /// Computes an identifying hash code for based upon reference. + /// Instance to generate a hash code for. + /// The reference computed hash code for . + public int GetHashCode(object? obj) + { + return RuntimeHelpers.GetHashCode(obj); + } + + /// Compares and by their reference hash for sorting. + /// Instance to compare with . + /// Instance to compare with . + /// + /// Positive value if > . + /// Zero if = . + /// Negative value if < . + /// + public int Compare(object? x, object? y) + { + return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); + } +} diff --git a/src/Design/Comparisons/ValueComparer.cs b/src/Design/Comparisons/ValueComparer.cs new file mode 100644 index 00000000..e5e7b4b8 --- /dev/null +++ b/src/Design/Comparisons/ValueComparer.cs @@ -0,0 +1,281 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Properties; + +namespace Werecodent.CreateAndFake.Design.Comparisons; + +/// +/// Compares s/collections by value via if possible. +/// +/// +/// Not reflection based. +public sealed class ValueComparer(int iterationLimit) + : IValueEquatable, + IComparer, + IComparer, + IComparer, + IComparer, + IComparer, + IEqualityComparer, + IEqualityComparer, + IEqualityComparer, + IEqualityComparer, + IEqualityComparer +{ + /// Hash code used for values. + public static int NullHash { get; } = 0; + + /// Starting hash code value. + public static int BaseHash { get; } = 1009; + + /// Multiplier for computing hash codes. + public static int HashMultiplier { get; } = 92821; + + /// Default instance to use for comparing by value. + public static ValueComparer Use { get; } = new(DesignDefaults.IterationLimit); + + /// Max supported size for iterating sequences. + private int IterationLimit { get; } = iterationLimit; + + /// Determines if equals by value. + /// Instance to compare with . + /// Instance to compare with . + /// + /// if equals + /// by value, otherwise. + /// + public new bool Equals(object? x, object? y) + { + if (ReferenceEquals(x, y)) + { + return true; + } + else if (x is null || y is null) + { + return false; + } + else if (x is IValueEquatable asValue) + { + return Equals(asValue, y as IValueEquatable); + } + else if (x is IEnumerable asEnum) + { + return Equals(asEnum, y as IEnumerable); + } + else + { + return x.Equals(y); + } + } + + /// + public bool Equals(IValueEquatable? x, IValueEquatable? y) + { + return x?.ValuesEqual(y) ?? y?.ValuesEqual(x) ?? true; + } + + /// + public bool Equals(IEnumerable? x, IEnumerable? y) + { + if (ReferenceEquals(x, y)) + { + return true; + } + else if (x is null || y is null) + { + return false; + } + else if (x is IDictionary asDict) + { + return Equals(asDict, y as IDictionary); + } + else + { + return EqualsBySequence(x, y); + } + } + + /// + public bool Equals(IDictionary? x, IDictionary? y) + { + if (ReferenceEquals(x, y)) + { + return true; + } + else if (x is null || y is null) + { + return false; + } + else if (x.Count != y.Count) + { + return false; + } + else + { + foreach (DictionaryEntry entry in x) + { + if (!y.Contains(entry.Key) || !Equals(entry.Value, y[entry.Key])) + { + return false; + } + } + return true; + } + } + + /// + private bool EqualsBySequence(IEnumerable x, IEnumerable y) + { + if (x is string) + { + return x.Equals(y); + } + + IEnumerator? xGen = null; + IEnumerator? yGen = null; + try + { + xGen = x.GetEnumerator(); + yGen = y.GetEnumerator(); + + for (int i = 0; xGen.MoveNext(); i++) + { + ArgumentGuard.ThrowUponIterationLimit(i, IterationLimit); + if (!yGen.MoveNext() || !Equals(xGen.Current, yGen.Current)) + { + return false; + } + } + return !yGen.MoveNext(); + } + finally + { + Disposer.Cleanup(xGen, yGen); + } + } + + /// Computes an identifying hash code for based upon value. + /// Bundled s to generate a single hash code for. + /// The value computed hash code for . + public int GetHashCode(params IEnumerable? items) + { + return GetHashCode((IEnumerable?)items); + } + + /// Computes an identifying hash code for based upon value. + /// Instance to generate a hash code for. + /// The value computed hash code for . + public int GetHashCode(object? obj) + { + if (obj is null) + { + return NullHash; + } + else if (obj is IValueEquatable asValue) + { + return GetHashCode(asValue); + } + else if (obj is IEnumerable asEnum) + { + return GetHashCode(asEnum); + } + else + { + return obj.GetHashCode(); + } + } + + /// + public int GetHashCode(IValueEquatable? obj) + { + return obj?.GetValueHash() ?? NullHash; + } + + /// + public int GetHashCode(IEnumerable? obj) + { + if (obj is null) + { + return NullHash; + } + else if (obj is string) + { + return obj.GetHashCode(); + } + else if (obj is IDictionary asDict) + { + return GetHashCode(asDict); + } + else + { + int i = 0; + int hash = BaseHash; + foreach (object item in obj) + { + ArgumentGuard.ThrowUponIterationLimit(i++, IterationLimit); + hash = hash * HashMultiplier + GetHashCode(item); + } + return hash; + } + } + + /// + public int GetHashCode(IDictionary? obj) + { + if (obj is null) + { + return NullHash; + } + + int hash = BaseHash; + foreach (DictionaryEntry item in obj) + { + hash += GetHashCode(item.Key); + hash += GetHashCode(item.Value); + } + return hash; + } + + /// Compares and by their value hash for sorting. + /// Instance to compare with . + /// Instance to compare with . + /// + /// Positive value if > . + /// Zero if = . + /// Negative value if < . + /// + public int Compare(object? x, object? y) + { + return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); + } + + /// + public int Compare(IValueEquatable? x, IValueEquatable? y) + { + return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); + } + + /// + public int Compare(IEnumerable? x, IEnumerable? y) + { + return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); + } + + /// + public int Compare(IDictionary? x, IDictionary? y) + { + return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y)); + } + + /// + public bool ValuesEqual(object? other) + { + return (other as ValueComparer)?.IterationLimit == IterationLimit; + } + + /// + public int GetValueHash() + { + return IterationLimit; + } +} diff --git a/src/Design/Comparisons/ValueComparer{T}.cs b/src/Design/Comparisons/ValueComparer{T}.cs new file mode 100644 index 00000000..8e02430f --- /dev/null +++ b/src/Design/Comparisons/ValueComparer{T}.cs @@ -0,0 +1,99 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Comparisons; + +/// Compares s/collections by value. +/// The supported . +/// +/// Not reflection based. +public sealed class ValueComparer(ValueComparer comparer) + : IValueEquatable, + ITypeSupporter, + IComparer, + IComparer>, + IEqualityComparer, + IEqualityComparer> + where T : IValueEquatable +{ + /// + public static ValueComparer Use { get; } = new(ValueComparer.Use); + + /// Handles the actual comparisons. + private readonly ValueComparer _comparer = + comparer ?? throw new ArgumentNullException(nameof(comparer)); + + /// + public Type? SupportedType { get; } = typeof(T); + + /// + public bool Equals(T? x, T? y) + { + return _comparer.Equals(x, y); + } + + /// + public bool Equals(IEnumerable? x, IEnumerable? y) + { + return _comparer.Equals(x, y); + } + + /// + public bool Equals(IDictionary? x, IDictionary? y) + { + return _comparer.Equals(x, y); + } + + /// + public int GetHashCode(T? obj) + { + return _comparer.GetHashCode(obj); + } + + /// + public int GetHashCode(IEnumerable? obj) + { + return _comparer.GetHashCode(obj); + } + + /// + public int GetHashCode(IDictionary? obj) + { + return _comparer.GetHashCode(obj); + } + + /// + public int Compare(T? x, T? y) + { + return _comparer.Compare(x, y); + } + + /// + public int Compare(IEnumerable? x, IEnumerable? y) + { + return _comparer.Compare(x, y); + } + + /// + public int Compare(IDictionary? x, IDictionary? y) + { + return _comparer.Compare(x, y); + } + + /// + public bool ValuesEqual(object? other) + { + return _comparer.ValuesEqual((other as ValueComparer)?._comparer); + } + + /// + public int GetValueHash() + { + return _comparer.GetHashCode(); + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Design/Content/AsyncHashSet.cs b/src/Design/Content/AsyncHashSet.cs new file mode 100644 index 00000000..b4f803cf --- /dev/null +++ b/src/Design/Content/AsyncHashSet.cs @@ -0,0 +1,133 @@ +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// +public static class AsyncHashSet +{ + /// Creates a set with initial . + /// Item content . + /// Initial contents for the set. + /// + /// Max number of items to iterate before throwing. + /// Aborts execution if triggered. + /// The created set. + public static AsyncHashSet CreateFromAsync( + IAsyncEnumerable contents, + IAsyncEqualityComparer comparer, + int iterationLimit, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(comparer); + + async Task>> setInitialContentsAsync() + { + Dictionary> results = []; + + await AsyncSeriesHelper + .ForEachAsync(contents, iterationLimit, canceler, async item => + _ = await AsyncHashSet + .AddToAsync(results, item, comparer, canceler) + .ConfigureAwait(false) + ) + .ConfigureAwait(false); + + return results; + } + + return new AsyncHashSet(setInitialContentsAsync(), comparer); + } + + /// + public static AsyncHashSet CreateFromAsync( + IEnumerable contents, + IAsyncEqualityComparer comparer, + int iterationLimit, + CancellationToken canceler + ) + { + return CreateFromAsync( + AsyncSeriesHelper.CreateFromAsync(contents, iterationLimit), + comparer, + iterationLimit, + canceler + ); + } + + /// + public static AsyncHashSet CreateFromAsync( + IAsyncEnumerable> contents, + IAsyncEqualityComparer comparer, + int iterationLimit, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(comparer); + + async Task>> setInitialContentsAsync() + { + Dictionary> results = []; + + await AsyncSeriesHelper + .ForEachAsync(contents, iterationLimit, canceler, pair => + { + if (results.TryGetValue(pair.Key, out IList? list)) + { + list.Add(pair.Value); + } + else + { + results.Add(pair.Key, [pair.Value]); + } + }) + .ConfigureAwait(false); + + return results; + } + + return new AsyncHashSet(setInitialContentsAsync(), comparer); + } + + /// + /// Uses to generate items until the resulting hash size is . + /// + /// Size of collection to create. + /// Method used to generate content. + /// + internal static AsyncHashSet CreateViaGeneratorAsync( + int size, + Func factory, + IAsyncEqualityComparer comparer, + int iterationLimit, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(factory, comparer); + + async Task>> setInitialContentsAsync() + { + Dictionary> results = []; + + int currentSize = 0; + for (int i = 0; currentSize < size; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i, iterationLimit); + + canceler.ThrowIfCancellationRequested(); + if ( + await AsyncHashSet + .AddToAsync(results, (T)factory.Invoke(), comparer, canceler) + .ConfigureAwait(false) + ) + { + currentSize += 1; + } + } + + return results; + } + + return new AsyncHashSet(setInitialContentsAsync(), comparer); + } +} diff --git a/src/Design/Content/AsyncHashSet{T}.cs b/src/Design/Content/AsyncHashSet{T}.cs new file mode 100644 index 00000000..0a2800a6 --- /dev/null +++ b/src/Design/Content/AsyncHashSet{T}.cs @@ -0,0 +1,256 @@ +using System.Runtime.CompilerServices; +using System.Text; +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// +public sealed class AsyncHashSet : IAsyncSet +{ + /// Current contents for the set. + private readonly Task>> _contents; + + /// + public IAsyncEqualityComparer Comparer { get; } + + /// Creates an empty set. + /// + public AsyncHashSet(IAsyncEqualityComparer comparer) + : this( + Task.FromResult>>(new Dictionary>()), + comparer + ) { } + + /// Creates a populated set. + /// + /// + internal AsyncHashSet( + Task>> contents, + IAsyncEqualityComparer comparer + ) + { + ArgumentGuard.ThrowIfNull(contents, comparer); + + Comparer = comparer; + _contents = contents; + } + + /// + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + async IAsyncEnumerable iterateAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + foreach (T item in (await _contents.ConfigureAwait(false)).SelectMany(x => x.Value)) + { + cancellationToken.ThrowIfCancellationRequested(); + yield return item; + } + } + + return iterateAsync().GetAsyncEnumerator(cancellationToken); + } + + /// + public IAsyncEnumerable> ByHashesAsync(CancellationToken canceler) + { + return IterateHashesAsync(canceler); + } + + /// + private async IAsyncEnumerable> IterateHashesAsync( + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + canceler.ThrowIfCancellationRequested(); + foreach (KeyValuePair> row in await _contents.ConfigureAwait(false)) + { + foreach (T item in row.Value) + { + canceler.ThrowIfCancellationRequested(); + yield return new KeyValuePair(row.Key, item); + } + } + } + + /// + public async Task ContainsKeyAsync(int key, CancellationToken canceler) + { + return (await _contents.ConfigureAwait(false)).ContainsKey(key); + } + + /// + public async Task ContainsAsync(T item, CancellationToken canceler) + { + int hash = await Comparer.GetHashCodeAsync(item, canceler).ConfigureAwait(false); + + return await ContainsAsync(new KeyValuePair(hash, item), canceler) + .ConfigureAwait(false); + } + + /// + public async Task ContainsAsync(KeyValuePair entry, CancellationToken canceler) + { + if ((await _contents.ConfigureAwait(false)).TryGetValue(entry.Key, out IList? data)) + { + foreach (T found in data) + { + if (await Comparer.EqualsAsync(found, entry.Value, canceler).ConfigureAwait(false)) + { + return true; + } + } + } + return false; + } + + /// + public async Task AddAsync(T item, CancellationToken canceler) + { + return await AddToAsync(await _contents.ConfigureAwait(false), item, Comparer, canceler) + .ConfigureAwait(false); + } + + internal static async Task AddToAsync( + IDictionary> contents, + T item, + IAsyncEqualityComparer comparer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(contents, comparer); + + int hash = await comparer.GetHashCodeAsync(item, canceler).ConfigureAwait(false); + if (contents.TryGetValue(hash, out IList? data)) + { + foreach (T found in data) + { + if (await comparer.EqualsAsync(found, item, canceler).ConfigureAwait(false)) + { + return false; + } + } + data.Add(item); + return true; + } + else + { + contents.Add(hash, [item]); + return true; + } + } + + /// + public IAsyncEnumerable FindMatchesInAsync( + IAsyncSet collection, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(collection); + + return IterateFindMatchesInAsync(collection, canceler); + } + + /// + private async IAsyncEnumerable IterateFindMatchesInAsync( + IAsyncSet collection, + [EnumeratorCancellation] CancellationToken token = default + ) + { + IDictionary> contents = await _contents.ConfigureAwait(false); + + await foreach ( + KeyValuePair item in collection.ByHashesAsync(token).ConfigureAwait(false) + ) + { + if (contents.TryGetValue(item.Key, out IList? match)) + { + foreach (T found in match) + { + if (await Comparer.EqualsAsync(item.Value, found, token).ConfigureAwait(false)) + { + yield return found; + } + } + } + } + } + + /// + public IAsyncEnumerable FindMissingFromAsync( + IAsyncSet collection, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(collection); + + return IterateFindMissingFromAsync(collection, canceler); + } + + /// + private async IAsyncEnumerable IterateFindMissingFromAsync( + IAsyncSet collection, + [EnumeratorCancellation] CancellationToken token = default + ) + { + IDictionary> contents = await _contents.ConfigureAwait(false); + + token.ThrowIfCancellationRequested(); + await foreach ( + KeyValuePair item in collection.ByHashesAsync(token).ConfigureAwait(false) + ) + { + bool missing = true; + + if (contents.TryGetValue(item.Key, out IList? match)) + { + foreach (T found in match) + { + if (await Comparer.EqualsAsync(item.Value, found, token).ConfigureAwait(false)) + { + missing = false; + break; + } + } + } + + token.ThrowIfCancellationRequested(); + if (missing) + { + yield return item.Value; + } + } + } + + /// + public override string ToString() + { + if (!_contents.IsCompleted) + { + return "AsyncHashSet: { 'Contents currently unresolved' }"; + } + +#pragma warning disable VSTHRD002, VSTHRD104 // Completion verified. + IDictionary> contents = _contents.Result; +#pragma warning restore VSTHRD002, VSTHRD104 + + if (contents.Count == 0) + { + return "AsyncHashSet: { }"; + } + + StringBuilder text = new(); + + text.Append("AsyncHashSet: {"); + foreach (KeyValuePair> row in contents) + { + foreach (T item in row.Value) + { + text.AppendLine().Append(" ").Append(row.Key).Append(", ").Append(item); + } + } + text.AppendLine().Append('}'); + + return text.ToString(); + } +} diff --git a/src/Design/Content/AsyncList.cs b/src/Design/Content/AsyncList.cs new file mode 100644 index 00000000..3bcc2d12 --- /dev/null +++ b/src/Design/Content/AsyncList.cs @@ -0,0 +1,51 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// Provides a repeatable asynchronous source. +/// The 's item . +public sealed class AsyncList : IAsyncEnumerable +{ + /// Backing content for the async enumerator. + public IEnumerable Content { get; } + + /// + /// + /// Max number of items to iterate before throwing. + public AsyncList(IEnumerable content, int iterationLimit) + { + List list = []; + + int i = 0; + foreach (T item in content ?? throw new ArgumentNullException(nameof(content))) + { + ArgumentGuard.ThrowUponIterationLimit(i++, iterationLimit); + list.Add(item); + } + + Content = list; + } + + /// + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + async IAsyncEnumerable iterateAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + foreach (T item in Content) + { + await Task.Delay(0, cancellationToken).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + yield return item; + } + } + + return iterateAsync().GetAsyncEnumerator(cancellationToken); + } + + /// + public override string ToString() + { + return $"{GenericConverter.ExpandName(GetType())}[{Content.Count()}]"; + } +} diff --git a/src/Design/Content/AsyncSeriesHelper.cs b/src/Design/Content/AsyncSeriesHelper.cs new file mode 100644 index 00000000..7a3c0bcc --- /dev/null +++ b/src/Design/Content/AsyncSeriesHelper.cs @@ -0,0 +1,280 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// Provides common patterns. +/// Manually required as .NET 10 breaks System.Linq.Async compatibility. +public static class AsyncSeriesHelper +{ + /// Converts the to an . + /// The 's item . + /// Series to convert via iteration. + /// Max number of items to iterate before throwing. + /// Asynchronous iteration of the . + [return: NotNullIfNotNull(nameof(collection))] + public static IAsyncEnumerable? CreateFromAsync( + IEnumerable? collection, + int iterationLimit + ) + { + if (collection == null) + { + return null; + } + else + { + return new AsyncList(collection, iterationLimit); + } + } + + /// Determines if the has any items. + /// The 's item . + /// Series to check for an item via iteration. + /// Aborts execution if triggered. + /// + /// if the + /// has at least one item, otherwise. + /// + public static async Task HasAnyAsync( + [NotNullWhen(true)] IAsyncEnumerable? collection, + CancellationToken canceler + ) + { + canceler.ThrowIfCancellationRequested(); + if (collection == null) + { + return false; + } + await foreach (T _ in collection.WithCancellation(canceler).ConfigureAwait(false)) + { + return true; + } + + canceler.ThrowIfCancellationRequested(); + return false; + } + + /// Determines if the has no items. + /// The 's item . + /// Series to check for an item via iteration. + /// Aborts execution if triggered. + /// + /// if the has no + /// items or is , otherwise. + /// + public static async Task HasNoneAsync( + [NotNullWhen(true)] IAsyncEnumerable? collection, + CancellationToken canceler + ) + { + canceler.ThrowIfCancellationRequested(); + if (collection == null) + { + return true; + } + await foreach (T _ in collection.WithCancellation(canceler).ConfigureAwait(false)) + { + return false; + } + + canceler.ThrowIfCancellationRequested(); + return true; + } + +#pragma warning disable CA1068 // Token is relevant to the core functionality for the method. + + /// + /// Safely executes on the contents of the . + /// + /// The 's item . + /// Series to iterate. + /// Max number of items to iterate before throwing. + /// Aborts execution if triggered. + /// Behavior to run on each item. + /// A that represents the asynchronous operation. + /// Properly handles cancellation and prevents infinite iteration. + /// + /// If the size is >= iterationLimit. + /// + public static Task ForEachAsync( + IAsyncEnumerable? collection, + int iterationLimit, + CancellationToken canceler, + Action itemHandler + ) + { + ArgumentGuard.ThrowIfNull(itemHandler); + return ForEachAsync(collection, iterationLimit, canceler, item => + { + itemHandler(item); + return Task.CompletedTask; + }); + } + + /// + public static async Task ForEachAsync( + IAsyncEnumerable? collection, + int iterationLimit, + CancellationToken canceler, + Func itemHandler + ) + { + ArgumentGuard.ThrowIfNull(itemHandler); + if (collection == null) + { + return; + } + + canceler.ThrowIfCancellationRequested(); + + int i = 0; + await foreach (T item in collection.WithCancellation(canceler).ConfigureAwait(false)) + { + ArgumentGuard.ThrowUponIterationLimit(i++, iterationLimit); + canceler.ThrowIfCancellationRequested(); + await itemHandler(item).ConfigureAwait(false); + } + + canceler.ThrowIfCancellationRequested(); + } + + /// + public static IAsyncEnumerable SelectAsync( + IAsyncEnumerable? collection, + int iterationLimit, + CancellationToken canceler, + Func itemHandler + ) + { + ArgumentGuard.ThrowIfNull(itemHandler); + return SelectAsync(collection, iterationLimit, canceler, item => + Task.FromResult(itemHandler(item)) + ); + } + + /// Sequentially modifies the . + /// The 's item . + /// The item . + /// + public static IAsyncEnumerable SelectAsync( + IAsyncEnumerable? collection, + int iterationLimit, + CancellationToken canceler, + Func> itemHandler + ) + { + ArgumentGuard.ThrowIfNull(itemHandler); + + return IterateSelectAsync(collection, iterationLimit, itemHandler, canceler); + } + + /// + private static async IAsyncEnumerable IterateSelectAsync( + IAsyncEnumerable? collection, + int iterationLimit, + Func> itemHandler, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + if (collection == null) + { + yield break; + } + + canceler.ThrowIfCancellationRequested(); + + int i = 0; + await foreach (TIn item in collection.WithCancellation(canceler).ConfigureAwait(false)) + { + ArgumentGuard.ThrowUponIterationLimit(i++, iterationLimit); + canceler.ThrowIfCancellationRequested(); + yield return await itemHandler(item).ConfigureAwait(false); + } + } + +#pragma warning restore CA1068 + + /// Converts the to an . + /// The 's item . + /// Series to convert via iteration. + /// Max number of items to iterate before throwing. + /// Aborts execution if triggered. + /// + /// Contents of the as an ; + /// an empty list if the is . + /// + public static async Task> ToListAsync( + IAsyncEnumerable? collection, + int iterationLimit, + CancellationToken canceler + ) + { + canceler.ThrowIfCancellationRequested(); + + List results = []; + if (collection != null) + { + int i = 0; + await foreach (T value in collection.WithCancellation(canceler).ConfigureAwait(false)) + { + ArgumentGuard.ThrowUponIterationLimit(i++, iterationLimit); + results.Add(value); + canceler.ThrowIfCancellationRequested(); + } + } + + canceler.ThrowIfCancellationRequested(); + return results; + } + + /// + /// Creates an empty that triggers + /// cancellation via the upon attempted iteration. + /// + /// An empty asynchronous series. + /// + public static async IAsyncEnumerable CreateCancelingIterationAsync( + CancellationTokenSource source + ) + { + ArgumentGuard.ThrowIfNull(source); + await TriggerCancellationAsync(source).ConfigureAwait(false); + yield break; + } + + /// + /// Converts the to an and + /// triggers cancellation via the after the first yielded value. + /// + /// Asynchronous iteration of the . + /// + public static async IAsyncEnumerable CreateCancelingIterationAsync( + IEnumerable collection, + CancellationTokenSource source + ) + { + ArgumentGuard.ThrowIfNull(collection, source); + + bool notCanceled = true; + int i = 0; + foreach (T value in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i++); + + yield return value; + if (notCanceled) + { + await TriggerCancellationAsync(source).ConfigureAwait(false); + notCanceled = false; + } + } + } + + /// + public static Task TriggerCancellationAsync(CancellationTokenSource source) + { + return MaybeAsyncCanceler.Use.TriggerCancellationAsync(source); + } +} diff --git a/src/Design/Content/AsyncSeriesHelper{T}.cs b/src/Design/Content/AsyncSeriesHelper{T}.cs new file mode 100644 index 00000000..e3c39ec9 --- /dev/null +++ b/src/Design/Content/AsyncSeriesHelper{T}.cs @@ -0,0 +1,34 @@ +namespace Werecodent.CreateAndFake.Design.Content; + +/// Provides common patterns. +/// +public static class AsyncSeriesHelper +{ + /// Cached series with no elements. + public static IAsyncEnumerable Empty { get; } = new EmptyAsyncEnumerator(); + + /// Represents a series with no elements. + private sealed class EmptyAsyncEnumerator : IAsyncEnumerable, IAsyncEnumerator + { + /// + public T Current => default!; + + /// + public ValueTask MoveNextAsync() + { + return new ValueTask(false); + } + + /// + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return this; + } + + /// + public ValueTask DisposeAsync() + { + return default; + } + } +} diff --git a/src/Design/Content/CustomLock.cs b/src/Design/Content/CustomLock.cs new file mode 100644 index 00000000..d4fa9da2 --- /dev/null +++ b/src/Design/Content/CustomLock.cs @@ -0,0 +1,26 @@ +namespace Werecodent.CreateAndFake.Design.Content; + +#pragma warning disable IDE0001 // False positive: Lock is not always CustomLock. + +/// Type for s to prevent conflicts. +/// +/// System.Threading.Lock should be used past .NET 9. +public sealed class CustomLock(Guid? id = null) +{ + /// Lock identifier. + public Guid Id { get; } = id ?? Guid.NewGuid(); + + /// + public override bool Equals(object? obj) + { + return Id == (obj as CustomLock)?.Id; + } + + /// + public override int GetHashCode() + { + return Id.GetHashCode(); + } +} + +#pragma warning restore diff --git a/src/Design/Content/Disposer.cs b/src/Design/Content/Disposer.cs new file mode 100644 index 00000000..01c490f4 --- /dev/null +++ b/src/Design/Content/Disposer.cs @@ -0,0 +1,42 @@ +namespace Werecodent.CreateAndFake.Design.Content; + +/// Cleans and objects. +public static class Disposer +{ + /// Disposes all s in the . + /// Collection with potential s to clean up. + public static void Cleanup(params ICollection? series) + { + foreach (object? item in series ?? []) + { + if (item is IDisposable disposable) + { + disposable.Dispose(); + } + } + } + + /// + /// Disposes all s and + /// s in the . + /// + /// + /// Collection with potential s and/or s to clean up. + /// + /// A that represents the asynchronous operation. + /// Will dispose an instance via if both are inherited. + public static async Task CleanupAsync(params ICollection? series) + { + foreach (object? item in series ?? []) + { + if (item is IAsyncDisposable asyncDisposable) + { + await asyncDisposable.DisposeAsync().ConfigureAwait(false); + } + else if (item is IDisposable disposable) + { + disposable.Dispose(); + } + } + } +} diff --git a/src/Design/Content/ExcludeFromCreateAndFakeAttribute.cs b/src/Design/Content/ExcludeFromCreateAndFakeAttribute.cs new file mode 100644 index 00000000..67c8a5f9 --- /dev/null +++ b/src/Design/Content/ExcludeFromCreateAndFakeAttribute.cs @@ -0,0 +1,12 @@ +namespace Werecodent.CreateAndFake.Design.Content; + +/// +/// Prevents the framework from dynamically +/// including the attached via reflection. +/// +/// Does not prevent use if directly specified by callers. +[AttributeUsage( + AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, + Inherited = false +)] +public sealed class ExcludeFromCreateAndFakeAttribute : Attribute; diff --git a/src/Design/Content/IAsyncSet.cs b/src/Design/Content/IAsyncSet.cs new file mode 100644 index 00000000..eb854540 --- /dev/null +++ b/src/Design/Content/IAsyncSet.cs @@ -0,0 +1,53 @@ +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// Collection using asynchronously calculated hashes and equality. +/// +public interface IAsyncSet : IAsyncEnumerable +{ + /// Determines value equality for the set. + IAsyncEqualityComparer Comparer { get; } + + /// Tries to add to the set. + /// Instance to add. + /// Aborts execution if triggered. + /// if added, if it's already been added. + Task AddAsync(T item, CancellationToken canceler); + + /// Determines if is in the set as a key. + /// Instance to check for. + /// Aborts execution if triggered. + /// if found, otherwise. + Task ContainsKeyAsync(int key, CancellationToken canceler); + + /// Determines if is in the set. + /// Instance to check for. + /// Aborts execution if triggered. + /// if found, otherwise. + Task ContainsAsync(T item, CancellationToken canceler); + + /// Determines if the is in the set. + /// Instance to check for. + /// Aborts execution if triggered. + /// if found, otherwise. + Task ContainsAsync(KeyValuePair entry, CancellationToken canceler); + + /// Enumerates all contents with their value hash. + /// Aborts execution if triggered. + /// The current contents. + /// Optimization for utilizing the 'find' methods. + IAsyncEnumerable> ByHashesAsync(CancellationToken canceler); + + /// Finds common items with the . + /// Set to check. + /// Aborts execution if triggered. + /// Each common item. + IAsyncEnumerable FindMatchesInAsync(IAsyncSet collection, CancellationToken canceler); + + /// Finds items missing that are present in . + /// Set to check. + /// Aborts execution if triggered. + /// Each missing item. + IAsyncEnumerable FindMissingFromAsync(IAsyncSet collection, CancellationToken canceler); +} diff --git a/src/Design/Content/Invoker.cs b/src/Design/Content/Invoker.cs new file mode 100644 index 00000000..e7eac3c9 --- /dev/null +++ b/src/Design/Content/Invoker.cs @@ -0,0 +1,38 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// Provides common patterns around executing code. +public static class Invoker +{ + /// Ensures the result is completed. + /// Potentially wrapped data. + /// The unwrapped result. + public static async Task AwaitAsync(Task task) + { + ArgumentGuard.ThrowIfNull(task); + + await task.ConfigureAwait(false); + + Type resultType = task.GetType(); + PropertyInfo? resultProp = TypeDescriber + .For(resultType) + .Properties.OnlyPublic.FirstOrDefault(p => p.Name == "Result"); + + if ( + !GenericConverter + .ExpandName(resultType) + .Contains("VoidTaskResult", StringComparison.Ordinal) + && resultProp != null + ) + { + // await ((dynamic)result) crashes legacy .NET. + return resultProp.GetValue(task); + } + else + { + return VoidType.Instance; + } + } +} diff --git a/src/Design/Content/MaybeAsyncCanceler.cs b/src/Design/Content/MaybeAsyncCanceler.cs new file mode 100644 index 00000000..3317b822 --- /dev/null +++ b/src/Design/Content/MaybeAsyncCanceler.cs @@ -0,0 +1,50 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// Attempts to cancel s via . +internal sealed class MaybeAsyncCanceler +{ + /// Instance to use for canceling s. + public static MaybeAsyncCanceler Use { get; } = + new(typeof(CancellationTokenSource).GetMethod("CancelAsync")); + + /// Delegate for triggering asynchronous cancellation. + /// when unavailable for the executing .NET version. + private readonly Func? _canceler; + + /// + /// + /// Method for triggering asynchronous cancellation on s. + /// + /// Do not call; exposed to enable testing. + internal MaybeAsyncCanceler(MethodInfo? tokenAsyncMethod) + { + _canceler = (Func?) + tokenAsyncMethod?.CreateDelegate(typeof(Func)); + } + + /// + /// Handles canceling a token via its using if possible. + /// + /// Owner of the to cancel. + /// A that represents the asynchronous operation. + internal async Task TriggerCancellationAsync(CancellationTokenSource source) + { + ArgumentGuard.ThrowIfNull(source); + + if (!source.IsCancellationRequested) + { + if (_canceler != null) + { + await _canceler(source).ConfigureAwait(false); + } + else + { +#pragma warning disable AsyncFixer02, S6966, CA1849, MA0042, VSTHRD103 // CancelAsync not available. + source.Cancel(); +#pragma warning restore AsyncFixer02, S6966, CA1849, MA0042, VSTHRD103 + } + } + } +} diff --git a/src/Design/Content/PlainAsyncDisposable.cs b/src/Design/Content/PlainAsyncDisposable.cs new file mode 100644 index 00000000..de7b189c --- /dev/null +++ b/src/Design/Content/PlainAsyncDisposable.cs @@ -0,0 +1,27 @@ +namespace Werecodent.CreateAndFake.Design.Content; + +/// Simple implementation for . +/// Result for when the instance has not been disposed. +/// Important for .NET 4.8 to have a creatable for the framework. +public sealed class PlainAsyncDisposable(string data) : IAsyncDisposable +{ + /// If has been called. + private bool _isDisposed = false; + + /// Access the held data if this has not been disposed. + /// The held data. + /// If was called before this. + public string GrabData() + { + return !_isDisposed + ? data + : throw new ObjectDisposedException("Instance was disposed before accessing its data."); + } + + /// + public ValueTask DisposeAsync() + { + _isDisposed = true; + return new ValueTask(Task.CompletedTask); + } +} diff --git a/src/Design/Content/SingleCallValueTaskSource.cs b/src/Design/Content/SingleCallValueTaskSource.cs new file mode 100644 index 00000000..4a5dd027 --- /dev/null +++ b/src/Design/Content/SingleCallValueTaskSource.cs @@ -0,0 +1,118 @@ +using System.Reflection; +using System.Threading.Tasks.Sources; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// Used to enforce resolving a only once. +/// +public sealed class SingleCallValueTaskSource(Guid? id = null) + : IDeepCloneable, + IEquatable, + IValueTaskSource, + IValueEquatable +{ + /// How to access the source via the containing . + private static readonly FieldInfo _TaskSourceGrabber = typeof(ValueTask).GetField( + "_obj", + BindingFlags.Instance | BindingFlags.NonPublic + )!; + + /// How to access a 's token. + private static readonly FieldInfo _TaskTokenGrabber = typeof(ValueTask).GetField( + "_token", + BindingFlags.Instance | BindingFlags.NonPublic + )!; + + /// Identifier representing task. + public Guid Id { get; } = id ?? Guid.NewGuid(); + + /// If the result has already been retrieved. + private bool _called = false; + + /// + public void GetResult(short token) + { + if (_called) + { + throw new ValueTaskRepeatedAccessException(token); + } + else + { + _called = true; + } + } + + /// + public ValueTaskSourceStatus GetStatus(short token) + { + return ValueTaskSourceStatus.Succeeded; + } + + /// + public void OnCompleted( + Action continuation, + object? state, + short token, + ValueTaskSourceOnCompletedFlags flags + ) + { + throw new NotSupportedException(); + } + + /// + public bool Equals(SingleCallValueTaskSource? other) + { + return other is not null && Id == other.Id; + } + + /// + public override bool Equals(object? obj) + { + return Equals(obj as SingleCallValueTaskSource); + } + + /// + public override int GetHashCode() + { + return Id.GetHashCode(); + } + + /// + public bool ValuesEqual(object? other) + { + return Equals(other); + } + + /// + public int GetValueHash() + { + return GetHashCode(); + } + + /// + public SingleCallValueTaskSource DeepClone() + { + return new SingleCallValueTaskSource(Id); + } + + /// Retrieves the source from a . + /// The task potentially containing the source. + /// + /// The 's source if it's a , + /// otherwise. + /// + public static SingleCallValueTaskSource? ExtractFrom(ValueTask task) + { + return _TaskSourceGrabber.GetValue(task) as SingleCallValueTaskSource; + } + + /// Retrieves the token from a . + /// The task containing the token. + /// The 's opaque token. + public static short ExtractTokenFrom(ValueTask task) + { + return (short)_TaskTokenGrabber.GetValue(task)!; + } +} diff --git a/src/Design/Content/SingleCallValueTaskSource{T}.cs b/src/Design/Content/SingleCallValueTaskSource{T}.cs new file mode 100644 index 00000000..dc80043e --- /dev/null +++ b/src/Design/Content/SingleCallValueTaskSource{T}.cs @@ -0,0 +1,79 @@ +using System.Reflection; +using System.Threading.Tasks.Sources; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Content; + +/// Used to enforce resolving a only once. +/// The contained result . +/// +public sealed class SingleCallValueTaskSource(T rawResult) : IValueTaskSource +{ + /// How to access the source via the containing . + private static readonly FieldInfo _TaskSourceGrabber = typeof(ValueTask).GetField( + "_obj", + BindingFlags.Instance | BindingFlags.NonPublic + )!; + + /// How to access a 's token. + private static readonly FieldInfo _TaskTokenGrabber = typeof(ValueTask).GetField( + "_token", + BindingFlags.Instance | BindingFlags.NonPublic + )!; + + /// Stored result to return. + public T RawResult { get; } = rawResult; + + /// If the result has already been retrieved. + private bool _called = false; + + /// + public T GetResult(short token) + { + if (_called) + { + throw new ValueTaskRepeatedAccessException(token); + } + else + { + _called = true; + return RawResult; + } + } + + /// + public ValueTaskSourceStatus GetStatus(short token) + { + return ValueTaskSourceStatus.Succeeded; + } + + /// + public void OnCompleted( + Action continuation, + object? state, + short token, + ValueTaskSourceOnCompletedFlags flags + ) + { + throw new NotSupportedException(); + } + + /// Retrieves the source from a . + /// The task potentially containing the source. + /// + /// The 's source if it's a , + /// otherwise. + /// + public static SingleCallValueTaskSource? ExtractFrom(ValueTask task) + { + return _TaskSourceGrabber.GetValue(task) as SingleCallValueTaskSource; + } + + /// Retrieves the token from a . + /// The task containing the token. + /// The 's opaque token. + public static short ExtractTokenFrom(ValueTask task) + { + return (short)_TaskTokenGrabber.GetValue(task)!; + } +} diff --git a/src/Design/Content/VoidType.cs b/src/Design/Content/VoidType.cs new file mode 100644 index 00000000..effde151 --- /dev/null +++ b/src/Design/Content/VoidType.cs @@ -0,0 +1,17 @@ +namespace Werecodent.CreateAndFake.Design.Content; + +/// Represents . +public sealed class VoidType +{ + /// Singleton instance to use. + public static VoidType Instance { get; } = new VoidType(); + + /// + private VoidType() { } + + /// + public override string ToString() + { + return "'void'"; + } +} diff --git a/src/Design/Context/BaseDataContext.cs b/src/Design/Context/BaseDataContext.cs new file mode 100644 index 00000000..85f6ded0 --- /dev/null +++ b/src/Design/Context/BaseDataContext.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.Design.Randomization; + +namespace Werecodent.CreateAndFake.Design.Context; + +/// Bundles associated random values from data pools. +/// +public abstract class BaseDataContext(IRandom gen) +{ + /// + protected IRandom Gen { get; } = gen ?? throw new ArgumentNullException(nameof(gen)); +} diff --git a/src/Design/Context/PersonContext.cs b/src/Design/Context/PersonContext.cs new file mode 100644 index 00000000..996a3d77 --- /dev/null +++ b/src/Design/Context/PersonContext.cs @@ -0,0 +1,30 @@ +using Werecodent.CreateAndFake.Design.Data; +using Werecodent.CreateAndFake.Design.Randomization; + +namespace Werecodent.CreateAndFake.Design.Context; + +/// Bundled random values for a person. +/// +public sealed class PersonContext(IRandom gen) : BaseDataContext(gen) +{ + /// Name fragment. + private readonly Lazy //. + _firstName = new(() => gen.NextItem(NameData.Values)), + _middleName = new(() => gen.NextItem(NameData.Values)), + _lastName = new(() => gen.NextItem(NameData.Values)); + + /// First name for the person. + public string FirstName => _firstName.Value; + + /// Middle name for the person. + public string MiddleName => _middleName.Value; + + /// Last name for the person. + public string LastName => _lastName.Value; + + /// First and last name for the person. + public string FullName => $"{FirstName} {LastName}"; + + /// Initials for the person's name. + public string Initials => $"{FirstName[0]}{MiddleName[0]}{LastName[0]}"; +} diff --git a/src/Design/CreateAndFake.Design.csproj b/src/Design/CreateAndFake.Design.csproj new file mode 100644 index 00000000..d8084d28 --- /dev/null +++ b/src/Design/CreateAndFake.Design.csproj @@ -0,0 +1,21 @@ + + + + net11.0;net10.0;netstandard2.0 + + + + LEGACY + + + + A C# class library that handles mocking, test data generation, and validation. + + + + + + + + + diff --git a/src/CreateAndFake/Design/Data/NameData.cs b/src/Design/Data/NameData.cs similarity index 93% rename from src/CreateAndFake/Design/Data/NameData.cs rename to src/Design/Data/NameData.cs index 9599aa02..64e87866 100644 --- a/src/CreateAndFake/Design/Data/NameData.cs +++ b/src/Design/Data/NameData.cs @@ -1,1053 +1,1058 @@ -namespace CreateAndFake.Design.Data; - -/// Provides a pool of names. -public static class NameData -{ - /// Possible names for randomization. - public static ICollection Values { get; } = - [ - // Aa - "Aaron", - // Ab - "Abby", - // Ac - "Acrid", - // Ad - "Adrian", - "Adrin", - // Ae - // Af - "Afton", - // Ag - "Agustus", - // Ah - "Ahbed", - // Ai - "Ailieen", - // Aj - "Ajax", - // Ak - "Akronis", - // Al - "Alabastr", - "Alyssa", - // Am - "Amanda", - "Amelia", - // An - "Andrew", - "Andy", - // Ao - "Aonis", - // Ap - "Appa", - // Aq - "Aquarius", - // Ar - "Aragorn", - "Ariel", - // As - "Astra", - // At - "Atta", - // Au - "Audre", - // Av - "Ava", - "Avrin", - // Aw - "Awen", - // Ax - "Axon", - // Ay - "Ayer", - // Az - "Azandria", - // Ba - "Babe", - "Bane", - "Barry", - // Bb - // Bc - // Bd - // Be - "Ben", - "Benji", - "Benjamin", - // Bf - // Bg - // Bh - // Bi - "Bingo", - "Bishop", - // Bj - "Bjorn", - // Bk - // Bl - "Blaine", - "Blake", - // Bm - // Bn - // Bo - "Bobby", - "Boris", - // Bp - // Bq - // Br - "Brent", - "Brianna", - // Bs - // Bt - // Bu - "Bud", - "Buddy", - "Bugs", - "Butters", - // Bv - // Bw - // Bx - // By - // Bz - // Ca - "Cander", - "Carson", - "Cat", - "Cathrine", - // Cb - // Cc - // Cd - // Ce - "Cecil", - // Cf - // Cg - // Ch - "Chi", - "Chris", - "Christine", - "Christopher", - // Ci - "Cinder", - "Cindy", - // Cj - // Ck - // Cl - "Cleo", - "Cleopatra", - "Cloe", - // Cm - // Cn - // Co - "Cody", - "Colby", - "Conor", - "Cook", - // Cp - // Cq - // Cr - "Cris", - // Cs - // Ct - // Cu - "Cuevas", - // Cv - // Cw - // Cx - // Cy - "Cynthia", - "Cyrus", - // Cz - // Da - "Dave", - "David", - // Db - // Dc - // Dd - // De - "Dean", - "Debbie", - "Debra", - "Dede", - "Deloris", - "Denny", - // Df - // Dg - // Dh - // Di - "Dia", - "Diana", - "Diane", - "Dina", - "Dipper", - // Dj - // Dk - // Dl - // Dm - // Dn - // Do - "Dobby", - "Doe", - "Dolly", - "Donna", - "Dora", - "Dorothy", - "Dot", - "Dotti", - // Dp - // Dq - // Dr - "Drake", - "Dren", - // Ds - // Dt - // Du - "Dustin", - // Dv - // Dw - "Dwayne", - // Dx - // Dy - "Dyna", - // Dz - // Ea - "Earl", - // Eb - // Ec - "Echo", - // Ed - "Ed", - "Edd", - "Eddie", - "Eddy", - "Edward", - // Ee - "Eevee", - // Ef - // Eg - // Eh - // Ei - "Einstein", - // Ej - // Ek - "Eka", - // El - "Elaine", - "Elora", - // Em - "Emma", - "Emmy", - // En - "Enzo", - // Eo - // Ep - "Epona", - // Eq - // Er - "Eric", - "Erica", - "Erik", - "Erin", - "Ernest", - // Es - "Esper", - "Estus", - // Et - // Eu - "Eugene", - "Eugenia", - // Ev - "Evaline", - "Everette", - // Ew - // Ex - // Ey - // Ez - "Eza", - // Fa - "Fabio", - "Fae", - // Fb - // Fc - // Fd - // Fe - "Ferris", - // Ff - // Fg - // Fh - // Fi - "Fifi", - "Fiona", - // Fj - // Fk - // Fl - "Flora", - "Florance", - // Fm - // Fn - // Fo - "Ford", - // Fp - // Fq - // Fr - "Fred", - "Freddy", - "Fredrick", - // Fs - // Ft - // Fu - "Fuller", - // Fv - // Fw - // Fx - // Fy - // Fz - // Ga - "Gabby", - "Garth", - "Gary", - // Gb - // Gc - // Gd - // Ge - "Geena", - "Gene", - "Genna", - // Gf - // Gg - // Gh - // Gi - "Gina", - // Gj - // Gk - // Gl - "Gloria", - // Gm - // Gn - // Go - "Gob", - // Gp - // Gq - // Gr - "Grant", - "Groot", - "Gryobo", - // Gs - // Gt - // Gu - "Guston", - // Gv - // Gw - "Gwen", - "Gwent", - // Gx - // Gy - "Gyro", - // Gz - // Ha - "Han", - "Hanje", - "Hanz", - "Hanzel", - "Harriet", - // Hb - // Hc - // Hd - // He - "Henry", - // Hf - // Hg - // Hh - // Hi - "Hindel", - // Hj - // Hk - // Hl - // Hm - // Hn - // Ho - "Holly", - "Hopper", - "Horis", - // Hp - // Hq - // Hr - // Hs - // Ht - // Hu - "Hue", - "Hubert", - // Hv - // Hw - // Hx - // Hy - // Hz - // Ia - "Ian", - // Ib - "Iberico", - // Ic - "Ice", - // Id - "Ida", - // Ie - // If - // Ig - "Iggy", - "Ignacio", - "Igor", - // Ih - // Ii - // Ij - // Ik - // Il - "Ilia", - // Im - "Imen", - // In - "India", - "Indrae", - // Io - // Ip - // Iq - // Ir - "Iris", - // Is - "Isabelle", - // It - // Iu - // Iv - // Iw - // Ix - // Iy - // Iz - "Izzi", - // Ja - "Jacob", - "James", - "Janae", - "Jane", - "Jasper", - // Jb - // Jc - // Jd - // Je - "Jeff", - "Jeffrey", - "Jesse", - "Jessica", - "Jessie", - "Jessy", - // Jf - // Jg - // Jh - // Ji - "Jim", - "Jimmy", - // Jj - // Jk - // Jl - // Jm - // Jn - // Jo - "Joanne", - "Jon", - "Jonny", - "Jordan", - // Jp - // Jq - // Jr - // Js - // Jt - // Ju - "Justin", - // Jv - // Jw - // Jx - // Jy - // Jz - // Ka - "Kane", - "Katie", - "Katy", - "Kayla", - // Kb - // Kc - // Kd - // Ke - "Keith", - "Ken", - "Kenny", - // Kf - // Kg - // Kh - // Ki - "Kiki", - // Kj - // Kk - // Kl - "Kloe", - // Km - // Kn - "Knox", - // Ko - "Kobe", - // Kp - // Kq - // Kr - "Kisty", - // Ks - // Kt - // Ku - // Kv - // Kw - // Kx - // Ky - "Kyla", - "Kyx", - // Kz - // La - "Lana", - "Lassie", - // Lb - // Lc - // Ld - // Le - "Leila", - "Lennie", - // Lf - // Lg - // Lh - // Li - "Lin", - "Linda", - // Lj - // Lk - // Ll - // Lm - // Ln - // Lo - "Lola", - "Lora", - // Lp - // Lq - // Lr - // Ls - // Lt - // Lu - "Luna", - "Lunabell", - // Lv - // Lw - // Lx - // Ly - "Lyssa", - // Lz - // Ma - "Mando", - "Mary", - // Mb - // Mc - "McChester", - // Md - // Me - "Melissa", - // Mf - // Mg - // Mh - // Mi - "Mika", - "Mike", - "Mikey", - "Minora", - "Mindy", - "Mira", - // Mj - // Mk - // Ml - // Mm - // Mn - // Mo - "Mochi", - "Moka", - "Montana", - "Monteblac", - // Mp - // Mq - // Mr - // Ms - // Mt - // Mu - // Mv - // Mw - // Mx - // My - // Mz - // Na - "Natasha", - // Nb - // Nc - // Nd - // Ne - "Ned", - "Nedry", - // Nf - // Ng - // Nh - // Ni - "Niki", - "Nina", - // Nj - // Nk - // Nl - // Nm - // Nn - // No - "Noma", - // Np - // Nq - // Nr - // Ns - // Nt - // Nu - // Nv - // Nw - // Nx - // Ny - "Nyx", - // Nz - // Oa - // Ob - "Obie", - // Oc - // Od - "Odeus", - // Oe - // Of - // Og - // Oh - // Oi - // Oj - // Ok - // Ol - "Ollie", - // Om - // On - // Oo - // Op - "Oprah", - // Oq - // Or - "Oryan", - // Os - "Oslo", - // Ot - "Otis", - // Ou - // Ov - // Ow - // Ox - "Oxford", - // Oy - // Oz - "Ozzie", - "Ozzy", - // Pa - "Palmer", - "Pam", - "Pamela", - "Parker", - "Paul", - // Pb - // Pc - // Pd - // Pe - "Pete", - "Peter", - // Pf - // Pg - // Ph - "Pheobe", - // Pi - // Pj - // Pk - // Pl - // Pm - // Pn - // Po - // Pp - // Pq - // Pr - "Priscilla", - // Ps - // Pt - // Pu - // Pv - // Pw - // Px - // Py - // Pz - // Qa - // Qb - "Qbert", - // Qc - // Qd - // Qe - // Qf - // Qg - // Qh - // Qi - // Qj - // Qk - // Ql - // Qm - // Qn - // Qo - // Qp - // Qq - // Qr - // Qs - // Qt - // Qu - "Quaid", - // Qv - // Qw - // Qx - // Qy - // Qz - // Ra - "Rachael", - "Ray", - "Raylene", - "Raymond", - "Razzy", - // Rb - // Rc - // Rd - // Re - "Red", - "Ren", - // Rf - // Rg - // Rh - // Ri - "Rianna", - "Rin", - // Rj - // Rk - // Rl - // Rm - // Rn - // Ro - "Rob", - "Robert", - "Rocky", - "Roland", - "Ronan", - // Rp - // Rq - // Rr - // Rs - // Rt - // Ru - "Ruckus", - "Rudford", - // Rv - // Rw - // Rx - // Ry - "Ryzen", - // Rz - // Sa - "Saber", - "Sabrina", - "Santa", - // Sb - // Sc - // Sd - // Se - "Seph", - "Sephora", - "Sephiroth", - // Sf - // Sg - // Sh - "Shoan", - // Si - "Sin", - "Sissy", - // Sj - // Sk - // Sl - // Sm - // Sn - // So - "Soka", - // Sp - // Sq - // Sr - // Ss - // St - "Steph", - "Stephen", - "Stu", - // Su - "Susan", - // Sv - "Sven", - // Sw - "Sweeny", - // Sx - // Sy - "Sylvester", - // Sz - // Ta - "Tae", - "Tanesha", - "Tanya", - "Tasha", - "Tay", - "Taz", - // Tb - // Tc - // Td - // Te - "Teressa", - // Tf - // Tg - // Th - "Thomas", - "Thuy", - // Ti - "Tiffany", - "Tina", - // Tj - // Tk - // Tl - // Tm - // Tn - // To - "Tobi", - "Tobias", - "Toby", - "Tom", - "Tony", - // Tp - // Tq - // Tr - "Tris", - "Trish", - "Trisha", - // Ts - // Tt - // Tu - "Tula", - // Tv - // Tw - // Tx - // Ty - "Ty", - // Tz - // Ua - // Ub - "Uba", - // Uc - // Ud - "Udo", - // Ue - // Uf - // Ug - // Uh - // Ui - // Uj - // Uk - // Ul - "Ulfrin", - // Um - "Umber", - // Un - // Uo - // Up - // Uq - // Ur - "Ur", - "Ursula", - // Us - // Ut - // Uu - // Uv - // Uw - // Ux - // Uy - // Uz - // Va - "Van", - "Vanessa", - // Vb - // Vc - // Vd - // Ve - "Venus", - // Vf - // Vg - // Vh - // Vi - "Vikki", - "Vin", - // Vj - // Vk - // Vl - "Vlad", - // Vm - // Vn - // Vo - "Von", - // Vp - // Vq - // Vr - // Vs - // Vt - // Vu - // Vv - // Vw - // Vx - // Vy - "Vyrnon", - // Vz - // Wa - "Wag", - "Wazowski", - // Wb - // Wc - // Wd - // We - "Wendy", - "Wensday", - "Wes", - "Wesley", - // Wf - // Wg - // Wh - "White", - // Wi - // Wj - // Wk - // Wl - // Wm - // Wn - // Wo - "Won", - // Wp - // Wq - // Wr - "Wright", - // Ws - // Wt - // Wu - "Wu", - // Wv - // Ww - // Wx - // Wy - "Wyzowski", - // Wz - // Xa - "Xavior", - // Xb - // Xc - // Xd - // Xe - "Xenon", - // Xf - // Xg - // Xh - // Xi - // Xj - // Xk - // Xl - // Xm - // Xn - // Xo - // Xp - // Xq - // Xr - // Xs - // Xt - // Xu - // Xv - // Xw - // Xx - // Xy - // Xz - // Ya - "Yando", - "Yas", - // Yb - // Yc - // Yd - // Ye - // Yf - // Yg - // Yh - // Yi - "Yin", - // Yj - // Yk - // Yl - // Ym - // Yn - // Yo - "Yola", - "Yona", - // Yp - // Yq - // Yr - // Ys - // Yt - // Yu - "Yuna", - "Yuta", - // Yv - // Yw - // Yx - // Yy - // Yz - // Za - "Zack", - "Zackery", - "Zan", - "Zander", - "Zap", - // Zb - // Zc - // Zd - // Ze - "Zebi", - // Zf - // Zg - // Zh - "Zhong", - // Zi - "Zim", - // Zj - // Zk - // Zl - // Zm - // Zn - // Zo - "Zot", - // Zp - // Zq - // Zr - // Zs - // Zt - // Zu - "Zuzu", - // Zv - "Zvuvu", - // Zw - "Zwen", - // Zx - // Zy - "Zyrus", - // Zz - ]; -} \ No newline at end of file +using System.Collections.Immutable; + +namespace Werecodent.CreateAndFake.Design.Data; + +/// Provides a pool of names. +public static class NameData +{ + /// Possible names for randomization. + public static ImmutableArray Values { get; } = + [ + // Aa + "Aaron", + // Ab + "Abby", + // Ac + "Acrid", + // Ad + "Adrian", + "Adrin", + // Ae + // Af + "Afton", + // Ag + "Agustus", + // Ah + "Ahbed", + // Ai + "Ailieen", + // Aj + "Ajax", + // Ak + "Akronis", + // Al + "Alabastr", + "Alyssa", + // Am + "Amanda", + "Amelia", + // An + "Andrew", + "Andy", + // Ao + "Aonis", + // Ap + "Appa", + // Aq + "Aquarius", + // Ar + "Aragorn", + "Ariel", + // As + "Astra", + // At + "Atta", + // Au + "Audre", + // Av + "Ava", + "Avrin", + // Aw + "Awen", + // Ax + "Axon", + // Ay + "Ayer", + // Az + "Azandria", + // Ba + "Babe", + "Bane", + "Barry", + // Bb + // Bc + // Bd + // Be + "Ben", + "Benji", + "Benjamin", + // Bf + // Bg + // Bh + // Bi + "Bingo", + "Bishop", + // Bj + "Bjorn", + // Bk + // Bl + "Blaine", + "Blake", + // Bm + // Bn + // Bo + "Bobby", + "Boris", + // Bp + // Bq + // Br + "Brent", + "Brianna", + // Bs + // Bt + // Bu + "Bud", + "Buddy", + "Bugs", + "Butters", + // Bv + // Bw + // Bx + // By + // Bz + // Ca + "Cander", + "Carson", + "Cat", + "Cathrine", + // Cb + // Cc + // Cd + // Ce + "Cecil", + // Cf + // Cg + // Ch + "Chi", + "Chris", + "Christine", + "Christopher", + // Ci + "Cinder", + "Cindy", + // Cj + // Ck + // Cl + "Cleo", + "Cleopatra", + "Cloe", + // Cm + // Cn + // Co + "Cody", + "Colby", + "Conor", + "Cook", + // Cp + // Cq + // Cr + "Cris", + // Cs + // Ct + // Cu + "Cuevas", + // Cv + // Cw + // Cx + // Cy + "Cynthia", + "Cyrus", + // Cz + // Da + "Dave", + "David", + // Db + // Dc + // Dd + // De + "Dean", + "Debbie", + "Debra", + "Dede", + "Deloris", + "Denny", + // Df + // Dg + // Dh + // Di + "Dia", + "Diana", + "Diane", + "Dina", + "Dipper", + // Dj + // Dk + // Dl + // Dm + // Dn + // Do + "Dobby", + "Doe", + "Dolly", + "Donna", + "Dora", + "Dorothy", + "Dot", + "Dotti", + // Dp + // Dq + // Dr + "Drake", + "Dren", + // Ds + // Dt + // Du + "Dustin", + // Dv + // Dw + "Dwayne", + // Dx + // Dy + "Dyna", + // Dz + // Ea + "Earl", + // Eb + // Ec + "Echo", + // Ed + "Ed", + "Edd", + "Eddie", + "Eddy", + "Edward", + // Ee + "Eevee", + // Ef + // Eg + // Eh + // Ei + "Einstein", + // Ej + // Ek + "Eka", + // El + "Elaine", + "Elora", + // Em + "Emma", + "Emmy", + // En + "Enzo", + // Eo + // Ep + "Epona", + // Eq + // Er + "Eric", + "Erica", + "Erik", + "Erin", + "Ernest", + // Es + "Esper", + "Estus", + // Et + // Eu + "Eugene", + "Eugenia", + // Ev + "Evaline", + "Everette", + // Ew + // Ex + // Ey + // Ez + "Eza", + // Fa + "Fabio", + "Fae", + // Fb + // Fc + // Fd + // Fe + "Ferris", + // Ff + // Fg + // Fh + // Fi + "Fifi", + "Fiona", + // Fj + // Fk + // Fl + "Flora", + "Florance", + // Fm + // Fn + // Fo + "Ford", + // Fp + // Fq + // Fr + "Fred", + "Freddy", + "Fredrick", + // Fs + // Ft + // Fu + "Fuller", + // Fv + // Fw + // Fx + // Fy + // Fz + // Ga + "Gabby", + "Garth", + "Gary", + // Gb + // Gc + // Gd + // Ge + "Geena", + "Gene", + "Genna", + // Gf + // Gg + // Gh + // Gi + "Gina", + // Gj + // Gk + // Gl + "Gloria", + // Gm + // Gn + // Go + "Gob", + // Gp + // Gq + // Gr + "Grant", + "Groot", + "Gryobo", + // Gs + // Gt + // Gu + "Guston", + "Guts", + // Gv + // Gw + "Gwen", + "Gwent", + // Gx + // Gy + "Gyro", + // Gz + // Ha + "Han", + "Hanje", + "Hanz", + "Hanzel", + "Harriet", + // Hb + // Hc + // Hd + // He + "Henry", + // Hf + // Hg + // Hh + // Hi + "Hindel", + // Hj + // Hk + // Hl + // Hm + // Hn + // Ho + "Holly", + "Hopper", + "Horis", + // Hp + // Hq + // Hr + // Hs + // Ht + // Hu + "Hue", + "Hubert", + // Hv + // Hw + // Hx + // Hy + // Hz + // Ia + "Ian", + // Ib + "Iberico", + // Ic + "Ice", + // Id + "Ida", + // Ie + // If + // Ig + "Iggy", + "Ignacio", + "Igor", + // Ih + // Ii + // Ij + // Ik + // Il + "Ilia", + // Im + "Imen", + // In + "India", + "Indrae", + // Io + // Ip + // Iq + // Ir + "Iris", + // Is + "Isabelle", + // It + // Iu + // Iv + // Iw + // Ix + // Iy + // Iz + "Izzi", + // Ja + "Jacob", + "James", + "Janae", + "Jane", + "Jasper", + // Jb + // Jc + // Jd + // Je + "Jeff", + "Jeffrey", + "Jesse", + "Jessica", + "Jessie", + "Jessy", + // Jf + // Jg + // Jh + // Ji + "Jim", + "Jimmy", + // Jj + // Jk + // Jl + // Jm + // Jn + // Jo + "Joanne", + "Jon", + "Jonny", + "Jordan", + // Jp + // Jq + // Jr + // Js + // Jt + // Ju + "Justin", + // Jv + // Jw + // Jx + // Jy + // Jz + // Ka + "Kane", + "Katie", + "Katy", + "Kayla", + // Kb + // Kc + // Kd + // Ke + "Keith", + "Ken", + "Kenny", + // Kf + // Kg + // Kh + // Ki + "Kiki", + // Kj + // Kk + // Kl + "Kloe", + // Km + // Kn + "Knox", + // Ko + "Kobe", + // Kp + // Kq + // Kr + "Kisty", + // Ks + // Kt + // Ku + // Kv + // Kw + // Kx + // Ky + "Kyla", + "Kyx", + // Kz + // La + "Lana", + "Lassie", + // Lb + // Lc + // Ld + // Le + "Leila", + "Lennie", + // Lf + // Lg + // Lh + // Li + "Lin", + "Linda", + // Lj + // Lk + // Ll + // Lm + // Ln + // Lo + "Lola", + "Lora", + // Lp + // Lq + // Lr + // Ls + // Lt + // Lu + "Luna", + "Lunabell", + // Lv + // Lw + // Lx + // Ly + "Lyssa", + // Lz + // Ma + "Mando", + "Mary", + // Mb + // Mc + "McChester", + // Md + // Me + "Melissa", + // Mf + // Mg + // Mh + // Mi + "Mika", + "Mike", + "Mikey", + "Minora", + "Mindy", + "Mira", + // Mj + // Mk + // Ml + // Mm + // Mn + // Mo + "Mochi", + "Moka", + "Montana", + "Monteblac", + // Mp + // Mq + // Mr + // Ms + // Mt + // Mu + // Mv + // Mw + // Mx + // My + // Mz + // Na + "Natasha", + // Nb + // Nc + // Nd + // Ne + "Ned", + "Nedry", + // Nf + // Ng + // Nh + // Ni + "Niki", + "Nina", + // Nj + // Nk + // Nl + // Nm + // Nn + // No + "Noma", + // Np + // Nq + // Nr + // Ns + // Nt + // Nu + // Nv + // Nw + // Nx + // Ny + "Nyx", + // Nz + // Oa + // Ob + "Obie", + // Oc + // Od + "Odeus", + // Oe + // Of + // Og + // Oh + // Oi + // Oj + // Ok + // Ol + "Ollie", + // Om + // On + // Oo + // Op + "Oprah", + // Oq + // Or + "Oryan", + // Os + "Oslo", + // Ot + "Otis", + // Ou + // Ov + // Ow + // Ox + "Oxford", + // Oy + // Oz + "Ozzie", + "Ozzy", + // Pa + "Palmer", + "Pam", + "Pamela", + "Parker", + "Paul", + // Pb + // Pc + // Pd + // Pe + "Pete", + "Peter", + // Pf + // Pg + // Ph + "Pheobe", + // Pi + // Pj + // Pk + // Pl + // Pm + // Pn + // Po + // Pp + // Pq + // Pr + "Priscilla", + // Ps + // Pt + // Pu + // Pv + // Pw + // Px + // Py + // Pz + // Qa + // Qb + "Qbert", + // Qc + // Qd + // Qe + // Qf + // Qg + // Qh + // Qi + // Qj + // Qk + // Ql + // Qm + // Qn + // Qo + // Qp + // Qq + // Qr + // Qs + // Qt + // Qu + "Quaid", + // Qv + // Qw + // Qx + // Qy + // Qz + // Ra + "Rachael", + "Ray", + "Raylene", + "Raymond", + "Razzy", + // Rb + // Rc + // Rd + // Re + "Red", + "Ren", + // Rf + // Rg + // Rh + // Ri + "Rianna", + "Rin", + // Rj + // Rk + // Rl + // Rm + // Rn + // Ro + "Rob", + "Robert", + "Rocky", + "Roland", + "Ronan", + // Rp + // Rq + // Rr + // Rs + // Rt + // Ru + "Ruckus", + "Rudford", + // Rv + // Rw + // Rx + // Ry + "Ryzen", + // Rz + // Sa + "Saber", + "Sabrina", + "Santa", + // Sb + // Sc + // Sd + // Se + "Seph", + "Sephora", + "Sephiroth", + // Sf + // Sg + // Sh + "Shoan", + // Si + "Sin", + "Sissy", + // Sj + // Sk + // Sl + // Sm + // Sn + // So + "Soka", + // Sp + // Sq + // Sr + // Ss + // St + "Steph", + "Stephen", + "Stu", + // Su + "Susan", + // Sv + "Sven", + // Sw + "Sweeny", + // Sx + // Sy + "Sylvester", + // Sz + // Ta + "Tae", + "Tanesha", + "Tanya", + "Tasha", + "Tay", + "Taz", + // Tb + // Tc + // Td + // Te + "Teressa", + // Tf + // Tg + // Th + "Thomas", + "Thuy", + // Ti + "Tiffany", + "Tina", + // Tj + // Tk + // Tl + // Tm + // Tn + // To + "Tobi", + "Tobias", + "Toby", + "Tom", + "Tony", + // Tp + // Tq + // Tr + "Tris", + "Trish", + "Trisha", + // Ts + // Tt + // Tu + "Tula", + // Tv + // Tw + // Tx + // Ty + "Ty", + // Tz + // Ua + // Ub + "Uba", + // Uc + // Ud + "Udo", + // Ue + // Uf + // Ug + // Uh + // Ui + // Uj + // Uk + // Ul + "Ulfrin", + // Um + "Umber", + // Un + // Uo + // Up + // Uq + // Ur + "Ur", + "Ursula", + // Us + // Ut + // Uu + // Uv + // Uw + // Ux + // Uy + // Uz + // Va + "Van", + "Vanessa", + // Vb + // Vc + // Vd + // Ve + "Venus", + // Vf + // Vg + // Vh + // Vi + "Vikki", + "Vin", + // Vj + // Vk + // Vl + "Vlad", + // Vm + // Vn + // Vo + "Von", + // Vp + // Vq + // Vr + // Vs + // Vt + // Vu + // Vv + // Vw + // Vx + // Vy + "Vyrnon", + // Vz + // Wa + "Wag", + "Wazowski", + // Wb + // Wc + // Wd + // We + "Wendy", + "Wensday", + "Wes", + "Wesley", + // Wf + // Wg + // Wh + "White", + // Wi + "Withers", + // Wj + // Wk + // Wl + // Wm + // Wn + // Wo + "Won", + // Wp + // Wq + // Wr + "Wright", + // Ws + // Wt + // Wu + "Wu", + // Wv + // Ww + // Wx + // Wy + "Wyzowski", + // Wz + // Xa + "Xavior", + // Xb + // Xc + // Xd + // Xe + "Xenon", + // Xf + // Xg + // Xh + // Xi + // Xj + // Xk + // Xl + // Xm + // Xn + // Xo + // Xp + // Xq + // Xr + // Xs + // Xt + // Xu + // Xv + // Xw + // Xx + // Xy + // Xz + // Ya + "Yando", + "Yas", + // Yb + // Yc + // Yd + // Ye + // Yf + // Yg + // Yh + // Yi + "Yin", + // Yj + // Yk + // Yl + // Ym + // Yn + // Yo + "Yola", + "Yona", + // Yp + // Yq + // Yr + // Ys + // Yt + // Yu + "Yuna", + "Yuta", + // Yv + // Yw + // Yx + // Yy + // Yz + // Za + "Zack", + "Zackery", + "Zan", + "Zander", + "Zap", + // Zb + // Zc + // Zd + // Ze + "Zebi", + "Zed", + // Zf + // Zg + // Zh + "Zhong", + // Zi + "Zim", + // Zj + // Zk + // Zl + // Zm + // Zn + // Zo + "Zot", + // Zp + // Zq + // Zr + // Zs + // Zt + // Zu + "Zuzu", + // Zv + "Zvuvu", + // Zw + "Zwen", + // Zx + // Zy + "Zyrus", + // Zz + ]; +} diff --git a/src/Design/Exceptions/AsynchronousAccessException.cs b/src/Design/Exceptions/AsynchronousAccessException.cs new file mode 100644 index 00000000..42c30843 --- /dev/null +++ b/src/Design/Exceptions/AsynchronousAccessException.cs @@ -0,0 +1,37 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// +/// for errors occurring +/// due to accessing asynchronous behavior in synchronous context. +/// +[Serializable] +public sealed class AsynchronousAccessException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private AsynchronousAccessException() + : base() { } + + /// Asynchronous instance attempting to be accessed. + /// Details to include in the error message. + /// + public AsynchronousAccessException(object? value, string? message) + : base( + BuildMessage( + $"Prevented synchronous access to instance of type '{GenericConverter.ExpandName(value)}'.", + message, + value?.ToString() + ) + ) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private AsynchronousAccessException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/AutoTesterFailureException.cs b/src/Design/Exceptions/AutoTesterFailureException.cs new file mode 100644 index 00000000..6af99b4c --- /dev/null +++ b/src/Design/Exceptions/AutoTesterFailureException.cs @@ -0,0 +1,31 @@ +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// for issues encountered during automated testing. +[Serializable] +public sealed class AutoTesterFailureException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private AutoTesterFailureException() + : base() { } + + /// Class containing the test that failed. + /// + public AutoTesterFailureException(Type testClass) + : base($"The '{testClass?.Name}' AutoTester encountered an issue.") { } + + /// Class containing the test that failed. + /// + public AutoTesterFailureException(Type testClass, Exception? innerException) + : base($"The '{testClass?.Name}' AutoTester encountered an issue.", innerException) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private AutoTesterFailureException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/BehaviorDefaultThrowException.cs b/src/Design/Exceptions/BehaviorDefaultThrowException.cs new file mode 100644 index 00000000..69b6ab8c --- /dev/null +++ b/src/Design/Exceptions/BehaviorDefaultThrowException.cs @@ -0,0 +1,31 @@ +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// Default when throwing via set Behavior for fakes. +[Serializable] +public sealed class BehaviorDefaultThrowException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private BehaviorDefaultThrowException() + : base() { } + + /// + /// + public BehaviorDefaultThrowException(string? message) + : base( + BuildMessage( + "Behavior called that has been configured to throw a general exception.", + message + ) + ) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private BehaviorDefaultThrowException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/CreateAndFakeException.cs b/src/Design/Exceptions/CreateAndFakeException.cs new file mode 100644 index 00000000..17fd5460 --- /dev/null +++ b/src/Design/Exceptions/CreateAndFakeException.cs @@ -0,0 +1,51 @@ +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// +/// for errors occurring within the CreateAndFake framework. +/// +[Serializable] +[KnownType(typeof(Exception))] +[KnownType(typeof(Exception[]))] +[KnownType(typeof(string[]))] +public abstract class CreateAndFakeException : Exception +{ + /// + /// Serialization constructor. + protected CreateAndFakeException() + : base() { } + + /// + /// + protected CreateAndFakeException(string? message) + : base(message) { } + + /// + /// + protected CreateAndFakeException(string? message, Exception? innerException) + : base(message, innerException) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + protected CreateAndFakeException(SerializationInfo info, StreamingContext context) + : base(info, context) { } + + /// Integrates the details into the message. + /// Starting message. + /// Details to integrate. + /// Content to integrate. + /// Message to use for the exception. + protected static string BuildMessage(string error, string? details, string? content = null) + { + string nl = Environment.NewLine; + + return $"{nameof(CreateAndFake)} library exception." + + $"{nl}Error: {error}" + + ((details != null) ? $"{nl}Details: {details}" : "") + + ((content != null) ? $"{nl}Content: {nl}{content}" : ""); + } +} diff --git a/src/Design/Exceptions/EngineException.cs b/src/Design/Exceptions/EngineException.cs new file mode 100644 index 00000000..82f544b1 --- /dev/null +++ b/src/Design/Exceptions/EngineException.cs @@ -0,0 +1,37 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// +/// for errors occurring within a . +/// +[Serializable] +public sealed class EngineException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private EngineException() + : base() { } + + /// + /// + public EngineException(string? message) + : base(BuildMessage("Encountered fatal framework engine issue.", message)) { } + + /// + /// + public EngineException(string? message, Exception? innerException) + : base( + BuildMessage("Encountered fatal framework engine exception.", message), + innerException + ) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private EngineException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/IterationLimitException.cs b/src/Design/Exceptions/IterationLimitException.cs new file mode 100644 index 00000000..5bcdc84e --- /dev/null +++ b/src/Design/Exceptions/IterationLimitException.cs @@ -0,0 +1,33 @@ +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// +/// for errors occurring +/// due trying to iterate past the configured iteration limit. +/// +[Serializable] +public sealed class IterationLimitException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private IterationLimitException() + : base() { } + + /// + public IterationLimitException(int iterationLimit, string? message) + : base( + BuildMessage( + $"Execution stopped at iteration {iterationLimit} to prevent infinite recursion.", + message + ) + ) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private IterationLimitException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/MismatchedAccessException.cs b/src/Design/Exceptions/MismatchedAccessException.cs new file mode 100644 index 00000000..3eb4def9 --- /dev/null +++ b/src/Design/Exceptions/MismatchedAccessException.cs @@ -0,0 +1,37 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// +/// for errors occurring due +/// to trying to extract from a different context than the initial one. +/// +[Serializable] +public sealed class MismatchedAccessException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private MismatchedAccessException() + : base() { } + + /// Instance attempting to be added. + /// Details to include in the error message. + /// + public MismatchedAccessException(object? value, string? message) + : base( + BuildMessage( + $"Prevented access to instance of type '{GenericConverter.ExpandName(value)}'.", + message, + value?.ToString() + ) + ) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private MismatchedAccessException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/RunnerMethodErrorException.cs b/src/Design/Exceptions/RunnerMethodErrorException.cs new file mode 100644 index 00000000..2645985c --- /dev/null +++ b/src/Design/Exceptions/RunnerMethodErrorException.cs @@ -0,0 +1,33 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// for when the Runner tool encounters an exception. +[Serializable] +public sealed class RunnerMethodErrorException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private RunnerMethodErrorException() + : base() { } + + /// + public RunnerMethodErrorException(string method, Exception innerException) + : base( + BuildMessage( + "Running a method failed.", + $"Encountered an exception of type '{GenericConverter.ExpandName(innerException)}'.", + method + ), + innerException + ) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private RunnerMethodErrorException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/RunnerTimeoutException.cs b/src/Design/Exceptions/RunnerTimeoutException.cs new file mode 100644 index 00000000..01da11a7 --- /dev/null +++ b/src/Design/Exceptions/RunnerTimeoutException.cs @@ -0,0 +1,31 @@ +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// for when the Runner tool times out. +[Serializable] +public sealed class RunnerTimeoutException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private RunnerTimeoutException() + : base() { } + + /// + public RunnerTimeoutException(TimeSpan timeout, string method) + : base( + BuildMessage( + "Attempting to run a method timed out.", + $"Timed out after {timeout}.", + method + ) + ) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private RunnerTimeoutException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/TesterFailureException.cs b/src/Design/Exceptions/TesterFailureException.cs new file mode 100644 index 00000000..d713ac26 --- /dev/null +++ b/src/Design/Exceptions/TesterFailureException.cs @@ -0,0 +1,31 @@ +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// for errors found via the Tester tool. +[Serializable] +public sealed class TesterFailureException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private TesterFailureException() + : base() { } + + /// + /// + public TesterFailureException(string? message) + : base(BuildMessage("Encountered fatal Tester issue.", message)) { } + + /// + /// + public TesterFailureException(string? message, Exception? innerException) + : base(BuildMessage("Encountered fatal Tester exception.", message), innerException) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private TesterFailureException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/ToolException.cs b/src/Design/Exceptions/ToolException.cs new file mode 100644 index 00000000..3dccbb6d --- /dev/null +++ b/src/Design/Exceptions/ToolException.cs @@ -0,0 +1,34 @@ +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// +/// for fatal errors occurring within tools. +/// +[Serializable] +public sealed class ToolException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private ToolException() + : base() { } + + /// + /// + public ToolException(string? message) + : base(BuildMessage("Encountered fatal framework tool issue.", message)) { } + + /// + /// + public ToolException(string? message, Exception? innerException) + : base(BuildMessage("Encountered fatal framework tool exception.", message), innerException) + { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private ToolException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/UnsupportedException.cs b/src/Design/Exceptions/UnsupportedException.cs new file mode 100644 index 00000000..11ecf340 --- /dev/null +++ b/src/Design/Exceptions/UnsupportedException.cs @@ -0,0 +1,26 @@ +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// for errors occurring due to lack of tooling support. +[Serializable] +public sealed class UnsupportedException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private UnsupportedException() + : base() { } + + /// + /// + public UnsupportedException(string? message) + : base(BuildMessage("Case not supported by the framework.", message)) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private UnsupportedException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Exceptions/ValueTaskRepeatedAccessException.cs b/src/Design/Exceptions/ValueTaskRepeatedAccessException.cs new file mode 100644 index 00000000..6ed53630 --- /dev/null +++ b/src/Design/Exceptions/ValueTaskRepeatedAccessException.cs @@ -0,0 +1,36 @@ +using System.Globalization; +using System.Runtime.Serialization; + +namespace Werecodent.CreateAndFake.Design.Exceptions; + +/// +/// for awaiting a +/// or multiple times. +/// +[Serializable] +public sealed class ValueTaskRepeatedAccessException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private ValueTaskRepeatedAccessException() + : base() { } + + /// + /// Token owned by the parent . + public ValueTaskRepeatedAccessException(short token) + : base( + BuildMessage( + "The ValueTask was resolved multiple times.", + "Resolving a ValueTask multiple times results in undefined behavior and indicates a bug.", + token.ToString(CultureInfo.InvariantCulture) + ) + ) { } + + /// + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private ValueTaskRepeatedAccessException(SerializationInfo info, StreamingContext context) + : base(info, context) { } +} diff --git a/src/Design/Extensions/TypeExtensions.cs b/src/Design/Extensions/TypeExtensions.cs new file mode 100644 index 00000000..3a6f8206 --- /dev/null +++ b/src/Design/Extensions/TypeExtensions.cs @@ -0,0 +1,134 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Extensions; + +/// Extends the with inheritance methods. +public static class TypeExtensions +{ + /// + /// Checks if is a base or + /// for . + /// + /// + /// Potential parent being inherited by the + /// (). + /// + /// The potentially inheriting . + /// + /// if + /// inherits , otherwise. + /// + /// + public static bool Inherits([NotNullWhen(true)] this Type? child) + { + if (child == null) + { + return false; + } + else if (child.IsGenericTypeDefinition) + { + return TypeDescriber.For(child).Inherits(); + } + else + { + return typeof(T).IsAssignableFrom(child); + } + } + + /// + /// Checks if the is a base + /// or for . + /// + /// potentially inheriting the . + /// + /// potentially inherited by the + /// (). + /// + /// + /// if inherits the + /// , otherwise. + /// + /// Supports generic definitions. + /// + public static bool Inherits( + [NotNullWhen(true)] this Type? child, + [NotNullWhen(true)] Type? parent + ) + { + if (child == null || parent == null) + { + return false; + } + else if (child.IsGenericTypeDefinition || parent.IsGenericTypeDefinition) + { + return TypeDescriber.For(child).Inherits(parent); + } + else + { + return parent.IsAssignableFrom(child); + } + } + + /// + /// Checks if is a base + /// or for . + /// + /// Potential child inheriting the + /// (). + /// + /// potentially inherited by . + /// + /// if inherits + /// , otherwise. + /// + /// + public static bool IsInheritedBy([NotNullWhen(true)] this Type? parent) + { + if (parent == null) + { + return false; + } + else if (parent.IsGenericTypeDefinition) + { + return TypeDescriber.For().Inherits(parent); + } + else + { + return parent.IsAssignableFrom(typeof(T)); + } + } + + /// + /// Checks if is a base + /// or for the . + /// + /// potentially inherited by the . + /// + /// potentially inheriting the + /// (). + /// + /// + /// if the inherits + /// , otherwise. + /// + /// + public static bool IsInheritedBy( + [NotNullWhen(true)] this Type? parent, + [NotNullWhen(true)] Type? child + ) + { + if (child == null || parent == null) + { + return false; + } + else if (child.IsGenericTypeDefinition || parent.IsGenericTypeDefinition) + { + return TypeDescriber.For(child).Inherits(parent); + } + else + { + return parent.IsAssignableFrom(child); + } + } +} diff --git a/src/Design/Nullable/DoesNotReturnAttribute.cs b/src/Design/Nullable/DoesNotReturnAttribute.cs new file mode 100644 index 00000000..1a9dc6de --- /dev/null +++ b/src/Design/Nullable/DoesNotReturnAttribute.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 +#pragma warning disable IDE0130, MA0182 // Must match existing location. + +namespace System.Diagnostics.CodeAnalysis; + +/// Applied to a method that will never return under any circumstance. +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute; + +#pragma warning restore +#endif diff --git a/src/Design/Nullable/MaybeNullAttribute.cs b/src/Design/Nullable/MaybeNullAttribute.cs new file mode 100644 index 00000000..b65c928f --- /dev/null +++ b/src/Design/Nullable/MaybeNullAttribute.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 +#pragma warning disable IDE0130, MA0182 // Must match existing location. + +namespace System.Diagnostics.CodeAnalysis; + +/// Specifies the attached data may actually be . +[ExcludeFromCodeCoverage] // Not present in all versions. +[AttributeUsage( + AttributeTargets.Parameter + | AttributeTargets.Property + | AttributeTargets.Field + | AttributeTargets.ReturnValue, + Inherited = false +)] +internal sealed class MaybeNullAttribute : Attribute; + +#pragma warning restore +#endif diff --git a/src/Design/Nullable/NotNullAttribute.cs b/src/Design/Nullable/NotNullAttribute.cs new file mode 100644 index 00000000..706c44c8 --- /dev/null +++ b/src/Design/Nullable/NotNullAttribute.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 +#pragma warning disable IDE0130 // Must match existing location. + +namespace System.Diagnostics.CodeAnalysis; + +/// Specifies the attached data will not be when the call returns. +[ExcludeFromCodeCoverage] // Not present in all versions. +[AttributeUsage( + AttributeTargets.Parameter + | AttributeTargets.Property + | AttributeTargets.Field + | AttributeTargets.ReturnValue, + Inherited = false +)] +internal sealed class NotNullAttribute : Attribute; + +#pragma warning restore +#endif diff --git a/src/Design/Nullable/NotNullIfNotNullAttribute.cs b/src/Design/Nullable/NotNullIfNotNullAttribute.cs new file mode 100644 index 00000000..653995f1 --- /dev/null +++ b/src/Design/Nullable/NotNullIfNotNullAttribute.cs @@ -0,0 +1,27 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 +#pragma warning disable IDE0130 // Must match existing location. + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies the attached data will not be +/// when is not . +/// +/// +[ExcludeFromCodeCoverage] // Not present in all versions. +[AttributeUsage( + AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, + AllowMultiple = true, + Inherited = false +)] +internal sealed class NotNullIfNotNullAttribute(string parameterName) : Attribute +{ + /// Name of the associated parameter that matches nullability. + public string ParameterName { get; } = parameterName; +} + +#pragma warning restore +#endif diff --git a/src/Design/Nullable/NotNullWhenAttribute.cs b/src/Design/Nullable/NotNullWhenAttribute.cs new file mode 100644 index 00000000..426fddd6 --- /dev/null +++ b/src/Design/Nullable/NotNullWhenAttribute.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Attribute added in .NET Standard 2.1 & Core 3.0 +#pragma warning disable IDE0130 // Must match existing location. + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies the attached data will not be +/// when the call returns with . +/// +/// +[ExcludeFromCodeCoverage] // Not present in all versions. +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class NotNullWhenAttribute(bool returnValue) : Attribute +{ + /// Result when the attached data will not be . + public bool ReturnValue { get; } = returnValue; +} + +#pragma warning restore +#endif diff --git a/src/Design/Properties/AssemblyInfo.cs b/src/Design/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..06466b53 --- /dev/null +++ b/src/Design/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: CLSCompliant(true)] +[assembly: InternalsVisibleTo("Werecodent.CreateAndFake.FakerTypes")] +[assembly: InternalsVisibleTo("CreateAndFake")] +[assembly: InternalsVisibleTo("CreateAndFake.Design.Tests")] diff --git a/src/Design/Properties/CallerArgumentExpressionAttribute.cs b/src/Design/Properties/CallerArgumentExpressionAttribute.cs new file mode 100644 index 00000000..dcd3adec --- /dev/null +++ b/src/Design/Properties/CallerArgumentExpressionAttribute.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Required feature shipped with C# 14 / .NET 10.0 +#pragma warning disable IDE0130 // Must match existing location. + +using System.Diagnostics.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[ExcludeFromCodeCoverage] // Not present in all versions. +[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] +internal sealed class CallerArgumentExpressionAttribute(string parameterName) : Attribute +{ + public string ParameterName { get; } = parameterName; +} + +#pragma warning restore +#endif diff --git a/src/Design/Properties/CompilerFeatureRequiredAttribute.cs b/src/Design/Properties/CompilerFeatureRequiredAttribute.cs new file mode 100644 index 00000000..935dfdf8 --- /dev/null +++ b/src/Design/Properties/CompilerFeatureRequiredAttribute.cs @@ -0,0 +1,37 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Required feature shipped with C# 13 / .NET 9.0 +#pragma warning disable IDE0130, MA0182 // Must match existing location. + +using System.Diagnostics.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +/// +/// Indicates that compiler support for a particular feature +/// is required for the location where this attribute is applied. +/// +/// +[ExcludeFromCodeCoverage] // Not present in all versions. +[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] +internal sealed class CompilerFeatureRequiredAttribute(string featureName) : Attribute +{ + /// The name of the compiler feature. + public string FeatureName { get; } = featureName; + + /// + /// If true, the compiler can choose to allow access to the location where + /// this attribute is applied if it does not understand . + /// + public bool IsOptional { get; init; } + + /// The used for the ref structs C# feature. + public const string RefStructs = nameof(RefStructs); + + /// The used for the required members C# feature. + public const string RequiredMembers = nameof(RequiredMembers); +} + +#pragma warning restore +#endif diff --git a/src/Design/Properties/DesignDefaults.cs b/src/Design/Properties/DesignDefaults.cs new file mode 100644 index 00000000..a862858b --- /dev/null +++ b/src/Design/Properties/DesignDefaults.cs @@ -0,0 +1,17 @@ +using System.Collections; + +namespace Werecodent.CreateAndFake.Design.Properties; + +/// Handles default settings for the Design namespace. +internal static class DesignDefaults +{ + /// Cap to iterating s and loops. + /// Used to prevent stack overflows and infinite execution cycles. + /// 19999 + internal const int IterationLimit = 19999; + + /// Flag to include generating invalid floating-point values (NaN, -∞ and +∞). + /// Only finite valid numbers are generated unless this flag is set to . + /// + internal const bool IncludeInfinityAndNaNGeneration = false; +} diff --git a/src/Design/Properties/Globals.cs b/src/Design/Properties/Globals.cs new file mode 100644 index 00000000..fa0ed0c0 --- /dev/null +++ b/src/Design/Properties/Globals.cs @@ -0,0 +1,5 @@ +#if NET9_0_OR_GREATER +global using Lock = System.Threading.Lock; +#else +global using Lock = Werecodent.CreateAndFake.Design.Content.CustomLock; +#endif diff --git a/src/Design/Properties/IsExternalInit.cs b/src/Design/Properties/IsExternalInit.cs new file mode 100644 index 00000000..a99bdfb9 --- /dev/null +++ b/src/Design/Properties/IsExternalInit.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Init type shipped with C# 7 / .NET 5.0 +#pragma warning disable IDE0130, MA0036, MA0182 // Must match existing version & location. + +using System.ComponentModel; + +namespace System.Runtime.CompilerServices; + +/// +/// Reserved to be used by the compiler for tracking metadata. +/// This class should not be used by developers in source code. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +internal sealed class IsExternalInit; + +#pragma warning restore +#endif diff --git a/src/Design/Properties/RequiredMemberAttribute.cs b/src/Design/Properties/RequiredMemberAttribute.cs new file mode 100644 index 00000000..17728dbf --- /dev/null +++ b/src/Design/Properties/RequiredMemberAttribute.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Required member shipped with C# 11 / .NET 7.0 +#pragma warning disable IDE0130, MA0182 // Must match existing location. + +namespace System.Runtime.CompilerServices; + +/// Specifies that a type has required members or that a member is required. +[AttributeUsage( + AttributeTargets.Class + | AttributeTargets.Struct + | AttributeTargets.Field + | AttributeTargets.Property, + AllowMultiple = false, + Inherited = false +)] +internal sealed class RequiredMemberAttribute : Attribute; + +#pragma warning restore +#endif diff --git a/src/Design/Properties/SetsRequiredMembersAttribute.cs b/src/Design/Properties/SetsRequiredMembersAttribute.cs new file mode 100644 index 00000000..04d28664 --- /dev/null +++ b/src/Design/Properties/SetsRequiredMembersAttribute.cs @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if LEGACY // Required feature shipped with C# 13 / .NET 11.0 +#pragma warning disable IDE0130, MA0182 // Must match existing location. + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that this constructor sets all required members for the current type, +/// and callers do not need to set any required members themselves. +/// +[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] +internal sealed class SetsRequiredMembersAttribute : Attribute; + +#pragma warning restore +#endif diff --git a/src/Design/Randomization/BoundaryChecker.cs b/src/Design/Randomization/BoundaryChecker.cs new file mode 100644 index 00000000..001d8f0b --- /dev/null +++ b/src/Design/Randomization/BoundaryChecker.cs @@ -0,0 +1,109 @@ +namespace Werecodent.CreateAndFake.Design.Randomization; + +/// Enforces boundaries for generating values. +/// +/// Required branching behavior due to and +/// not inheriting in legacy .NET. +/// +internal static class BoundaryChecker +{ + /// Ensures max >= 0. + /// The 0 value of 's . + /// Value being proposed as the maximum value to generate. + /// If < 0. + internal static void EnforcePositiveMax(object zero, object max) + { + bool isInvalid; + switch (max) + { + case IntPtr intPtrMax: + isInvalid = intPtrMax.ToInt64() < 0L; + break; + case UIntPtr: + isInvalid = false; + break; + default: + isInvalid = ((IComparable)zero).CompareTo(max) > 0; + break; + } + + if (isInvalid) + { + throw new ArgumentOutOfRangeException( + nameof(max), + max, + $"Must be greater than or equal to: '{zero}'." + ); + } + } + + /// Ensures min <= max. + /// Value being proposed as the minimum value to generate. + /// Value being proposed as the maximum value to generate. + /// If < 0. + internal static void EnforceRange(object min, object max) + { + bool isInvalid; + switch (min) + { + case IntPtr intPtrMin: + isInvalid = intPtrMin.ToInt64() > ((IntPtr)max).ToInt64(); + break; + case UIntPtr uIntPtrMin: + isInvalid = uIntPtrMin.ToUInt64() > ((UIntPtr)max).ToUInt64(); + break; + default: + isInvalid = ((IComparable)min).CompareTo(max) > 0; + break; + } + + if (isInvalid) + { + throw new ArgumentOutOfRangeException( + nameof(max), + max, + $"Must be greater than or equal to the specified min: '{min}'." + ); + } + } + + /// Constrains value to prevent issues stemming from scaling imprecision. + /// The generated value to ensure is within range. + /// The 0 value of 's . + /// Positive exclusive upper boundary for the value. + /// + /// if value < max. + /// if value >= max. + /// + internal static object BindToMax(object value, object zero, object max) + { + if (value is IComparable result) + { + return result.CompareTo(max) < 0 ? result : zero; + } + else + { + return value; + } + } + + /// Constrains value to prevent issues stemming from scaling imprecision. + /// The generated value to ensure is within range. + /// Inclusive lower boundary for the value. + /// Inclusive upper boundary for the value. + /// + /// if value <= max. + /// if value > max. + /// + internal static object BindToRange(object value, object min, object max) + { + if (value is IComparable result) + { + return result.CompareTo(max) <= 0 ? result : min; + } + else + { + return value; + } + } +} diff --git a/src/Design/Randomization/DataRandom.cs b/src/Design/Randomization/DataRandom.cs new file mode 100644 index 00000000..9c07c2aa --- /dev/null +++ b/src/Design/Randomization/DataRandom.cs @@ -0,0 +1,69 @@ +using System.Collections.Frozen; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Context; +using Werecodent.CreateAndFake.Design.Extensions; + +namespace Werecodent.CreateAndFake.Design.Randomization; + +/// Collects random predefined values to use for data generation. +/// +public sealed class DataRandom(IRandom gen) +{ + /// Supported searchable names for values. + private static readonly FrozenDictionary> _Matcher = + new Dictionary>() + { + { "FIRSTNAME", dat => dat.Person.FirstName }, + { "MIDDLENAME", dat => dat.Person.MiddleName }, + { "LASTNAME", dat => dat.Person.LastName }, + { "FULLNAME", dat => dat.Person.FullName }, + { "INITIALS", dat => dat.Person.Initials }, + } + .SelectMany(pair => new[] { pair, new("GET" + pair.Key, pair.Value) }) + .ToFrozenDictionary(); + + /// All searchable names. + internal static IEnumerable SupportedProperties { get; } = _Matcher.Keys.ToFrozenSet(); + + /// + private readonly Lazy _person = new(() => new PersonContext(gen)); + + /// + public PersonContext Person => _person.Value; + + /// Searches for an identifying value representing the . + /// Property with the name to find a value for. + /// A value for the if found, otherwise. + public string? Find(PropertyInfo property) + { + ArgumentGuard.ThrowIfNull(property); + return property.PropertyType.IsInheritedBy() ? Find(property.Name) : null; + } + + /// Searches for an identifying value representing the . + /// Field with the name to find a value for. + /// A value for the if found, otherwise. + public string? Find(FieldInfo field) + { + ArgumentGuard.ThrowIfNull(field); + return field.FieldType.IsInheritedBy() ? Find(field.Name) : null; + } + + /// Searches for an identifying value representing the . + /// Name to find a value for. + /// A value for the if found, otherwise. + public string? Find(string? name) + { + return _Matcher.TryGetValue(ToUpperOnly(name), out Func? finder) + ? finder.Invoke(this) + : null; + } + + /// Converts the to uppercase letters only. + /// Text to convert. + /// The uppercase equivalent of the 's letters. + private static string ToUpperOnly(string? value) + { + return string.Concat(value?.ToUpperInvariant().Where(c => c is >= 'A' and <= 'Z') ?? []); + } +} diff --git a/src/Design/Randomization/FastRandom.cs b/src/Design/Randomization/FastRandom.cs new file mode 100644 index 00000000..91add423 --- /dev/null +++ b/src/Design/Randomization/FastRandom.cs @@ -0,0 +1,40 @@ +using Werecodent.CreateAndFake.Design.Properties; + +namespace Werecodent.CreateAndFake.Design.Randomization; + +#pragma warning disable CA5394 // Secure alternative provided. + +/// For quickly generating cryptographically insecure random values. +/// +public sealed class FastRandom( + int iterationLimit = DesignDefaults.IterationLimit, + bool onlyValidValues = !DesignDefaults.IncludeInfinityAndNaNGeneration +) : ValueRandom(iterationLimit, onlyValidValues) +{ + /// Prevents concurrency issues for . + private static readonly Lock _Lock = new(); + + /// Source generator used for random s. + private static readonly Random _Gen = new(); + + /// + public override int? InitialSeed { get; } = null; + + /// + public override byte[] NextBytes(short length) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException(nameof(length), length, "Cannot be negative."); + } + + byte[] buffer = new byte[length]; + lock (_Lock) + { + _Gen.NextBytes(buffer); + } + return buffer; + } +} + +#pragma warning restore diff --git a/src/Design/Randomization/Handlers/BFloat16ValueHandler.cs b/src/Design/Randomization/Handlers/BFloat16ValueHandler.cs new file mode 100644 index 00000000..e0abe667 --- /dev/null +++ b/src/Design/Randomization/Handlers/BFloat16ValueHandler.cs @@ -0,0 +1,86 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing BFloat16 values. +[ExcludeFromCreateAndFake] +internal sealed class BFloat16ValueHandler : IValueHandler +{ + /// Attempts to create a handler if BFloat16 exists in the current .NET version. + /// The created handler if BFloat16 exists, null otherwise. + internal static BFloat16ValueHandler? TryToCreate() + { + try + { + return new BFloat16ValueHandler( + Assembly.Load("System.Private.CoreLib").GetType("System.Numerics.BFloat16", true)! + ); + } + catch + { + return null; + } + } + + /// Handles converting using dynamic with generics. + private readonly MethodInfo _maker; + + /// Represents the smallest possible value of BFloat16. + private readonly float _minBFloat; + + /// Represents the largest possible value of BFloat16. + private readonly float _maxBFloat; + + /// + public Type? SupportedType { get; } + + /// + /// BFloat16 if current .NET version supports it. + private BFloat16ValueHandler(Type bFloat16Type) + { + SupportedType = bFloat16Type; + + _minBFloat = (float) + (dynamic) + bFloat16Type + .GetProperty("MinValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + _maxBFloat = (float) + (dynamic) + bFloat16Type + .GetProperty("MaxValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + + _maker = typeof(BFloat16ValueHandler) + .GetMethod(nameof(CastFromFloat), BindingFlags.NonPublic | BindingFlags.Static)! + .MakeGenericMethod(bFloat16Type); + } + + /// + public object CreateSupported(IRandom gen) + { + return _maker.Invoke(null, [gen.Next(_minBFloat, _maxBFloat)])!; + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, 0, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + return _maker.Invoke(null, [gen.Next((float)(dynamic)min, (float)(dynamic)max)])!; + } + + /// Converts to BFloat16. + /// . + /// Value to convert. + /// The converted value. + private static T CastFromFloat(float value) + { + return (T)(dynamic)value; + } +} diff --git a/src/Design/Randomization/Handlers/BigIntegerValueHandler.cs b/src/Design/Randomization/Handlers/BigIntegerValueHandler.cs new file mode 100644 index 00000000..40e5febb --- /dev/null +++ b/src/Design/Randomization/Handlers/BigIntegerValueHandler.cs @@ -0,0 +1,51 @@ +using System.Numerics; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +#pragma warning disable IDE0056 // Indexing not available. + +/// +internal sealed class BigIntegerValueHandler : ValueHandler +{ + /// + protected override BigInteger Create(IRandom gen) + { + return new BigInteger(gen.NextBytes(8)); + } + + /// + protected override BigInteger Create(IRandom gen, BigInteger min, BigInteger max) + { + BigInteger range = max - min; + byte[] rangeBytes = range.ToByteArray(); + + byte zeroBitsMask = 0b00000000; + byte mostSignificantByte = rangeBytes[rangeBytes.Length - 1]; + + for (int i = 7; i >= 0; i--) // Sign bit 8 is always 0 for a positive range. + { + if ((mostSignificantByte & (0b1 << i)) != 0) + { + // Caps randomization range to only bits with values to improve performance. + zeroBitsMask = (byte)(0b11111111 >> (7 - i)); + break; + } + } + + int j = 0; + BigInteger result; + do + { + ArgumentGuard.ThrowUponIterationLimit(j++); + + byte[] bytes = gen.NextBytes((short)rangeBytes.Length); + bytes[bytes.Length - 1] &= zeroBitsMask; + + result = new BigInteger(bytes); + } while (result > range); + + return result + min; + } +} + +#pragma warning restore diff --git a/src/Design/Randomization/Handlers/BoolValueHandler.cs b/src/Design/Randomization/Handlers/BoolValueHandler.cs new file mode 100644 index 00000000..14736a70 --- /dev/null +++ b/src/Design/Randomization/Handlers/BoolValueHandler.cs @@ -0,0 +1,17 @@ +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// +internal sealed class BoolValueHandler : ValueHandler +{ + /// + protected override bool Create(IRandom gen) + { + return gen.NextBytes(1)[0] % 2 == 1; + } + + /// + protected override bool Create(IRandom gen, bool min, bool max) + { + return min == max ? min : Create(gen); + } +} diff --git a/src/Design/Randomization/Handlers/DateOnlyValueHandler.cs b/src/Design/Randomization/Handlers/DateOnlyValueHandler.cs new file mode 100644 index 00000000..2dd634a7 --- /dev/null +++ b/src/Design/Randomization/Handlers/DateOnlyValueHandler.cs @@ -0,0 +1,64 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing DateOnly values. +[ExcludeFromCreateAndFake] +internal sealed class DateOnlyValueHandler : IValueHandler +{ + /// Number of days from 1/1/0001 to 12/31/9999. + private const int _MaxDayNumber = 3652058; + + /// DateOnly factory using day numbers. + private readonly MethodInfo _createFromDayNumber; + + /// Attempts to create a handler if DateOnly exists in the current .NET version. + /// The created handler if DateOnly exists, null otherwise. + internal static DateOnlyValueHandler? TryToCreate() + { + try + { + return new DateOnlyValueHandler( + Assembly.Load("System.Runtime").GetType("System.DateOnly", true)! + ); + } + catch + { + return null; + } + } + + /// + public Type? SupportedType { get; } + + /// + /// DateOnly if current .NET version supports it. + private DateOnlyValueHandler(Type dateOnlyType) + { + SupportedType = dateOnlyType; + + _createFromDayNumber = dateOnlyType.GetMethod("FromDayNumber")!; + } + + /// + public object CreateSupported(IRandom gen) + { + int dayNumber = gen.Next(0, _MaxDayNumber); + return _createFromDayNumber.Invoke(null, [dayNumber])!; + } + + /// + public object CreateSupported(IRandom gen, object max) + { + int dayNumber = gen.Next(0, ((dynamic)max).DayNumber); + return _createFromDayNumber.Invoke(null, [dayNumber])!; + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + int dayNumber = gen.Next(((dynamic)min).DayNumber, ((dynamic)max).DayNumber); + return _createFromDayNumber.Invoke(null, [dayNumber])!; + } +} diff --git a/src/Design/Randomization/Handlers/DateTimeOffsetValueHandler.cs b/src/Design/Randomization/Handlers/DateTimeOffsetValueHandler.cs new file mode 100644 index 00000000..2742c468 --- /dev/null +++ b/src/Design/Randomization/Handlers/DateTimeOffsetValueHandler.cs @@ -0,0 +1,28 @@ +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// +internal sealed class DateTimeOffsetValueHandler : ValueHandler +{ + /// Maximum supported . + private const long _MaxOffsetTicks = 14 * TimeSpan.TicksPerHour; + + /// + protected override DateTimeOffset Create(IRandom gen) + { + return Create(gen, DateTimeOffset.MinValue, DateTimeOffset.MaxValue); + } + + /// + protected override DateTimeOffset Create(IRandom gen, DateTimeOffset min, DateTimeOffset max) + { + long ticks = gen.Next(min.Ticks - min.Offset.Ticks, max.Ticks - max.Offset.Ticks); + + long offset = + gen.Next( + -Math.Min(ticks - DateTime.MinValue.Ticks, _MaxOffsetTicks), + Math.Min(DateTime.MaxValue.Ticks - ticks, _MaxOffsetTicks) + ) / TimeSpan.TicksPerMinute; + + return new(ticks + offset * TimeSpan.TicksPerMinute, TimeSpan.FromMinutes(offset)); + } +} diff --git a/src/Design/Randomization/Handlers/DateTimeValueHandler.cs b/src/Design/Randomization/Handlers/DateTimeValueHandler.cs new file mode 100644 index 00000000..45dbb035 --- /dev/null +++ b/src/Design/Randomization/Handlers/DateTimeValueHandler.cs @@ -0,0 +1,29 @@ +using System.Collections.Immutable; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +#pragma warning disable CA2263 // Not available in all .NET versions. + +/// +internal sealed class DateTimeValueHandler : ValueHandler +{ + /// All possible s. + private static readonly ImmutableArray _Kinds = + [ + .. Enum.GetValues(typeof(DateTimeKind)).Cast(), + ]; + + /// + protected override DateTime Create(IRandom gen) + { + return Create(gen, DateTime.MinValue, DateTime.MaxValue); + } + + /// + protected override DateTime Create(IRandom gen, DateTime min, DateTime max) + { + return new DateTime(gen.Next(min.Ticks, max.Ticks), gen.NextItem(_Kinds)); + } +} + +#pragma warning restore diff --git a/src/Design/Randomization/Handlers/Decimal128ValueHandler.cs b/src/Design/Randomization/Handlers/Decimal128ValueHandler.cs new file mode 100644 index 00000000..350c06b1 --- /dev/null +++ b/src/Design/Randomization/Handlers/Decimal128ValueHandler.cs @@ -0,0 +1,103 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing Decimal128 values. +[ExcludeFromCreateAndFake] +internal sealed class Decimal128ValueHandler : IValueHandler +{ + /// Attempts to create a handler if Decimal128 exists in the current .NET version. + /// The created handler if Decimal128 exists, null otherwise. + internal static Decimal128ValueHandler? TryToCreate() + { + try + { + return new Decimal128ValueHandler( + Assembly.Load("System.Private.CoreLib").GetType("System.Numerics.Decimal128", true)! + ); + } + catch + { + return null; + } + } + + /// Handles randomization using dynamic with generics. + private readonly MethodInfo _maker; + + /// Determines if a Decimal128 is -∞. + private readonly MethodInfo _isNegativeInfinity; + + /// Determines if a Decimal128 is ∞. + private readonly MethodInfo _isPositiveInfinity; + + /// Represents 0 for Decimal128. + private readonly object _zero; + + /// Represents the smallest possible value of Decimal128. + private readonly object _minDecimal128; + + /// Represents the largest possible value of Decimal128. + private readonly object _maxDecimal128; + + /// + public Type? SupportedType { get; } + + /// + /// Decimal128 if current .NET version supports it. + private Decimal128ValueHandler(Type decimal32Type) + { + SupportedType = decimal32Type; + + _zero = Activator.CreateInstance(decimal32Type)!; + _minDecimal128 = decimal32Type + .GetProperty("MinValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + _maxDecimal128 = decimal32Type + .GetProperty("MaxValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + + _isNegativeInfinity = decimal32Type.GetMethod( + "IsNegativeInfinity", + BindingFlags.Public | BindingFlags.Static + )!; + _isPositiveInfinity = decimal32Type.GetMethod( + "IsPositiveInfinity", + BindingFlags.Public | BindingFlags.Static + )!; + _maker = typeof(Decimal128ValueHandler) + .GetMethod(nameof(Create), BindingFlags.NonPublic | BindingFlags.Instance)! + .MakeGenericMethod(decimal32Type); + } + + /// + public object CreateSupported(IRandom gen) + { + return CreateSupported(gen, _minDecimal128, _maxDecimal128); + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, _zero, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + return _maker.Invoke(this, [gen, min, max])!; + } + + /// + private T Create(IRandom gen, dynamic min, dynamic max) + where T : IComparable + { + dynamic usefulMin = (bool)_isNegativeInfinity.Invoke(null, [min])! ? _minDecimal128 : min; + dynamic usefulMax = (bool)_isPositiveInfinity.Invoke(null, [max])! ? _maxDecimal128 : max; + + dynamic percent = gen.NextPercent(); + T result = usefulMax * (T)percent + usefulMin * (T)(1d - percent); + return result.CompareTo(min) > 0 ? result : min; + } +} diff --git a/src/Design/Randomization/Handlers/Decimal32ValueHandler.cs b/src/Design/Randomization/Handlers/Decimal32ValueHandler.cs new file mode 100644 index 00000000..64beb49b --- /dev/null +++ b/src/Design/Randomization/Handlers/Decimal32ValueHandler.cs @@ -0,0 +1,103 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing Decimal32 values. +[ExcludeFromCreateAndFake] +internal sealed class Decimal32ValueHandler : IValueHandler +{ + /// Attempts to create a handler if Decimal32 exists in the current .NET version. + /// The created handler if Decimal32 exists, null otherwise. + internal static Decimal32ValueHandler? TryToCreate() + { + try + { + return new Decimal32ValueHandler( + Assembly.Load("System.Private.CoreLib").GetType("System.Numerics.Decimal32", true)! + ); + } + catch + { + return null; + } + } + + /// Handles randomization using dynamic with generics. + private readonly MethodInfo _maker; + + /// Determines if a Decimal32 is -∞. + private readonly MethodInfo _isNegativeInfinity; + + /// Determines if a Decimal32 is ∞. + private readonly MethodInfo _isPositiveInfinity; + + /// Represents 0 for Decimal32. + private readonly object _zero; + + /// Represents the smallest possible value of Decimal32. + private readonly object _minDecimal32; + + /// Represents the largest possible value of Decimal32. + private readonly object _maxDecimal32; + + /// + public Type? SupportedType { get; } + + /// + /// Decimal32 if current .NET version supports it. + private Decimal32ValueHandler(Type decimal32Type) + { + SupportedType = decimal32Type; + + _zero = Activator.CreateInstance(decimal32Type)!; + _minDecimal32 = decimal32Type + .GetProperty("MinValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + _maxDecimal32 = decimal32Type + .GetProperty("MaxValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + + _isNegativeInfinity = decimal32Type.GetMethod( + "IsNegativeInfinity", + BindingFlags.Public | BindingFlags.Static + )!; + _isPositiveInfinity = decimal32Type.GetMethod( + "IsPositiveInfinity", + BindingFlags.Public | BindingFlags.Static + )!; + _maker = typeof(Decimal32ValueHandler) + .GetMethod(nameof(Create), BindingFlags.NonPublic | BindingFlags.Instance)! + .MakeGenericMethod(decimal32Type); + } + + /// + public object CreateSupported(IRandom gen) + { + return CreateSupported(gen, _minDecimal32, _maxDecimal32); + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, _zero, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + return _maker.Invoke(this, [gen, min, max])!; + } + + /// + private T Create(IRandom gen, dynamic min, dynamic max) + where T : IComparable + { + dynamic usefulMin = (bool)_isNegativeInfinity.Invoke(null, [min])! ? _minDecimal32 : min; + dynamic usefulMax = (bool)_isPositiveInfinity.Invoke(null, [max])! ? _maxDecimal32 : max; + + dynamic percent = gen.NextPercent(); + T result = usefulMax * (T)percent + usefulMin * (T)(1d - percent); + return result.CompareTo(min) > 0 ? result : min; + } +} diff --git a/src/Design/Randomization/Handlers/Decimal64ValueHandler.cs b/src/Design/Randomization/Handlers/Decimal64ValueHandler.cs new file mode 100644 index 00000000..4a3d9a2c --- /dev/null +++ b/src/Design/Randomization/Handlers/Decimal64ValueHandler.cs @@ -0,0 +1,103 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing Decimal64 values. +[ExcludeFromCreateAndFake] +internal sealed class Decimal64ValueHandler : IValueHandler +{ + /// Attempts to create a handler if Decimal64 exists in the current .NET version. + /// The created handler if Decimal64 exists, null otherwise. + internal static Decimal64ValueHandler? TryToCreate() + { + try + { + return new Decimal64ValueHandler( + Assembly.Load("System.Private.CoreLib").GetType("System.Numerics.Decimal64", true)! + ); + } + catch + { + return null; + } + } + + /// Handles randomization using dynamic with generics. + private readonly MethodInfo _maker; + + /// Determines if a Decimal64 is -∞. + private readonly MethodInfo _isNegativeInfinity; + + /// Determines if a Decimal64 is ∞. + private readonly MethodInfo _isPositiveInfinity; + + /// Represents 0 for Decimal64. + private readonly object _zero; + + /// Represents the smallest possible value of Decimal64. + private readonly object _minDecimal64; + + /// Represents the largest possible value of Decimal64. + private readonly object _maxDecimal64; + + /// + public Type? SupportedType { get; } + + /// + /// Decimal64 if current .NET version supports it. + private Decimal64ValueHandler(Type decimal32Type) + { + SupportedType = decimal32Type; + + _zero = Activator.CreateInstance(decimal32Type)!; + _minDecimal64 = decimal32Type + .GetProperty("MinValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + _maxDecimal64 = decimal32Type + .GetProperty("MaxValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + + _isNegativeInfinity = decimal32Type.GetMethod( + "IsNegativeInfinity", + BindingFlags.Public | BindingFlags.Static + )!; + _isPositiveInfinity = decimal32Type.GetMethod( + "IsPositiveInfinity", + BindingFlags.Public | BindingFlags.Static + )!; + _maker = typeof(Decimal64ValueHandler) + .GetMethod(nameof(Create), BindingFlags.NonPublic | BindingFlags.Instance)! + .MakeGenericMethod(decimal32Type); + } + + /// + public object CreateSupported(IRandom gen) + { + return CreateSupported(gen, _minDecimal64, _maxDecimal64); + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, _zero, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + return _maker.Invoke(this, [gen, min, max])!; + } + + /// + private T Create(IRandom gen, dynamic min, dynamic max) + where T : IComparable + { + dynamic usefulMin = (bool)_isNegativeInfinity.Invoke(null, [min])! ? _minDecimal64 : min; + dynamic usefulMax = (bool)_isPositiveInfinity.Invoke(null, [max])! ? _maxDecimal64 : max; + + dynamic percent = gen.NextPercent(); + T result = usefulMax * (T)percent + usefulMin * (T)(1d - percent); + return result.CompareTo(min) > 0 ? result : min; + } +} diff --git a/src/Design/Randomization/Handlers/DecimalValueHandler.cs b/src/Design/Randomization/Handlers/DecimalValueHandler.cs new file mode 100644 index 00000000..744f1aa8 --- /dev/null +++ b/src/Design/Randomization/Handlers/DecimalValueHandler.cs @@ -0,0 +1,43 @@ +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// +internal sealed class DecimalValueHandler : ValueHandler +{ + /// + protected override decimal Create(IRandom gen) + { + return new decimal( + gen.Next(), + gen.Next(), + gen.Next(), + gen.Next(), + gen.Next(29) + ); + } + + /// + protected override decimal Create(IRandom gen, decimal min, decimal max) + { + for (int i = 0; true; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + decimal percent = NextPercent(gen); + try + { + decimal result = max * percent + min * (1.0m - percent); + return result.CompareTo(min) > 0 ? result : min; + } + catch (OverflowException) + { + // Rare edge case due to decimal imprecision. + } + } + } + + /// + private static decimal NextPercent(IRandom gen) + { + return new(gen.Next(), gen.Next(), gen.Next(542101086), false, 28); + } +} diff --git a/src/Design/Randomization/Handlers/DoubleValueHandler.cs b/src/Design/Randomization/Handlers/DoubleValueHandler.cs new file mode 100644 index 00000000..48549f62 --- /dev/null +++ b/src/Design/Randomization/Handlers/DoubleValueHandler.cs @@ -0,0 +1,38 @@ +using System.Collections.Frozen; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// +internal sealed class DoubleValueHandler : ValueHandler +{ + /// Abnormal double values to potentially exclude. + private static readonly FrozenSet _SpecialDoubles = FrozenSet.Create( + double.NaN, + double.NegativeInfinity, + double.PositiveInfinity + ); + + /// + protected override double Create(IRandom gen) + { + int i = 0; + double value; + do + { + ArgumentGuard.ThrowUponIterationLimit(i++); + value = BitConverter.ToDouble(gen.NextBytes(8), 0); + } while (gen.OnlyValidValues && _SpecialDoubles.Contains(value)); + return value; + } + + /// + protected override double Create(IRandom gen, double min, double max) + { + double usefulMin = double.IsNegativeInfinity(min) ? double.MinValue : min; + double usefulMax = double.IsPositiveInfinity(max) ? double.MaxValue : max; + + double percent = gen.NextPercent(); + double result = usefulMax * percent + usefulMin * (1d - percent); + return result.CompareTo(min) > 0 ? result : min; + } +} diff --git a/src/Design/Randomization/Handlers/FloatValueHandler.cs b/src/Design/Randomization/Handlers/FloatValueHandler.cs new file mode 100644 index 00000000..99c09385 --- /dev/null +++ b/src/Design/Randomization/Handlers/FloatValueHandler.cs @@ -0,0 +1,37 @@ +using System.Collections.Frozen; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// +internal sealed class FloatValueHandler : ValueHandler +{ + /// Abnormal float values to potentially exclude. + private static readonly FrozenSet _SpecialFloats = FrozenSet.Create( + float.NaN, + float.NegativeInfinity, + float.PositiveInfinity + ); + + /// + protected override float Create(IRandom gen) + { + int i = 0; + float value; + do + { + ArgumentGuard.ThrowUponIterationLimit(i++); + value = BitConverter.ToSingle(gen.NextBytes(4), 0); + } while (gen.OnlyValidValues && _SpecialFloats.Contains(value)); + return value; + } + + /// + protected override float Create(IRandom gen, float min, float max) + { + float usefulMin = float.IsNegativeInfinity(min) ? float.MinValue : min; + float usefulMax = float.IsPositiveInfinity(max) ? float.MaxValue : max; + + double percent = gen.NextPercent(); + return (float)(usefulMax * percent + usefulMin * (1d - percent)); + } +} diff --git a/src/Design/Randomization/Handlers/GuidValueHandler.cs b/src/Design/Randomization/Handlers/GuidValueHandler.cs new file mode 100644 index 00000000..73cd3a34 --- /dev/null +++ b/src/Design/Randomization/Handlers/GuidValueHandler.cs @@ -0,0 +1,40 @@ +using System.Globalization; +using System.Numerics; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// +internal sealed class GuidValueHandler : ValueHandler +{ + /// + protected override Guid Create(IRandom gen) + { + return new Guid(gen.NextBytes(16)); + } + + /// + protected override Guid Create(IRandom gen, Guid min, Guid max) + { + return ToGuid(gen.Next(ToBigInteger(min), ToBigInteger(max))); + } + + /// Converts via 's hex representation. + /// Instance to convert. + /// The converted . + internal static BigInteger ToBigInteger(Guid value) + { + return BigInteger.Parse( + "0" + value.ToString("N"), + NumberStyles.AllowHexSpecifier, + CultureInfo.InvariantCulture + ); + } + + /// Converts via 's hex representation. + /// Instance to convert. + /// The converted . + internal static Guid ToGuid(BigInteger value) + { + return Guid.Parse(value.ToString("x33", CultureInfo.InvariantCulture).Remove(0, 1)); + } +} diff --git a/src/Design/Randomization/Handlers/HalfValueHandler.cs b/src/Design/Randomization/Handlers/HalfValueHandler.cs new file mode 100644 index 00000000..daee7f2d --- /dev/null +++ b/src/Design/Randomization/Handlers/HalfValueHandler.cs @@ -0,0 +1,86 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing Half values. +[ExcludeFromCreateAndFake] +internal sealed class HalfValueHandler : IValueHandler +{ + /// Attempts to create a handler if Half exists in the current .NET version. + /// The created handler if Half exists, null otherwise. + internal static HalfValueHandler? TryToCreate() + { + try + { + return new HalfValueHandler( + Assembly.Load("System.Runtime").GetType("System.Half", true)! + ); + } + catch + { + return null; + } + } + + /// Handles converting using dynamic with generics. + private readonly MethodInfo _maker; + + /// Represents the smallest possible value of Half. + private readonly float _minHalf; + + /// Represents the largest possible value of Half. + private readonly float _maxHalf; + + /// + public Type? SupportedType { get; } + + /// + /// Half if current .NET version supports it. + private HalfValueHandler(Type halfType) + { + SupportedType = halfType; + + _minHalf = (float) + (dynamic) + halfType + .GetProperty("MinValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + _maxHalf = (float) + (dynamic) + halfType + .GetProperty("MaxValue", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + + _maker = typeof(HalfValueHandler) + .GetMethod(nameof(CastFromFloat), BindingFlags.NonPublic | BindingFlags.Static)! + .MakeGenericMethod(halfType); + } + + /// + public object CreateSupported(IRandom gen) + { + return _maker.Invoke(null, [gen.Next(_minHalf, _maxHalf)])!; + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, 0f, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + return _maker.Invoke(null, [gen.Next((float)(dynamic)min, (float)(dynamic)max)])!; + } + + /// Converts to Half. + /// . + /// Value to convert. + /// The converted value. + private static T CastFromFloat(float value) + { + return (T)(dynamic)value; + } +} diff --git a/src/Design/Randomization/Handlers/IValueHandler.cs b/src/Design/Randomization/Handlers/IValueHandler.cs new file mode 100644 index 00000000..566add90 --- /dev/null +++ b/src/Design/Randomization/Handlers/IValueHandler.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handle randomizing a specific value type. +internal interface IValueHandler : ITypeSupporter +{ + /// Generates a random value of the . + /// Handles randomizing supporting values. + /// + object CreateSupported(IRandom gen); + + /// Generates a positive constrained value of the . + /// Handles randomizing supporting values. + /// Handlers may return ; bound constrained by . + /// + object CreateSupported(IRandom gen, object max); + + /// Generates a constrained value of the . + /// Handles randomizing supporting values. + /// + object CreateSupported(IRandom gen, object min, object max); +} diff --git a/src/Design/Randomization/Handlers/Int128ValueHandler.cs b/src/Design/Randomization/Handlers/Int128ValueHandler.cs new file mode 100644 index 00000000..e96f98b9 --- /dev/null +++ b/src/Design/Randomization/Handlers/Int128ValueHandler.cs @@ -0,0 +1,67 @@ +using System.Numerics; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing Int128 values. +[ExcludeFromCreateAndFake] +internal sealed class Int128ValueHandler : IValueHandler +{ + /// Attempts to create a handler if Int128 exists in the current .NET version. + /// The created handler if Int128 exists, null otherwise. + internal static Int128ValueHandler? TryToCreate() + { + try + { + return new Int128ValueHandler( + Assembly.Load("System.Private.CoreLib").GetType("System.Int128", true)! + ); + } + catch + { + return null; + } + } + + /// Handles randomization using dynamic with generics. + private readonly MethodInfo _maker; + + /// + public Type? SupportedType { get; } + + /// + /// Int128 if current .NET version supports it. + private Int128ValueHandler(Type int128Type) + { + SupportedType = int128Type; + + _maker = typeof(Int128ValueHandler) + .GetMethod(nameof(CreateViaBigInteger), BindingFlags.NonPublic | BindingFlags.Static)! + .MakeGenericMethod(int128Type); + } + + /// + public object CreateSupported(IRandom gen) + { + return Activator.CreateInstance(SupportedType!, [gen.Next(), gen.Next()])!; + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, 0, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + return _maker.Invoke(null, [gen, min, max])!; + } + + /// + private static T CreateViaBigInteger(IRandom gen, object min, object max) + { + return (T)(dynamic)gen.Next((BigInteger)(dynamic)min, (BigInteger)(dynamic)max); + } +} diff --git a/src/Design/Randomization/Handlers/IntPtrValueHandler.cs b/src/Design/Randomization/Handlers/IntPtrValueHandler.cs new file mode 100644 index 00000000..b2280df6 --- /dev/null +++ b/src/Design/Randomization/Handlers/IntPtrValueHandler.cs @@ -0,0 +1,41 @@ +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing values. +/// The size of a signed integer in the executing process, measured in bytes. +internal sealed class IntPtrValueHandler(int size) : IValueHandler +{ + /// + public Type? SupportedType { get; } = typeof(IntPtr); + + /// + public object CreateSupported(IRandom gen) + { + if (size == 4) + { + return new IntPtr(gen.Next()); + } + else + { + return new IntPtr(gen.Next()); + } + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, (IntPtr)default, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + if (size == 4) + { + return new IntPtr(gen.Next(((IntPtr)min).ToInt32(), ((IntPtr)max).ToInt32())); + } + else + { + return new IntPtr(gen.Next(((IntPtr)min).ToInt64(), ((IntPtr)max).ToInt64())); + } + } +} diff --git a/src/Design/Randomization/Handlers/IntegralValueHandler.cs b/src/Design/Randomization/Handlers/IntegralValueHandler.cs new file mode 100644 index 00000000..714bfd3b --- /dev/null +++ b/src/Design/Randomization/Handlers/IntegralValueHandler.cs @@ -0,0 +1,34 @@ +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// +/// Size of in bytes. +/// Converts random bytes to . +/// Not to be used for floating-point numeric types. +internal sealed class IntegralValueHandler(short byteSize, Func bitFactory) + : IValueHandler + where T : struct, IComparable, IComparable, IEquatable +{ + /// + public Type? SupportedType => typeof(T); + + /// + public object CreateSupported(IRandom gen) + { + return bitFactory.Invoke(gen.NextBytes(byteSize), 0); + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return (T)Math.Floor(gen.NextPercent() * (dynamic)max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + T result = (T)Math.Floor(gen.NextPercent() * (1.0 + (dynamic)max - (T)min) + (T)min); + + // Algorithm can rarely produce an overflow in .NET 4.8. + return result.CompareTo(min) > 0 ? result : min; + } +} diff --git a/src/Design/Randomization/Handlers/NFloatValueHandler.cs b/src/Design/Randomization/Handlers/NFloatValueHandler.cs new file mode 100644 index 00000000..e58959f6 --- /dev/null +++ b/src/Design/Randomization/Handlers/NFloatValueHandler.cs @@ -0,0 +1,87 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing NFloat values. +[ExcludeFromCreateAndFake] +internal sealed class NFloatValueHandler : IValueHandler +{ + /// Attempts to create a handler if NFloat exists in the current .NET version. + /// + /// The created handler if NFloat exists, null otherwise. + internal static NFloatValueHandler? TryToCreate(int? size = null) + { + try + { + return new NFloatValueHandler( + Assembly + .Load("System.Private.CoreLib") + .GetType("System.Runtime.InteropServices.NFloat", true)!, + size + ); + } + catch + { + return null; + } + } + + /// The size of a NFloat in the executing process, measured in bytes. + private readonly int _size; + + /// + public Type? SupportedType { get; } + + /// + /// NFloat if current .NET version supports it. + private NFloatValueHandler(Type nFloatType, int? size) + { + SupportedType = nFloatType; + + _size = + size + ?? (int) + nFloatType + .GetProperty("Size", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null)!; + } + + /// + public object CreateSupported(IRandom gen) + { + if (_size == 4) + { + return Activator.CreateInstance(SupportedType!, [gen.Next()])!; + } + else + { + return Activator.CreateInstance(SupportedType!, [gen.Next()])!; + } + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, 0f, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + if (_size == 4) + { + return Activator.CreateInstance( + SupportedType!, + [gen.Next(typeof(float), (float)(dynamic)min, (float)(dynamic)max)] + )!; + } + else + { + return Activator.CreateInstance( + SupportedType!, + [gen.Next(typeof(double), (double)(dynamic)min, (double)(dynamic)max)] + )!; + } + } +} diff --git a/src/Design/Randomization/Handlers/RuneValueHandler.cs b/src/Design/Randomization/Handlers/RuneValueHandler.cs new file mode 100644 index 00000000..884964ae --- /dev/null +++ b/src/Design/Randomization/Handlers/RuneValueHandler.cs @@ -0,0 +1,84 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +#pragma warning disable CA2263 // Not available in all .NET versions. + +/// Handles randomizing Rune values. +[ExcludeFromCreateAndFake] +internal sealed class RuneValueHandler : IValueHandler +{ + /// Determines if an can be used to successfully create a Rune. + private readonly Func _isValidRuneValue; + + /// Attempts to create a handler if Rune exists in the current .NET version. + /// The created handler if Rune exists, null otherwise. + internal static RuneValueHandler? TryToCreate() + { + try + { + return new RuneValueHandler( + Assembly.Load("System.Runtime").GetType("System.Text.Rune", true)! + ); + } + catch + { + return null; + } + } + + /// + public Type? SupportedType { get; } + + /// + /// Rune if current .NET version supports it. + private RuneValueHandler(Type runeType) + { + SupportedType = runeType; + + _isValidRuneValue = + (Func) + runeType + .GetMethod("IsValid", [typeof(int)])! + .CreateDelegate(typeof(Func)); + } + + /// + public object CreateSupported(IRandom gen) + { + int runeValue = NextRuneValue(gen, 0x0000, 0x10FFFF); + return Activator.CreateInstance(SupportedType!, [runeValue])!; + } + + /// + public object CreateSupported(IRandom gen, object max) + { + int runeValue = NextRuneValue(gen, 0x0000, ((dynamic)max).Value); + return Activator.CreateInstance(SupportedType!, [runeValue])!; + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + int runeValue = NextRuneValue(gen, ((dynamic)min).Value, ((dynamic)max).Value); + return Activator.CreateInstance(SupportedType!, [runeValue])!; + } + + /// Generates a constrained value that can be used to successfully create a Rune. + /// + private int NextRuneValue(IRandom gen, int min, int max) + { + int i = 0; + int result; + do + { + ArgumentGuard.ThrowUponIterationLimit(i++); + result = gen.Next(min, max); + } while (!_isValidRuneValue(result)); + + return result; + } +} + +#pragma warning restore diff --git a/src/Design/Randomization/Handlers/TimeOnlyValueHandler.cs b/src/Design/Randomization/Handlers/TimeOnlyValueHandler.cs new file mode 100644 index 00000000..9d1641bf --- /dev/null +++ b/src/Design/Randomization/Handlers/TimeOnlyValueHandler.cs @@ -0,0 +1,59 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing TimeOnly values. +[ExcludeFromCreateAndFake] +internal sealed class TimeOnlyValueHandler : IValueHandler +{ + /// Number of ticks in a day. + private const long _MaxTicks = TimeSpan.TicksPerDay - 1; + + /// Attempts to create a handler if TimeOnly exists in the current .NET version. + /// The created handler if TimeOnly exists, null otherwise. + internal static TimeOnlyValueHandler? TryToCreate() + { + try + { + return new TimeOnlyValueHandler( + Assembly.Load("System.Runtime").GetType("System.TimeOnly", true)! + ); + } + catch + { + return null; + } + } + + /// + public Type? SupportedType { get; } + + /// + /// TimeOnly if current .NET version supports it. + private TimeOnlyValueHandler(Type timeOnlyType) + { + SupportedType = timeOnlyType; + } + + /// + public object CreateSupported(IRandom gen) + { + long ticks = gen.Next(0, _MaxTicks); + return Activator.CreateInstance(SupportedType!, [ticks])!; + } + + /// + public object CreateSupported(IRandom gen, object max) + { + long ticks = gen.Next(0, ((dynamic)max).Ticks); + return Activator.CreateInstance(SupportedType!, [ticks])!; + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + long ticks = gen.Next(((dynamic)min).Ticks, ((dynamic)max).Ticks); + return Activator.CreateInstance(SupportedType!, [ticks])!; + } +} diff --git a/src/Design/Randomization/Handlers/TimeSpanValueHandler.cs b/src/Design/Randomization/Handlers/TimeSpanValueHandler.cs new file mode 100644 index 00000000..ff3079cc --- /dev/null +++ b/src/Design/Randomization/Handlers/TimeSpanValueHandler.cs @@ -0,0 +1,17 @@ +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// +internal sealed class TimeSpanValueHandler : ValueHandler +{ + /// + protected override TimeSpan Create(IRandom gen) + { + return Create(gen, TimeSpan.MinValue, TimeSpan.MaxValue); + } + + /// + protected override TimeSpan Create(IRandom gen, TimeSpan min, TimeSpan max) + { + return TimeSpan.FromTicks(gen.Next(min.Ticks, max.Ticks)); + } +} diff --git a/src/Design/Randomization/Handlers/UInt128ValueHandler.cs b/src/Design/Randomization/Handlers/UInt128ValueHandler.cs new file mode 100644 index 00000000..487fb697 --- /dev/null +++ b/src/Design/Randomization/Handlers/UInt128ValueHandler.cs @@ -0,0 +1,67 @@ +using System.Numerics; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing UInt128 values. +[ExcludeFromCreateAndFake] +internal sealed class UInt128ValueHandler : IValueHandler +{ + /// Attempts to create a handler if UInt128 exists in the current .NET version. + /// The created handler if UInt128 exists, null otherwise. + internal static UInt128ValueHandler? TryToCreate() + { + try + { + return new UInt128ValueHandler( + Assembly.Load("System.Private.CoreLib").GetType("System.UInt128", true)! + ); + } + catch + { + return null; + } + } + + /// Handles randomization using dynamic with generics. + private readonly MethodInfo _maker; + + /// + public Type? SupportedType { get; } + + /// + /// UInt128 if current .NET version supports it. + private UInt128ValueHandler(Type int128Type) + { + SupportedType = int128Type; + + _maker = typeof(UInt128ValueHandler) + .GetMethod(nameof(CreateViaBigInteger), BindingFlags.NonPublic | BindingFlags.Static)! + .MakeGenericMethod(int128Type); + } + + /// + public object CreateSupported(IRandom gen) + { + return Activator.CreateInstance(SupportedType!, [gen.Next(), gen.Next()])!; + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, 0, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + return _maker.Invoke(null, [gen, min, max])!; + } + + /// + private static T CreateViaBigInteger(IRandom gen, object min, object max) + { + return (T)(dynamic)gen.Next((BigInteger)(dynamic)min, (BigInteger)(dynamic)max); + } +} diff --git a/src/Design/Randomization/Handlers/UIntPtrValueHandler.cs b/src/Design/Randomization/Handlers/UIntPtrValueHandler.cs new file mode 100644 index 00000000..d71d3cd4 --- /dev/null +++ b/src/Design/Randomization/Handlers/UIntPtrValueHandler.cs @@ -0,0 +1,41 @@ +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +/// Handles randomizing values. +/// The size of an unsigned integer in the executing process, measured in bytes. +internal sealed class UIntPtrValueHandler(int size) : IValueHandler +{ + /// + public Type? SupportedType { get; } = typeof(UIntPtr); + + /// + public object CreateSupported(IRandom gen) + { + if (size == 4) + { + return new UIntPtr(gen.Next()); + } + else + { + return new UIntPtr(gen.Next()); + } + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, (UIntPtr)default, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + if (size == 4) + { + return new UIntPtr(gen.Next(((UIntPtr)min).ToUInt32(), ((UIntPtr)max).ToUInt32())); + } + else + { + return new UIntPtr(gen.Next(((UIntPtr)min).ToUInt64(), ((UIntPtr)max).ToUInt64())); + } + } +} diff --git a/src/Design/Randomization/Handlers/ValueHandler.cs b/src/Design/Randomization/Handlers/ValueHandler.cs new file mode 100644 index 00000000..1691d1c6 --- /dev/null +++ b/src/Design/Randomization/Handlers/ValueHandler.cs @@ -0,0 +1,38 @@ +namespace Werecodent.CreateAndFake.Design.Randomization.Handlers; + +#pragma warning disable IDE0004 // False positive. + +/// Handles randomizing values. +/// The . +internal abstract class ValueHandler : IValueHandler + where T : struct, IComparable, IComparable, IEquatable +{ + /// + public Type? SupportedType => typeof(T); + + /// + public object CreateSupported(IRandom gen) + { + return Create(gen); + } + + /// + public object CreateSupported(IRandom gen, object max) + { + return CreateSupported(gen, (T)default, max); + } + + /// + public object CreateSupported(IRandom gen, object min, object max) + { + return Create(gen, (T)min, (T)max); + } + + /// + protected abstract T Create(IRandom gen); + + /// + protected abstract T Create(IRandom gen, T min, T max); +} + +#pragma warning restore diff --git a/src/Design/Randomization/IRandom.cs b/src/Design/Randomization/IRandom.cs new file mode 100644 index 00000000..e6f9730c --- /dev/null +++ b/src/Design/Randomization/IRandom.cs @@ -0,0 +1,132 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Randomization; + +#pragma warning disable CA1716 // Matches the Random convention. + +/// Provides the core functionality for generic value randomization. +public interface IRandom +{ + /// First seed used to begin generating values if randomization is seeded. + /// Can be used to recreate the same sequence of values from randomization. + /// + int? InitialSeed { get; } + + /// Flag to prevent generating invalid values (NaN, -∞ and +∞). + bool OnlyValidValues { get; } + + /// Checks if can be used for . + /// The to check randomization support for. + /// + /// if is supported, otherwise. + /// + bool Supports() + where T : struct, IComparable, IComparable, IEquatable; + + /// Checks if the can be used for . + /// The to check randomization support for. + /// + /// if the is supported, otherwise. + /// + bool Supports([NotNullWhen(true)] Type? type); + + /// Generates a random value. + /// Value to generate. + /// The generated value. + /// If isn't supported. + T Next() + where T : struct, IComparable, IComparable, IEquatable; + + /// Generates a random value. + /// Value to generate. + /// The generated value. + /// If isn't supported. + object Next(Type valueType); + + /// Generates a positive constrained value. + /// Value to generate. + /// Positive exclusive upper boundary for the value. + /// + /// The generated value < and + /// >= 0. If == 0, 0 is returned instead. + /// + /// If isn't supported. + /// If < 0. + T Next(T max) + where T : struct, IComparable, IComparable, IEquatable; + + /// Generates a positive constrained value. + /// Value to generate. + /// Positive exclusive upper boundary for the value. + /// + /// The generated value < and + /// >= 0. If == 0, 0 is returned instead. + /// + /// If isn't supported. + /// If < 0. + object Next(Type valueType, object max); + + /// Generates a constrained value. + /// Value to generate. + /// Inclusive lower boundary for the value. + /// Inclusive upper boundary for the value. + /// + /// The generated value <= + /// and >= . + /// + /// If isn't supported. + /// If < . + T Next(T min, T max) + where T : struct, IComparable, IComparable, IEquatable; + + /// Generates a constrained value. + /// Value to generate. + /// Inclusive lower boundary for the value. + /// Inclusive upper boundary for the value. + /// + /// The generated value <= + /// and >= . + /// + /// If isn't supported. + /// If < . + object Next(Type valueType, object min, object max); + + /// Generates a [0,1) value for scaling. + /// The generated value >= 0 and < 1. + double NextPercent(); + + /// Generates a array filled with random bytes. + /// Length of the array to generate. + /// The generated array. + byte[] NextBytes(short length); + + /// The picked item from . + /// + /// If is or empty. + /// + /// + T NextItem(IEnumerable items); + + /// Picks a random item from . + /// of the items being picked from. + /// The collection of items to pick from. + /// + /// The picked item from if any exist, + /// value for otherwise. + /// + T? NextItemOrDefault(IEnumerable? items); + + /// Generates random predefined data.> + /// The generated group of random predefined data. + DataRandom NextData(); + + /// Generates a randomized sequence of the . + /// of the items being picked from. + /// The collection of items to pick from. + /// The sequence of randomly ordered. + [return: NotNullIfNotNull(nameof(items))] + IEnumerable? NextSequence(IEnumerable? items); +} + +#pragma warning restore diff --git a/src/Design/Randomization/SecureRandom.cs b/src/Design/Randomization/SecureRandom.cs new file mode 100644 index 00000000..d47b6774 --- /dev/null +++ b/src/Design/Randomization/SecureRandom.cs @@ -0,0 +1,31 @@ +using System.Security.Cryptography; +using Werecodent.CreateAndFake.Design.Properties; + +namespace Werecodent.CreateAndFake.Design.Randomization; + +/// For slowly generating cryptographically secure random values. +/// +public sealed class SecureRandom( + int iterationLimit = DesignDefaults.IterationLimit, + bool onlyValidValues = !DesignDefaults.IncludeInfinityAndNaNGeneration +) : ValueRandom(iterationLimit, onlyValidValues) +{ + /// + public override int? InitialSeed { get; } = null; + + /// Source generator used for random bytes. + private static readonly RandomNumberGenerator _Gen = RandomNumberGenerator.Create(); + + /// + public override byte[] NextBytes(short length) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException(nameof(length), length, "Cannot be negative."); + } + + byte[] buffer = new byte[length]; + _Gen.GetBytes(buffer); + return buffer; + } +} diff --git a/src/Design/Randomization/SeededRandom.cs b/src/Design/Randomization/SeededRandom.cs new file mode 100644 index 00000000..ce238620 --- /dev/null +++ b/src/Design/Randomization/SeededRandom.cs @@ -0,0 +1,84 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Properties; + +namespace Werecodent.CreateAndFake.Design.Randomization; + +#pragma warning disable CA5394, S2245 // Secure alternative provided. + +/// For generating deterministic random values. +public sealed class SeededRandom : ValueRandom, IDeepCloneable +{ + /// Prevents concurrency issues for . + private readonly Lock _lock = new(); + + /// + private int _seed; + + /// Current seed to be used for the next randomized value. + public int Seed + { + get + { + lock (_lock) + { + return _seed; + } + } + } + + /// + public override int? InitialSeed { get; } + + /// + public SeededRandom(int? seed = null) + : this(DesignDefaults.IterationLimit, !DesignDefaults.IncludeInfinityAndNaNGeneration, seed) + { } + + /// + /// + public SeededRandom(int iterationLimit, bool onlyValidValues, int? seed = null) + : base(iterationLimit, onlyValidValues) + { + InitialSeed = seed ?? Environment.TickCount; + _seed = InitialSeed.Value; + } + + /// + /// + /// + /// + private SeededRandom(int iterationLimit, bool onlyValidValues, int? initialSeed, int seed) + : base(iterationLimit, onlyValidValues) + { + InitialSeed = initialSeed; + _seed = seed; + } + + /// + public override byte[] NextBytes(short length) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException(nameof(length), length, "Cannot be negative."); + } + + Random gen; + lock (_lock) + { + gen = new Random(_seed); + _seed = gen.Next(); + } + + byte[] buffer = new byte[length]; + gen.NextBytes(buffer); + return buffer; + } + + /// + public SeededRandom DeepClone() + { + return new SeededRandom(IterationLimit, OnlyValidValues, InitialSeed, Seed); + } +} + +#pragma warning restore diff --git a/src/Design/Randomization/ValueRandom.cs b/src/Design/Randomization/ValueRandom.cs new file mode 100644 index 00000000..0a21a916 --- /dev/null +++ b/src/Design/Randomization/ValueRandom.cs @@ -0,0 +1,245 @@ +using System.Collections.Frozen; +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Properties; +using Werecodent.CreateAndFake.Design.Randomization.Handlers; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Randomization; + +/// +/// +/// +public abstract class ValueRandom( + int iterationLimit = DesignDefaults.IterationLimit, + bool onlyValidValues = !DesignDefaults.IncludeInfinityAndNaNGeneration +) : IRandom +{ + /// Handlers for all the supported types. + private static readonly IEnumerable _Handlers = Enumerable + .Empty() + .Concat([ + new BoolValueHandler(), + new GuidValueHandler(), + new FloatValueHandler(), + new DoubleValueHandler(), + new DecimalValueHandler(), + new TimeSpanValueHandler(), + new DateTimeValueHandler(), + new BigIntegerValueHandler(), + new DateTimeOffsetValueHandler(), + new IntPtrValueHandler(IntPtr.Size), + new UIntPtrValueHandler(UIntPtr.Size), + new IntegralValueHandler(2, BitConverter.ToChar), + new IntegralValueHandler(4, BitConverter.ToInt32), + new IntegralValueHandler(4, BitConverter.ToUInt32), + new IntegralValueHandler(8, BitConverter.ToInt64), + new IntegralValueHandler(8, BitConverter.ToUInt64), + new IntegralValueHandler(2, BitConverter.ToInt16), + new IntegralValueHandler(2, BitConverter.ToUInt16), + new IntegralValueHandler(1, (bytes, _) => bytes[0]), + new IntegralValueHandler(1, (bytes, _) => (sbyte)bytes[0]), + Decimal128ValueHandler.TryToCreate(), + Decimal64ValueHandler.TryToCreate(), + Decimal32ValueHandler.TryToCreate(), + DateOnlyValueHandler.TryToCreate(), + TimeOnlyValueHandler.TryToCreate(), + BFloat16ValueHandler.TryToCreate(), + UInt128ValueHandler.TryToCreate(), + Int128ValueHandler.TryToCreate(), + NFloatValueHandler.TryToCreate(), + HalfValueHandler.TryToCreate(), + RuneValueHandler.TryToCreate(), + ]) + .OfType(); + + /// Supported types paired with the handler used to generate them. + private static readonly IDictionary _HandlersByType = + TypeSupporter.GroupBySupportedType(_Handlers); + + /// Default values by their type. + private static readonly Dictionary _DefaultCache = _HandlersByType.ToDictionary( + p => p.Key, + p => Activator.CreateInstance(p.Key)! + ); + + /// All supported value types. + public static IEnumerable SupportedTypes { get; } = _HandlersByType.Keys.ToFrozenSet(); + + /// Max supported size for iterating uncollected sequences. + protected int IterationLimit { get; } = iterationLimit; + + /// + public bool OnlyValidValues { get; } = onlyValidValues; + + /// + public abstract int? InitialSeed { get; } + + /// + public abstract byte[] NextBytes(short length); + + /// + public double NextPercent() + { + return (Next() >> 11) * (1.0 / (1ul << 53)); + } + + /// + public bool Supports() + where T : struct, IComparable, IComparable, IEquatable + { + return Supports(typeof(T)); + } + + /// + public bool Supports([NotNullWhen(true)] Type? type) + { + return (type != null) && SupportedTypes.Contains(type); + } + + /// + public T Next() + where T : struct, IComparable, IComparable, IEquatable + { + return (T)Next(typeof(T)); + } + + /// + public object Next(Type valueType) + { + if (valueType is not null && _HandlersByType.TryGetValue(valueType, out IValueHandler? gen)) + { + return gen.CreateSupported(this); + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(valueType)}' not supported." + ); + } + } + + /// + public T Next(T max) + where T : struct, IComparable, IComparable, IEquatable + { + return (T)Next(typeof(T), max); + } + + /// + public object Next(Type valueType, object max) + { + ArgumentGuard.ThrowIfNull(valueType, max); + + if (_HandlersByType.TryGetValue(valueType, out IValueHandler? gen)) + { + object zero = _DefaultCache[valueType]; + + BoundaryChecker.EnforcePositiveMax(zero, max); + + return BoundaryChecker.BindToMax(gen.CreateSupported(this, max), zero, max); + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(valueType)}' not supported." + ); + } + } + + /// + public T Next(T min, T max) + where T : struct, IComparable, IComparable, IEquatable + { + return (T)Next(typeof(T), min, max); + } + + /// + public object Next(Type valueType, object min, object max) + { + ArgumentGuard.ThrowIfNull(valueType, min, max); + + if (_HandlersByType.TryGetValue(valueType, out IValueHandler? gen)) + { + BoundaryChecker.EnforceRange(min, max); + + return BoundaryChecker.BindToRange(gen.CreateSupported(this, min, max), min, max); + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(valueType)}' not supported." + ); + } + } + + /// + public T NextItem(IEnumerable items) + { + ArgumentGuard.ThrowIfNull(items); + + if (items is ICollection collection && collection.Count > 0) + { + return collection.ElementAt(Next(collection.Count)); + } + else if (items is IReadOnlyCollection readOnlyCollection && readOnlyCollection.Count > 0) + { + return readOnlyCollection.ElementAt(Next(readOnlyCollection.Count)); + } + else + { + return NextSequence(items).First(); + } + } + + /// + public T? NextItemOrDefault(IEnumerable? items) + { + if (items == null) + { + return default; + } + else if (items is ICollection collection && collection.Count > 0) + { + return collection.ElementAt(Next(collection.Count)); + } + else if (items is IReadOnlyCollection readOnlyCollection && readOnlyCollection.Count > 0) + { + return readOnlyCollection.ElementAt(Next(readOnlyCollection.Count)); + } + else + { + return NextSequence(items).FirstOrDefault(); + } + } + + /// + public DataRandom NextData() + { + return new(this); + } + + /// + [return: NotNullIfNotNull(nameof(items))] + public IEnumerable? NextSequence(IEnumerable? items) + { + return items == null ? null : CapSize(items).OrderBy(_ => Next()); + } + + /// Iterates . + /// The collection's item . + /// Series to iterate. + /// + /// + /// If the size is >= IterationLimit. + /// + private IEnumerable CapSize(IEnumerable items) + { + int i = 0; + foreach (T item in items) + { + ArgumentGuard.ThrowUponIterationLimit(i++, IterationLimit); + yield return item; + } + } +} diff --git a/src/Design/Reiteration/ILimiter.cs b/src/Design/Reiteration/ILimiter.cs new file mode 100644 index 00000000..56d5946d --- /dev/null +++ b/src/Design/Reiteration/ILimiter.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.Design.Reiteration; + +/// Provides the core functionality for repetition. +public interface ILimiter + : ILimiterAsync, + ILimiterSync, + ILimiterTask, + IValueEquatable, + IEquatable, + IComparable +{ + /// Calculates how long the constrains to. + /// How long an attempt is presumed to last. Defaults to 1. + /// The calculated duration. + /// If is <= 0. + TimeSpan GetMaxDurationEstimate(int millisecondsPerAttempt = 1); +} diff --git a/src/Design/Reiteration/ILimiterAsync.cs b/src/Design/Reiteration/ILimiterAsync.cs new file mode 100644 index 00000000..73b9ee89 --- /dev/null +++ b/src/Design/Reiteration/ILimiterAsync.cs @@ -0,0 +1,154 @@ +namespace Werecodent.CreateAndFake.Design.Reiteration; + +/// Provides the core functionality for asynchronous repetition. +public interface ILimiterAsync +{ + /// A that represents the asynchronous operation. + /// + Task RepeatAsync(string message, Action? behavior, CancellationToken canceler); + + /// + Task> RepeatAsync( + string message, + Func behavior, + CancellationToken canceler + ); + + /// A that represents the asynchronous operation. + /// + Task StallUntilAsync(string message, Func behavior, CancellationToken canceler); + + /// A that represents the asynchronous operation. + /// + Task StallUntilAsync( + string message, + Action? behavior, + Func checkState, + CancellationToken canceler + ); + + /// + Task> StallUntilAsync( + string message, + Func behavior, + Func checkState, + CancellationToken canceler + ); + + /// + Task> StallUntilAsync( + string message, + Func behavior, + Func checkState, + CancellationToken canceler + ); + + /// + Task RetryAsync(string message, Action behavior, CancellationToken canceler); + + /// + Task RetryAsync(string message, Action behavior, Action resetState, CancellationToken canceler); + + /// + Task RetryAsync(string message, Action behavior, CancellationToken canceler) + where TError : Exception; + + /// A that represents the asynchronous operation. + /// + Task RetryAsync( + string message, + Action behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task RetryAsync( + string message, + Func behavior, + CancellationToken canceler + ); + + /// + Task RetryAsync( + string message, + Func behavior, + Action resetState, + CancellationToken canceler + ); + + /// + Task RetryAsync( + string message, + Func behavior, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task RetryAsync( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task AttemptAsync(string message, Action behavior, CancellationToken canceler); + + /// + Task AttemptAsync( + string message, + Action behavior, + Action resetState, + CancellationToken canceler + ); + + /// + Task AttemptAsync(string message, Action behavior, CancellationToken canceler) + where TError : Exception; + + /// A that represents the asynchronous operation. + /// + Task AttemptAsync( + string message, + Action? behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task AttemptAsync( + string message, + Func behavior, + CancellationToken canceler + ); + + /// + Task AttemptAsync( + string message, + Func behavior, + Action resetState, + CancellationToken canceler + ); + + /// + Task AttemptAsync( + string message, + Func behavior, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task AttemptAsync( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception; +} diff --git a/src/Design/Reiteration/ILimiterSync.cs b/src/Design/Reiteration/ILimiterSync.cs new file mode 100644 index 00000000..13177d7e --- /dev/null +++ b/src/Design/Reiteration/ILimiterSync.cs @@ -0,0 +1,189 @@ +namespace Werecodent.CreateAndFake.Design.Reiteration; + +#pragma warning disable RCS1228 // Empty to override the inherited tag. + +/// Provides the core functionality for synchronous repetition. +public interface ILimiterSync +{ + /// Repeats until the limit is reached. + /// + void Repeat(string message, Action? behavior, CancellationToken canceler = default); + + /// Repeats until the limit is reached. + /// Results from all calls. + /// + IReadOnlyCollection Repeat( + string message, + Func behavior, + CancellationToken canceler = default + ); + + /// Retries the until it returns . + /// + void StallUntil(string message, Func behavior, CancellationToken canceler = default); + + /// + /// + void StallUntil( + string message, + Action? behavior, + Func checkState, + CancellationToken canceler = default + ); + + /// + IReadOnlyCollection StallUntil( + string message, + Func behavior, + Func checkState, + CancellationToken canceler = default + ); + + /// + /// Retries until the + /// result is . + /// + /// Polls if the behavior was successful. + /// + /// Results of all calls from , with the last one + /// being when returned . + /// + /// + IReadOnlyCollection StallUntil( + string message, + Func behavior, + Func checkState, + CancellationToken canceler = default + ); + + /// + void Retry(string message, Action behavior, CancellationToken canceler = default); + + /// + void Retry( + string message, + Action behavior, + Action resetState, + CancellationToken canceler = default + ); + + /// + void Retry(string message, Action behavior, CancellationToken canceler = default) + where TError : Exception; + + /// + /// + void Retry( + string message, + Action behavior, + Action? resetState, + CancellationToken canceler = default + ) + where TError : Exception; + + /// + TResult Retry( + string message, + Func behavior, + CancellationToken canceler = default + ); + + /// + TResult Retry( + string message, + Func behavior, + Action resetState, + CancellationToken canceler = default + ); + + /// + TResult Retry( + string message, + Func behavior, + CancellationToken canceler = default + ) + where TError : Exception; + + /// The result of the successful attempt. + /// If the limit is reached. + /// + TResult Retry( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler = default + ) + where TError : Exception; + + /// + void Attempt(string message, Action behavior, CancellationToken canceler = default); + + /// + void Attempt( + string message, + Action behavior, + Action resetState, + CancellationToken canceler = default + ); + + /// + void Attempt(string message, Action behavior, CancellationToken canceler = default) + where TError : Exception; + + /// + /// + void Attempt( + string message, + Action? behavior, + Action? resetState, + CancellationToken canceler = default + ) + where TError : Exception; + + /// + TResult? Attempt( + string message, + Func behavior, + CancellationToken canceler = default + ); + + /// + TResult? Attempt( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler = default + ); + + /// + TResult? Attempt( + string message, + Func behavior, + CancellationToken canceler = default + ) + where TError : Exception; + + /// Retries upon encountering exceptions. + /// + /// Exception to ignore and retry the if encountered. + /// + /// Result returned from the . + /// Details to include when throwing exceptions. + /// Code to repeatably attempt. + /// Code to run between attempts. + /// Aborts execution if triggered. + /// + /// Result of the successful attempt or if limit reached. + /// + /// If canceled via . + /// Beware infinite loops in . + TResult? Attempt( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler = default + ) + where TError : Exception; +} + +#pragma warning restore diff --git a/src/Design/Reiteration/ILimiterTask.cs b/src/Design/Reiteration/ILimiterTask.cs new file mode 100644 index 00000000..096ad3ee --- /dev/null +++ b/src/Design/Reiteration/ILimiterTask.cs @@ -0,0 +1,262 @@ +namespace Werecodent.CreateAndFake.Design.Reiteration; + +/// Provides the core functionality for asynchronous task repetition. +public interface ILimiterTask +{ + /// + Task RepeatAsync(string message, Func behavior, CancellationToken canceler); + + /// + Task> RepeatAsync( + string message, + Func> behavior, + CancellationToken canceler + ); + + /// + Task StallUntilAsync(string message, Func> behavior, CancellationToken canceler); + + /// + Task StallUntilAsync( + string message, + Func behavior, + Func checkState, + CancellationToken canceler + ); + + /// + Task StallUntilAsync( + string message, + Func behavior, + Func> checkState, + CancellationToken canceler + ); + + /// + Task> StallUntilAsync( + string message, + Func> behavior, + Func checkState, + CancellationToken canceler + ); + + /// + Task> StallUntilAsync( + string message, + Func behavior, + Func> checkState, + CancellationToken canceler + ); + + /// + Task> StallUntilAsync( + string message, + Func> behavior, + Func> checkState, + CancellationToken canceler + ); + + /// + Task> StallUntilAsync( + string message, + Func> behavior, + Func checkState, + CancellationToken canceler + ); + + /// + Task> StallUntilAsync( + string message, + Func behavior, + Func> checkState, + CancellationToken canceler + ); + + /// + Task> StallUntilAsync( + string message, + Func> behavior, + Func> checkState, + CancellationToken canceler + ); + + /// + Task RetryAsync(string message, Func behavior, CancellationToken canceler); + + /// + Task RetryAsync( + string message, + Func behavior, + Action resetState, + CancellationToken canceler + ); + + /// + Task RetryAsync( + string message, + Func behavior, + Func resetState, + CancellationToken canceler + ); + + /// + Task RetryAsync(string message, Func behavior, CancellationToken canceler) + where TError : Exception; + + /// + Task RetryAsync( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task RetryAsync( + string message, + Func behavior, + Func? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task RetryAsync( + string message, + Func> behavior, + CancellationToken canceler + ); + + /// + Task RetryAsync( + string message, + Func> behavior, + Action resetState, + CancellationToken canceler + ); + + /// + Task RetryAsync( + string message, + Func> behavior, + Func resetState, + CancellationToken canceler + ); + + /// + Task RetryAsync( + string message, + Func> behavior, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task RetryAsync( + string message, + Func> behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task RetryAsync( + string message, + Func> behavior, + Func? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task AttemptAsync(string message, Func behavior, CancellationToken canceler); + + /// + Task AttemptAsync( + string message, + Func behavior, + Action resetState, + CancellationToken canceler + ); + + /// + Task AttemptAsync( + string message, + Func behavior, + Func resetState, + CancellationToken canceler + ); + + /// + Task AttemptAsync(string message, Func behavior, CancellationToken canceler) + where TError : Exception; + + /// + Task AttemptAsync( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task AttemptAsync( + string message, + Func behavior, + Func? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task AttemptAsync( + string message, + Func> behavior, + CancellationToken canceler + ); + + /// + Task AttemptAsync( + string message, + Func> behavior, + Action resetState, + CancellationToken canceler + ); + + /// + Task AttemptAsync( + string message, + Func> behavior, + Func resetState, + CancellationToken canceler + ); + + /// + Task AttemptAsync( + string message, + Func> behavior, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task AttemptAsync( + string message, + Func> behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception; + + /// + Task AttemptAsync( + string message, + Func> behavior, + Func? resetState, + CancellationToken canceler + ) + where TError : Exception; +} diff --git a/src/Design/Reiteration/Limiter.Async.cs b/src/Design/Reiteration/Limiter.Async.cs new file mode 100644 index 00000000..ff8803a0 --- /dev/null +++ b/src/Design/Reiteration/Limiter.Async.cs @@ -0,0 +1,392 @@ +using System.Diagnostics; + +namespace Werecodent.CreateAndFake.Design.Reiteration; + +/// +public sealed partial class Limiter : ILimiterAsync +{ + /// + public Task RepeatAsync(string message, Action? behavior, CancellationToken canceler) + { + return RepeatAsync( + message, + () => + { + behavior?.Invoke(); + return true; + }, + canceler + ); + } + + /// + public async Task> RepeatAsync( + string message, + Func behavior, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(behavior); + + int i = 0; + List results = []; + Stopwatch watch = Stopwatch.StartNew(); + do + { + ArgumentGuard.ThrowUponIterationLimit(i); + results.Add(behavior.Invoke()); + } while ( + await DelayIfNotDoneAsync(message, watch.Elapsed, ++i, canceler).ConfigureAwait(false) + ); + + return results.AsReadOnly(); + } + + /// + public Task StallUntilAsync(string message, Func behavior, CancellationToken canceler) + { + return StallUntilAsync(message, (Action?)null, behavior, canceler); + } + + /// + public Task StallUntilAsync( + string message, + Action? behavior, + Func checkState, + CancellationToken canceler + ) + { + return StallUntilAsync( + message, + () => + { + behavior?.Invoke(); + return true; + }, + checkState, + canceler + ); + } + + /// + public Task> StallUntilAsync( + string message, + Func behavior, + Func checkState, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(checkState); + + return StallUntilAsync(message, behavior, _ => checkState.Invoke(), canceler); + } + + /// + public async Task> StallUntilAsync( + string message, + Func behavior, + Func checkState, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(behavior, checkState); + + List results = []; + Stopwatch watch = Stopwatch.StartNew(); + for (int i = 1; true; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + T result = behavior.Invoke(); + + results.Add(result); + if (checkState.Invoke(result)) + { + break; + } + await DelayOrFaultAsync(message, watch.Elapsed, i, canceler).ConfigureAwait(false); + } + + return results.AsReadOnly(); + } + + /// + public Task RetryAsync(string message, Action behavior, CancellationToken canceler) + { + return RetryAsync(message, behavior, null, canceler); + } + + /// + public Task RetryAsync( + string message, + Action behavior, + Action resetState, + CancellationToken canceler + ) + { + return RetryAsync(message, behavior, resetState, canceler); + } + + /// + public Task RetryAsync(string message, Action behavior, CancellationToken canceler) + where TError : Exception + { + return RetryAsync(message, behavior, null, canceler); + } + + /// + public Task RetryAsync( + string message, + Action behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception + { + return RetryAsync( + message, + () => + { + behavior?.Invoke(); + return true; + }, + resetState, + canceler + ); + } + + /// + public Task RetryAsync( + string message, + Func behavior, + CancellationToken canceler + ) + { + return RetryAsync(message, behavior, null, canceler); + } + + /// + public Task RetryAsync( + string message, + Func behavior, + Action resetState, + CancellationToken canceler + ) + { + return RetryAsync(message, behavior, resetState, canceler); + } + + /// + public Task RetryAsync( + string message, + Func behavior, + CancellationToken canceler + ) + where TError : Exception + { + return RetryAsync(message, behavior, null, canceler); + } + + /// + public async Task RetryAsync( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception + { + ArgumentGuard.ThrowIfNull(behavior); + + Stopwatch watch = Stopwatch.StartNew(); + for (int i = 1; true; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + TError lastError; + try + { + return behavior.Invoke(); + } + catch (TError error) + { + lastError = error; + } + resetState?.Invoke(); + await DelayOrFaultAsync(message, watch.Elapsed, i, canceler, lastError) + .ConfigureAwait(false); + } + } + + /// + public Task AttemptAsync(string message, Action behavior, CancellationToken canceler) + { + return AttemptAsync(message, behavior, null, canceler); + } + + /// + public Task AttemptAsync( + string message, + Action behavior, + Action resetState, + CancellationToken canceler + ) + { + return AttemptAsync(message, behavior, resetState, canceler); + } + + /// + public Task AttemptAsync(string message, Action behavior, CancellationToken canceler) + where TError : Exception + { + return AttemptAsync(message, behavior, null, canceler); + } + + /// + public Task AttemptAsync( + string message, + Action? behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception + { + return AttemptAsync( + message, + () => + { + behavior?.Invoke(); + return true; + }, + resetState, + canceler + ); + } + + /// + public Task AttemptAsync( + string message, + Func behavior, + CancellationToken canceler + ) + { + return AttemptAsync(message, behavior, null, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func behavior, + Action resetState, + CancellationToken canceler + ) + { + return AttemptAsync(message, behavior, resetState, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func behavior, + CancellationToken canceler + ) + where TError : Exception + { + return AttemptAsync(message, behavior, null, canceler); + } + + /// + public async Task AttemptAsync( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception + { + ArgumentGuard.ThrowIfNull(behavior); + + int i = 0; + Stopwatch watch = Stopwatch.StartNew(); + do + { + ArgumentGuard.ThrowUponIterationLimit(i); + try + { + return behavior.Invoke(); + } + catch (TError) { } + + resetState?.Invoke(); + } while ( + await DelayIfNotDoneAsync(message, watch.Elapsed, ++i, canceler).ConfigureAwait(false) + ); + + return default; + } + + /// Awaitable handling the delay. + /// + private async Task DelayIfNotDoneAsync( + string message, + TimeSpan elapsed, + int tries, + CancellationToken canceler + ) + { + if (tries < _tries && elapsed + _delay < _timeout) + { + await DelayOrCancelAsync(message, canceler).ConfigureAwait(false); + return true; + } + else + { + return false; + } + } + + /// Awaitable handling the delay. + /// + private async Task DelayOrFaultAsync( + string message, + TimeSpan elapsed, + int tries, + CancellationToken canceler, + Exception? ex = null + ) + { + if (tries >= _tries) + { + throw CreateFault($"Reached max attempts after '{elapsed}'", message, ex); + } + else if (elapsed + _delay >= _timeout) + { + throw CreateFault($"Reached timeout after '{elapsed}'", message, ex); + } + else + { + await DelayOrCancelAsync(message, canceler).ConfigureAwait(false); + } + } + + /// Awaitable handling the delay. + /// + private async Task DelayOrCancelAsync(string message, CancellationToken canceler) + { + try + { + if (_delay > TimeSpan.Zero) + { + await Task.Delay(_delay, canceler).ConfigureAwait(false); + } + else + { + canceler.ThrowIfCancellationRequested(); + } + } + catch (OperationCanceledException e) + { + throw CreateCancelFault("Operation canceled via token", message, e); + } + } +} diff --git a/src/Design/Reiteration/Limiter.Base.cs b/src/Design/Reiteration/Limiter.Base.cs new file mode 100644 index 00000000..9547f46a --- /dev/null +++ b/src/Design/Reiteration/Limiter.Base.cs @@ -0,0 +1,319 @@ +using System.ComponentModel; +using System.Globalization; +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.Design.Reiteration; + +/// +/// +/// +/// +[TypeConverter(typeof(LimiterTypeConverter))] +public sealed partial class Limiter(TimeSpan timeout, int tries, TimeSpan? delay = null) + : ILimiter, + IEquatable +{ + /// Instance set to 1 attempt. + public static Limiter Once { get; } = new Limiter(1); + + /// Instance set to 5 attempts. + public static Limiter Few { get; } = new Limiter(5); + + /// Instance set to 12 attempts. + public static Limiter Dozen { get; } = new Limiter(12); + + /// Instance set to 20 attempts. + public static Limiter Score { get; } = new Limiter(20); + + /// Instance set to 100 attempts. + public static Limiter Hundred { get; } = new Limiter(100); + + /// Instance set to 10,000 attempts. + public static Limiter Myriad { get; } = new Limiter(10000); + + /// Instance set to 25ms with a 1ms delay. + public static Limiter Quick { get; } = + new Limiter(new TimeSpan(0, 0, 0, 0, 25), new TimeSpan(0, 0, 0, 0, 1)); + + /// Instance set to 0.5 seconds with a 20ms delay. + public static Limiter Fast { get; } = + new Limiter(new TimeSpan(0, 0, 0, 0, 500), new TimeSpan(0, 0, 0, 0, 20)); + + /// Instance set to 5 seconds with a 200ms delay. + public static Limiter Slow { get; } = + new Limiter(new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 0, 0, 200)); + + /// Specific names that can be converted. + private static readonly Dictionary _NamedLimiters = new() + { + { nameof(Once), Once }, + { nameof(Few), Few }, + { nameof(Dozen), Dozen }, + { nameof(Score), Score }, + { nameof(Hundred), Hundred }, + { nameof(Myriad), Myriad }, + { nameof(Quick), Quick }, + { nameof(Fast), Fast }, + { nameof(Slow), Slow }, + }; + + /// Specific limiters with their name. + private static readonly Dictionary _LimiterNames = _NamedLimiters.ToDictionary( + pair => pair.Value, + pair => pair.Key + ); + + /// Maximum attempts to try. + private readonly int _tries = + (tries > 0) + ? tries + : throw new ArgumentOutOfRangeException( + nameof(tries), + tries, + "Minimum number of attempts is 1." + ); + + /// Maximum duration to attempt for. + private readonly TimeSpan _timeout = + (timeout > TimeSpan.Zero) + ? timeout + : throw new ArgumentOutOfRangeException( + nameof(timeout), + timeout, + "Duration must be greater than 0." + ); + + /// Delay between attempts; no delay by default. + private readonly TimeSpan _delay = !(delay < TimeSpan.Zero) + ? delay ?? TimeSpan.Zero + : throw new ArgumentOutOfRangeException(nameof(delay), delay, "Minimum delay is 0."); + + /// + public Limiter(int tries, TimeSpan? delay = null) + : this(TimeSpan.MaxValue, tries, delay) { } + + /// + public Limiter(TimeSpan timeout, TimeSpan? delay = null) + : this(timeout, int.MaxValue, delay) { } + + /// + public TimeSpan GetMaxDurationEstimate(int millisecondsPerAttempt = 1) + { + if (millisecondsPerAttempt <= 0) + { + throw new ArgumentOutOfRangeException( + nameof(millisecondsPerAttempt), + "Must be positive." + ); + } + + double duration = _delay.TotalMilliseconds + millisecondsPerAttempt; + double timeTries = + Math.Floor(_timeout.TotalMilliseconds / duration) + millisecondsPerAttempt; + + double result; + if (timeTries < _tries) + { + result = (timeTries - millisecondsPerAttempt) * duration + millisecondsPerAttempt; + } + else + { + result = duration * _tries - _delay.TotalMilliseconds; + } + + return TimeSpan.FromMilliseconds(Math.Min(result, TimeSpan.MaxValue.TotalMilliseconds - 1)); + } + + /// Compares to by value. + /// Instance to compare with. + /// + /// if is equal to by value; + /// otherwise. + /// + public override bool Equals(object? obj) + { + return Equals(obj as Limiter); + } + + /// + public bool Equals(ILimiter? other) + { + return Equals(other as Limiter); + } + + /// + public bool Equals(Limiter? other) + { + return other is not null + && other._delay == _delay + && other._tries == _tries + && other._timeout == _timeout; + } + + /// + public int CompareTo(ILimiter? other) + { + return GetMaxDurationEstimate().CompareTo(other?.GetMaxDurationEstimate() ?? TimeSpan.Zero); + } + + /// + public override int GetHashCode() + { + return ValueComparer.Use.GetHashCode(_tries, _timeout, _delay); + } + + /// + public bool ValuesEqual(object? other) + { + return Equals(other); + } + + /// + public int GetValueHash() + { + return GetHashCode(); + } + + /// Converts to a . + /// representation of . + public override string ToString() + { + if (_LimiterNames.TryGetValue(this, out string? name)) + { + return name; + } + + if (_delay == TimeSpan.Zero) + { + if (_timeout == TimeSpan.MaxValue) + { + return $"{_tries}"; + } + else if (_tries == int.MaxValue) + { + return $"{_timeout}"; + } + } + return $"{_tries}-{_timeout}-{_delay}"; + } + + /// Creates a from its representation. + /// representation to convert from. + /// Culture used for conversion. + /// The created instance. + /// When is not valid. + public static Limiter ConvertFrom(string data, CultureInfo? culture) + { + ArgumentGuard.ThrowIfNull(data); + + if (_NamedLimiters.TryGetValue(data, out Limiter? named)) + { + return named; + } + else if (int.TryParse(data, NumberStyles.Any, culture, out int justTries)) + { + return new Limiter(justTries); + } + else if (TimeSpan.TryParse(data, culture, out TimeSpan justTimeout)) + { + return new Limiter(justTimeout); + } + else + { + string[] parts = data.Split('-') ?? []; + if ( + parts.Length == 3 + && int.TryParse(parts[0], NumberStyles.Any, culture, out int tries) + && TimeSpan.TryParse(parts[1], culture, out TimeSpan timeout) + && TimeSpan.TryParse(parts[2], culture, out TimeSpan delay) + ) + { + return new Limiter(timeout, tries, delay); + } + else + { + throw new FormatException($"Invalid format for {nameof(Limiter)}: {data}"); + } + } + } + + /// Throws a . + /// Issue causing the . + /// Details to include in the . + /// Encountered exception causing the . + /// With the error and message details. + private TimeoutException CreateFault(string error, string message, Exception? ex = null) + { + string details = + $" with Limiter '{ToString()}'" + + (string.IsNullOrWhiteSpace(message) ? "." : $": {message}"); + + return ex != null + ? new TimeoutException(error + details, ex) + : new TimeoutException(error + details); + } + + /// Throws a . + /// Issue causing the . + /// Details to include in the . + /// Encountered exception causing the . + /// With the error and message details. + private OperationCanceledException CreateCancelFault( + string error, + string message, + Exception? ex = null + ) + { + string details = + $" with Limiter '{ToString()}'" + + (string.IsNullOrWhiteSpace(message) ? "." : $": {message}"); + + return ex != null + ? new OperationCanceledException(error + details, ex) + : new OperationCanceledException(error + details); + } + + /// Compares to by value. + /// Instance to compare against. + /// Instance to compare with. + /// True if equal, false otherwise. + public static bool operator ==(Limiter? left, Limiter? right) + { + return left is null ? right is null : left.Equals(right); + } + + /// True if not equal, false otherwise. + /// + public static bool operator !=(Limiter? left, Limiter? right) + { + return !(left == right); + } + + /// True if less than, false otherwise. + /// + public static bool operator <(Limiter? left, Limiter? right) + { + return left is null ? right is not null : left.CompareTo(right) < 0; + } + + /// True if less than or equal, false otherwise. + /// + public static bool operator <=(Limiter? left, Limiter? right) + { + return left is null || left.CompareTo(right) <= 0; + } + + /// True if greater than, false otherwise. + /// + public static bool operator >(Limiter? left, Limiter? right) + { + return left?.CompareTo(right) > 0; + } + + /// True if greater than or equal, false otherwise. + /// + public static bool operator >=(Limiter? left, Limiter? right) + { + return left is null ? right is null : left.CompareTo(right) >= 0; + } +} diff --git a/src/Design/Reiteration/Limiter.Sync.cs b/src/Design/Reiteration/Limiter.Sync.cs new file mode 100644 index 00000000..03a58daa --- /dev/null +++ b/src/Design/Reiteration/Limiter.Sync.cs @@ -0,0 +1,403 @@ +using System.Diagnostics; + +namespace Werecodent.CreateAndFake.Design.Reiteration; + +/// +public sealed partial class Limiter : ILimiterSync +{ + /// + public void Repeat(string message, Action? behavior, CancellationToken canceler = default) + { + _ = Repeat( + message, + () => + { + behavior?.Invoke(); + return true; + }, + canceler + ); + } + + /// + public IReadOnlyCollection Repeat( + string message, + Func behavior, + CancellationToken canceler = default + ) + { + ArgumentGuard.ThrowIfNull(behavior); + + int i = 0; + List results = []; + Stopwatch watch = Stopwatch.StartNew(); + do + { + ArgumentGuard.ThrowUponIterationLimit(i); + results.Add(behavior.Invoke()); + } while (DelayIfNotDone(message, watch.Elapsed, ++i, canceler)); + + return results.AsReadOnly(); + } + + /// + public void StallUntil( + string message, + Func behavior, + CancellationToken canceler = default + ) + { + StallUntil(message, null, behavior, canceler); + } + + /// + public void StallUntil( + string message, + Action? behavior, + Func checkState, + CancellationToken canceler = default + ) + { + _ = StallUntil( + message, + () => + { + behavior?.Invoke(); + return true; + }, + checkState, + canceler + ); + } + + /// + public IReadOnlyCollection StallUntil( + string message, + Func behavior, + Func checkState, + CancellationToken canceler = default + ) + { + ArgumentGuard.ThrowIfNull(checkState); + + return StallUntil(message, behavior, _ => checkState.Invoke(), canceler); + } + + /// + public IReadOnlyCollection StallUntil( + string message, + Func behavior, + Func checkState, + CancellationToken canceler = default + ) + { + ArgumentGuard.ThrowIfNull(behavior, checkState); + + List results = []; + Stopwatch watch = Stopwatch.StartNew(); + for (int i = 1; true; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + T result = behavior.Invoke(); + + results.Add(result); + if (checkState.Invoke(result)) + { + break; + } + else + { + DelayOrFault(message, watch.Elapsed, i, canceler); + } + } + + return results.AsReadOnly(); + } + + /// + public void Retry(string message, Action behavior, CancellationToken canceler = default) + { + Retry(message, behavior, null, canceler); + } + + /// + public void Retry( + string message, + Action behavior, + Action resetState, + CancellationToken canceler = default + ) + { + Retry(message, behavior, resetState, canceler); + } + + /// + public void Retry(string message, Action behavior, CancellationToken canceler = default) + where TError : Exception + { + Retry(message, behavior, null, canceler); + } + + /// + public void Retry( + string message, + Action behavior, + Action? resetState, + CancellationToken canceler = default + ) + where TError : Exception + { + _ = Retry( + message, + () => + { + behavior?.Invoke(); + return true; + }, + resetState, + canceler + ); + } + + /// + public TResult Retry( + string message, + Func behavior, + CancellationToken canceler = default + ) + { + return Retry(message, behavior, null, canceler); + } + + /// + public TResult Retry( + string message, + Func behavior, + Action resetState, + CancellationToken canceler = default + ) + { + return Retry(message, behavior, resetState, canceler); + } + + /// + public TResult Retry( + string message, + Func behavior, + CancellationToken canceler = default + ) + where TError : Exception + { + return Retry(message, behavior, null, canceler); + } + + /// + public TResult Retry( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler = default + ) + where TError : Exception + { + ArgumentGuard.ThrowIfNull(behavior); + + Stopwatch watch = Stopwatch.StartNew(); + for (int i = 1; true; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + TError lastError; + try + { + return behavior.Invoke(); + } + catch (TError error) + { + lastError = error; + } + resetState?.Invoke(); + DelayOrFault(message, watch.Elapsed, i, canceler, lastError); + } + } + + /// + public void Attempt(string message, Action behavior, CancellationToken canceler = default) + { + Attempt(message, behavior, null, canceler); + } + + /// + public void Attempt( + string message, + Action behavior, + Action resetState, + CancellationToken canceler = default + ) + { + Attempt(message, behavior, resetState, canceler); + } + + /// + public void Attempt( + string message, + Action behavior, + CancellationToken canceler = default + ) + where TError : Exception + { + Attempt(message, behavior, null, canceler); + } + + /// + public void Attempt( + string message, + Action? behavior, + Action? resetState, + CancellationToken canceler = default + ) + where TError : Exception + { + _ = Attempt( + message, + () => + { + behavior?.Invoke(); + return true; + }, + resetState, + canceler + ); + } + + /// + public TResult? Attempt( + string message, + Func behavior, + CancellationToken canceler = default + ) + { + return Attempt(message, behavior, null, canceler); + } + + /// + public TResult? Attempt( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler = default + ) + { + return Attempt(message, behavior, resetState, canceler); + } + + /// + public TResult? Attempt( + string message, + Func behavior, + CancellationToken canceler = default + ) + where TError : Exception + { + return Attempt(message, behavior, null, canceler); + } + + /// + public TResult? Attempt( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler = default + ) + where TError : Exception + { + ArgumentGuard.ThrowIfNull(behavior); + + int i = 0; + Stopwatch watch = Stopwatch.StartNew(); + do + { + ArgumentGuard.ThrowUponIterationLimit(i); + try + { + return behavior.Invoke(); + } + catch (TError) { } + + resetState?.Invoke(); + } while (DelayIfNotDone(message, watch.Elapsed, ++i, canceler)); + + return default; + } + + /// Delays if terminal condition not reached. + /// Details to include upon a . + /// Current amount of time that has elapsed. + /// Current number of repetitions. + /// Token indicating behavior should be canceled. + /// if terminal condition not reached, otherwise. + private bool DelayIfNotDone( + string message, + TimeSpan elapsed, + int tries, + CancellationToken canceler + ) + { + if (tries < _tries && elapsed + _delay < _timeout) + { + DelayOrCancel(message, canceler); + return true; + } + else + { + return false; + } + } + + /// Faults if terminal condition reached; delays otherwise. + /// Details to include upon a . + /// Current amount of time that has elapsed. + /// Current number of repetitions. + /// Token indicating behavior should be canceled. + /// Current if present. + /// If the limit is reached. + /// If cancelled via . + private void DelayOrFault( + string message, + TimeSpan elapsed, + int tries, + CancellationToken canceler, + Exception? ex = null + ) + { + if (tries >= _tries) + { + throw CreateFault($"Reached max attempts after '{elapsed}'", message, ex); + } + else if (elapsed + _delay >= _timeout) + { + throw CreateFault($"Reached timeout after '{elapsed}'", message, ex); + } + else + { + DelayOrCancel(message, canceler); + } + } + + /// Faults if behavior has been canceled; delays otherwise. + /// Details to include upon a . + /// Token indicating behavior should be canceled. + /// If cancelled via . + private void DelayOrCancel(string message, CancellationToken canceler) + { + if (_delay > TimeSpan.Zero) + { + _ = canceler.WaitHandle.WaitOne(_delay); + } + if (canceler.IsCancellationRequested) + { + throw CreateCancelFault("Operation canceled via token", message); + } + } +} diff --git a/src/Design/Reiteration/Limiter.Task.cs b/src/Design/Reiteration/Limiter.Task.cs new file mode 100644 index 00000000..a4b9e311 --- /dev/null +++ b/src/Design/Reiteration/Limiter.Task.cs @@ -0,0 +1,549 @@ +using System.Diagnostics; + +namespace Werecodent.CreateAndFake.Design.Reiteration; + +/// +public sealed partial class Limiter : ILimiterTask +{ + /// + public Task RepeatAsync(string message, Func behavior, CancellationToken canceler) + { + return RepeatAsync(message, () => ToGenericAsync(behavior), canceler); + } + + /// + public async Task> RepeatAsync( + string message, + Func> behavior, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(behavior); + + int i = 0; + List results = []; + Stopwatch watch = Stopwatch.StartNew(); + do + { + ArgumentGuard.ThrowUponIterationLimit(i); + results.Add(await SafeInvokeAsync(behavior).ConfigureAwait(false)); + } while ( + await DelayIfNotDoneAsync(message, watch.Elapsed, ++i, canceler).ConfigureAwait(false) + ); + + return results.AsReadOnly(); + } + + /// + public Task StallUntilAsync( + string message, + Func> behavior, + CancellationToken canceler + ) + { + return StallUntilAsync(message, () => Task.CompletedTask, behavior, canceler); + } + + /// + public Task StallUntilAsync( + string message, + Func behavior, + Func checkState, + CancellationToken canceler + ) + { + return StallUntilAsync(message, () => ToGenericAsync(behavior), checkState, canceler); + } + + /// + public Task StallUntilAsync( + string message, + Func behavior, + Func> checkState, + CancellationToken canceler + ) + { + return StallUntilAsync(message, () => ToGenericAsync(behavior), checkState, canceler); + } + + /// + public Task> StallUntilAsync( + string message, + Func> behavior, + Func checkState, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(checkState); + return StallUntilAsync(message, behavior, (T _) => checkState.Invoke(), canceler); + } + + /// + public Task> StallUntilAsync( + string message, + Func behavior, + Func> checkState, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(behavior); + return StallUntilAsync( + message, + () => Task.FromResult(behavior.Invoke()), + checkState, + canceler + ); + } + + /// + public Task> StallUntilAsync( + string message, + Func> behavior, + Func> checkState, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(checkState); + return StallUntilAsync(message, behavior, (T _) => checkState.Invoke(), canceler); + } + + /// + public Task> StallUntilAsync( + string message, + Func> behavior, + Func checkState, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(checkState); + return StallUntilAsync( + message, + behavior, + x => Task.FromResult(checkState.Invoke(x)), + canceler + ); + } + + /// + public Task> StallUntilAsync( + string message, + Func behavior, + Func> checkState, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(behavior); + return StallUntilAsync( + message, + () => Task.FromResult(behavior.Invoke()), + checkState, + canceler + ); + } + + /// + public async Task> StallUntilAsync( + string message, + Func> behavior, + Func> checkState, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(behavior, checkState); + + List results = []; + Stopwatch watch = Stopwatch.StartNew(); + for (int i = 1; true; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + T result = await SafeInvokeAsync(behavior).ConfigureAwait(false); + + results.Add(result); + + Task checker = checkState.Invoke(result); + if (await SafeInvokeAsync(() => checker).ConfigureAwait(false)) + { + break; + } + await DelayOrFaultAsync(message, watch.Elapsed, i, canceler).ConfigureAwait(false); + } + + return results.AsReadOnly(); + } + + /// + public Task RetryAsync(string message, Func behavior, CancellationToken canceler) + { + return RetryAsync(message, behavior, (Action?)null, canceler); + } + + /// + public Task RetryAsync( + string message, + Func behavior, + Action resetState, + CancellationToken canceler + ) + { + return RetryAsync(message, behavior, resetState, canceler); + } + + /// + public Task RetryAsync( + string message, + Func behavior, + Func resetState, + CancellationToken canceler + ) + { + return RetryAsync(message, behavior, resetState, canceler); + } + + /// + public Task RetryAsync(string message, Func behavior, CancellationToken canceler) + where TError : Exception + { + return RetryAsync(message, behavior, (Action?)null, canceler); + } + + /// + public Task RetryAsync( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception + { + return RetryAsync( + message, + () => ToGenericAsync(behavior), + resetState, + canceler + ); + } + + /// + public Task RetryAsync( + string message, + Func behavior, + Func? resetState, + CancellationToken canceler + ) + where TError : Exception + { + return RetryAsync( + message, + () => ToGenericAsync(behavior), + resetState, + canceler + ); + } + + /// + public Task RetryAsync( + string message, + Func> behavior, + CancellationToken canceler + ) + { + return RetryAsync(message, behavior, (Action?)null, canceler); + } + + /// + public Task RetryAsync( + string message, + Func> behavior, + Action resetState, + CancellationToken canceler + ) + { + return RetryAsync(message, behavior, resetState, canceler); + } + + /// + public Task RetryAsync( + string message, + Func> behavior, + Func resetState, + CancellationToken canceler + ) + { + return RetryAsync(message, behavior, resetState, canceler); + } + + /// + public Task RetryAsync( + string message, + Func> behavior, + CancellationToken canceler + ) + where TError : Exception + { + return RetryAsync(message, behavior, (Action?)null, canceler); + } + + /// + public async Task RetryAsync( + string message, + Func> behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception + { + ArgumentGuard.ThrowIfNull(behavior); + + Stopwatch watch = Stopwatch.StartNew(); + for (int i = 1; true; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + TError lastError; + try + { + return await SafeInvokeAsync(behavior).ConfigureAwait(false); + } + catch (TError error) + { + lastError = error; + } + resetState?.Invoke(); + await DelayOrFaultAsync(message, watch.Elapsed, i, canceler, lastError) + .ConfigureAwait(false); + } + } + + /// + public async Task RetryAsync( + string message, + Func> behavior, + Func? resetState, + CancellationToken canceler + ) + where TError : Exception + { + ArgumentGuard.ThrowIfNull(behavior); + + Stopwatch watch = Stopwatch.StartNew(); + for (int i = 1; true; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + TError lastError; + try + { + return await SafeInvokeAsync(behavior).ConfigureAwait(false); + } + catch (TError error) + { + lastError = error; + } + + Task? resetter = resetState?.Invoke(); + if (resetter != null) + { + await resetter.ConfigureAwait(false); + } + + await DelayOrFaultAsync(message, watch.Elapsed, i, canceler, lastError) + .ConfigureAwait(false); + } + } + + /// + public Task AttemptAsync(string message, Func behavior, CancellationToken canceler) + { + return AttemptAsync(message, behavior, (Action?)null, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func behavior, + Action resetState, + CancellationToken canceler + ) + { + return AttemptAsync(message, behavior, resetState, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func behavior, + Func resetState, + CancellationToken canceler + ) + { + return AttemptAsync(message, behavior, resetState, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func behavior, + CancellationToken canceler + ) + where TError : Exception + { + return AttemptAsync(message, behavior, (Action?)null, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception + { + return AttemptAsync( + message, + () => ToGenericAsync(behavior), + resetState, + canceler + ); + } + + /// + public Task AttemptAsync( + string message, + Func behavior, + Func? resetState, + CancellationToken canceler + ) + where TError : Exception + { + return AttemptAsync( + message, + () => ToGenericAsync(behavior), + resetState, + canceler + ); + } + + /// + public Task AttemptAsync( + string message, + Func> behavior, + CancellationToken canceler + ) + { + return AttemptAsync(message, behavior, (Action?)null, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func> behavior, + Action resetState, + CancellationToken canceler + ) + { + return AttemptAsync(message, behavior, resetState, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func> behavior, + Func resetState, + CancellationToken canceler + ) + { + return AttemptAsync(message, behavior, resetState, canceler); + } + + /// + public Task AttemptAsync( + string message, + Func> behavior, + CancellationToken canceler + ) + where TError : Exception + { + return AttemptAsync(message, behavior, (Action?)null, canceler); + } + + /// + public async Task AttemptAsync( + string message, + Func> behavior, + Action? resetState, + CancellationToken canceler + ) + where TError : Exception + { + ArgumentGuard.ThrowIfNull(behavior); + + int i = 0; + Stopwatch watch = Stopwatch.StartNew(); + do + { + ArgumentGuard.ThrowUponIterationLimit(i); + try + { + return await SafeInvokeAsync(behavior).ConfigureAwait(false); + } + catch (TError) { } + + resetState?.Invoke(); + } while ( + await DelayIfNotDoneAsync(message, watch.Elapsed, ++i, canceler).ConfigureAwait(false) + ); + + return default; + } + + /// + public async Task AttemptAsync( + string message, + Func> behavior, + Func? resetState, + CancellationToken canceler + ) + where TError : Exception + { + ArgumentGuard.ThrowIfNull(behavior); + + int i = 0; + Stopwatch watch = Stopwatch.StartNew(); + do + { + ArgumentGuard.ThrowUponIterationLimit(i); + try + { + return await SafeInvokeAsync(behavior).ConfigureAwait(false); + } + catch (TError) { } + + Task? resetter = resetState?.Invoke(); + if (resetter != null) + { + await resetter.ConfigureAwait(false); + } + } while ( + await DelayIfNotDoneAsync(message, watch.Elapsed, ++i, canceler).ConfigureAwait(false) + ); + + return default; + } + + private static Task SafeInvokeAsync(Func> behavior) + { + return behavior.Invoke() ?? throw new ArgumentNullException(nameof(behavior)); + } + + private static async Task ToGenericAsync(Func behavior) + { + Task? innerBehavior = behavior?.Invoke(); + if (innerBehavior != null) + { + await innerBehavior.ConfigureAwait(false); + } + return true; + } +} diff --git a/src/Design/Reiteration/LimiterTypeConverter.cs b/src/Design/Reiteration/LimiterTypeConverter.cs new file mode 100644 index 00000000..f4124330 --- /dev/null +++ b/src/Design/Reiteration/LimiterTypeConverter.cs @@ -0,0 +1,70 @@ +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Reiteration; + +/// Handles serialization/deserialization for . +public sealed class LimiterTypeConverter : TypeConverter +{ + /// + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) + { + return sourceType == typeof(int) || sourceType == typeof(string); + } + + /// + public override object? ConvertFrom( + ITypeDescriptorContext? context, + CultureInfo? culture, + object value + ) + { + if (value is int tries) + { + return new Limiter(tries); + } + else if (value is string data) + { + return Limiter.ConvertFrom(data, culture); + } + else + { + throw new ArgumentException( + $"Cannot convert {nameof(Limiter)} from type: '{GenericConverter.ExpandName(value)}'", + nameof(value) + ); + } + } + + /// + public override bool CanConvertTo( + ITypeDescriptorContext? context, + [NotNullWhen(true)] Type? destinationType + ) + { + return destinationType == typeof(string); + } + + /// + public override object? ConvertTo( + ITypeDescriptorContext? context, + CultureInfo? culture, + object? value, + Type destinationType + ) + { + if (value is Limiter limiter) + { + return limiter.ToString(); + } + else + { + throw new ArgumentException( + $"Can only convert {nameof(Limiter)}s, not type: '{GenericConverter.ExpandName(value)}'", + nameof(value) + ); + } + } +} diff --git a/src/Design/Tooling/ConfigurableOptionAttribute.cs b/src/Design/Tooling/ConfigurableOptionAttribute.cs new file mode 100644 index 00000000..054d50d0 --- /dev/null +++ b/src/Design/Tooling/ConfigurableOptionAttribute.cs @@ -0,0 +1,5 @@ +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Flag to mark the attached property as a value settable via configuration. +[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] +public sealed class ConfigurableOptionAttribute : Attribute; diff --git a/src/Design/Tooling/DesignOptions.cs b/src/Design/Tooling/DesignOptions.cs new file mode 100644 index 00000000..15e984e9 --- /dev/null +++ b/src/Design/Tooling/DesignOptions.cs @@ -0,0 +1,26 @@ +using Werecodent.CreateAndFake.Design.Properties; +using Werecodent.CreateAndFake.Design.Randomization; + +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Settings for manipulating shared tool behavior. +public record DesignOptions +{ + /// First seed used to begin generating values for seeded randomization. + /// + /// Useful for recreating the same sequence of values from randomization (beware parallelism). If not set, + /// the on will be a generated value instead. + /// + /// + [ConfigurableOption] + public int? Seed { get; init; } = null; + + /// + [ConfigurableOption] + public int IterationLimit { get; init; } = DesignDefaults.IterationLimit; + + /// + [ConfigurableOption] + public bool IncludeInfinityAndNaNGeneration { get; init; } = + DesignDefaults.IncludeInfinityAndNaNGeneration; +} diff --git a/src/Design/Tooling/HintResult.cs b/src/Design/Tooling/HintResult.cs new file mode 100644 index 00000000..17957459 --- /dev/null +++ b/src/Design/Tooling/HintResult.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// +/// +/// +public abstract class HintResult(bool hasData, T data) : IHintResult +{ + /// + public bool HasData { get; } = hasData; + + /// + public T Data { get; } = data; + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Design/Tooling/IHintResult.cs b/src/Design/Tooling/IHintResult.cs new file mode 100644 index 00000000..91a19003 --- /dev/null +++ b/src/Design/Tooling/IHintResult.cs @@ -0,0 +1,12 @@ +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Execution result of an with potential resulting data. +/// Result for the hint. +public interface IHintResult +{ + /// If the was successful and is populated. + bool HasData { get; } + + /// Result of the if == true. + T Data { get; } +} diff --git a/src/Design/Tooling/IHintTool.cs b/src/Design/Tooling/IHintTool.cs new file mode 100644 index 00000000..307b219b --- /dev/null +++ b/src/Design/Tooling/IHintTool.cs @@ -0,0 +1,12 @@ +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Reflection tool that utilizes s. +/// +/// +public interface IHintTool : ITool + where TOptions : IToolHintOptions + where THint : IToolHint +{ + /// + IEnumerable SupportedTypes { get; } +} diff --git a/src/Design/Tooling/ITool.cs b/src/Design/Tooling/ITool.cs new file mode 100644 index 00000000..50de3081 --- /dev/null +++ b/src/Design/Tooling/ITool.cs @@ -0,0 +1,10 @@ +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Reflection tool. +/// The configuration for the tool. +public interface ITool + where TOptions : IToolOptions +{ + /// Configured options for manipulating tool behavior. + TOptions Options { get; } +} diff --git a/src/Design/Tooling/IToolChainer.cs b/src/Design/Tooling/IToolChainer.cs new file mode 100644 index 00000000..0bae9e98 --- /dev/null +++ b/src/Design/Tooling/IToolChainer.cs @@ -0,0 +1,8 @@ +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Handles the recursive portion of tool behavior. +/// Type for the options. +/// Type for the hint. +public interface IToolChainer : IHintTool + where TOptions : IToolHintOptions + where THint : IToolHint; diff --git a/src/Design/Tooling/IToolEngine.cs b/src/Design/Tooling/IToolEngine.cs new file mode 100644 index 00000000..32e7cea0 --- /dev/null +++ b/src/Design/Tooling/IToolEngine.cs @@ -0,0 +1,14 @@ +namespace Werecodent.CreateAndFake.Design.Tooling; + +#pragma warning disable S2326 // Marker for inheritance. + +/// Handles the behavior pipeline for the tool. +/// Hint being used by the tool. +public interface IToolEngine + where THint : IToolHint +{ + /// + IEnumerable SupportedTypes { get; } +} + +#pragma warning restore diff --git a/src/Design/Tooling/IToolHint.cs b/src/Design/Tooling/IToolHint.cs new file mode 100644 index 00000000..f42e2040 --- /dev/null +++ b/src/Design/Tooling/IToolHint.cs @@ -0,0 +1,16 @@ +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Hint for controlling behavior. +public interface IToolHint +{ + /// Determines running order for dynamically loaded hints. + /// Higher values take precedence. Refer to the tool's priority . + int EnginePriority { get; } + + /// Specific s explicitly supported. + /// + /// Not inclusive and not required. Generic bases might only indicate + /// support for the specified with generics populated. + /// + IEnumerable SupportedTypes { get; } +} diff --git a/src/Design/Tooling/IToolHintOptions.cs b/src/Design/Tooling/IToolHintOptions.cs new file mode 100644 index 00000000..b7a7d4a1 --- /dev/null +++ b/src/Design/Tooling/IToolHintOptions.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; + +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Settings for manipulating behavior. +/// Self-reference . +/// Hint used by the associated Tool. +public interface IToolHintOptions : IToolOptions + where TSelf : IToolHintOptions + where THint : IToolHint +{ + /// + /// Maximum number of nested tool method calls from s allowed before failing. + /// + /// Helps prevent infinite loops from custom s. + [ConfigurableOption] + int MaxRecursionDepth { get; } + + /// If the default framework s are enabled. + /// + /// Useful for testing custom s. Associated Tool behavior will + /// completely rely upon custom s if set to . + /// + [ConfigurableOption] + bool IncludeFrameworkHints { get; } + + /// If found custom s are automatically enabled. + /// + /// Useful for reverting custom behavior in the associated Tool. + /// The s declared are used automatically unless set to . + /// + [ConfigurableOption] + bool IncludeFoundHints { get; } + + /// Additional hints to be used by the tool. + /// These hints are used in the order given before any other hint. + ImmutableArray Hints { get; } + + /// Options to use when working on child values during recursion. + /// If , the current options are utilized. + TSelf? NestedOptions { get; } +} diff --git a/src/Design/Tooling/IToolOptions.cs b/src/Design/Tooling/IToolOptions.cs new file mode 100644 index 00000000..fd8dfbc2 --- /dev/null +++ b/src/Design/Tooling/IToolOptions.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Randomization; + +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Settings for manipulating behavior. +public interface IToolOptions +{ + /// + /// These options are shared among all tools from a configured toolset. + DesignOptions Design { get; init; } + + /// Value generator used for base randomization. + /// Provides access to the . + IRandom Gen { get; init; } +} diff --git a/src/Design/Tooling/ToolChainer.cs b/src/Design/Tooling/ToolChainer.cs new file mode 100644 index 00000000..db8bc282 --- /dev/null +++ b/src/Design/Tooling/ToolChainer.cs @@ -0,0 +1,97 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// Self-reference . +/// The for the hint engine. +/// The managing configuration options. +/// The of hints being used. +/// +public abstract class ToolChainer : IToolChainer + where TSelf : ToolChainer + where TEngine : IToolEngine + where TOptions : IToolHintOptions + where THint : IToolHint +{ + /// + protected TEngine Engine { get; } + + /// + public TOptions Options { get; } + + /// + public IEnumerable SupportedTypes => Engine.SupportedTypes; + + /// Current recursion level. + private readonly int _nestedDepth; + + /// Starting constructor used to begin recursion tracking with. + /// + /// + protected ToolChainer(TOptions options, TEngine engine) + { + ArgumentGuard.ThrowIfNull(options, engine); + + Options = options; + Engine = engine; + _nestedDepth = 0; + } + + /// Nested constructor used to work on a child value with. + /// + /// Previous chainer to build upon. + /// + /// Not to be called directly. + /// should be called instead. Implementation should be private. + /// + /// + /// Upon hitting the depth. + /// + protected ToolChainer(TOptions options, TSelf prevChainer) + { + ArgumentGuard.ThrowIfNull(options, prevChainer); + + Options = options; + Engine = prevChainer.Engine; + _nestedDepth = prevChainer._nestedDepth + 1; + + if (_nestedDepth >= options.MaxRecursionDepth) + { + throw new EngineException( + $"Reached max recursion depth of '{_nestedDepth}/{options.MaxRecursionDepth}' " + + $"for tool '{GenericConverter.ExpandName(this)}'." + ); + } + } + + /// Gets the appropriate for child values. + /// Modifications of for the new chainer. + /// The created to use. + protected TSelf GetSubChainer(Func? optionConfiguration) + { + TOptions subOptions = Options.NestedOptions ?? Options; + return CreateSubChainer( + (optionConfiguration != null) ? optionConfiguration.Invoke(subOptions) : subOptions + ); + } + + /// + /// Provides access to the concrete implementation of + /// for the . + /// + /// Configured options to use for the new chainer. + /// The created to use for child values. + /// + /// Not to be called directly. should be called instead. + /// Implementation should be like: + /// return new ToolChainer(subOptions, this); + /// + protected abstract TSelf CreateSubChainer(TOptions subOptions); + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Design/Tooling/ToolEngine.cs b/src/Design/Tooling/ToolEngine.cs new file mode 100644 index 00000000..2bc614aa --- /dev/null +++ b/src/Design/Tooling/ToolEngine.cs @@ -0,0 +1,71 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// +public abstract class ToolEngine : IToolEngine + where THint : IToolHint +{ + /// All found hints from all loaded assemblies. + private static readonly ImmutableArray _AllHints = + [ + .. TypeDescriber + .For() + .FindLoadedSubclasses() + .Select(Activator.CreateInstance) + .Cast() + .Where(h => h.EnginePriority != int.MinValue) + .OrderByDescending(h => h.EnginePriority), + ]; + + /// All CreateAndFake hints. + private static readonly FrozenSet _FrameworkHints = _AllHints + .Where(h => h.GetType().Assembly == typeof(THint).Assembly) + .ToFrozenSet(); + + /// + private static readonly FrozenSet _HintSupportedTypes = _AllHints + .SelectMany(h => h.SupportedTypes) + .Distinct() + .ToFrozenSet(); + + /// + public virtual IEnumerable SupportedTypes { get; } = _HintSupportedTypes; + + /// Picks hints to use for the tool based upon configured options. + /// The managing configuration options. + /// Holds the configured options to use. + /// The selected hints to utilize in the order returned. + protected static IEnumerable SelectHints(IToolChainer chainer) + where TOptions : IToolHintOptions + { + ArgumentGuard.ThrowIfNull(chainer); + + foreach (THint hint in chainer.Options.Hints) + { + yield return hint; + } + foreach (THint hint in _AllHints) + { + if (_FrameworkHints.Contains(hint)) + { + if (chainer.Options.IncludeFrameworkHints) + { + yield return hint; + } + } + else if (chainer.Options.IncludeFoundHints) + { + yield return hint; + } + } + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Design/Tooling/ToolHintOptions.cs b/src/Design/Tooling/ToolHintOptions.cs new file mode 100644 index 00000000..dece904e --- /dev/null +++ b/src/Design/Tooling/ToolHintOptions.cs @@ -0,0 +1,55 @@ +using System.Collections.Immutable; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// +public abstract record ToolHintOptions + : ToolOptions, + IToolHintOptions + where TSelf : ToolOptions, IToolHintOptions + where THint : IToolHint +{ + /// + /// 30 + [ConfigurableOption] + public int MaxRecursionDepth { get; init; } = 30; + + /// + /// + [ConfigurableOption] + public bool IncludeFrameworkHints { get; init; } = true; + + /// + /// + [ConfigurableOption] + public bool IncludeFoundHints { get; init; } = true; + + /// + /// [] + public ImmutableArray Hints { get; init; } = []; + + /// + /// + public TSelf? NestedOptions { get; init; } = default; + + /// + public sealed override string ToString() + { + // Prevents infinite loop from nested options. + return GenericConverter.ExpandName(GetType()); + } + + /// + public override int GetHashCode() + { + // Prevents infinite loop from nested options. + return ValueComparer.Use.GetHashCode( + Gen, + IncludeFrameworkHints, + IncludeFoundHints, + MaxRecursionDepth + ); + } +} diff --git a/src/Design/Tooling/ToolOptions.cs b/src/Design/Tooling/ToolOptions.cs new file mode 100644 index 00000000..ddf54088 --- /dev/null +++ b/src/Design/Tooling/ToolOptions.cs @@ -0,0 +1,14 @@ +using Werecodent.CreateAndFake.Design.Randomization; + +namespace Werecodent.CreateAndFake.Design.Tooling; + +/// +public abstract record ToolOptions : IToolOptions + where TSelf : ToolOptions +{ + /// + public required DesignOptions Design { get; init; } + + /// + public required IRandom Gen { get; init; } +} diff --git a/src/Design/Types/ConstructorScanner.cs b/src/Design/Types/ConstructorScanner.cs new file mode 100644 index 00000000..9095e121 --- /dev/null +++ b/src/Design/Types/ConstructorScanner.cs @@ -0,0 +1,36 @@ +using System.Collections.Frozen; +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Types; + +#pragma warning disable RCS1228 // Empty to override the inherited tag. + +/// +public sealed class ConstructorScanner(Type? type) : MemberScanner(type) +{ + /// + /// + public override IEnumerable All { get; } = + FindAllConstructors(type).ToFrozenSet(); + + /// + /// + public override IEnumerable OnlyPublic => All.Where(c => c.IsPublic); + + /// + /// + public override IEnumerable PublicOrInternal => + All.Where(c => c.IsPublic || c.IsAssembly); + + /// Finds all constructors on the . + /// The to find constructors on. + /// All found constructors on the . + private static ConstructorInfo[] FindAllConstructors(Type? type) + { + return type?.GetConstructors( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ) ?? []; + } +} + +#pragma warning restore diff --git a/src/Design/Types/FactoryScanner.cs b/src/Design/Types/FactoryScanner.cs new file mode 100644 index 00000000..9aa80ecc --- /dev/null +++ b/src/Design/Types/FactoryScanner.cs @@ -0,0 +1,37 @@ +using System.Collections.Frozen; +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// Finds factories on the . +/// +public sealed class FactoryScanner(Type? type) : MemberScanner(type) +{ + /// + /// All methods that create the . + /// + public override IEnumerable All { get; } = FindAllFactories(type).ToFrozenSet(); + + /// + /// The + /// methods that create the . + /// + public override IEnumerable OnlyPublic => All.Where(m => m.IsPublic); + + /// + /// The or + /// methods that create the . + /// + public override IEnumerable PublicOrInternal => + All.Where(m => m.IsPublic || m.IsAssembly); + + /// Finds all methods that create the . + /// The to find factories on. + /// All found factory methods on the . + private static IEnumerable FindAllFactories(Type? type) + { + return type?.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + .Where(m => m.ReturnType == type) + ?? []; + } +} diff --git a/src/Design/Types/FieldScanner.cs b/src/Design/Types/FieldScanner.cs new file mode 100644 index 00000000..68394b8a --- /dev/null +++ b/src/Design/Types/FieldScanner.cs @@ -0,0 +1,72 @@ +using System.Collections.Frozen; +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// +public sealed class FieldScanner(Type? type) : MemberScanner(type) +{ + /// + public override IEnumerable All { get; } = FindAllFields(type).ToFrozenSet(); + + /// + public override IEnumerable OnlyPublic => All.Where(f => f.IsPublic); + + /// + public override IEnumerable PublicOrInternal => + All.Where(f => f.IsPublic || f.IsAssembly); + + /// + /// The and instance fields + /// on the that can be written to. + /// + /// + public IEnumerable Writable => FindWritable(Assembly.GetCallingAssembly().GetName()); + + /// + /// Finds and instance fields + /// on the that can be written to. + /// + /// + internal IEnumerable FindWritable(AssemblyName assembly) + { + return FindVisible(assembly).Where(f => !f.IsInitOnly && !f.IsLiteral); + } + + /// Finds all instance fields on the . + /// The to find fields on. + /// All found fields on the . + /// The fields in inherited s are included. + private static IEnumerable FindAllFields(Type? type) + { + if (type == null) + { + yield break; + } + + foreach ( + FieldInfo field in type.GetFields( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ) + ) + { + yield return field; + } + + Type? currentType = type.BaseType; + HashSet completedTypes = [type]; + for (int i = 0; currentType != null && completedTypes.Add(currentType); i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + foreach ( + FieldInfo field in currentType + .GetFields(BindingFlags.Instance | BindingFlags.NonPublic) + .Where(f => f.IsPrivate) + ) + { + yield return field; + } + currentType = currentType.BaseType; + } + } +} diff --git a/src/Design/Types/GenericConverter.cs b/src/Design/Types/GenericConverter.cs new file mode 100644 index 00000000..335f8a0e --- /dev/null +++ b/src/Design/Types/GenericConverter.cs @@ -0,0 +1,179 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// Provides common patterns for identifying generics. +public static class GenericConverter +{ + /// The found inherited . + /// Example: + /// FindConcreteType<List<int>>(typeof(IList<>)) == typeof(IList<int>) // true + /// + /// + /// + public static Type FindConcreteType(Type genericBase) + { + return FindConcreteType(typeof(T), genericBase); + } + + /// The found inherited . + /// + /// If the does not inherit . + /// + /// Example: + /// FindConcreteType(typeof(List<int>), typeof(IList<>)) == typeof(IList<int>) // true + /// + /// + public static Type FindConcreteType(Type child, Type genericBase) + { + ArgumentGuard.ThrowIfNull(child); + + return AsConcreteType(child, genericBase) + ?? throw new InvalidOperationException( + $"Type {child} doesn't inherit {genericBase} as a generic base class." + ); + } + + /// + /// Finds the defined with generics + /// specified that is inherited by . + /// + /// The to find the generic base of. + /// Example: + /// AsConcreteInterface<List<int>>(typeof(IList<>)) == typeof(IList<int>) // true + /// + /// + public static Type? AsConcreteType(Type genericBase) + { + return AsConcreteType(typeof(T), genericBase); + } + + /// + /// Finds the defined with generics specified + /// that is inherited by the . + /// + /// The to find the generic base of. + /// Generic definition without generics specified. + /// The inherited if found, null otherwise. + /// Example: + /// AsConcreteType(typeof(List<int>), typeof(IList<>)) == typeof(IList<int>) // true + /// + public static Type? AsConcreteType(Type? child, Type genericBase) + { + static IEnumerable loopBaseTypes(Type? origin) + { + Type? current = origin; + for (int i = 0; current != null; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + yield return current; + current = current.BaseType; + } + } + + List matches = + [ + .. Enumerable + .Empty() + .Concat(child?.GetInterfaces() ?? []) + .Concat(loopBaseTypes(child)) + .Where(i => i.IsGenericType) + .Where(i => !i.IsGenericTypeDefinition) + .Where(i => i.GetGenericTypeDefinition() == genericBase), + ]; + return matches.Count == 1 ? matches[0] : null; + } + + /// Attempts to convert the to its generic definition. + /// The to convert. + /// + /// The generic definition for if it's generic, + /// otherwise. + /// + public static Type? AsGenericBase(Type? type) + { + return type?.IsGenericType == true ? type.GetGenericTypeDefinition() : null; + } + + /// + /// Attempts to convert the to the concrete + /// representation inherited by the . + /// + /// Generic base to define generics for. + /// Type inheriting generic base with defined generics. + /// The concrete type if a match is found, otherwise. + public static Type? AsMatchedGeneric(Type? genericBase, Type concreteType) + { + if (genericBase?.IsGenericTypeDefinition ?? false) + { + return AsConcreteType(concreteType, genericBase); + } + return null; + } + + /// Builds a name with any generics included. + /// The instance to create a name for. + /// The built display name. + public static string ExpandName(object? instance) + { + return ExpandName(instance is Type type ? type : instance?.GetType()); + } + + /// Builds a name with any generics included. + /// The to create a name for. + /// The built display name. + public static string ExpandName() + { + return ExpandName(typeof(T)); + } + + /// Builds a name with any generics included. + /// The to create a name for. + /// The built display name. + public static string ExpandName(Type? type) + { + if (type?.IsGenericType == true && type.Name.Contains("`", StringComparison.Ordinal)) + { + return string.Concat( + type.Name.Substring(0, type.Name.IndexOf("`", StringComparison.Ordinal)), + "<", + string.Join(",", type.GetGenericArguments().Select(ExpandName)), + ">" + ); + } + else + { + return type?.Name ?? ""; + } + } + + /// Builds a display name for the under test. + /// The method being tested needing a name. + /// The built display name. + public static string BuildTestName(MethodBase method) + { + if (method != null) + { + string generics = method.IsGenericMethod + ? $"<{string.Join(",", method.GetGenericArguments().Select(ExpandName))}>" + : ""; + + return $"{method.Name}{generics}({BuildTestParametersName(method)})"; + } + else + { + return ""; + } + } + + /// Builds a display name for the 's parameters under test. + /// The method being tested needing a name. + /// The built display name for just the parameters. + public static string BuildTestParametersName(MethodBase method) + { + return string.Join( + ",", + method?.GetParameters().Select(p => ExpandName(p.ParameterType)) ?? [] + ); + } +} diff --git a/src/Design/Types/ITypeSupporter.cs b/src/Design/Types/ITypeSupporter.cs new file mode 100644 index 00000000..03a3300d --- /dev/null +++ b/src/Design/Types/ITypeSupporter.cs @@ -0,0 +1,8 @@ +namespace Werecodent.CreateAndFake.Design.Types; + +/// Provides a that the behavior is relevant for. +public interface ITypeSupporter +{ + /// Specific instance can handle. + Type? SupportedType { get; } +} diff --git a/src/Design/Types/MemberScanner.cs b/src/Design/Types/MemberScanner.cs new file mode 100644 index 00000000..3ccfff35 --- /dev/null +++ b/src/Design/Types/MemberScanner.cs @@ -0,0 +1,74 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// Finds members on the . +/// The member being found on the . +/// +public abstract class MemberScanner(Type? type) : ITypeSupporter + where T : MemberInfo +{ + /// + public Type? SupportedType { get; } = type; + + /// All instance members on the . + /// + /// The + /// members in inherited s are included. + /// + public abstract IEnumerable All { get; } + + /// + /// The instance members on the . + /// + /// Includes inherited members. + public abstract IEnumerable OnlyPublic { get; } + + /// + /// The and instance + /// members on the . + /// + /// Includes inherited members. + public abstract IEnumerable PublicOrInternal { get; } + + /// + /// Finds members only if + /// they are visible to the calling method's . Mark an + /// with InternalsVisibleTo("CreateAndFake") to + /// access its properties for the test framework. + /// + /// + public IEnumerable Visible => FindVisible(Assembly.GetCallingAssembly().GetName()); + + /// + /// Finds and + /// instance properties on the . + /// + /// Name of the to determine visibility for. + /// All found properties on the . + protected internal IEnumerable FindVisible(AssemblyName assembly) + { + HashSet internalTypes = []; + + Type? currentType = SupportedType; + for (int i = 0; currentType != null; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + if (ScopeChecker.InternalsAreVisible(currentType, assembly)) + { + _ = internalTypes.Add(currentType); + } + currentType = currentType.BaseType; + } + + return OnlyPublic + .Concat(PublicOrInternal.Where(m => internalTypes.Contains(m.DeclaringType))) + .Distinct(); + } + + /// + public override string ToString() + { + return $"{GenericConverter.ExpandName(this)}({GenericConverter.ExpandName(SupportedType)})"; + } +} diff --git a/src/Design/Types/MethodScanner.cs b/src/Design/Types/MethodScanner.cs new file mode 100644 index 00000000..8233555b --- /dev/null +++ b/src/Design/Types/MethodScanner.cs @@ -0,0 +1,58 @@ +using System.Collections.Frozen; +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// +public sealed class MethodScanner(Type? type) : MemberScanner(type) +{ + /// + public override IEnumerable All { get; } = FindAllMethods(type).ToFrozenSet(); + + /// + public override IEnumerable OnlyPublic => All.Where(m => m.IsPublic); + + /// + public override IEnumerable PublicOrInternal => + All.Where(c => c.IsPublic || c.IsAssembly || c.IsFamilyOrAssembly); + + /// Finds all methods on the . + /// The to find methods on. + /// All found methods on the . + /// The methods in inherited s are included. + private static IEnumerable FindAllMethods(Type? type) + { + if (type == null) + { + yield break; + } + + foreach ( + MethodInfo method in type.GetMethods( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ) + ) + { + if (method.Name != "Finalize") + { + yield return method; + } + } + + Type? currentType = type; + HashSet completedTypes = [typeof(object)]; + for (int i = 0; currentType != null && completedTypes.Add(currentType); i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + foreach ( + MethodInfo method in currentType + .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) + .Where(m => m.IsPrivate) + ) + { + yield return method; + } + currentType = currentType.BaseType; + } + } +} diff --git a/src/Design/Types/PropertyScanner.cs b/src/Design/Types/PropertyScanner.cs new file mode 100644 index 00000000..dee91c5b --- /dev/null +++ b/src/Design/Types/PropertyScanner.cs @@ -0,0 +1,113 @@ +using System.Collections.Frozen; +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// +public sealed class PropertyScanner(Type? type) : MemberScanner(type) +{ + /// + public override IEnumerable All { get; } = FindAllProperties(type).ToFrozenSet(); + + /// + public override IEnumerable OnlyPublic { get; } = + FindAllProperties(type) + .Where(p => p.GetGetMethod(false) != null || p.GetSetMethod(false) != null) + .ToFrozenSet(); + + /// + public override IEnumerable PublicOrInternal { get; } = + FindAllProperties(type) + .Where(p => + { + MethodInfo? getMethod = p.GetGetMethod(true); + MethodInfo? setMethod = p.GetSetMethod(true); + return (getMethod != null && (getMethod.IsPublic || getMethod.IsAssembly)) + || (setMethod != null && (setMethod.IsPublic || setMethod.IsAssembly)); + }) + .ToFrozenSet(); + + /// + /// The readable and instance + /// properties on the that can be written to. + /// + /// + public IEnumerable SetAndGetable => + FindSetAndGetable(Assembly.GetCallingAssembly().GetName()); + + /// + /// The and instance properties + /// on the that can be written to. + /// + /// + public IEnumerable Settable => + FindSettable(Assembly.GetCallingAssembly().GetName()); + + /// + internal IEnumerable FindSetAndGetable(AssemblyName assembly) + { + bool nonPublic = ScopeChecker.InternalsAreVisible(SupportedType, assembly); + return FindSettable(assembly) + .Where(p => + { + MethodInfo? getMethod = p.GetGetMethod(nonPublic); + return getMethod != null && (getMethod.IsPublic || getMethod.IsAssembly); + }); + } + + /// + /// Finds and instance properties + /// on the that can be written to. + /// + /// + internal IEnumerable FindSettable(AssemblyName assembly) + { + bool nonPublic = ScopeChecker.InternalsAreVisible(SupportedType, assembly); + return FindVisible(assembly) + .Where(p => + { + MethodInfo? setMethod = p.GetSetMethod(nonPublic); + return setMethod != null && (setMethod.IsPublic || setMethod.IsAssembly); + }); + } + + /// Finds all instance properties on the . + /// The to find properties on. + /// All found properties on the . + /// The properties in inherited s are included. + private static IEnumerable FindAllProperties(Type? type) + { + if (type == null) + { + yield break; + } + + foreach ( + PropertyInfo prop in type.GetProperties( + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance + ) + ) + { + yield return prop; + } + + Type? currentType = type; + HashSet completedTypes = []; + for (int i = 0; currentType != null && completedTypes.Add(currentType); i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + foreach ( + PropertyInfo prop in currentType + .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic) + .Where(p => + p.GetSetMethod(true)?.IsPrivate != false + && p.GetGetMethod(true)?.IsPrivate != false + ) + ) + { + yield return prop; + } + currentType = currentType.BaseType; + } + } +} diff --git a/src/Design/Types/RuntimeDetails.cs b/src/Design/Types/RuntimeDetails.cs new file mode 100644 index 00000000..3a79c5d5 --- /dev/null +++ b/src/Design/Types/RuntimeDetails.cs @@ -0,0 +1,85 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// Provides information only available at runtime. +public static class RuntimeDetails +{ + /// The used runtime . + public static Type RuntimeType { get; } = typeof(Type).GetType(); + + /// The used runtime . + public static Type RuntimeConstructorInfoType { get; } = + typeof(RuntimeData).GetConstructors()[0].GetType(); + + /// The used runtime . + public static Type RuntimeMethodInfoType { get; } = + typeof(RuntimeData).GetMethod(nameof(RuntimeData.TestCompare))!.GetType(); + + /// The used runtime . + public static Type RuntimePropertyInfoType { get; } = + typeof(RuntimeData).GetProperty(nameof(RuntimeData.Data))!.GetType(); + + /// The used runtime . + /// See for s. + public static Type RtFieldInfoType { get; } = + typeof(RuntimeData).GetField(nameof(RuntimeData._data))!.GetType(); + + /// The used runtime for s. + /// Inherits the from . + public static Type MdFieldInfoType { get; } = + typeof(RuntimeData).GetField(nameof(RuntimeData._Default))!.GetType(); + + /// The used runtime . + public static Type RuntimeParameterInfoType { get; } = + typeof(RuntimeData) + .GetMethod(nameof(RuntimeData.TestCompare))! + .GetParameters()[0] + .GetType(); + + /// The used runtime . + public static Type RuntimeAssemblyType { get; } = Assembly.GetExecutingAssembly().GetType(); + + /// All provided runtime s. + public static IEnumerable RuntimeTypes { get; } = + [ + RuntimeType, + RuntimeConstructorInfoType, + RuntimeMethodInfoType, + RuntimePropertyInfoType, + RtFieldInfoType, + MdFieldInfoType, + RuntimeParameterInfoType, + RuntimeAssemblyType, + ]; + + /// Validates the runtime provider class works. + /// + internal static bool InnerClassValidation(string? x, string? y) + { + return new RuntimeData(x).TestCompare(new(y)); + } + + /// Provides concrete runtime s via inspection. + /// Vehicle for providing members to inspect. + private sealed class RuntimeData(string? data) + { + /// + public const string _Default = ""; + + /// + public readonly string _data = data ?? _Default; + + /// + public string Data => _data; + + /// + /// + /// Results of comparison via . + public bool TestCompare(RuntimeData other) + { + return Data.Equals(other.Data, StringComparison.Ordinal); + } + } +} diff --git a/src/Design/Types/ScopeChecker.cs b/src/Design/Types/ScopeChecker.cs new file mode 100644 index 00000000..e8270443 --- /dev/null +++ b/src/Design/Types/ScopeChecker.cs @@ -0,0 +1,94 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// Provides common patterns for verifying access. +public static class ScopeChecker +{ + /// Determines if is usable in the . + /// The to verify visibility for. + /// + public static bool IsVisible(AssemblyName assembly) + { + return IsVisible(typeof(T), assembly); + } + + /// Determines if the is usable in the . + /// The to verify visibility for. + /// Name of the trying to use the . + /// + /// if the is visible to + /// the , otherwise. + /// + /// + /// Mark an with InternalsVisibleTo("CreateAndFake") + /// to access its types for this method. + /// + public static bool IsVisible(Type? type, AssemblyName assembly) + { + return type != null && (type.IsVisible || InternalsAreVisible(type, assembly)); + } + + /// + /// Determines if the 's + /// members are usable in the . + /// + /// The to verify visibility for. + /// Name of the to check scope privilege for. + /// + /// if the 's s + /// are visible to the , otherwise. + /// + /// + /// Mark an with InternalsVisibleTo("CreateAndFake") + /// to enable members visibility per this method. + /// + internal static bool InternalsAreVisible(Type? type, AssemblyName assembly) + { + ArgumentGuard.ThrowIfNull(assembly); + + Assembly? typeAssembly = type?.Assembly; + return typeAssembly != null + && ( + typeAssembly.FullName == assembly.FullName + || typeAssembly + .GetCustomAttributes() + .Any(a => a.AssemblyName == assembly.Name) + ); + } + + /// + /// Finds every and in the . + /// + /// containing the s to search for. + /// Every found if the loads, none otherwise. + public static IEnumerable FindLoadedSpecificTypes(Assembly? assembly) + { + if (assembly == null) + { + return []; + } + + return FindLoadedTypes(assembly) + .Where(t => t.IsClass || t.IsValueType) + .Where(t => !t.IsNestedPrivate) + .Where(t => !t.IsDefined(typeof(CompilerGeneratedAttribute), false)); + } + + /// Finds every in the . + /// containing the s to search for. + /// Every found if the can load, none otherwise. + internal static IEnumerable FindLoadedTypes(Assembly? assembly) + { + try + { + return assembly?.GetTypes() ?? Type.EmptyTypes; + } + catch + { + return Type.EmptyTypes; + } + } +} diff --git a/src/Design/Types/StaticMethodScanner.cs b/src/Design/Types/StaticMethodScanner.cs new file mode 100644 index 00000000..fd3679f7 --- /dev/null +++ b/src/Design/Types/StaticMethodScanner.cs @@ -0,0 +1,35 @@ +using System.Collections.Frozen; +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// +public sealed class StaticMethodScanner(Type? type) : MemberScanner(type) +{ + /// All static methods on the . + /// Does not include inherited static members. + public override IEnumerable All { get; } = FindAllMethods(type).ToFrozenSet(); + + /// + /// The static methods on the . + /// + /// Does not include inherited static members. + public override IEnumerable OnlyPublic => All.Where(m => m.IsPublic); + + /// + /// The and static + /// methods on the . + /// + /// Does not include inherited static members. + public override IEnumerable PublicOrInternal => + All.Where(c => c.IsPublic || c.IsAssembly || c.IsFamilyOrAssembly); + + /// Finds all static methods on the . + /// The to find methods on. + /// All found static methods on the . + private static MethodInfo[] FindAllMethods(Type? type) + { + return type?.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + ?? []; + } +} diff --git a/src/Design/Types/TypeDescriber.cs b/src/Design/Types/TypeDescriber.cs new file mode 100644 index 00000000..45e1e4b2 --- /dev/null +++ b/src/Design/Types/TypeDescriber.cs @@ -0,0 +1,372 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Extensions; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// Identifies and caches a 's inheritance tree and members. +/// WARNING: Loads all assemblies upon first use. +[ExcludeFromCreateAndFake] +public sealed class TypeDescriber : IValueEquatable, IEquatable, ITypeSupporter +{ + /// Every possible specific type. + private static readonly Lazy> _AllTypesFromAllAssemblies = new(() => + FindAllAssemblies() + .Where(a => !a.ReflectionOnly) + .Where(a => !a.IsDynamic) + .SelectMany(ScopeChecker.FindLoadedTypes) + .Where(t => !Attribute.IsDefined(t, typeof(ExcludeFromCreateAndFakeAttribute))) + .ToFrozenSet() + ); + + /// Prevents concurrency issues for . + private static readonly Lock _Lock = new(); + + /// Caches every parent inherited per . + private static readonly Dictionary _InheritCache = []; + + /// Associates no parents for . + private static readonly TypeDescriber _NullDescriber = new(null); + + /// Finds or loads inheritance/member data for . + /// The to find inheritance for. + /// The found/loaded inheritance data. + /// WARNING: Loads all assemblies upon first use. + public static TypeDescriber For() + { + return For(typeof(T)); + } + + /// The instance whose to find inheritance/member for. + /// + public static TypeDescriber For(object? instance) + { + if (instance is Type type) + { + return For(type); + } + else + { + return For(instance?.GetType()); + } + } + + /// Finds or loads inheritance/member data for the . + /// The to find inheritance for. + /// The found/loaded inheritance data. + /// WARNING: Loads all assemblies upon first use. + public static TypeDescriber For(Type? type) + { + if (type == null) + { + return _NullDescriber; + } + + TypeDescriber? describer; + lock (_Lock) + { + if (!_InheritCache.TryGetValue(type, out describer)) + { + describer = _InheritCache[type] = new(type); + } + } + return describer; + } + + /// + public Type? SupportedType { get; } + + /// All found s the inherits. + public IEnumerable InheritedTypes => _inheritedTypes.Value; + + /// All found s inheriting the . + public IEnumerable SubTypes => _subTypes.Value; + + /// Finds properties on the . + public PropertyScanner Properties => _properties.Value; + + /// Finds fields on the . + public FieldScanner Fields => _fields.Value; + + /// Finds instance methods on the . + public MethodScanner Methods => _methods.Value; + + /// Finds static methods on the . + public StaticMethodScanner StaticMethods => _staticMethods.Value; + + /// Finds constructors on the . + public ConstructorScanner Constructors => _constructors.Value; + + /// Finds factories on the . + public FactoryScanner Factories => _factories.Value; + + /// + private readonly Lazy> _inheritedTypes; + + /// + private readonly Lazy> _subTypes; + + /// + private readonly Lazy _properties; + + /// + private readonly Lazy _fields; + + /// + private readonly Lazy _methods; + + /// + private readonly Lazy _staticMethods; + + /// + private readonly Lazy _constructors; + + /// + private readonly Lazy _factories; + + /// + /// + private TypeDescriber(Type? type) + { + SupportedType = type; + _inheritedTypes = new(() => [.. FindParentInheritance(type)]); + _subTypes = new(() => [.. FindLoadedChildren(type)]); + _fields = new(() => new FieldScanner(type)); + _properties = new(() => new PropertyScanner(type)); + _methods = new(() => new MethodScanner(type)); + _staticMethods = new(() => new StaticMethodScanner(type)); + _constructors = new(() => new ConstructorScanner(type)); + _factories = new(() => new FactoryScanner(type)); + } + + /// + /// Checks if is a base + /// or for the . + /// + /// + /// Potential base / for the . + /// + /// + /// if the inherits + /// , otherwise. + /// + public bool Inherits() + { + return Inherits(typeof(T)); + } + + /// + /// Checks if is a base + /// or for the . + /// + /// + /// Potential base / for the . + /// + /// + /// if the inherits + /// , otherwise. + /// + public bool Inherits([NotNullWhen(true)] Type? parent) + { + return parent != null + && InheritedTypes.Contains(Nullable.GetUnderlyingType(parent) ?? parent); + } + + /// + /// Finds every non- inheriting + /// the in its defined . + /// + /// + public IEnumerable FindLocalSubclasses() + { + AssemblyName assembly = Assembly.GetCallingAssembly().GetName(); + return FindLoadedSubclasses(assembly).Where(t => SupportedType?.Assembly == t.Assembly); + } + + /// + public IEnumerable FindLoadedSubclasses() + { + return FindLoadedSubclasses(Assembly.GetCallingAssembly().GetName()); + } + + /// + /// Finds every non- + /// inheriting the in all loaded assemblies. + /// + /// Accessing assembly to check visibility access for. + /// The found creatable subclasses. + /// + /// Mark an with InternalsVisibleTo("CreateAndFake") + /// to access its types for the test framework. + /// + private IEnumerable FindLoadedSubclasses(AssemblyName assembly) + { + return SubTypes + .Where(t => !t.IsAbstract) + .Where(t => !t.IsGenericTypeDefinition) + .Where(t => ScopeChecker.IsVisible(t, assembly)); + } + + /// Determines if the is a . + /// if , otherwise. + public bool IsStatic() + { + return SupportedType?.IsAbstract == true && SupportedType.IsSealed; + } + + /// + public bool IsMutable() + { + return IsMutable(Assembly.GetCallingAssembly().GetName()); + } + + /// Determines if the has any modifiable properties/fields. + /// + private bool IsMutable(AssemblyName assembly) + { + return Properties.FindSettable(assembly).Any() || Fields.FindWritable(assembly).Any(); + } + + /// + public bool HasInitializableOnlyState() + { + return HasInitializableOnlyState(Assembly.GetCallingAssembly().GetName()); + } + + /// + /// Determines if the has any properties/fields only settable via a constructor. + /// + /// Beware that this does not always mean the value is changeable. + /// + private bool HasInitializableOnlyState(AssemblyName assembly) + { + return ( + Constructors.FindVisible(assembly).Any(c => c.GetParameters().Length > 0) + || Factories.FindVisible(assembly).Any(f => f.GetParameters().Length > 0) + ) && Fields.All.Any(f => f.IsInitOnly && !f.IsLiteral); + } + + /// + /// Finds every child inheriting the in all loaded assemblies. + /// + /// The to find subclasses for. + /// The found subclasses. + private static IEnumerable FindLoadedChildren(Type? type) + { + return (type == null) ? [] : _AllTypesFromAllAssemblies.Value.Where(t => t.Inherits(type)); + } + + /// Finds every that the inherits. + /// The to find base classes/interfaces for. + /// All found base classes/interfaces. + private static HashSet FindParentInheritance(Type? type) + { + if (type == null) + { + return []; + } + + HashSet foundParents = [type]; + Stack sourceTypes = new(foundParents); + + void attemptAdd(Type? newType) + { + if (newType != null && foundParents.Add(newType)) + { + sourceTypes.Push(newType); + } + } + + for (int i = 0; sourceTypes.Count > 0; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + Type source = sourceTypes.Pop(); + if (source.IsGenericType) + { + attemptAdd(source.GetGenericTypeDefinition()); + } + foreach (Type parent in source.GetInterfaces()) + { + attemptAdd(parent); + } + attemptAdd(source.BaseType); + } + return foundParents; + } + + /// Finds all possible assemblies. + /// The found assemblies. + [ExcludeFromCodeCoverage] // Any known fail cases are to be fixed. + private static HashSet FindAllAssemblies() + { + HashSet foundAssemblies = [.. AppDomain.CurrentDomain.GetAssemblies()]; + + Stack sourceAssemblies = new(foundAssemblies); + for (int i = 0; sourceAssemblies.Count > 0; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i); + + Assembly assembly = sourceAssemblies.Pop(); + foreach (AssemblyName referenced in assembly.GetReferencedAssemblies()) + { + try + { + Assembly loaded = Assembly.Load(referenced); + if (foundAssemblies.Add(loaded)) + { + sourceAssemblies.Push(loaded); + } + } + catch (Exception e) + { + // Ignore assemblies that can't be loaded. + Console.Error.WriteLine( + $"Could not load assembly '{assembly.FullName}' due to error: {e}" + ); + } + } + } + return foundAssemblies; + } + + /// + public override string ToString() + { + return $"{nameof(TypeDescriber)}({GenericConverter.ExpandName(SupportedType)})"; + } + + /// + public bool Equals(TypeDescriber? other) + { + return SupportedType == other?.SupportedType; + } + + /// + public override bool Equals(object? obj) + { + return Equals(obj as TypeDescriber); + } + + /// + public override int GetHashCode() + { + return SupportedType?.GetHashCode() ?? ValueComparer.NullHash; + } + + /// + public bool ValuesEqual(object? other) + { + return Equals(other); + } + + /// + public int GetValueHash() + { + return GetHashCode(); + } +} diff --git a/src/Design/Types/TypeSupporter.cs b/src/Design/Types/TypeSupporter.cs new file mode 100644 index 00000000..f41e1676 --- /dev/null +++ b/src/Design/Types/TypeSupporter.cs @@ -0,0 +1,109 @@ +using System.Collections.Frozen; +using Werecodent.CreateAndFake.Design.Extensions; + +namespace Werecodent.CreateAndFake.Design.Types; + +/// Provides common patterns. +public static class TypeSupporter +{ + /// + /// Groups the by their . + /// + /// The being grouped. + /// The collection to group via iteration. + /// + /// The collected keyed by their . + /// + public static IDictionary GroupBySupportedType(IEnumerable typeHandlers) + where T : ITypeSupporter + { + Dictionary results = []; + int i = 0; + foreach (T handler in typeHandlers ?? []) + { + ArgumentGuard.ThrowUponIterationLimit(i++); + if (handler.SupportedType != null) + { + results.Add(handler.SupportedType, handler); + } + } + return results.ToFrozenDictionary(p => p.Key, p => p.Value); + } + + /// + /// Groups the by what the inherits. + /// + /// The being grouped. + /// The collection to group via iteration. + /// Types to prevent being added. + /// + /// The collected keyed by every & + /// their inherits. + /// + public static IDictionary GroupByInheritance( + IEnumerable typeHandlers, + params ICollection exclusions + ) + where T : ITypeSupporter + { + ArgumentGuard.ThrowIfNull(exclusions); + + Dictionary> results = []; + int i = 0; + foreach (T handler in typeHandlers ?? []) + { + foreach ( + Type type in TypeDescriber + .For(handler.SupportedType) + .InheritedTypes.Where(t => !t.IsGenericTypeDefinition) + .Where(t => !t.Inherits() || t == handler.SupportedType) + .Where(t => !exclusions.Contains(t)) + ) + { + ArgumentGuard.ThrowUponIterationLimit(i++); + if (results.TryGetValue(type, out IList? values)) + { + values.Add(handler); + } + else + { + results.Add(type, [handler]); + } + } + } + return results.ToFrozenDictionary(p => p.Key, p => p.Value.ToArray()); + } + + /// + /// Groups the by what the + /// is inherited by. + /// + /// The being grouped. + /// The collection to group via iteration. + /// + /// The collected keyed by every & + /// their is inherited by. + /// + public static IDictionary GroupBySubclasses(IEnumerable typeHandlers) + where T : ITypeSupporter + { + Dictionary> results = []; + int i = 0; + foreach (T handler in typeHandlers ?? []) + { + foreach (Type type in TypeDescriber.For(handler.SupportedType).FindLoadedSubclasses()) + { + ArgumentGuard.ThrowUponIterationLimit(i++); + if (results.TryGetValue(type, out IList? values)) + { + values.Add(handler); + } + else + { + results.Add(type, [handler]); + } + } + } + return results.ToFrozenDictionary(p => p.Key, p => p.Value.ToArray()); + } +} diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 498023fa..9b517527 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,12 +2,45 @@ latest enable + enable true All true + v + $(NoWarn);NU1510;NU1903 + Werecodent.$(MSBuildProjectName) + + + true - $(MSBuildThisFileDirectory)..\artifacts\obj\$(MSBuildProjectName)\ - $(MSBuildThisFileDirectory)..\artifacts\bin\$(MSBuildProjectName)\$(Configuration)\ $(MSBuildThisFileDirectory)..\artifacts\bin\$(MSBuildProjectName)\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName).xml + $(MSBuildThisFileDirectory)..\artifacts\obj\$(MSBuildProjectName) + $(MSBuildThisFileDirectory)..\artifacts\bin\$(MSBuildProjectName) + $(MSBuildThisFileDirectory)..\artifacts\bin\$(MSBuildProjectName)\$(Configuration)\ + false + + + + Werecodent + MPL-2.0 + https://werecodent.github.io/CreateAndFake/ + https://github.com/Werecodent/CreateAndFake + https://github.com/Werecodent/CreateAndFake/releases/ + Github + create, fake, tdd, agile, testing, tests, stubs, mocking, mocks, mock, data, random, cloning, clones, clone - \ No newline at end of file + + + + + + + + + + + + + + + diff --git a/src/MSTest.v3/AssemblyTester.cs b/src/MSTest.v3/AssemblyTester.cs new file mode 100644 index 00000000..f5cc2515 --- /dev/null +++ b/src/MSTest.v3/AssemblyTester.cs @@ -0,0 +1,65 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +[TestClass] +public abstract class AssemblyTester : BaseAssemblyTester +{ + /// Used to store information that is provided to unit tests for the MSTest framework. + public TestContext? TestContext { get; set; } + + /// + [TestMethod] + public override void Tester_TestClassCoverage() + { + TestClassCoverageImplementation(); + } + + /// + [TestMethod] + public override Task Tester_ValidateAutoTesterInstances() + { + return ValidateAutoTesterInstancesImplementation( + TestContext!.CancellationTokenSource.Token + ); + } + + /// + [TestMethod] + public override Task Tester_ValidateRandomDataParameters() + { + return ValidateRandomDataParametersImplementation( + TestContext!.CancellationTokenSource.Token + ); + } + + /// + [TestMethod] + public override void Tester_ValidateTestMethodNaming() + { + ValidateTestMethodNamingImplementation([typeof(TestMethodAttribute)]); + } + + /// + [TestMethod] + public override void Tester_VerifyAllToStrings() + { + VerifyAllToStringsImplementation(); + } + + /// + [TestMethod] + public override Task Tester_VerifyTestSettingsConfig_Default() + { + return VerifyTestSettingsConfigImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_VerifyToolSetIntegrity() + { + return VerifyToolSetIntegrityImplementation(TestContext!.CancellationTokenSource.Token); + } +} diff --git a/src/MSTest.v3/AutoTester.cs b/src/MSTest.v3/AutoTester.cs new file mode 100644 index 00000000..a78adb53 --- /dev/null +++ b/src/MSTest.v3/AutoTester.cs @@ -0,0 +1,47 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +[TestClass] +public abstract class AutoTester(Type testType) : BaseAutoTester(testType) +{ + /// Used to store information that is provided to unit tests for the MSTest framework. + public TestContext? TestContext { get; set; } + + /// + [TestMethod] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/MSTest.v3/AutoTester{T}.cs b/src/MSTest.v3/AutoTester{T}.cs new file mode 100644 index 00000000..010aaae0 --- /dev/null +++ b/src/MSTest.v3/AutoTester{T}.cs @@ -0,0 +1,46 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +public abstract class AutoTester : BaseAutoTester +{ + /// Used to store information that is provided to unit tests for the MSTest framework. + public TestContext? TestContext { get; set; } + + /// + [TestMethod] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(TestContext!.CancellationTokenSource.Token); + } + + /// + [TestMethod] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/MSTest.v3/CapAttribute.cs b/src/MSTest.v3/CapAttribute.cs new file mode 100644 index 00000000..7a84999f --- /dev/null +++ b/src/MSTest.v3/CapAttribute.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +public sealed class CapAttribute : BaseCapAttribute +{ + /// + public CapAttribute(object min, object max) + : base(min, max) { } + + /// + public CapAttribute(object max) + : base(max) { } + + /// + public override object Clone() + { + return IsMinSet ? new CapAttribute(Min, Max) : new CapAttribute(Max); + } +} diff --git a/src/MSTest.v3/CopyAttribute.cs b/src/MSTest.v3/CopyAttribute.cs new file mode 100644 index 00000000..0d34b408 --- /dev/null +++ b/src/MSTest.v3/CopyAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +public sealed class CopyAttribute : BaseCopyAttribute; diff --git a/src/MSTest.v3/CreateAndFake.MSTest.v3.csproj b/src/MSTest.v3/CreateAndFake.MSTest.v3.csproj new file mode 100644 index 00000000..7df3bafa --- /dev/null +++ b/src/MSTest.v3/CreateAndFake.MSTest.v3.csproj @@ -0,0 +1,16 @@ + + + + net11.0;net10.0;netstandard2.0 + + + + A C# class library that handles mocking, test data generation, and validation. + + + + + + + + diff --git a/src/MSTest.v3/FakeAttribute.cs b/src/MSTest.v3/FakeAttribute.cs new file mode 100644 index 00000000..cd5401fe --- /dev/null +++ b/src/MSTest.v3/FakeAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +public sealed class FakeAttribute : BaseFakeAttribute; diff --git a/src/MSTest.v3/InjectAttribute.cs b/src/MSTest.v3/InjectAttribute.cs new file mode 100644 index 00000000..f62c7520 --- /dev/null +++ b/src/MSTest.v3/InjectAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +public sealed class InjectAttribute : BaseInjectAttribute; diff --git a/src/MSTest.v3/RandomDataAttribute.cs b/src/MSTest.v3/RandomDataAttribute.cs new file mode 100644 index 00000000..49dcbd53 --- /dev/null +++ b/src/MSTest.v3/RandomDataAttribute.cs @@ -0,0 +1,78 @@ +using System.Reflection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +/// Flags methods +/// to be populated with random values for testing. +/// +/// +/// Earlier Parameters will be used to construct later Parameters if possible.
+/// Use with Parameter attributes to control randomization behavior: +/// +/// , +/// & +/// +/// +/// +/// Example test: +/// [TestMethod, RandomData] +/// public void Test([Size(2)] string data) +/// { +/// data.Length.Assert().Is(2); +/// } +/// +///
+[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class RandomDataAttribute : Attribute, ITestDataSource, IRandomDataMarker +{ + /// + public int Trials { get; set; } = 1; + + /// + public IEnumerable GetData(MethodInfo methodInfo) + { + if (methodInfo == null) + { + return []; + } + + List results = []; + for (int i = 0; i < Trials; i++) + { + try + { + ArgumentGuard.ThrowUponIterationLimit( + i, + Tools.Runner.Options.Design.IterationLimit + ); + MethodCallWrapper data = Tools.Runner.CreateFor(methodInfo, default); + results.Add([.. data.Args]); + } + catch (Exception e) + { + Console.Error.WriteLine($"Test generation failure on {methodInfo}= {e.Message}"); + break; + } + } + return results; + } + + /// + public string? GetDisplayName(MethodInfo methodInfo, object?[]? data) + { + if (methodInfo != null) + { + string args = string.Join(",", methodInfo.GetParameters().Select(p => p.ParameterType)); + return $"{methodInfo.Name}({args})"; + } + else + { + return null; + } + } +} diff --git a/src/MSTest.v3/SizeAttribute.cs b/src/MSTest.v3/SizeAttribute.cs new file mode 100644 index 00000000..03dce3f4 --- /dev/null +++ b/src/MSTest.v3/SizeAttribute.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +public sealed class SizeAttribute : BaseSizeAttribute +{ + /// + public SizeAttribute(int min, int max) + : base(min, max) { } + + /// + public SizeAttribute(int count) + : base(count) { } +} diff --git a/src/MSTest.v3/StubAttribute.cs b/src/MSTest.v3/StubAttribute.cs new file mode 100644 index 00000000..9ed739ce --- /dev/null +++ b/src/MSTest.v3/StubAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +public sealed class StubAttribute : BaseStubAttribute; diff --git a/src/MSTest.v3/UniqueAttribute.cs b/src/MSTest.v3/UniqueAttribute.cs new file mode 100644 index 00000000..28d93afe --- /dev/null +++ b/src/MSTest.v3/UniqueAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v3; + +/// +public sealed class UniqueAttribute : BaseUniqueAttribute; diff --git a/src/MSTest.v4/AssemblyTester.cs b/src/MSTest.v4/AssemblyTester.cs new file mode 100644 index 00000000..2c42a409 --- /dev/null +++ b/src/MSTest.v4/AssemblyTester.cs @@ -0,0 +1,60 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +[TestClass] +public abstract class AssemblyTester : BaseAssemblyTester +{ + /// Used to store information that is provided to unit tests for the MSTest framework. + public TestContext? TestContext { get; set; } + + /// + [TestMethod] + public override void Tester_TestClassCoverage() + { + TestClassCoverageImplementation(); + } + + /// + [TestMethod] + public override Task Tester_ValidateAutoTesterInstances() + { + return ValidateAutoTesterInstancesImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_ValidateRandomDataParameters() + { + return ValidateRandomDataParametersImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override void Tester_ValidateTestMethodNaming() + { + ValidateTestMethodNamingImplementation([typeof(TestMethodAttribute)]); + } + + /// + [TestMethod] + public override void Tester_VerifyAllToStrings() + { + VerifyAllToStringsImplementation(); + } + + /// + [TestMethod] + public override Task Tester_VerifyTestSettingsConfig_Default() + { + return VerifyTestSettingsConfigImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_VerifyToolSetIntegrity() + { + return VerifyToolSetIntegrityImplementation(TestContext!.CancellationToken); + } +} diff --git a/src/MSTest.v4/AutoTester.cs b/src/MSTest.v4/AutoTester.cs new file mode 100644 index 00000000..d7e1a2e0 --- /dev/null +++ b/src/MSTest.v4/AutoTester.cs @@ -0,0 +1,45 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public abstract class AutoTester(Type testType) : BaseAutoTester(testType) +{ + /// Used to store information that is provided to unit tests for the MSTest framework. + public TestContext? TestContext { get; set; } + + /// + [TestMethod] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/MSTest.v4/AutoTester{T}.cs b/src/MSTest.v4/AutoTester{T}.cs new file mode 100644 index 00000000..1acc4341 --- /dev/null +++ b/src/MSTest.v4/AutoTester{T}.cs @@ -0,0 +1,45 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public abstract class AutoTester : BaseAutoTester +{ + /// Used to store information that is provided to unit tests for the MSTest framework. + public TestContext? TestContext { get; set; } + + /// + [TestMethod] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(TestContext!.CancellationToken); + } + + /// + [TestMethod] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/MSTest.v4/CapAttribute.cs b/src/MSTest.v4/CapAttribute.cs new file mode 100644 index 00000000..9daf7c66 --- /dev/null +++ b/src/MSTest.v4/CapAttribute.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public sealed class CapAttribute : BaseCapAttribute +{ + /// + public CapAttribute(object min, object max) + : base(min, max) { } + + /// + public CapAttribute(object max) + : base(max) { } + + /// + public override object Clone() + { + return IsMinSet ? new CapAttribute(Min, Max) : new CapAttribute(Max); + } +} diff --git a/src/MSTest.v4/CopyAttribute.cs b/src/MSTest.v4/CopyAttribute.cs new file mode 100644 index 00000000..c4cca6d3 --- /dev/null +++ b/src/MSTest.v4/CopyAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public sealed class CopyAttribute : BaseCopyAttribute; diff --git a/src/MSTest.v4/CreateAndFake.MSTest.v4.csproj b/src/MSTest.v4/CreateAndFake.MSTest.v4.csproj new file mode 100644 index 00000000..440c8db3 --- /dev/null +++ b/src/MSTest.v4/CreateAndFake.MSTest.v4.csproj @@ -0,0 +1,16 @@ + + + + net11.0;net10.0;netstandard2.0 + + + + A C# class library that handles mocking, test data generation, and validation. + + + + + + + + diff --git a/src/MSTest.v4/FakeAttribute.cs b/src/MSTest.v4/FakeAttribute.cs new file mode 100644 index 00000000..24b2bea5 --- /dev/null +++ b/src/MSTest.v4/FakeAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public sealed class FakeAttribute : BaseFakeAttribute; diff --git a/src/MSTest.v4/InjectAttribute.cs b/src/MSTest.v4/InjectAttribute.cs new file mode 100644 index 00000000..88ec6127 --- /dev/null +++ b/src/MSTest.v4/InjectAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public sealed class InjectAttribute : BaseInjectAttribute; diff --git a/src/MSTest.v4/RandomDataAttribute.cs b/src/MSTest.v4/RandomDataAttribute.cs new file mode 100644 index 00000000..df18441a --- /dev/null +++ b/src/MSTest.v4/RandomDataAttribute.cs @@ -0,0 +1,77 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +/// Flags methods +/// to be populated with random values for testing. +/// +/// +/// Earlier Parameters will be used to construct later Parameters if possible.
+/// Use with Parameter attributes to control randomization behavior: +/// +/// , +/// & +/// +/// +/// +/// Example test: +/// [TestMethod, RandomData] +/// public void Test([Size(2)] string data) +/// { +/// data.Length.Assert().Is(2); +/// } +/// +///
+[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class RandomDataAttribute : Attribute, ITestDataSource, IRandomDataMarker +{ + /// + public int Trials { get; set; } = 1; + + /// + public IEnumerable GetData(MethodInfo methodInfo) + { + if (methodInfo == null) + { + return []; + } + + List results = []; + for (int i = 0; i < Trials; i++) + { + try + { + ArgumentGuard.ThrowUponIterationLimit( + i, + Tools.Runner.Options.Design.IterationLimit + ); + MethodCallWrapper data = Tools.Runner.CreateFor(methodInfo, default); + results.Add([.. data.Args]); + } + catch (Exception e) + { + Console.Error.WriteLine($"Test generation failure on {methodInfo}= {e.Message}"); + break; + } + } + return results; + } + + /// + public string? GetDisplayName(MethodInfo methodInfo, object?[]? data) + { + if (methodInfo != null) + { + string args = string.Join(",", methodInfo.GetParameters().Select(p => p.ParameterType)); + return $"{methodInfo.Name}({args})"; + } + else + { + return null; + } + } +} diff --git a/src/MSTest.v4/SizeAttribute.cs b/src/MSTest.v4/SizeAttribute.cs new file mode 100644 index 00000000..087c96d8 --- /dev/null +++ b/src/MSTest.v4/SizeAttribute.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public sealed class SizeAttribute : BaseSizeAttribute +{ + /// + public SizeAttribute(int min, int max) + : base(min, max) { } + + /// + public SizeAttribute(int count) + : base(count) { } +} diff --git a/src/MSTest.v4/StubAttribute.cs b/src/MSTest.v4/StubAttribute.cs new file mode 100644 index 00000000..d31c1b53 --- /dev/null +++ b/src/MSTest.v4/StubAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public sealed class StubAttribute : BaseStubAttribute; diff --git a/src/MSTest.v4/UniqueAttribute.cs b/src/MSTest.v4/UniqueAttribute.cs new file mode 100644 index 00000000..877f3ee3 --- /dev/null +++ b/src/MSTest.v4/UniqueAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.MSTest.v4; + +/// +public sealed class UniqueAttribute : BaseUniqueAttribute; diff --git a/src/NUnit.v3/.editorconfig b/src/NUnit.v3/.editorconfig new file mode 100644 index 00000000..965fdd0e --- /dev/null +++ b/src/NUnit.v3/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# Crashes; fix not available in all .NET versions. +dotnet_diagnostic.CA2263.severity = None diff --git a/src/NUnit.v3/AssemblyTester.cs b/src/NUnit.v3/AssemblyTester.cs new file mode 100644 index 00000000..8cbb3cb9 --- /dev/null +++ b/src/NUnit.v3/AssemblyTester.cs @@ -0,0 +1,57 @@ +using NUnit.Framework; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public abstract class AssemblyTester : BaseAssemblyTester +{ + /// + [Test] + public override void Tester_TestClassCoverage() + { + TestClassCoverageImplementation(); + } + + /// + [Test] + public override Task Tester_ValidateAutoTesterInstances() + { + return ValidateAutoTesterInstancesImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_ValidateRandomDataParameters() + { + return ValidateRandomDataParametersImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override void Tester_ValidateTestMethodNaming() + { + ValidateTestMethodNamingImplementation([typeof(TestAttribute)]); + } + + /// + [Test] + public override void Tester_VerifyAllToStrings() + { + VerifyAllToStringsImplementation(); + } + + /// + [Test] + public override Task Tester_VerifyTestSettingsConfig_Default() + { + return VerifyTestSettingsConfigImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_VerifyToolSetIntegrity() + { + return VerifyToolSetIntegrityImplementation(CancellationTokenProvider.Get()); + } +} diff --git a/src/NUnit.v3/AutoTester.cs b/src/NUnit.v3/AutoTester.cs new file mode 100644 index 00000000..9f10705f --- /dev/null +++ b/src/NUnit.v3/AutoTester.cs @@ -0,0 +1,43 @@ +using NUnit.Framework; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public abstract class AutoTester(Type testType) : BaseAutoTester(testType) +{ + /// + [Test] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/NUnit.v3/AutoTester{T}.cs b/src/NUnit.v3/AutoTester{T}.cs new file mode 100644 index 00000000..5e496f92 --- /dev/null +++ b/src/NUnit.v3/AutoTester{T}.cs @@ -0,0 +1,43 @@ +using NUnit.Framework; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public abstract class AutoTester : BaseAutoTester +{ + /// + [Test] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(CancellationTokenProvider.Get()); + } + + /// + [Test] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/NUnit.v3/CancellationTokenProvider.cs b/src/NUnit.v3/CancellationTokenProvider.cs new file mode 100644 index 00000000..955d330b --- /dev/null +++ b/src/NUnit.v3/CancellationTokenProvider.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// Accesses the framework provides for tests. +[ExcludeFromCodeCoverage] // Missing case cannot be covered by updated test frameworks. +internal static class CancellationTokenProvider +{ + /// Property used to access the current test's . + /// NUnit v4.1.0 required. Cannot use as a dependency due to not supporting .NET Standard 2.0. + private static readonly Func? _CancellationTokenGrabber = (Func< + TestContext, + CancellationToken + >?) + typeof(TestContext) + .GetProperty("CancellationToken") + ?.GetGetMethod()! + .CreateDelegate(typeof(Func)); + + /// Retrieves the current test's . + /// Valid token if available, default token if not. + internal static CancellationToken Get() + { + return _CancellationTokenGrabber?.Invoke(TestContext.CurrentContext) + ?? CancellationToken.None; + } +} diff --git a/src/NUnit.v3/CapAttribute.cs b/src/NUnit.v3/CapAttribute.cs new file mode 100644 index 00000000..9c4df545 --- /dev/null +++ b/src/NUnit.v3/CapAttribute.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public sealed class CapAttribute : BaseCapAttribute +{ + /// + public CapAttribute(object min, object max) + : base(min, max) { } + + /// + public CapAttribute(object max) + : base(max) { } + + /// + public override object Clone() + { + return IsMinSet ? new CapAttribute(Min, Max) : new CapAttribute(Max); + } +} diff --git a/src/NUnit.v3/CopyAttribute.cs b/src/NUnit.v3/CopyAttribute.cs new file mode 100644 index 00000000..ec5a9d5a --- /dev/null +++ b/src/NUnit.v3/CopyAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public sealed class CopyAttribute : BaseCopyAttribute; diff --git a/src/NUnit.v3/CreateAndFake.NUnit.v3.csproj b/src/NUnit.v3/CreateAndFake.NUnit.v3.csproj new file mode 100644 index 00000000..6a9b34b7 --- /dev/null +++ b/src/NUnit.v3/CreateAndFake.NUnit.v3.csproj @@ -0,0 +1,17 @@ + + + + net11.0;net10.0;netstandard2.0 + + + + A C# class library that handles mocking, test data generation, and validation. + + + + + + + + + diff --git a/src/NUnit.v3/FakeAttribute.cs b/src/NUnit.v3/FakeAttribute.cs new file mode 100644 index 00000000..56fd9713 --- /dev/null +++ b/src/NUnit.v3/FakeAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public sealed class FakeAttribute : BaseFakeAttribute; diff --git a/src/NUnit.v3/InjectAttribute.cs b/src/NUnit.v3/InjectAttribute.cs new file mode 100644 index 00000000..f0ae9c45 --- /dev/null +++ b/src/NUnit.v3/InjectAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public sealed class InjectAttribute : BaseInjectAttribute; diff --git a/src/NUnit.v3/MethodWrapperCreateHint.cs b/src/NUnit.v3/MethodWrapperCreateHint.cs new file mode 100644 index 00000000..26ce0fca --- /dev/null +++ b/src/NUnit.v3/MethodWrapperCreateHint.cs @@ -0,0 +1,25 @@ +using System.Reflection; +using NUnit.Framework.Internal; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public sealed class MethodWrapperCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.ObjectHint + 1; + + /// + public override IEnumerable SupportedTypes => []; + + /// + protected override MethodWrapper Create(IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + MethodInfo method = randomizer.Create(); + return new MethodWrapper(method.DeclaringType, method); + } +} diff --git a/src/NUnit.v3/Properties/AssemblyInfo.cs b/src/NUnit.v3/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..6bdd88b9 --- /dev/null +++ b/src/NUnit.v3/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("CreateAndFake.NUnit.v3.Tests")] diff --git a/src/NUnit.v3/RandomDataAttribute.cs b/src/NUnit.v3/RandomDataAttribute.cs new file mode 100644 index 00000000..194c3158 --- /dev/null +++ b/src/NUnit.v3/RandomDataAttribute.cs @@ -0,0 +1,76 @@ +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Builders; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// Flags test methods to be populated with random values for testing. +/// +/// Earlier Parameters will be used to construct later Parameters if possible.
+/// Use with Parameter attributes to control randomization behavior: +/// +/// , +/// & +/// +/// +/// +/// Example test: +/// [RandomData] +/// public static void Test([Size(2)] string data) +/// { +/// data.Length.Assert().Is(2); +/// } +/// +///
+[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class RandomDataAttribute : NUnitAttribute, ITestBuilder, IRandomDataMarker +{ + /// + public int Trials { get; set; } = 1; + + /// + public IEnumerable BuildFrom(IMethodInfo method, Test suite) + { + if (method == null) + { + return []; + } + + List results = []; + for (int i = 0; i < Trials; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i, Tools.Runner.Options.Design.IterationLimit); + + MethodCallWrapper data; + try + { + data = Tools.Runner.CreateFor(method.MethodInfo, default); + } + catch (Exception e) + { + Console.Error.WriteLine($"Test generation failure on {method}= {e.Message}"); + break; + } + + string args = string.Join(",", method.GetParameters().Select(p => p.ParameterType)); + + results.Add( + new NUnitTestCaseBuilder().BuildTestMethod( + method, + suite, + new TestCaseParameters( + new TestCaseAttribute([.. data.Args]) + { + TestName = $"{method.Name}({args})", + } + ) + ) + ); + } + return results; + } +} diff --git a/src/NUnit.v3/SizeAttribute.cs b/src/NUnit.v3/SizeAttribute.cs new file mode 100644 index 00000000..11ff3e57 --- /dev/null +++ b/src/NUnit.v3/SizeAttribute.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public sealed class SizeAttribute : BaseSizeAttribute +{ + /// + public SizeAttribute(int min, int max) + : base(min, max) { } + + /// + public SizeAttribute(int count) + : base(count) { } +} diff --git a/src/NUnit.v3/StubAttribute.cs b/src/NUnit.v3/StubAttribute.cs new file mode 100644 index 00000000..9400bbec --- /dev/null +++ b/src/NUnit.v3/StubAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public sealed class StubAttribute : BaseStubAttribute; diff --git a/src/NUnit.v3/UniqueAttribute.cs b/src/NUnit.v3/UniqueAttribute.cs new file mode 100644 index 00000000..4b08c0ec --- /dev/null +++ b/src/NUnit.v3/UniqueAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.NUnit.v3; + +/// +public sealed class UniqueAttribute : BaseUniqueAttribute; diff --git a/src/Samples/.editorconfig b/src/Samples/.editorconfig new file mode 100644 index 00000000..39343662 --- /dev/null +++ b/src/Samples/.editorconfig @@ -0,0 +1,23 @@ +[*.cs] + +# For testing designs regardless of best practices. +dotnet_diagnostic.IDE0005.severity = None +dotnet_diagnostic.IDE0058.severity = None +dotnet_diagnostic.IDE0250.severity = None +dotnet_diagnostic.IDE0251.severity = None +dotnet_diagnostic.CA1024.severity = None +dotnet_diagnostic.CA1044.severity = None +dotnet_diagnostic.CA1051.severity = None +dotnet_diagnostic.CA1819.severity = None +dotnet_diagnostic.CA2227.severity = None +dotnet_diagnostic.CS1591.severity = None +dotnet_diagnostic.S1104.severity = None +dotnet_diagnostic.S1144.severity = None +dotnet_diagnostic.S2094.severity = None +dotnet_diagnostic.S2376.severity = None +dotnet_diagnostic.MA0025.severity = None +dotnet_diagnostic.MA0036.severity = None +dotnet_diagnostic.MA0075.severity = None +dotnet_diagnostic.MA0102.severity = None +dotnet_diagnostic.MA0182.severity = None +dotnet_diagnostic.RCS1170.severity = None diff --git a/src/Samples/BasicData/CollectionDto.cs b/src/Samples/BasicData/CollectionDto.cs new file mode 100644 index 00000000..ce6eb9f1 --- /dev/null +++ b/src/Samples/BasicData/CollectionDto.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.BasicData; + +/// Contains many concrete collections to test. +[ValidSample] +public class CollectionDto +{ + public CollectionDto? IntCollectionValue { get; set; } + + public CollectionDto? DoubleCollectionValue { get; set; } + + public CollectionDto? StringCollectionValue { get; set; } + + public CollectionDto? ObjectCollectionValue { get; set; } + + public CollectionDto? DateTimeCollectionValue { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/BasicData/CollectionDto{T}.cs b/src/Samples/BasicData/CollectionDto{T}.cs new file mode 100644 index 00000000..94164c16 --- /dev/null +++ b/src/Samples/BasicData/CollectionDto{T}.cs @@ -0,0 +1,28 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.BasicData; + +/// Assorted collection types to test. +/// Item type for the collections. +[ValidSample] +public class CollectionDto +{ + public T[]? ArrayValues { get; set; } + + public IEnumerable? EnumerableValues { get; set; } + + public ICollection? CollectionValues { get; set; } + + public IList? ListValues { get; set; } + + public ISet? SetValues { get; set; } + + public IDictionary? DictValues { get; set; } + + public IDictionary? IntDictValues { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/BasicData/CompleteDto.cs b/src/Samples/BasicData/CompleteDto.cs new file mode 100644 index 00000000..952d4afd --- /dev/null +++ b/src/Samples/BasicData/CompleteDto.cs @@ -0,0 +1,10 @@ +namespace Werecodent.CreateAndFake.Samples.BasicData; + +/// Combination of all basic data sample designs. +[ValidSample] +public class CompleteDto : SimpleDto +{ + public SimpleDto? SimpleValue { get; set; } + + public CollectionDto? CollectionsValue { get; set; } +} diff --git a/src/Samples/BasicData/NestedDto.cs b/src/Samples/BasicData/NestedDto.cs new file mode 100644 index 00000000..84b3e65f --- /dev/null +++ b/src/Samples/BasicData/NestedDto.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.BasicData; + +/// Holds a reference to another basic data class. +[ValidSample] +public class NestedDto +{ + public SimpleDto? SimpleValue { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/BasicData/RecursiveDto.cs b/src/Samples/BasicData/RecursiveDto.cs new file mode 100644 index 00000000..5616154c --- /dev/null +++ b/src/Samples/BasicData/RecursiveDto.cs @@ -0,0 +1,8 @@ +namespace Werecodent.CreateAndFake.Samples.BasicData; + +/// Inherits and references a child class. +[ValidSample] +public class RecursiveDto : SimpleDto +{ + public SimpleDto? SimpleValue { get; set; } +} diff --git a/src/Samples/BasicData/SimpleDto.cs b/src/Samples/BasicData/SimpleDto.cs new file mode 100644 index 00000000..9ce79d57 --- /dev/null +++ b/src/Samples/BasicData/SimpleDto.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.BasicData; + +/// Assorted basic values. +[ValidSample] +public class SimpleDto +{ + public int IntValue { get; set; } + + public double DoubleValue { get; set; } + + public string? StringValue { get; set; } + + public object? ObjectValue { get; set; } + + public DateTime DateValue { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/CreateAndFake.Samples.csproj b/src/Samples/CreateAndFake.Samples.csproj new file mode 100644 index 00000000..c8c225f7 --- /dev/null +++ b/src/Samples/CreateAndFake.Samples.csproj @@ -0,0 +1,18 @@ + + + + net11.0;net10.0;netstandard2.0 + + + + false + + + + + + + + + + diff --git a/src/Samples/DoubleValue/BaseHolder.cs b/src/Samples/DoubleValue/BaseHolder.cs new file mode 100644 index 00000000..47d1deed --- /dev/null +++ b/src/Samples/DoubleValue/BaseHolder.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public abstract class BaseHolder(T value, TOther otherValue) + : Holder(value), + IHolder +{ + public virtual TOther OtherValue { get; set; } = otherValue; + + public abstract TOther ReadOtherValue(); + + public abstract void WriteOtherValue(TOther otherValue); + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/DoubleValue/BaseReadableHolder.cs b/src/Samples/DoubleValue/BaseReadableHolder.cs new file mode 100644 index 00000000..f7f6db97 --- /dev/null +++ b/src/Samples/DoubleValue/BaseReadableHolder.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public abstract class BaseReadableHolder(T value, TOther otherValue) + : BaseReadableHolder(value), + IReadableHolder +{ + public virtual TOther OtherValue { get; } = otherValue; + + public abstract TOther ReadOtherValue(); + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/DoubleValue/BaseWriteableHolder.cs b/src/Samples/DoubleValue/BaseWriteableHolder.cs new file mode 100644 index 00000000..fd04cc06 --- /dev/null +++ b/src/Samples/DoubleValue/BaseWriteableHolder.cs @@ -0,0 +1,24 @@ +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public abstract class BaseWriteableHolder + : BaseWriteableHolder, + IWriteableHolder +{ + internal TOther? _otherValue = default; + + public virtual TOther OtherValue + { + set => _otherValue = value; + } + + public abstract void WriteOtherValue(TOther otherValue); + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/DoubleValue/Holder.cs b/src/Samples/DoubleValue/Holder.cs new file mode 100644 index 00000000..8809a4de --- /dev/null +++ b/src/Samples/DoubleValue/Holder.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public class Holder(T value, TOther otherValue) + : BaseHolder(value, otherValue) +{ + public override TOther ReadOtherValue() + { + return OtherValue; + } + + public override void WriteOtherValue(TOther otherValue) + { + OtherValue = otherValue; + } +} diff --git a/src/Samples/DoubleValue/IHolder.cs b/src/Samples/DoubleValue/IHolder.cs new file mode 100644 index 00000000..d093974b --- /dev/null +++ b/src/Samples/DoubleValue/IHolder.cs @@ -0,0 +1,4 @@ +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public interface IHolder : IReadableHolder, IWriteableHolder; diff --git a/src/Samples/DoubleValue/IReadableHolder.cs b/src/Samples/DoubleValue/IReadableHolder.cs new file mode 100644 index 00000000..3bd25482 --- /dev/null +++ b/src/Samples/DoubleValue/IReadableHolder.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public interface IReadableHolder : IReadableHolder +{ + TOther OtherValue { get; } + + TOther ReadOtherValue(); +} diff --git a/src/Samples/DoubleValue/IWriteableHolder.cs b/src/Samples/DoubleValue/IWriteableHolder.cs new file mode 100644 index 00000000..0031bcca --- /dev/null +++ b/src/Samples/DoubleValue/IWriteableHolder.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public interface IWriteableHolder : IWriteableHolder +{ + TOther OtherValue { set; } + + void WriteOtherValue(TOther otherValue); +} diff --git a/src/Samples/DoubleValue/ReadableHolder.cs b/src/Samples/DoubleValue/ReadableHolder.cs new file mode 100644 index 00000000..e9dc28a2 --- /dev/null +++ b/src/Samples/DoubleValue/ReadableHolder.cs @@ -0,0 +1,16 @@ +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public class ReadableHolder(T value, TOther otherValue) + : BaseReadableHolder(value, otherValue) +{ + public override T ReadValue() + { + return Value; + } + + public override TOther ReadOtherValue() + { + return OtherValue; + } +} diff --git a/src/Samples/DoubleValue/WriteableHolder.cs b/src/Samples/DoubleValue/WriteableHolder.cs new file mode 100644 index 00000000..802a66b2 --- /dev/null +++ b/src/Samples/DoubleValue/WriteableHolder.cs @@ -0,0 +1,15 @@ +namespace Werecodent.CreateAndFake.Samples.DoubleValue; + +[ValidSample] +public class WriteableHolder : BaseWriteableHolder +{ + public override void WriteValue(T value) + { + Value = value; + } + + public override void WriteOtherValue(TOther otherValue) + { + OtherValue = otherValue; + } +} diff --git a/src/Samples/ErrorCases/FactoryAlterSample.cs b/src/Samples/ErrorCases/FactoryAlterSample.cs new file mode 100644 index 00000000..61cc755e --- /dev/null +++ b/src/Samples/ErrorCases/FactoryAlterSample.cs @@ -0,0 +1,26 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public sealed class FactoryAlterSample +{ + public string Data { get; } + + private FactoryAlterSample(string data) + { + Data = data; + } + + public static FactoryAlterSample Create(int data) + { + return new FactoryAlterSample("Value:" + data); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/ErrorCases/IOnlyMockSample.cs b/src/Samples/ErrorCases/IOnlyMockSample.cs new file mode 100644 index 00000000..5e5de033 --- /dev/null +++ b/src/Samples/ErrorCases/IOnlyMockSample.cs @@ -0,0 +1,9 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public interface IOnlyMockSample +{ + bool FailIfNotMocked(); +} diff --git a/src/Samples/ErrorCases/IUnimplementedSample.cs b/src/Samples/ErrorCases/IUnimplementedSample.cs new file mode 100644 index 00000000..818ee86e --- /dev/null +++ b/src/Samples/ErrorCases/IUnimplementedSample.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public interface IUnimplementedSample +{ + int Flag { get; } + + bool Funny { set; } + + string GetData(); +} diff --git a/src/Samples/ErrorCases/InfiniteSample.cs b/src/Samples/ErrorCases/InfiniteSample.cs new file mode 100644 index 00000000..c37bc481 --- /dev/null +++ b/src/Samples/ErrorCases/InfiniteSample.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public sealed class InfiniteSample +{ + public InfiniteSample? Hole { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/ErrorCases/InjectMockSample.cs b/src/Samples/ErrorCases/InjectMockSample.cs new file mode 100644 index 00000000..60d60917 --- /dev/null +++ b/src/Samples/ErrorCases/InjectMockSample.cs @@ -0,0 +1,26 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public sealed class InjectMockSample(IOnlyMockSample sample1, IOnlyMockSample sample2) +{ + private readonly IOnlyMockSample _sample1 = sample1 + ?? throw new ArgumentNullException(nameof(sample1)); + + private readonly IOnlyMockSample _sample2 = sample2 + ?? throw new ArgumentNullException(nameof(sample2)); + + public void TestIfMockedSeparately() + { + _sample1.FailIfNotMocked(); + _sample2.FailIfNotMocked(); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/ErrorCases/InvalidCreateSample.cs b/src/Samples/ErrorCases/InvalidCreateSample.cs new file mode 100644 index 00000000..0d80c2e9 --- /dev/null +++ b/src/Samples/ErrorCases/InvalidCreateSample.cs @@ -0,0 +1,19 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public sealed class InvalidCreateSample : IOnlyMockSample +{ + public InvalidCreateSample() + { + throw new InvalidOperationException("Tried to create invalid sample."); + } + + [ExcludeFromCodeCoverage] // Designed to never be reached. + public bool FailIfNotMocked() + { + throw new InvalidOperationException("Mock was not created."); + } +} diff --git a/src/Samples/ErrorCases/IsBadSample.cs b/src/Samples/ErrorCases/IsBadSample.cs new file mode 100644 index 00000000..a89455b7 --- /dev/null +++ b/src/Samples/ErrorCases/IsBadSample.cs @@ -0,0 +1,21 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample] +public class IsBadSample : IIsGoodOrBadSample +{ + public int GoodOrBadProp + { + get => 0; + set => throw new NotImplementedException(); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/ErrorCases/MismatchDataSample.cs b/src/Samples/ErrorCases/MismatchDataSample.cs new file mode 100644 index 00000000..391df50a --- /dev/null +++ b/src/Samples/ErrorCases/MismatchDataSample.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public class MismatchDataSample(int value) +{ + public string Data { get; set; } = "Value:" + value; + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/ErrorCases/ObsoleteSample.cs b/src/Samples/ErrorCases/ObsoleteSample.cs new file mode 100644 index 00000000..c61f5099 --- /dev/null +++ b/src/Samples/ErrorCases/ObsoleteSample.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public sealed class ObsoleteSample(string data) +{ + public string GrabData() + { + return data; + } + + [Obsolete("For testing.")] + public string IsObsolete() + { + throw new InvalidOperationException("Obsolete method called."); + } +} diff --git a/src/Samples/ErrorCases/PrivateCreateSample.cs b/src/Samples/ErrorCases/PrivateCreateSample.cs new file mode 100644 index 00000000..ec93ccce --- /dev/null +++ b/src/Samples/ErrorCases/PrivateCreateSample.cs @@ -0,0 +1,9 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Samples.ErrorCases; + +[InvalidSample, ExcludeFromCreateAndFake] +public sealed class PrivateCreateSample +{ + private PrivateCreateSample() { } +} diff --git a/src/Samples/InvalidSampleAttribute.cs b/src/Samples/InvalidSampleAttribute.cs new file mode 100644 index 00000000..5d1216de --- /dev/null +++ b/src/Samples/InvalidSampleAttribute.cs @@ -0,0 +1,7 @@ +namespace Werecodent.CreateAndFake.Samples; + +[AttributeUsage( + AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, + Inherited = false +)] +public sealed class InvalidSampleAttribute : Attribute; diff --git a/src/Samples/Properties/AssemblyInfo.cs b/src/Samples/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..4dc08fe2 --- /dev/null +++ b/src/Samples/Properties/AssemblyInfo.cs @@ -0,0 +1,7 @@ +using System.Runtime.CompilerServices; + +[assembly: CLSCompliant(true)] +[assembly: InternalsVisibleTo("Werecodent.CreateAndFake.FakerTypes")] +[assembly: InternalsVisibleTo("CreateAndFake.Design.Tests")] +[assembly: InternalsVisibleTo("CreateAndFake")] +[assembly: InternalsVisibleTo("CreateAndFake.Tests")] diff --git a/src/Samples/SampleGenerator.cs b/src/Samples/SampleGenerator.cs new file mode 100644 index 00000000..bd3ac480 --- /dev/null +++ b/src/Samples/SampleGenerator.cs @@ -0,0 +1,84 @@ +using System.Collections.Immutable; +using System.Dynamic; +using System.Reflection; +using Werecodent.CreateAndFake.Samples.DoubleValue; +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples; + +public static class SampleGenerator +{ + private static readonly Type[] _BaseTypes = + [ + typeof(int), + typeof(double), + typeof(string), + typeof(object), + typeof(DateTime), + ]; + + private static readonly Type[] _SingleCollections = + [ + typeof(IList<>), + typeof(List<>), + typeof(ISet<>), + typeof(HashSet<>), + typeof(ICollection<>), + typeof(IEnumerable<>), + ]; + + private static readonly Type[] _DoubleCollections = + [ + typeof(IDictionary<,>), + typeof(Dictionary<,>), + typeof(KeyValuePair<,>), + ]; + + private static readonly Type[] _SingleHolders = + [ + typeof(BaseHolder<>), + typeof(BaseReadableHolder<>), + typeof(BaseWriteableHolder<>), + typeof(Holder<>), + typeof(IHolder<>), + typeof(IReadableHolder<>), + typeof(IWriteableHolder<>), + typeof(ReadableHolder<>), + typeof(WriteableHolder<>), + ]; + + private static ImmutableArray MakeMasterList() + { + return + [ + .. Assembly + .GetExecutingAssembly() + .GetTypes() + .Where(t => Attribute.IsDefined(t, typeof(ValidSampleAttribute))), + .. _BaseTypes, + .. InsertIntoSingleGenerics(_BaseTypes, _SingleCollections), + .. InsertIntoSingleGenerics(_BaseTypes, _SingleHolders), + .. InsertIntoDoubleGenerics(_BaseTypes, _DoubleCollections), + ]; + } + + private static IEnumerable InsertIntoSingleGenerics( + ICollection types, + IEnumerable generics + ) + { + return generics.SelectMany(generic => types.Select(type => generic.MakeGenericType(type))); + } + + private static IEnumerable InsertIntoDoubleGenerics( + ICollection types, + IEnumerable generics + ) + { + return generics.SelectMany(generic => + types.SelectMany(typeA => types.Select(typeB => generic.MakeGenericType(typeA, typeB))) + ); + } + + public static ImmutableArray AllValidDataSamples { get; } = MakeMasterList(); +} diff --git a/src/Samples/Scenarios/AsyncDataSample.cs b/src/Samples/Scenarios/AsyncDataSample.cs new file mode 100644 index 00000000..0aa4e670 --- /dev/null +++ b/src/Samples/Scenarios/AsyncDataSample.cs @@ -0,0 +1,31 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class AsyncDataSample +{ + public string? StringValue { get; set; } + + public Task? NumberValue { get; set; } + + public IAsyncEnumerable? CollectionValue { get; set; } + + public async Task WriteToStringValueAsync(Task newString) + { + ArgumentGuard.ThrowIfNull(newString); + + StringValue = await newString.ConfigureAwait(false); + } + + public async Task ReadFromNumberValueAsync() + { + return NumberValue == null ? default : await NumberValue.ConfigureAwait(false); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/ChildWithParentSample.cs b/src/Samples/Scenarios/ChildWithParentSample.cs new file mode 100644 index 00000000..dd49844d --- /dev/null +++ b/src/Samples/Scenarios/ChildWithParentSample.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public sealed class ChildWithParentSample +{ + public ParentLoopSample? Parent { get; set; } + + public int Id { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/ConstraintSample.cs b/src/Samples/Scenarios/ConstraintSample.cs new file mode 100644 index 00000000..c814bba4 --- /dev/null +++ b/src/Samples/Scenarios/ConstraintSample.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public abstract class ConstraintSample + where TStruct : struct + where TClass : DataSample, new() +{ + public TStruct StructValue { get; set; } + + public TClass? ClassValue { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/ContentEnumerableSample.cs b/src/Samples/Scenarios/ContentEnumerableSample.cs new file mode 100644 index 00000000..37163592 --- /dev/null +++ b/src/Samples/Scenarios/ContentEnumerableSample.cs @@ -0,0 +1,29 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public sealed class ContentEnumerableSample(string? data) : IEnumerable +{ + public string Data { get; } = data ?? ""; + + public ContentEnumerableSample(ContentEnumerableSample original) + : this(original?.Data) { } + + public IEnumerator GetEnumerator() + { + return Data.Select(x => (int)x).GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/DataHolderSample.cs b/src/Samples/Scenarios/DataHolderSample.cs new file mode 100644 index 00000000..f30df12f --- /dev/null +++ b/src/Samples/Scenarios/DataHolderSample.cs @@ -0,0 +1,14 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class DataHolderSample : DataSample +{ + public DataSample? NestedValue { get; set; } + + public virtual bool HasNested(DataSample value) + { + return false; + } +} diff --git a/src/Samples/Scenarios/DataSample.cs b/src/Samples/Scenarios/DataSample.cs new file mode 100644 index 00000000..37bcc0dc --- /dev/null +++ b/src/Samples/Scenarios/DataSample.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class DataSample +{ + public string? StringValue { get; set; } + + public int NumberValue { get; set; } + + public IEnumerable? CollectionValue { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/DoubleEnumerableSample.cs b/src/Samples/Scenarios/DoubleEnumerableSample.cs new file mode 100644 index 00000000..d7163068 --- /dev/null +++ b/src/Samples/Scenarios/DoubleEnumerableSample.cs @@ -0,0 +1,31 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public sealed class DoubleEnumerableSample(IEnumerable intData, IEnumerable stringData) + : IEnumerable, + IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public IEnumerator GetEnumerator() + { + return (stringData ?? []).GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return (intData ?? []).GetEnumerator(); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/ExtractableSample.cs b/src/Samples/Scenarios/ExtractableSample.cs new file mode 100644 index 00000000..c80beb78 --- /dev/null +++ b/src/Samples/Scenarios/ExtractableSample.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class ExtractableSample : IExtractable +{ + public int NumberValue { get; set; } + + public IEnumerable ExtractContents() + { + yield return $"{NumberValue}"; + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/FieldSample.cs b/src/Samples/Scenarios/FieldSample.cs new file mode 100644 index 00000000..edd738eb --- /dev/null +++ b/src/Samples/Scenarios/FieldSample.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class FieldSample(string stringValue, string stringValue2) +{ + public const int Perm = 1; + + public readonly string PermText = stringValue2; + + public string StringValue = stringValue; + + public int NumberValue; + + public IEnumerable? CollectionValue; + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/GenericSample.cs b/src/Samples/Scenarios/GenericSample.cs new file mode 100644 index 00000000..18f3fdce --- /dev/null +++ b/src/Samples/Scenarios/GenericSample.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public abstract class GenericSample +{ + public abstract string Run(TMethod input); + + public abstract TReturn Run(TClass in1, TMethod in2) + where TMethod : DataSample + where TReturn : new(); + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/GoodOrBadSampleHolder.cs b/src/Samples/Scenarios/GoodOrBadSampleHolder.cs new file mode 100644 index 00000000..5814d553 --- /dev/null +++ b/src/Samples/Scenarios/GoodOrBadSampleHolder.cs @@ -0,0 +1,10 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public sealed class GoodOrBadSampleHolder(T instance) : Holder(instance) + where T : IIsGoodOrBadSample; diff --git a/src/Samples/Scenarios/IChildType.cs b/src/Samples/Scenarios/IChildType.cs new file mode 100644 index 00000000..5e700487 --- /dev/null +++ b/src/Samples/Scenarios/IChildType.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public interface IChildType : IParentType; diff --git a/src/Samples/Scenarios/IIsGoodOrBadSample.cs b/src/Samples/Scenarios/IIsGoodOrBadSample.cs new file mode 100644 index 00000000..e89b3805 --- /dev/null +++ b/src/Samples/Scenarios/IIsGoodOrBadSample.cs @@ -0,0 +1,7 @@ +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public interface IIsGoodOrBadSample +{ + int GoodOrBadProp { get; set; } +} diff --git a/src/Samples/Scenarios/IParentType.cs b/src/Samples/Scenarios/IParentType.cs new file mode 100644 index 00000000..1b823608 --- /dev/null +++ b/src/Samples/Scenarios/IParentType.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public interface IParentType; diff --git a/src/Samples/Scenarios/InheritedPrivatesSample.cs b/src/Samples/Scenarios/InheritedPrivatesSample.cs new file mode 100644 index 00000000..848a6c2b --- /dev/null +++ b/src/Samples/Scenarios/InheritedPrivatesSample.cs @@ -0,0 +1,7 @@ +using System; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public sealed class InheritedPrivatesSample(string stringValue) + : PrivateValuerEquatableSample(stringValue); diff --git a/src/Samples/Scenarios/InjectSample.cs b/src/Samples/Scenarios/InjectSample.cs new file mode 100644 index 00000000..e4e101b4 --- /dev/null +++ b/src/Samples/Scenarios/InjectSample.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class InjectSample(DataSample data, DataSample data2) +{ + public DataSample Data { get; } = data; + + public DataSample Data2 { get; } = data2; + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/InternalSample.cs b/src/Samples/Scenarios/InternalSample.cs new file mode 100644 index 00000000..218d8d1c --- /dev/null +++ b/src/Samples/Scenarios/InternalSample.cs @@ -0,0 +1,9 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +internal sealed class InternalSample +{ + public string? Data { get; set; } +} diff --git a/src/Samples/Scenarios/IsGoodSample.cs b/src/Samples/Scenarios/IsGoodSample.cs new file mode 100644 index 00000000..d1aff06f --- /dev/null +++ b/src/Samples/Scenarios/IsGoodSample.cs @@ -0,0 +1,14 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class IsGoodSample : IIsGoodOrBadSample +{ + public int GoodOrBadProp { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/OutSample.cs b/src/Samples/Scenarios/OutSample.cs new file mode 100644 index 00000000..ec136a83 --- /dev/null +++ b/src/Samples/Scenarios/OutSample.cs @@ -0,0 +1,9 @@ +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public abstract class OutSample +{ + public abstract void ReturnVoid(out string input); + + public abstract int ReturnValue(out int input); +} diff --git a/src/Samples/Scenarios/ParentLoopSample.cs b/src/Samples/Scenarios/ParentLoopSample.cs new file mode 100644 index 00000000..b30a7a71 --- /dev/null +++ b/src/Samples/Scenarios/ParentLoopSample.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public sealed class ParentLoopSample +{ + public ChildWithParentSample? Child { get; set; } + + public int Id { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/PrivateValuerEquatableSample.cs b/src/Samples/Scenarios/PrivateValuerEquatableSample.cs new file mode 100644 index 00000000..f449b80e --- /dev/null +++ b/src/Samples/Scenarios/PrivateValuerEquatableSample.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class PrivateValuerEquatableSample(string stringValue) : IValuerEquatable +{ + private string StringValue { get; } = stringValue; + + public virtual bool ValuesEqual(object? other, IValuer valuer) + { + ArgumentGuard.ThrowIfNull(valuer); + + return (other is PrivateValuerEquatableSample sample) + && valuer.Equals(StringValue, sample.StringValue); + } + + public virtual int GetValueHash(IValuer valuer) + { + return valuer?.GetHashCode(StringValue) ?? throw new ArgumentNullException(nameof(valuer)); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/ProtectedSample.cs b/src/Samples/Scenarios/ProtectedSample.cs new file mode 100644 index 00000000..85ad8591 --- /dev/null +++ b/src/Samples/Scenarios/ProtectedSample.cs @@ -0,0 +1,7 @@ +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public abstract class ProtectedSample +{ + protected abstract void ChildMethod(); +} diff --git a/src/Samples/Scenarios/RefSample.cs b/src/Samples/Scenarios/RefSample.cs new file mode 100644 index 00000000..68d036a0 --- /dev/null +++ b/src/Samples/Scenarios/RefSample.cs @@ -0,0 +1,9 @@ +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public abstract class RefSample +{ + public abstract void ReturnVoid(ref string input); + + public abstract int ReturnValue(ref int input); +} diff --git a/src/Samples/Scenarios/ScopeSample.cs b/src/Samples/Scenarios/ScopeSample.cs new file mode 100644 index 00000000..0100d0d1 --- /dev/null +++ b/src/Samples/Scenarios/ScopeSample.cs @@ -0,0 +1,82 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class ScopeSample +{ + public virtual string? PublicProp { get; set; } + + internal virtual string? InternalProp { get; set; } + + protected internal virtual string? ProIntProp { get; set; } + + protected virtual string? ProtectProp { get; set; } + + public virtual string? InternalGet { internal get; set; } + + public virtual string? ProIntGet { protected internal get; set; } + + public virtual string? ProtectGet { protected get; set; } + + public virtual string? PrivateGet { private get; set; } + + public virtual string? InternalSet { get; internal set; } + + public virtual string? ProIntSet { get; protected internal set; } + + public virtual string? ProtectSet { get; protected set; } + + public virtual string? PrivateSet { get; private set; } + + public virtual string PublicMethod() + { + return "Value"; + } + + internal virtual string InternalMethod() + { + return "Value"; + } + + protected internal virtual string ProIntMethod() + { + return "Value"; + } + + protected virtual string ProtectMethod() + { + return "Value"; + } + + public string? CallProtectProp() + { + return ProtectProp; + } + + public void SetProtectProp(string data) + { + ProtectProp = data; + } + + public string? CallProtectGet() + { + return ProtectGet; + } + + public void SetProtectSet(string data) + { + ProtectSet = data; + } + + public string CallProtectMethod() + { + return ProtectMethod(); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/SelfReferencingDisposable.cs b/src/Samples/Scenarios/SelfReferencingDisposable.cs new file mode 100644 index 00000000..be573a08 --- /dev/null +++ b/src/Samples/Scenarios/SelfReferencingDisposable.cs @@ -0,0 +1,32 @@ +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public sealed class SelfReferencingDisposable(string data) : IDisposable, IAsyncDisposable +{ + private bool _isDisposed = false; + + public string GrabData() + { + return !_isDisposed + ? data + : throw new ObjectDisposedException("Instance was disposed before accessing its data."); + } + + public SelfReferencingDisposable GetSelf() + { + return !_isDisposed + ? this + : throw new ObjectDisposedException("Instance was disposed before accessing itself."); + } + + public void Dispose() + { + _isDisposed = true; + } + + public ValueTask DisposeAsync() + { + _isDisposed = true; + return new ValueTask(Task.CompletedTask); + } +} diff --git a/src/Samples/Scenarios/StatelessSample.cs b/src/Samples/Scenarios/StatelessSample.cs new file mode 100644 index 00000000..52aa3492 --- /dev/null +++ b/src/Samples/Scenarios/StatelessSample.cs @@ -0,0 +1,4 @@ +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public sealed class StatelessSample; diff --git a/src/Samples/Scenarios/StructSample.cs b/src/Samples/Scenarios/StructSample.cs new file mode 100644 index 00000000..7bf7f9fe --- /dev/null +++ b/src/Samples/Scenarios/StructSample.cs @@ -0,0 +1,69 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public struct StructSample(string stringValue) + : IEquatable, + IComparable, + IComparable +{ + public string StringValue { get; set; } = stringValue; + + public int CompareTo(StructSample other) + { + return ValueComparer.Use.Compare(this, other); + } + + public int CompareTo(object? obj) + { + return ValueComparer.Use.Compare(this, obj); + } + + public override bool Equals(object? obj) + { + return (obj is StructSample sample) && Equals(sample); + } + + public bool Equals(StructSample other) + { + return ValueComparer.Use.Equals(StringValue, other.StringValue); + } + + public override int GetHashCode() + { + return ValueComparer.Use.GetHashCode(StringValue); + } + + public static bool operator ==(StructSample left, StructSample right) + { + return left.Equals(right); + } + + public static bool operator !=(StructSample left, StructSample right) + { + return !(left == right); + } + + public static bool operator <(StructSample left, StructSample right) + { + return left.CompareTo(right) < 0; + } + + public static bool operator <=(StructSample left, StructSample right) + { + return left.CompareTo(right) <= 0; + } + + public static bool operator >(StructSample left, StructSample right) + { + return left.CompareTo(right) > 0; + } + + public static bool operator >=(StructSample left, StructSample right) + { + return left.CompareTo(right) >= 0; + } +} diff --git a/src/Samples/Scenarios/ValueEquatableSample.cs b/src/Samples/Scenarios/ValueEquatableSample.cs new file mode 100644 index 00000000..745bcad4 --- /dev/null +++ b/src/Samples/Scenarios/ValueEquatableSample.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class ValueEquatableSample : IValueEquatable +{ + public string? StringValue { get; set; } + + public int NumberValue; + + public virtual bool ValuesEqual(object? other) + { + return (other is ValueEquatableSample sample) + && StringValue == sample.StringValue + && NumberValue == sample.NumberValue; + } + + public virtual int GetValueHash() + { + return ValueComparer.Use.GetHashCode(StringValue, NumberValue); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/ValuerAsyncComparableSample.cs b/src/Samples/Scenarios/ValuerAsyncComparableSample.cs new file mode 100644 index 00000000..cd4d4fd9 --- /dev/null +++ b/src/Samples/Scenarios/ValuerAsyncComparableSample.cs @@ -0,0 +1,59 @@ +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class ValuerAsyncComparableSample : IValuerAsyncComparable +{ + public string? StringValue { get; set; } + + public int NumberValue; + + public virtual async IAsyncEnumerable CompareAsync( + object? other, + IValuer valuer, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + ArgumentGuard.ThrowIfNull(valuer); + + if (other is ValuerAsyncComparableSample sample) + { + await foreach ( + Difference diff in valuer + .CompareAsync(StringValue, sample.StringValue, canceler) + .ConfigureAwait(false) + ) + { + yield return new Difference($".{nameof(StringValue)}", diff); + } + await foreach ( + Difference diff in valuer + .CompareAsync(NumberValue, sample.NumberValue, canceler) + .ConfigureAwait(false) + ) + { + yield return new Difference($".{nameof(NumberValue)}", diff); + } + } + else + { + yield return new Difference(GetType(), other?.GetType()); + } + } + + public virtual Task GetValueHashAsync(IValuer valuer, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(valuer); + + return valuer.GetHashCodeAsync(new object?[] { StringValue, NumberValue }, canceler); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/ValuerComparableSample.cs b/src/Samples/Scenarios/ValuerComparableSample.cs new file mode 100644 index 00000000..9f767ecf --- /dev/null +++ b/src/Samples/Scenarios/ValuerComparableSample.cs @@ -0,0 +1,50 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class ValuerComparableSample : IValuerComparable +{ + public string? StringValue { get; set; } + + public int NumberValue; + + public virtual IEnumerable Compare(object? other, IValuer valuer) + { + ArgumentGuard.ThrowIfNull(valuer); + + if (other is ValuerComparableSample sample) + { + foreach (Difference diff in valuer.Compare(StringValue, sample.StringValue)) + { + yield return new Difference($".{nameof(StringValue)}", diff); + } + foreach (Difference diff in valuer.Compare(NumberValue, sample.NumberValue)) + { + yield return new Difference($".{nameof(NumberValue)}", diff); + } + } + else + { + yield return new Difference(GetType(), other?.GetType()); + } + } + + public virtual bool ValuesEqual(object? other, IValuer valuer) + { + return !Compare(other, valuer).Any(); + } + + public virtual int GetValueHash(IValuer valuer) + { + return valuer?.GetHashCode(new object?[] { StringValue, NumberValue }) + ?? throw new ArgumentNullException(nameof(valuer)); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/Scenarios/ValuerEquatableSample.cs b/src/Samples/Scenarios/ValuerEquatableSample.cs new file mode 100644 index 00000000..8843ca10 --- /dev/null +++ b/src/Samples/Scenarios/ValuerEquatableSample.cs @@ -0,0 +1,33 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Samples.Scenarios; + +[ValidSample] +public class ValuerEquatableSample : IValuerEquatable +{ + public string? StringValue { get; set; } + + public int NumberValue; + + public virtual bool ValuesEqual(object? other, IValuer valuer) + { + ArgumentGuard.ThrowIfNull(valuer); + + return (other is ValuerEquatableSample sample) + && valuer.Equals(StringValue, sample.StringValue) + && valuer.Equals(NumberValue, sample.NumberValue); + } + + public virtual int GetValueHash(IValuer valuer) + { + return valuer?.GetHashCode(new object?[] { StringValue, NumberValue }) + ?? throw new ArgumentNullException(nameof(valuer)); + } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/SingleValue/BaseHolder.cs b/src/Samples/SingleValue/BaseHolder.cs new file mode 100644 index 00000000..c46d1cd3 --- /dev/null +++ b/src/Samples/SingleValue/BaseHolder.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public abstract class BaseHolder(T value) : IReadableHolder, IWriteableHolder +{ + public virtual T Value { get; set; } = value; + + public abstract T ReadValue(); + + public abstract void WriteValue(T value); + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/SingleValue/BaseReadableHolder.cs b/src/Samples/SingleValue/BaseReadableHolder.cs new file mode 100644 index 00000000..606e1d4a --- /dev/null +++ b/src/Samples/SingleValue/BaseReadableHolder.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public abstract class BaseReadableHolder(T value) : IReadableHolder +{ + public virtual T Value { get; } = value; + + public abstract T ReadValue(); + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/SingleValue/BaseWriteableHolder.cs b/src/Samples/SingleValue/BaseWriteableHolder.cs new file mode 100644 index 00000000..84ef779c --- /dev/null +++ b/src/Samples/SingleValue/BaseWriteableHolder.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public abstract class BaseWriteableHolder : IWriteableHolder +{ + internal T? _value = default; + + public virtual T Value + { + set => _value = value; + } + + public abstract void WriteValue(T value); + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Samples/SingleValue/Holder.cs b/src/Samples/SingleValue/Holder.cs new file mode 100644 index 00000000..b6d9ad43 --- /dev/null +++ b/src/Samples/SingleValue/Holder.cs @@ -0,0 +1,15 @@ +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public class Holder(T value) : BaseHolder(value) +{ + public override T ReadValue() + { + return Value; + } + + public override void WriteValue(T value) + { + Value = value; + } +} diff --git a/src/Samples/SingleValue/IHolder.cs b/src/Samples/SingleValue/IHolder.cs new file mode 100644 index 00000000..71389bdc --- /dev/null +++ b/src/Samples/SingleValue/IHolder.cs @@ -0,0 +1,4 @@ +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public interface IHolder : IReadableHolder, IWriteableHolder; diff --git a/src/Samples/SingleValue/IReadableHolder.cs b/src/Samples/SingleValue/IReadableHolder.cs new file mode 100644 index 00000000..7b14466c --- /dev/null +++ b/src/Samples/SingleValue/IReadableHolder.cs @@ -0,0 +1,9 @@ +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public interface IReadableHolder +{ + T Value { get; } + + T ReadValue(); +} diff --git a/src/Samples/SingleValue/IWriteableHolder.cs b/src/Samples/SingleValue/IWriteableHolder.cs new file mode 100644 index 00000000..3bba5606 --- /dev/null +++ b/src/Samples/SingleValue/IWriteableHolder.cs @@ -0,0 +1,9 @@ +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public interface IWriteableHolder +{ + T Value { set; } + + void WriteValue(T value); +} diff --git a/src/Samples/SingleValue/ReadableHolder.cs b/src/Samples/SingleValue/ReadableHolder.cs new file mode 100644 index 00000000..8b060a82 --- /dev/null +++ b/src/Samples/SingleValue/ReadableHolder.cs @@ -0,0 +1,10 @@ +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public class ReadableHolder(T value) : BaseReadableHolder(value) +{ + public override T ReadValue() + { + return Value; + } +} diff --git a/src/Samples/SingleValue/WriteableHolder.cs b/src/Samples/SingleValue/WriteableHolder.cs new file mode 100644 index 00000000..2f307c7c --- /dev/null +++ b/src/Samples/SingleValue/WriteableHolder.cs @@ -0,0 +1,10 @@ +namespace Werecodent.CreateAndFake.Samples.SingleValue; + +[ValidSample] +public class WriteableHolder : BaseWriteableHolder +{ + public override void WriteValue(T value) + { + Value = value; + } +} diff --git a/src/Samples/ValidSampleAttribute.cs b/src/Samples/ValidSampleAttribute.cs new file mode 100644 index 00000000..666f801e --- /dev/null +++ b/src/Samples/ValidSampleAttribute.cs @@ -0,0 +1,7 @@ +namespace Werecodent.CreateAndFake.Samples; + +[AttributeUsage( + AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, + Inherited = false +)] +public sealed class ValidSampleAttribute : Attribute; diff --git a/src/Toolbox/AsserterTool/.editorconfig b/src/Toolbox/AsserterTool/.editorconfig new file mode 100644 index 00000000..8fdb32d2 --- /dev/null +++ b/src/Toolbox/AsserterTool/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# Cleaner calls. +dotnet_diagnostic.CA1068.severity = None diff --git a/src/Toolbox/AsserterTool/AssertException.cs b/src/Toolbox/AsserterTool/AssertException.cs new file mode 100644 index 00000000..8ce71fc9 --- /dev/null +++ b/src/Toolbox/AsserterTool/AssertException.cs @@ -0,0 +1,76 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// Exception for a failed case. +[Serializable] +public sealed class AssertException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private AssertException() + : base() { } + + /// + /// Reason for the exception. + /// Optional fail details. + /// Seed used for data generation. + /// Optional related content. + public AssertException(string? message, string? details, int? seed, string? content = null) + : base(BuildMessage(message, details, seed, content)) { } + + /// + /// Reason for the exception. + /// Optional fail details. + /// Seed used for data generation. + /// Inner exception that occurred. + public AssertException(string? message, string? details, int? seed, Exception? innerException) + : base(BuildMessage(message, details, seed), innerException) { } + + /// + /// Reason for the exception. + /// Optional fail details. + /// Seed used for data generation. + /// Optional related content. + /// Inner exception that occurred. + public AssertException( + string? message, + string? details, + int? seed, + string? content, + Exception? innerException + ) + : base(BuildMessage(message, details, seed, content), innerException) { } + + /// + /// Object data. + /// Additional info. + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private AssertException(SerializationInfo info, StreamingContext context) + : base(info, context) { } + + /// Integrates the details into the message. + /// Starting message. + /// Details to integrate. + /// Seed used for data generation. + /// Content to integrate. + /// Message to use for the exception. + private static string BuildMessage( + string? message, + string? details, + int? seed, + string? content = null + ) + { + string nl = Environment.NewLine; + + return (message ?? "Unknown assert failure.") + + ((details != null) ? $"{nl}Details: {details}" : "") + + (seed.HasValue ? $"{nl}Seed: {seed.Value}" : "") + + ((content != null) ? $"{nl}Content: {nl}{content}" : ""); + } +} diff --git a/src/Toolbox/AsserterTool/Asserter.Base.cs b/src/Toolbox/AsserterTool/Asserter.Base.cs new file mode 100644 index 00000000..21cf77c7 --- /dev/null +++ b/src/Toolbox/AsserterTool/Asserter.Base.cs @@ -0,0 +1,122 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +/// +/// If given a parameter. +public partial class Asserter(AsserterOptions options) : IAsserter +{ + /// + public AsserterOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// Default option configuration to use. + protected AsserterMod? Unconfigured { get; } = null; + + /// Merges with . + /// Provided modifications of to merge. + /// The merged options to use. + protected AsserterOptions ApplyConfiguration(AsserterMod? optionConfiguration) + { + return optionConfiguration?.Invoke(Options) ?? Options; + } + + /// + public IAsserter WithOptions(AsserterMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Asserter(optionConfiguration.Invoke(Options)); + } + + /// + public virtual void Pass() { } + + /// + public virtual void Pass(AsserterMod? optionConfiguration) + { + _ = ApplyConfiguration(optionConfiguration); + } + + /// + [DoesNotReturn, ExcludeFromCodeCoverage] + public virtual void Fail(string? details = null) + { + Fail(Unconfigured, details); + } + + /// + [DoesNotReturn] + public virtual void Fail(AsserterMod? optionConfiguration, string? details = null) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + throw new AssertException("Test failed.", details, localOptions.Gen.InitialSeed); + } + + /// + public void Debug(string? details = null) + { + Debug(Unconfigured, details); + } + + /// + public void Debug(AsserterMod? optionConfiguration, string? details = null) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (localOptions.TriggerFailureForDebugAsserts) + { + throw new AssertException( + $"{nameof(AsserterOptions.TriggerFailureForDebugAsserts)} set to '{true}'.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public virtual void CheckAll(params IEnumerable cases) + { + if (cases == null) + { + return; + } + + List errors = []; + foreach (Action test in cases) + { + try + { + test.Invoke(); + errors.Add(null); + } + catch (Exception e) + { + errors.Add(e); + } + } + + if (errors.Exists(e => e != null)) + { + throw new AggregateException( + "Cases failed: " + + string.Join( + ", ", + Enumerable.Range(0, errors.Count).Where(i => errors[i] != null) + ) + + " -", + errors.Where(e => e != null).Select(e => e!) + ); + } + } + + /// Finds a suitable name to use for assertion messages. + /// Instance being compared to . + /// Instance to test. + /// The name to use if found, otherwise. + private static string? GetTypeName(object? expected, object? actual) + { + return GenericConverter.ExpandName(expected ?? actual); + } +} diff --git a/src/Toolbox/AsserterTool/AsserterOptions.cs b/src/Toolbox/AsserterTool/AsserterOptions.cs new file mode 100644 index 00000000..05e0654f --- /dev/null +++ b/src/Toolbox/AsserterTool/AsserterOptions.cs @@ -0,0 +1,89 @@ +using System.Reflection; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// Settings for manipulating behavior. +public sealed record AsserterOptions : ToolOptions +{ + /// Identifier for the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Asserter); + + /// + public required IExtractor Extractor { get; init; } + + /// + public required IValuer Valuer { get; init; } + + /// Comparison method used for assertions. + /// Useful for specifying cultures or ignoring case. + /// StringComparison.Ordinal + [ConfigurableOption] + public StringComparison ComparisonModeForStringAsserts { get; init; } = + StringComparison.Ordinal; + + /// + /// Triggers all s to be rethrown instead of successfully caught in Throw assertions. + /// + /// Useful for looking at the s being thrown during testing. + /// + [ConfigurableOption] + public bool DisableCatchingForThrowAsserts { get; init; } = false; + + /// + /// Enables to satisfy the target condition + /// for Throw assertions if the caught doesn't itself match. + /// + /// + /// Helps test for the intended without worrying about wrappers such + /// as . is affected + /// only when not wrapping multiple s. The behavior is not recursive, + /// only checks the first . + /// + /// + [ConfigurableOption] + public bool IncludeInternalExceptionForThrowAsserts { get; init; } = true; + + /// Causes Debug assertions to throw in order to fail the containing test. + /// + /// Useful for creating tests with data that can be manually reviewed + /// via the resulting 's contents, such + /// as the formatting of implementations. + /// + /// + [ConfigurableOption] + public bool TriggerFailureForDebugAsserts { get; init; } = false; + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal AsserterOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + ComparisonModeForStringAsserts = Config.GetValue( + section, + ComparisonModeForStringAsserts + ), + DisableCatchingForThrowAsserts = Config.GetValue( + section, + DisableCatchingForThrowAsserts + ), + IncludeInternalExceptionForThrowAsserts = Config.GetValue( + section, + IncludeInternalExceptionForThrowAsserts + ), + TriggerFailureForDebugAsserts = Config.GetValue(section, TriggerFailureForDebugAsserts), + }; + } +} diff --git a/src/Toolbox/AsserterTool/AsyncCategories/IAsserterAsyncEnumerable.cs b/src/Toolbox/AsserterTool/AsyncCategories/IAsserterAsyncEnumerable.cs new file mode 100644 index 00000000..57a9a59c --- /dev/null +++ b/src/Toolbox/AsserterTool/AsyncCategories/IAsserterAsyncEnumerable.cs @@ -0,0 +1,240 @@ +using System.Collections; +using Werecodent.CreateAndFake.AsserterTool.Categories; + +namespace Werecodent.CreateAndFake.AsserterTool.AsyncCategories; + +/// Handles common collection test scenarios. +public interface IAsserterAsyncEnumerable +{ + /// + /// + Task IsEmptyAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task IsEmptyAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task IsNotEmptyAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task IsNotEmptyAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task HasCountAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task HasCountAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task HasCountLessThanAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task HasCountLessThanAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task HasCountLessOrExactlyAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task HasCountLessOrExactlyAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task HasCountMoreThanAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task HasCountMoreThanAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task HasCountMoreOrExactlyAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task HasCountMoreOrExactlyAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task ContainsAsync( + T? content, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task ContainsAsync( + T? content, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task ContainsNotAsync( + T? content, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task ContainsNotAsync( + T? content, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task FailAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task FailAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task DebugAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task DebugAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ThrowsAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + where TException : Exception; + + /// + Task ThrowsAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception; + + /// + Task ThrowsExceptionAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + Task ThrowsExceptionAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); +} diff --git a/src/Toolbox/AsserterTool/AsyncCategories/IAsserterAsyncObject.cs b/src/Toolbox/AsserterTool/AsyncCategories/IAsserterAsyncObject.cs new file mode 100644 index 00000000..4b49c4a6 --- /dev/null +++ b/src/Toolbox/AsserterTool/AsyncCategories/IAsserterAsyncObject.cs @@ -0,0 +1,103 @@ +using Werecodent.CreateAndFake.AsserterTool.Categories; + +namespace Werecodent.CreateAndFake.AsserterTool.AsyncCategories; + +/// Handles common object test scenarios. +public interface IAsserterAsyncObject +{ + /// + /// + Task IsAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ); + + /// + /// Aborts execution if triggered. + /// A that represents the asynchronous operation. + Task IsAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task IsNotAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task IsNotAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task ValuesEqualAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task ValuesEqualAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task ValuesNotEqualAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task ValuesNotEqualAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + /// + Task AreUniqueAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task AreUniqueAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); +} diff --git a/src/Toolbox/AsserterTool/AsyncCategories/IAsserterTask.cs b/src/Toolbox/AsserterTool/AsyncCategories/IAsserterTask.cs new file mode 100644 index 00000000..4be1f42a --- /dev/null +++ b/src/Toolbox/AsserterTool/AsyncCategories/IAsserterTask.cs @@ -0,0 +1,97 @@ +using Werecodent.CreateAndFake.AsserterTool.Categories; + +namespace Werecodent.CreateAndFake.AsserterTool.AsyncCategories; + +/// Handles common async test scenarios. +public interface IAsserterTask +{ + /// + Task HasResultAsync( + Task? behavior, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task HasResultAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task HasResultAsync( + T content, + Task? behavior, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task HasResultAsync( + T content, + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ThrowsAsync(Task? behavior, CancellationToken canceler, string? details = null) + where T : Exception; + + /// + /// + Task ThrowsAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception; + + /// + Task ThrowsExceptionAsync( + Task? behavior, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task ThrowsExceptionAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ThrowsNoAsync(Task? behavior, CancellationToken canceler, string? details = null) + where T : Exception; + + /// + /// + Task ThrowsNoAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception; + + /// + Task ThrowsNoExceptionAsync(Task? behavior, CancellationToken canceler, string? details = null); + + /// + /// + Task ThrowsNoExceptionAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); +} diff --git a/src/Toolbox/AsserterTool/AsyncCategories/IAsserterValueTask.cs b/src/Toolbox/AsserterTool/AsyncCategories/IAsserterValueTask.cs new file mode 100644 index 00000000..d9c3ac06 --- /dev/null +++ b/src/Toolbox/AsserterTool/AsyncCategories/IAsserterValueTask.cs @@ -0,0 +1,170 @@ +namespace Werecodent.CreateAndFake.AsserterTool.AsyncCategories; + +/// Handles common async test scenarios. +public interface IAsserterValueTask +{ + /// + Task HasResultAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ); + + /// + Task HasResultAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task HasResultAsync( + T content, + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ); + + /// + Task HasResultAsync( + T content, + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ThrowsAsync(ValueTask? behavior, CancellationToken canceler, string? details = null) + where T : Exception; + + /// + Task ThrowsAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception; + + /// + Task ThrowsAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + where TException : Exception; + + /// + /// Verifies the behavior throws a . + /// + /// expected to be thrown. + /// The behavior's content . + /// + Task ThrowsAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception; + + /// + Task ThrowsExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ); + + /// + Task ThrowsExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ThrowsExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ); + + /// The behavior's content . + /// + Task ThrowsExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ThrowsNoAsync(ValueTask? behavior, CancellationToken canceler, string? details = null) + where T : Exception; + + /// The behavior's content . + /// + Task ThrowsNoAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception; + + /// + Task ThrowsNoAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + where TException : Exception; + + /// + /// Verifies the behavior does not throw a . + /// + /// expected to not be thrown. + /// The behavior's content . + /// + Task ThrowsNoAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception; + + /// + Task ThrowsNoExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ); + + /// + Task ThrowsNoExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ThrowsNoExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ); + + /// The behavior's content . + /// + Task ThrowsNoExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); +} diff --git a/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.AsyncEnumerable.cs b/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.AsyncEnumerable.cs new file mode 100644 index 00000000..a9dd1248 --- /dev/null +++ b/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.AsyncEnumerable.cs @@ -0,0 +1,675 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterAsyncEnumerable +{ + /// + public virtual Task FailAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return FailAsync(collection, canceler, Unconfigured, details); + } + + /// + [DoesNotReturn, ExcludeFromCodeCoverage] + public virtual async Task FailAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + Fail( + await AsyncSeriesHelper + .ToListAsync(collection, localOptions.Design.IterationLimit, canceler) + .ConfigureAwait(false), + optionConfiguration != null ? _ => localOptions : null, + details + ); + } + + /// + public Task DebugAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return DebugAsync(collection, canceler, Unconfigured, details); + } + + /// + public async Task DebugAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + string? content = AsString( + await AsyncSeriesHelper + .ToListAsync(collection, localOptions.Design.IterationLimit, canceler) + .ConfigureAwait(false), + localOptions + ); + + if (localOptions.TriggerFailureForDebugAsserts) + { + throw new AssertException( + $"{nameof(AsserterOptions.TriggerFailureForDebugAsserts)} set to '{true}'.", + details, + localOptions.Gen.InitialSeed, + content + ); + } + } + + /// + public virtual Task IsEmptyAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return IsEmptyAsync(collection, canceler, Unconfigured, details); + } + + /// + public virtual Task IsEmptyAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return HasCountAsync(0, collection, canceler, optionConfiguration, details); + } + + /// + public virtual Task IsNotEmptyAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return IsNotEmptyAsync(collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task IsNotEmptyAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + "Expected collection with elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + bool hasItems = false; + try + { + await foreach (T item in collection.WithCancellation(canceler).ConfigureAwait(false)) + { + hasItems = true; + await Disposer.CleanupAsync(item).ConfigureAwait(false); + break; + } + } + catch (Exception e) + { + throw new AssertException( + $"Expected collection with elements, but exception occurred at index '{0}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (!hasItems) + { + throw new AssertException( + "Expected collection with elements, but was empty.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public virtual Task HasCountAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return HasCountAsync(count, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasCountAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '{count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + try + { + await AsyncSeriesHelper + .ForEachAsync(collection, localOptions.Design.IterationLimit, canceler, item => + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine() + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AssertException( + $"Expected collection of '{count}' elements, but exception occurred at index '{i}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (i != count) + { + throw new AssertException( + $"Expected collection of '{count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual Task HasCountLessThanAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return HasCountLessThanAsync(count, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasCountLessThanAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '< {count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + try + { + await AsyncSeriesHelper + .ForEachAsync(collection, localOptions.Design.IterationLimit, canceler, item => + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine() + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AssertException( + $"Expected collection of '< {count}' elements, but exception occurred at index '{i}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (i >= count) + { + throw new AssertException( + $"Expected collection of '< {count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual Task HasCountLessOrExactlyAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return HasCountLessOrExactlyAsync(count, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasCountLessOrExactlyAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '<= {count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + try + { + await AsyncSeriesHelper + .ForEachAsync(collection, localOptions.Design.IterationLimit, canceler, item => + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine() + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AssertException( + $"Expected collection of '<= {count}' elements, but exception occurred at index '{i}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (i > count) + { + throw new AssertException( + $"Expected collection of '<= {count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual Task HasCountMoreThanAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return HasCountMoreThanAsync(count, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasCountMoreThanAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '> {count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + try + { + await AsyncSeriesHelper + .ForEachAsync(collection, localOptions.Design.IterationLimit, canceler, item => + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine() + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AssertException( + $"Expected collection of '> {count}' elements, but exception occurred at index '{i}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (i <= count) + { + throw new AssertException( + $"Expected collection of '> {count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual Task HasCountMoreOrExactlyAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return HasCountMoreOrExactlyAsync(count, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasCountMoreOrExactlyAsync( + int count, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '>= {count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + try + { + await AsyncSeriesHelper + .ForEachAsync(collection, localOptions.Design.IterationLimit, canceler, item => + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine() + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AssertException( + $"Expected collection of '>= {count}' elements, but exception occurred at index '{i}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (i < count) + { + throw new AssertException( + $"Expected collection of '>= {count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual Task ContainsAsync( + T? content, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return ContainsAsync(content, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task ContainsAsync( + T? content, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection to contain '{content}', but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + int i = 0; + bool found = false; + StringBuilder contents = new(); + try + { + await AsyncSeriesHelper + .ForEachAsync( + collection, + localOptions.Design.IterationLimit, + canceler, + async item => + { + found |= await localOptions + .Valuer.EqualsAsync(content, item, canceler) + .ConfigureAwait(false); + + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AssertException( + $"Expected collection to contain '{content}', but exception occurred at index '{i}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (!found) + { + throw new AssertException( + $"Expected collection to contain '{content}' but didn't.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual Task ContainsNotAsync( + T? content, + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return ContainsNotAsync(content, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task ContainsNotAsync( + T? content, + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + return; + } + + int i = 0; + bool notFound = true; + StringBuilder contents = new(); + try + { + await AsyncSeriesHelper + .ForEachAsync( + collection, + localOptions.Design.IterationLimit, + canceler, + async item => + { + notFound &= !await localOptions + .Valuer.EqualsAsync(content, item, canceler) + .ConfigureAwait(false); + + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AssertException( + $"Expected collection to not contain '{content}', but exception occurred at index '{i}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (!notFound) + { + throw new AssertException( + $"Expected collection to not contain '{content}' but did.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public Task ThrowsAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + return ThrowsAsync(collection, canceler, Unconfigured, details); + } + + /// + public async Task ThrowsAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(collection); + + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + string errorMessage = + $"Expected exception of type '{GenericConverter.ExpandName()}' but received: "; + + int i = 0; + try + { + await foreach ( + TContent item in collection.WithCancellation(canceler).ConfigureAwait(false) + ) + { + await Disposer.CleanupAsync(item).ConfigureAwait(false); + ArgumentGuard.ThrowUponIterationLimit(i++, Options.Design.IterationLimit); + } + } + catch (Exception e) + { + return UnwrapException(e, errorMessage, localOptions, details); + } + + throw new AssertException(errorMessage + "None", details, localOptions.Gen.InitialSeed); + } + + /// + public Task ThrowsExceptionAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return ThrowsExceptionAsync(collection, canceler, Unconfigured, details); + } + + /// + public Task ThrowsExceptionAsync( + IAsyncEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ThrowsAsync(collection, canceler, optionConfiguration, details); + } +} diff --git a/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.AsyncObject.cs b/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.AsyncObject.cs new file mode 100644 index 00000000..73d88500 --- /dev/null +++ b/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.AsyncObject.cs @@ -0,0 +1,182 @@ +using System.Text; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterAsyncObject +{ + /// + public Task IsAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ) + { + return ValuesEqualAsync(expected, actual, canceler, details); + } + + /// + public Task IsAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ValuesEqualAsync(expected, actual, canceler, optionConfiguration, details); + } + + /// + public Task IsNotAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ) + { + return ValuesNotEqualAsync(expected, actual, canceler, details); + } + + /// + public Task IsNotAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ValuesNotEqualAsync(expected, actual, canceler, optionConfiguration, details); + } + + /// + public virtual Task ValuesEqualAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ) + { + return ValuesEqualAsync(expected, actual, canceler, Unconfigured, details); + } + + /// + public virtual async Task ValuesEqualAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + IList differences = await AsyncSeriesHelper + .ToListAsync( + localOptions.Valuer.CompareAsync(expected, actual, canceler), + localOptions.Design.IterationLimit, + canceler + ) + .ConfigureAwait(false); + + if (differences.Count > 0) + { + throw new AssertException( + $"Value equality failed for type '{GetTypeName(expected, actual)}'.", + details, + localOptions.Gen.InitialSeed, + string.Join(Environment.NewLine, differences) + ); + } + } + + /// + public virtual Task ValuesNotEqualAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ) + { + return ValuesNotEqualAsync(expected, actual, canceler, Unconfigured, details); + } + + /// + public virtual async Task ValuesNotEqualAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (await localOptions.Valuer.EqualsAsync(expected, actual, canceler).ConfigureAwait(false)) + { + throw new AssertException( + $"Value inequality failed for type '{GetTypeName(expected, actual)}'.", + details, + localOptions.Gen.InitialSeed, + expected?.ToString() + ); + } + } + + /// + public virtual Task AreUniqueAsync( + object? expected, + object? actual, + CancellationToken canceler, + string? details = null + ) + { + return AreUniqueAsync(expected, actual, canceler, Unconfigured, details); + } + + /// + public virtual async Task AreUniqueAsync( + object? expected, + object? actual, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + ReferenceNotEqual(expected, actual, details); + + int i = 0; + StringBuilder contents = new(); + await foreach ( + object value in ( + await localOptions.Extractor.ExtractAsync(actual, canceler).ConfigureAwait(false) + ) + .FindSharedContentAsync( + await localOptions + .Extractor.ExtractAsync(expected, canceler) + .ConfigureAwait(false), + canceler + ) + .ConfigureAwait(false) + ) + { + _ = contents.Append('#').Append(i++).Append(':').Append(value).AppendLine(); + } + + if (i != 0) + { + throw new AssertException( + $"Expected no shared content, but had '{i}' shared items.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } +} diff --git a/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.Task.cs b/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.Task.cs new file mode 100644 index 00000000..b86f54fc --- /dev/null +++ b/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.Task.cs @@ -0,0 +1,187 @@ +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterTask +{ + /// + public virtual Task HasResultAsync( + Task? behavior, + CancellationToken canceler, + string? details = null + ) + { + return HasResultAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual Task HasResultAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + IsNotNull(behavior, optionConfiguration, details); + return behavior; + } + + /// + public virtual Task HasResultAsync( + T content, + Task? behavior, + CancellationToken canceler, + string? details = null + ) + { + return HasResultAsync(content, behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasResultAsync( + T content, + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + T result = await HasResultAsync(behavior, canceler, _ => localOptions, details) + .ConfigureAwait(false); + + await IsAsync(content, result, canceler, _ => localOptions, details).ConfigureAwait(false); + return result; + } + + /// + public virtual Task ThrowsAsync( + Task? behavior, + CancellationToken canceler, + string? details = null + ) + where T : Exception + { + return ThrowsAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task ThrowsAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + string errorMessage = + $"Expected exception of type '{GenericConverter.ExpandName()}' but received: "; + if (behavior != null) + { + try + { + await Disposer + .CleanupAsync(await Invoker.AwaitAsync(behavior).ConfigureAwait(false)) + .ConfigureAwait(false); + } + catch (Exception e) + { + return UnwrapException(e, errorMessage, localOptions, details); + } + } + + throw new AssertException(errorMessage + "None", details, localOptions.Gen.InitialSeed); + } + + /// + public virtual Task ThrowsExceptionAsync( + Task? behavior, + CancellationToken canceler, + string? details = null + ) + { + return ThrowsExceptionAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual Task ThrowsExceptionAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ThrowsAsync(behavior, canceler, optionConfiguration, details); + } + + /// + public virtual Task ThrowsNoAsync( + Task? behavior, + CancellationToken canceler, + string? details = null + ) + where T : Exception + { + return ThrowsNoAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task ThrowsNoAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (behavior != null) + { + try + { + await Disposer + .CleanupAsync(await Invoker.AwaitAsync(behavior).ConfigureAwait(false)) + .ConfigureAwait(false); + } + catch (Exception e) + { + if (e is T) + { + throw new AssertException( + $"Expected no exception of type '{typeof(T).Name}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + } + } + } + + /// + public virtual Task ThrowsNoExceptionAsync( + Task? behavior, + CancellationToken canceler, + string? details = null + ) + { + return ThrowsNoExceptionAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual Task ThrowsNoExceptionAsync( + Task? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ThrowsNoAsync(behavior, canceler, optionConfiguration, details); + } +} diff --git a/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.ValueTask.cs b/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.ValueTask.cs new file mode 100644 index 00000000..f13587e5 --- /dev/null +++ b/src/Toolbox/AsserterTool/AsyncImplementation/Asserter.ValueTask.cs @@ -0,0 +1,314 @@ +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterValueTask +{ + /// + public virtual Task HasResultAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + { + return HasResultAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasResultAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + IsNotNull(behavior, optionConfiguration, details); + return await behavior.Value.ConfigureAwait(false); + } + + /// + public virtual Task HasResultAsync( + T content, + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + { + return HasResultAsync(content, behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasResultAsync( + T content, + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + T result = await HasResultAsync(behavior, canceler, _ => localOptions, details) + .ConfigureAwait(false); + + await IsAsync(content, result, canceler, _ => localOptions, details).ConfigureAwait(false); + return result; + } + + /// + public virtual Task ThrowsAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + where T : Exception + { + return ThrowsAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task ThrowsAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + string errorMessage = + $"Expected exception of type '{GenericConverter.ExpandName()}' but received: "; + if (behavior != null) + { + try + { + await behavior.Value.ConfigureAwait(false); + } + catch (Exception e) + { + return UnwrapException(e, errorMessage, localOptions, details); + } + } + + throw new AssertException(errorMessage + "None", details, localOptions.Gen.InitialSeed); + } + + /// + public virtual Task ThrowsAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + return ThrowsAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task ThrowsAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + string errorMessage = + $"Expected exception of type '{GenericConverter.ExpandName()}' but received: "; + if (behavior != null) + { + try + { + await Disposer + .CleanupAsync(await behavior.Value.ConfigureAwait(false)) + .ConfigureAwait(false); + } + catch (Exception e) + { + return UnwrapException(e, errorMessage, localOptions, details); + } + } + + throw new AssertException(errorMessage + "None", details, localOptions.Gen.InitialSeed); + } + + /// + public virtual Task ThrowsExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + { + return ThrowsExceptionAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual Task ThrowsExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ThrowsAsync(behavior, canceler, optionConfiguration, details); + } + + /// + public virtual Task ThrowsExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + { + return ThrowsExceptionAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual Task ThrowsExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ThrowsAsync(behavior, canceler, optionConfiguration, details); + } + + /// + public virtual Task ThrowsNoAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + where T : Exception + { + return ThrowsNoAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task ThrowsNoAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + canceler.ThrowIfCancellationRequested(); + + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (behavior != null) + { + try + { + await behavior.Value.ConfigureAwait(false); + } + catch (Exception e) + { + if (e is T) + { + throw new AssertException( + $"Expected no exception of type '{typeof(T).Name}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + } + } + } + + /// + public virtual Task ThrowsNoAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + return ThrowsNoAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task ThrowsNoAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + canceler.ThrowIfCancellationRequested(); + + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (behavior != null) + { + try + { + await Disposer + .CleanupAsync(await behavior.Value.ConfigureAwait(false)) + .ConfigureAwait(false); + } + catch (Exception e) + { + if (e is TException) + { + throw new AssertException( + $"Expected no exception of type '{typeof(TException).Name}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + } + } + } + + /// + public virtual Task ThrowsNoExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + { + return ThrowsNoExceptionAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual Task ThrowsNoExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ThrowsNoAsync(behavior, canceler, optionConfiguration, details); + } + + /// + public virtual Task ThrowsNoExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + string? details = null + ) + { + return ThrowsNoExceptionAsync(behavior, canceler, Unconfigured, details); + } + + /// + public virtual Task ThrowsNoExceptionAsync( + ValueTask? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return ThrowsNoAsync(behavior, canceler, optionConfiguration, details); + } +} diff --git a/src/Toolbox/AsserterTool/Categories/IAsserterAction.cs b/src/Toolbox/AsserterTool/Categories/IAsserterAction.cs new file mode 100644 index 00000000..b4ed05f6 --- /dev/null +++ b/src/Toolbox/AsserterTool/Categories/IAsserterAction.cs @@ -0,0 +1,41 @@ +namespace Werecodent.CreateAndFake.AsserterTool.Categories; + +/// Handles common delegate test scenarios. +public interface IAsserterAction +{ + /// + T Throws(Action? behavior, string? details = null) + where T : Exception; + + /// + T Throws(Action? behavior, AsserterMod? optionConfiguration, string? details = null) + where T : Exception; + + /// + Exception ThrowsException(Action? behavior, string? details = null); + + /// + Exception ThrowsException( + Action? behavior, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void ThrowsNo(Action? behavior, string? details = null) + where T : Exception; + + /// + void ThrowsNo(Action? behavior, AsserterMod? optionConfiguration, string? details = null) + where T : Exception; + + /// + void ThrowsNoException(Action? behavior, string? details = null); + + /// + void ThrowsNoException( + Action? behavior, + AsserterMod? optionConfiguration, + string? details = null + ); +} diff --git a/src/Toolbox/AsserterTool/Categories/IAsserterComparable.cs b/src/Toolbox/AsserterTool/Categories/IAsserterComparable.cs new file mode 100644 index 00000000..d177a6f4 --- /dev/null +++ b/src/Toolbox/AsserterTool/Categories/IAsserterComparable.cs @@ -0,0 +1,94 @@ +namespace Werecodent.CreateAndFake.AsserterTool.Categories; + +/// Handles common comparable test scenarios. +public interface IAsserterComparable +{ + /// + void GreaterThan(IComparable? target, IComparable? value, string? details = null); + + /// Verifies value > . + /// Expected value to compare with. + /// Actual value under test needing to match the condition + /// + void GreaterThan( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void GreaterThanOrEqualTo(IComparable? target, IComparable? value, string? details = null); + + /// Verifies value >= . + /// + void GreaterThanOrEqualTo( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void GreaterThanOrIs(IComparable? target, IComparable? value, string? details = null); + + /// Verifies value > or equals by value. + /// + void GreaterThanOrIs( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void LessThan(IComparable? target, IComparable? value, string? details = null); + + /// Verifies value < . + /// + void LessThan( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void LessThanOrEqualTo(IComparable? target, IComparable? value, string? details = null); + + /// Verifies value <= . + /// + void LessThanOrEqualTo( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void LessThanOrIs(IComparable? target, IComparable? value, string? details = null); + + /// Verifies value < or equals by value. + /// + void LessThanOrIs( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void InRange(IComparable? min, IComparable? max, IComparable? value, string? details = null); + + /// Verifies <= value <= . + /// Inclusive lower bound. + /// Inclusive upper bound. + /// + void InRange( + IComparable? min, + IComparable? max, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ); +} diff --git a/src/Toolbox/AsserterTool/Categories/IAsserterDelegate.cs b/src/Toolbox/AsserterTool/Categories/IAsserterDelegate.cs new file mode 100644 index 00000000..55a99710 --- /dev/null +++ b/src/Toolbox/AsserterTool/Categories/IAsserterDelegate.cs @@ -0,0 +1,103 @@ +namespace Werecodent.CreateAndFake.AsserterTool.Categories; + +#pragma warning disable CA1711 // Follows existing pattern. + +/// Handles common delegate test scenarios. +public interface IAsserterDelegate +{ + /// + T Throws(Delegate? behavior, string? details = null) + where T : Exception; + + /// Verifies the behavior throws a . + /// expected to be thrown. + /// The thrown . + /// Important relevant options: + /// + /// + /// + /// + T Throws(Delegate? behavior, AsserterMod? optionConfiguration, string? details = null) + where T : Exception; + + /// + Exception ThrowsException(Delegate? behavior, string? details = null); + + /// Verifies the behavior throws an . + /// + Exception ThrowsException( + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void ThrowsNo(Delegate? behavior, string? details = null) + where T : Exception; + + /// + /// Verifies the behavior does not throw a . + /// + /// expected to not be thrown. + /// Instance to test. + /// + void ThrowsNo(Delegate? behavior, AsserterMod? optionConfiguration, string? details = null) + where T : Exception; + + /// + void ThrowsNoException(Delegate? behavior, string? details = null); + + /// Verifies the behavior does not throw an . + /// + void ThrowsNoException( + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + T HasResult(Delegate? behavior, string? details = null); + + /// + /// Verifies the behavior successfully executes resulting with a value. + /// + /// + T HasResult(Delegate? behavior, AsserterMod? optionConfiguration, string? details = null); + + /// + T HasResult(T content, Delegate? behavior, string? details = null); + + /// + T HasResult( + T content, + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task HasResultAsync( + T content, + Delegate? behavior, + CancellationToken canceler, + string? details = null + ); + + /// + /// Verifies the behavior successfully executes resulting with the given . + /// + /// Expected return of the behavior. + /// Expected result for the behavior. + /// Aborts execution if triggered. + /// Result from invoking the behavior. + /// + Task HasResultAsync( + T content, + Delegate? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); +} + +#pragma warning restore diff --git a/src/Toolbox/AsserterTool/Categories/IAsserterEnumerable.cs b/src/Toolbox/AsserterTool/Categories/IAsserterEnumerable.cs new file mode 100644 index 00000000..eda40d83 --- /dev/null +++ b/src/Toolbox/AsserterTool/Categories/IAsserterEnumerable.cs @@ -0,0 +1,171 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; + +namespace Werecodent.CreateAndFake.AsserterTool.Categories; + +/// Handles common collection test scenarios. +public interface IAsserterEnumerable +{ + /// + void IsEmpty(IEnumerable? collection, string? details = null); + + /// Verifies the collection contains no elements. + /// Instance to test. + /// + void IsEmpty(IEnumerable? collection, AsserterMod? optionConfiguration, string? details = null); + + /// + void IsNotEmpty(IEnumerable? collection, string? details = null); + + /// Verifies the collection contains elements. + /// + void IsNotEmpty( + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void HasCount(int count, IEnumerable? collection, string? details = null); + + /// Verifies the collection has elements. + /// Size constraint to verify the collection with. + /// + void HasCount( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void HasCountLessThan(int count, IEnumerable? collection, string? details = null); + + /// Verifies collection has < count elements. + /// + void HasCountLessThan( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void HasCountLessOrExactly(int count, IEnumerable? collection, string? details = null); + + /// Verifies collection has <= count elements. + /// + void HasCountLessOrExactly( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void HasCountMoreThan(int count, IEnumerable? collection, string? details = null); + + /// Verifies collection has > count elements. + /// + void HasCountMoreThan( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void HasCountMoreOrExactly(int count, IEnumerable? collection, string? details = null); + + /// Verifies collection has >= count elements. + /// + void HasCountMoreOrExactly( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void Contains(object? content, IEnumerable? collection, string? details = null); + + /// + /// Verifies the collection contains an element equal to the given by value. + /// + /// Expected item to be present. + /// + void Contains( + object? content, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ContainsAsync( + object? content, + IEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// Aborts execution if triggered. + /// A that represents the asynchronous operation. + Task ContainsAsync( + object? content, + IEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void ContainsNot(object? content, IEnumerable? collection, string? details = null); + + /// + /// Verifies the collection contains no element equal to given by value. + /// + /// Expected item to be missing. + /// + void ContainsNot( + object? content, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + Task ContainsNotAsync( + object? content, + IEnumerable? collection, + CancellationToken canceler, + string? details = null + ); + + /// + /// + Task ContainsNotAsync( + object? content, + IEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + [DoesNotReturn] + void Fail(IEnumerable? collection, string? details = null); + + /// Collection responsible for the failure. + /// + [DoesNotReturn] + void Fail(IEnumerable? collection, AsserterMod? optionConfiguration, string? details = null); + + /// + void Debug(IEnumerable? collection, string? details = null); + + /// Collection to display information for. + /// + void Debug(IEnumerable? collection, AsserterMod? optionConfiguration, string? details = null); +} diff --git a/src/Toolbox/AsserterTool/Categories/IAsserterError.cs b/src/Toolbox/AsserterTool/Categories/IAsserterError.cs new file mode 100644 index 00000000..63d93c32 --- /dev/null +++ b/src/Toolbox/AsserterTool/Categories/IAsserterError.cs @@ -0,0 +1,23 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Werecodent.CreateAndFake.AsserterTool.Categories; + +/// Handles common exception test scenarios. +public interface IAsserterError +{ + /// + [DoesNotReturn] + void Fail(Exception? exception, string? details = null); + + /// responsible for the failure. + /// + [DoesNotReturn] + void Fail(Exception? exception, AsserterMod? optionConfiguration, string? details = null); + + /// + void Debug(Exception? exception, string? details = null); + + /// to display information for. + /// + void Debug(Exception? exception, AsserterMod? optionConfiguration, string? details = null); +} diff --git a/src/Toolbox/AsserterTool/Categories/IAsserterFunc.cs b/src/Toolbox/AsserterTool/Categories/IAsserterFunc.cs new file mode 100644 index 00000000..68b1ad2b --- /dev/null +++ b/src/Toolbox/AsserterTool/Categories/IAsserterFunc.cs @@ -0,0 +1,11 @@ +namespace Werecodent.CreateAndFake.AsserterTool.Categories; + +/// Handles common delegate test scenarios. +public interface IAsserterFunc +{ + /// + T HasResult(Func? behavior, string? details = null); + + /// + T HasResult(Func? behavior, AsserterMod? optionConfiguration, string? details = null); +} diff --git a/src/Toolbox/AsserterTool/Categories/IAsserterObject.cs b/src/Toolbox/AsserterTool/Categories/IAsserterObject.cs new file mode 100644 index 00000000..f0bf2bdc --- /dev/null +++ b/src/Toolbox/AsserterTool/Categories/IAsserterObject.cs @@ -0,0 +1,220 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.AsserterTool.Categories; + +#pragma warning disable CA1716 // Matches existing usage. + +/// Handles common object test scenarios. +public interface IAsserterObject +{ + /// + void Is(object? expected, object? actual, string? details = null); + + /// Verifies actual equals by value. + /// Instance to compare against. + /// Instance to test. + /// Modifications of this tool's options to apply for this call. + /// Description to include in assertion failure messages. + /// If the comparison fails to match the expected behavior. + void Is( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void IsNull(object? actual, string? details = null); + + /// Verifies actual equals . + /// + void IsNull(object? actual, AsserterMod? optionConfiguration, string? details = null); + + /// + void IsNot(object? expected, object? actual, string? details = null); + + /// Verifies actual does not equal by value. + /// + void IsNot( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void IsNotNull([NotNull] object? actual, string? details = null); + + /// Verifies actual does not equal . + /// + void IsNotNull( + [NotNull] object? actual, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void ReferenceEqual(object? expected, object? actual, string? details = null); + + /// Verifies actual equals by reference. + /// + void ReferenceEqual( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void ReferenceNotEqual(object? expected, object? actual, string? details = null); + + /// Verifies actual does not equal by reference. + /// + void ReferenceNotEqual( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void ValuesEqual(object? expected, object? actual, string? details = null); + + /// + void ValuesEqual( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void ValuesNotEqual(object? expected, object? actual, string? details = null); + + /// + void ValuesNotEqual( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void AreUnique(object? expected, object? actual, string? details = null); + + /// Verifies actual shares no data with . + /// + void AreUnique( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void Inherits(object? instance, string? details = null); + + /// + /// Verifies that is a base + /// or for the instance. + /// + /// + /// Expected base / for the instance. + /// + /// Instance to test. + /// + void Inherits( + object? instance, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void Inherits(Type? parent, object? instance, string? details = null); + + /// + /// Verifies that the is a base + /// or for the instance. + /// + /// + /// Expected base / for the instance. + /// + /// + void Inherits( + Type? parent, + object? instance, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void InheritedBy(object? instance, string? details = null); + + /// + /// Verifies that the instance is a base + /// or for . + /// + /// + /// Expected child inheriting the given instance . + /// + /// + void InheritedBy( + object? instance, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void InheritedBy(Type? child, object? instance, string? details = null); + + /// + /// Verifies that the instance is a base + /// or for the . + /// + /// + /// Expected child potentially inheriting the given instance . + /// + /// + void InheritedBy( + Type? child, + object? instance, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void Called(object? fake, AsserterMod? optionConfiguration = null); + + /// Verifies all behaviors with associated were called as expected. + /// instance with behavior set. + /// Expected total number of calls across all methods to test as well. + /// Modifications of this tool's options to apply for this call. + /// + /// For use on stubs from the tool only. + /// When specifying , be aware of test framework calls for info/display. + /// + /// If the instance is not an instance. + /// For any behavior verification failures. + void Called(object? fake, Times total, AsserterMod? optionConfiguration = null); + + /// + [DoesNotReturn] + void Fail(object? content, string? details = null); + + /// Content responsible for the failure. + /// + [DoesNotReturn] + void Fail(object? content, AsserterMod? optionConfiguration, string? details = null); + + /// + void Debug(object? content, string? details = null); + + /// Content to display information for. + /// + void Debug(object? content, AsserterMod? optionConfiguration, string? details = null); +} + +#pragma warning restore diff --git a/src/Toolbox/AsserterTool/Categories/IAsserterString.cs b/src/Toolbox/AsserterTool/Categories/IAsserterString.cs new file mode 100644 index 00000000..64c52c8c --- /dev/null +++ b/src/Toolbox/AsserterTool/Categories/IAsserterString.cs @@ -0,0 +1,131 @@ +namespace Werecodent.CreateAndFake.AsserterTool.Categories; + +/// Handles common string test scenarios. +public interface IAsserterString +{ + /// + void Contains(string content, string? text, string? details = null); + + /// Verifies the text contains the given . + /// Expected text to be present. + /// Instance to test. + /// Important relevant options: + /// + /// + /// + void Contains( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void ContainsNot(string content, string? text, string? details = null); + + /// Verifies the text does not contain the given . + /// Expected text to be missing. + /// + void ContainsNot( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void StartsWith(char content, string? text, string? details = null); + + /// + void StartsWith( + char content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void StartsWith(string content, string? text, string? details = null); + + /// Verifies the text starts with the given . + /// Expected text to be at the start. + /// + void StartsWith( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void StartsNotWith(char content, string? text, string? details = null); + + /// + void StartsNotWith( + char content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void StartsNotWith(string content, string? text, string? details = null); + + /// Verifies the text does not start with the given . + /// Expected text to not be at the start. + /// + void StartsNotWith( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void EndsWith(char content, string? text, string? details = null); + + /// + void EndsWith( + char content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void EndsWith(string content, string? text, string? details = null); + + /// Verifies the text ends with the given . + /// Expected text to be at the end. + /// + void EndsWith( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void EndsNotWith(char content, string? text, string? details = null); + + /// + void EndsNotWith( + char content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); + + /// + void EndsNotWith(string content, string? text, string? details = null); + + /// Verifies the text does not end with . + /// Expected text to not be at the end. + /// + void EndsNotWith( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ); +} diff --git a/src/Toolbox/AsserterTool/IAsserter.cs b/src/Toolbox/AsserterTool/IAsserter.cs new file mode 100644 index 00000000..f7b5c24d --- /dev/null +++ b/src/Toolbox/AsserterTool/IAsserter.cs @@ -0,0 +1,71 @@ +global using AsserterMod = System.Func< + Werecodent.CreateAndFake.AsserterTool.AsserterOptions, + Werecodent.CreateAndFake.AsserterTool.AsserterOptions +>; +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// Tool to verify states and behavior. +/// Useful for handling common test scenarios. +public interface IAsserter + : ITool, + IAsserterAsyncEnumerable, + IAsserterAsyncObject, + IAsserterTask, + IAsserterValueTask, + IAsserterAction, + IAsserterComparable, + IAsserterDelegate, + IAsserterEnumerable, + IAsserterError, + IAsserterFunc, + IAsserterObject, + IAsserterString +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + IAsserter WithOptions(AsserterMod optionConfiguration); + + /// + void Pass(); + + /// Specifies the test is successful if it reaches this point. + /// Modifications of this tool's options to apply for this call. + void Pass(AsserterMod? optionConfiguration); + + /// + [DoesNotReturn] + void Fail(string? details = null); + + /// Specifies the test has failed if it reaches this point. + /// Description to include in assertion failure messages. + /// Always. + /// + [DoesNotReturn] + void Fail(AsserterMod? optionConfiguration, string? details = null); + + /// + void Debug(string? details = null); + + /// Fails the test only if the option is set. + /// Description to include in assertion failure messages. + /// Important relevant options: + /// + /// + /// Always. + /// + void Debug(AsserterMod? optionConfiguration, string? details = null); + + /// Verifies all given throw no s. + /// Assertion cases to run. + /// Aggregates all caught s. + /// + /// All s thrown by the given . + /// + void CheckAll(params IEnumerable cases); +} diff --git a/src/Toolbox/AsserterTool/Implementation/Asserter.Action.cs b/src/Toolbox/AsserterTool/Implementation/Asserter.Action.cs new file mode 100644 index 00000000..e7c88943 --- /dev/null +++ b/src/Toolbox/AsserterTool/Implementation/Asserter.Action.cs @@ -0,0 +1,75 @@ +using Werecodent.CreateAndFake.AsserterTool.Categories; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterAction +{ + /// + public virtual T Throws(Action? behavior, string? details = null) + where T : Exception + { + return Throws(behavior, Unconfigured, details); + } + + /// + public virtual T Throws( + Action? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + return Throws((Delegate?)behavior, optionConfiguration, details); + } + + /// + public virtual Exception ThrowsException(Action? behavior, string? details = null) + { + return ThrowsException(behavior, Unconfigured, details); + } + + /// + public virtual Exception ThrowsException( + Action? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return Throws(behavior, optionConfiguration, details); + } + + /// + public virtual void ThrowsNo(Action? behavior, string? details = null) + where T : Exception + { + ThrowsNo(behavior, Unconfigured, details); + } + + /// + public virtual void ThrowsNo( + Action? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + ThrowsNo((Delegate?)behavior, optionConfiguration, details); + } + + /// + public virtual void ThrowsNoException(Action? behavior, string? details = null) + { + ThrowsNoException(behavior, Unconfigured, details); + } + + /// + public virtual void ThrowsNoException( + Action? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ThrowsNo(behavior, optionConfiguration, details); + } +} diff --git a/src/Toolbox/AsserterTool/Implementation/Asserter.Comparable.cs b/src/Toolbox/AsserterTool/Implementation/Asserter.Comparable.cs new file mode 100644 index 00000000..25e1ae9f --- /dev/null +++ b/src/Toolbox/AsserterTool/Implementation/Asserter.Comparable.cs @@ -0,0 +1,257 @@ +using Werecodent.CreateAndFake.AsserterTool.Categories; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterComparable +{ + /// + public virtual void GreaterThan(IComparable? target, IComparable? value, string? details = null) + { + GreaterThan(target, value, Unconfigured, details); + } + + /// + public virtual void GreaterThan( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ) + { + HandleMathCheck( + () => value!.CompareTo(target) > 0, + "greater than", + target, + value, + optionConfiguration, + details + ); + } + + /// + public virtual void GreaterThanOrEqualTo( + IComparable? target, + IComparable? value, + string? details = null + ) + { + GreaterThanOrEqualTo(target, value, Unconfigured, details); + } + + /// + public virtual void GreaterThanOrEqualTo( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ) + { + HandleMathCheck( + () => value!.CompareTo(target) >= 0, + "greater than or equal to", + target, + value, + optionConfiguration, + details + ); + } + + /// + public virtual void GreaterThanOrIs( + IComparable? target, + IComparable? value, + string? details = null + ) + { + GreaterThanOrIs(target, value, Unconfigured, details); + } + + /// + public virtual void GreaterThanOrIs( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (!localOptions.Valuer.Equals(value, target)) + { + GreaterThanOrEqualTo(target, value, _ => localOptions, details); + } + } + + /// + public virtual void LessThan(IComparable? target, IComparable? value, string? details = null) + { + LessThan(target, value, Unconfigured, details); + } + + /// + public virtual void LessThan( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ) + { + HandleMathCheck( + () => value!.CompareTo(target) < 0, + "less than", + target, + value, + optionConfiguration, + details + ); + } + + /// + public virtual void LessThanOrEqualTo( + IComparable? target, + IComparable? value, + string? details = null + ) + { + LessThanOrEqualTo(target, value, Unconfigured, details); + } + + /// + public virtual void LessThanOrEqualTo( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ) + { + HandleMathCheck( + () => value!.CompareTo(target) <= 0, + "less than or equal to", + target, + value, + optionConfiguration, + details + ); + } + + /// + public virtual void LessThanOrIs( + IComparable? target, + IComparable? value, + string? details = null + ) + { + LessThanOrIs(target, value, Unconfigured, details); + } + + /// + public virtual void LessThanOrIs( + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (!localOptions.Valuer.Equals(value, target)) + { + LessThanOrEqualTo(target, value, _ => localOptions, details); + } + } + + /// + public virtual void InRange( + IComparable? min, + IComparable? max, + IComparable? value, + string? details = null + ) + { + InRange(min, max, value, Unconfigured, details); + } + + /// + public virtual void InRange( + IComparable? min, + IComparable? max, + IComparable? value, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (value == null) + { + throw new AssertException( + $"Value was null and not in range [{min}, {max}].", + details, + localOptions.Gen.InitialSeed + ); + } + else if (min == null || max == null) + { + throw new AssertException( + $"Min {min} or max {max} was null and not valid for math comparison check.", + details, + localOptions.Gen.InitialSeed, + value.ToString() + ); + } + else if (value.CompareTo(min) < 0 || value.CompareTo(max) > 0) + { + throw new AssertException( + $"Value was not in range [{min}, {max}].", + details, + localOptions.Gen.InitialSeed, + value.ToString() + ); + } + } + + /// Verifies value matches the . + /// Math used to check the value. + /// Math description to use for error message. + /// Value to compare with. + /// Value to compare with. + /// Modifications of this tool's options to apply for this call. + /// Optional failure details to include. + /// Chainer to make additional assertions with. + /// If value does not match . + private void HandleMathCheck( + Func math, + string description, + IComparable? target, + IComparable? value, + AsserterMod? optionConfiguration, + string? details + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (value == null) + { + throw new AssertException( + $"Value was null and not {description} '{target}'.", + details, + localOptions.Gen.InitialSeed + ); + } + else if (target == null) + { + throw new AssertException( + "Target was null and not valid for math comparison check.", + details, + localOptions.Gen.InitialSeed, + value.ToString() + ); + } + else if (!math()) + { + throw new AssertException( + $"Value was not {description} '{target}'.", + details, + localOptions.Gen.InitialSeed, + value.ToString() + ); + } + } +} diff --git a/src/Toolbox/AsserterTool/Implementation/Asserter.Delegate.cs b/src/Toolbox/AsserterTool/Implementation/Asserter.Delegate.cs new file mode 100644 index 00000000..490cc63a --- /dev/null +++ b/src/Toolbox/AsserterTool/Implementation/Asserter.Delegate.cs @@ -0,0 +1,303 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.ExceptionServices; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterDelegate +{ + /// + public virtual T Throws(Delegate? behavior, string? details = null) + where T : Exception + { + return Throws(behavior, Unconfigured, details); + } + + /// + public virtual T Throws( + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + VerifyCanCall(behavior, localOptions, details); + + string errorMessage = + $"Expected exception of type '{GenericConverter.ExpandName()}' but received: "; + try + { + JustInvoke(behavior); + } + catch (Exception e) + { + return UnwrapException(e, errorMessage, localOptions, details); + } + + throw new AssertException(errorMessage + "None", details, localOptions.Gen.InitialSeed); + } + + /// + public virtual Exception ThrowsException(Delegate? behavior, string? details = null) + { + return ThrowsException(behavior, Unconfigured, details); + } + + /// + public virtual Exception ThrowsException( + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return Throws(behavior, optionConfiguration, details); + } + + [ExcludeFromCodeCoverage] // Captured rethrow impossible to reach ending bracket. + private static T UnwrapException( + Exception e, + string errorMessage, + AsserterOptions localOptions, + string? details + ) + where T : Exception + { + if (localOptions.DisableCatchingForThrowAsserts) + { + ExceptionDispatchInfo.Capture(e).Throw(); + } + + if (e is T noWrap) + { + return noWrap; + } + + if (!localOptions.IncludeInternalExceptionForThrowAsserts) + { + throw new AssertException( + errorMessage + GenericConverter.ExpandName(e), + details, + localOptions.Gen.InitialSeed, + e + ); + } + + Exception? error = e.InnerException; + if (e is AggregateException agg) + { + if (agg.InnerExceptions.Count == 1) + { + error = agg.InnerExceptions[0]; + } + else + { + error = e; + } + } + + return error as T + ?? throw new AssertException( + errorMessage + GenericConverter.ExpandName(e), + details, + localOptions.Gen.InitialSeed, + e + ); + } + + /// + public virtual void ThrowsNo(Delegate? behavior, string? details = null) + where T : Exception + { + ThrowsNo(behavior, Unconfigured, details); + } + + /// + public virtual void ThrowsNo( + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + VerifyCanCall(behavior, localOptions, details); + try + { + JustInvoke(behavior); + } + catch (Exception e) + { + if (e is T) + { + throw new AssertException( + $"Expected no exception of type '{typeof(T).Name}'.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + } + } + + /// + public virtual void ThrowsNoException(Delegate? behavior, string? details = null) + { + ThrowsNoException(behavior, Unconfigured, details); + } + + /// + public virtual void ThrowsNoException( + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ThrowsNo(behavior, optionConfiguration, details); + } + + /// + public virtual T HasResult(Delegate? behavior, string? details = null) + { + return HasResult(behavior, Unconfigured, details); + } + + /// + public virtual T HasResult( + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + VerifyCanCall(behavior, localOptions, details); + + object? result; + try + { + result = Invoke(behavior); + } + catch (Exception e) + { + throw new AssertException( + "Expected no exception.", + details, + localOptions.Gen.InitialSeed, + e + ); + } + + if (result is T data) + { + return data; + } + else + { + throw new AssertException( + $"Expected result type of '{GenericConverter.ExpandName()}," + + $" but was '{GenericConverter.ExpandName(result)}'.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public virtual T HasResult(T content, Delegate? behavior, string? details = null) + { + return HasResult(content, behavior, Unconfigured, details); + } + + /// + public virtual T HasResult( + T content, + Delegate? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + T result = HasResult(behavior, _ => localOptions, details); + Is(content, result, _ => localOptions, details); + return result; + } + + /// + public virtual Task HasResultAsync( + T content, + Delegate? behavior, + CancellationToken canceler, + string? details = null + ) + { + return HasResultAsync(content, behavior, canceler, Unconfigured, details); + } + + /// + public virtual async Task HasResultAsync( + T content, + Delegate? behavior, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + T result = HasResult(behavior, _ => localOptions, details); + await IsAsync(content, result, canceler, _ => localOptions, details).ConfigureAwait(false); + return result; + } + + private static void VerifyCanCall(Delegate? behavior, AsserterOptions options, string? details) + { + if (behavior is null) + { + return; + } + + if (behavior.Method.GetParameters().Length != 0) + { + throw new AssertException( + "Delegate to test must not require an instance or arguments.", + details, + options.Gen.InitialSeed + ); + } + } + + private static void JustInvoke(Delegate? behavior) + { + Disposer.Cleanup(Invoke(behavior)); + } + + [ExcludeFromCodeCoverage] // Rethrow impossible to reach. + private static object? Invoke(Delegate? behavior) + { + if (behavior is Action action) + { + action.Invoke(); + return VoidType.Instance; + } + else + { + try + { + return behavior?.DynamicInvoke([]); + } + catch (TargetInvocationException e) + { + ExceptionDispatchInfo.Capture(e.InnerException!).Throw(); + throw; + } + } + } +} diff --git a/src/Toolbox/AsserterTool/Implementation/Asserter.Enumerable.cs b/src/Toolbox/AsserterTool/Implementation/Asserter.Enumerable.cs new file mode 100644 index 00000000..5689b6e6 --- /dev/null +++ b/src/Toolbox/AsserterTool/Implementation/Asserter.Enumerable.cs @@ -0,0 +1,578 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterEnumerable +{ + /// + [DoesNotReturn, ExcludeFromCodeCoverage] + public virtual void Fail(IEnumerable? collection, string? details = null) + { + Fail(collection, Unconfigured, details); + } + + /// + [DoesNotReturn] + public virtual void Fail( + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + throw new AssertException( + "Test failed.", + details, + localOptions.Gen.InitialSeed, + AsString(collection, localOptions) + ); + } + + private static string? AsString(IEnumerable? collection, AsserterOptions localOptions) + { + if (collection == null) + { + return null; + } + else if (collection is string text) + { + return text; + } + else + { + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + return contents.ToString(); + } + } + + /// + public void Debug(IEnumerable? collection, string? details = null) + { + Debug(collection, Unconfigured, details); + } + + /// + public void Debug( + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + string? content = AsString(collection, localOptions); + + if (localOptions.TriggerFailureForDebugAsserts) + { + throw new AssertException( + $"{nameof(AsserterOptions.TriggerFailureForDebugAsserts)} set to '{true}'.", + details, + localOptions.Gen.InitialSeed, + content + ); + } + } + + /// + public virtual void IsEmpty(IEnumerable? collection, string? details = null) + { + IsEmpty(collection, Unconfigured, details); + } + + /// + public virtual void IsEmpty( + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + HasCount(0, collection, optionConfiguration, details); + } + + /// + public virtual void IsNotEmpty(IEnumerable? collection, string? details = null) + { + IsNotEmpty(collection, Unconfigured, details); + } + + /// + public virtual void IsNotEmpty( + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + "Expected collection with elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + IEnumerator gen = collection.GetEnumerator(); + try + { + if (!gen.MoveNext()) + { + throw new AssertException( + "Expected collection with elements, but was empty.", + details, + localOptions.Gen.InitialSeed + ); + } + } + finally + { + Disposer.Cleanup(gen); + } + } + + /// + public virtual void HasCount(int count, IEnumerable? collection, string? details = null) + { + HasCount(count, collection, Unconfigured, details); + } + + /// + public virtual void HasCount( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '{count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (i != count) + { + throw new AssertException( + $"Expected collection of '{count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual void HasCountLessThan(int count, IEnumerable? collection, string? details = null) + { + HasCountLessThan(count, collection, Unconfigured, details); + } + + /// + public virtual void HasCountLessThan( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '< {count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (i >= count) + { + throw new AssertException( + $"Expected collection of '< {count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual void HasCountLessOrExactly( + int count, + IEnumerable? collection, + string? details = null + ) + { + HasCountLessOrExactly(count, collection, Unconfigured, details); + } + + /// + public virtual void HasCountLessOrExactly( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '<= {count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (i > count) + { + throw new AssertException( + $"Expected collection of '<= {count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual void HasCountMoreThan(int count, IEnumerable? collection, string? details = null) + { + HasCountMoreThan(count, collection, Unconfigured, details); + } + + /// + public virtual void HasCountMoreThan( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '> {count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (i <= count) + { + throw new AssertException( + $"Expected collection of '> {count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual void HasCountMoreOrExactly( + int count, + IEnumerable? collection, + string? details = null + ) + { + HasCountMoreOrExactly(count, collection, Unconfigured, details); + } + + /// + public virtual void HasCountMoreOrExactly( + int count, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection of '>= {count}' elements, but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (i < count) + { + throw new AssertException( + $"Expected collection of '>= {count}' elements, but was '{i}'.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual void Contains(object? content, IEnumerable? collection, string? details = null) + { + Contains(content, collection, Unconfigured, details); + } + + /// + public virtual void Contains( + object? content, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection to contain '{content}', but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + bool found = false; + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + + found |= localOptions.Valuer.Equals(content, item); + + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (!found) + { + throw new AssertException( + $"Expected collection to contain '{content}' but didn't.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual Task ContainsAsync( + object? content, + IEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return ContainsAsync(content, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task ContainsAsync( + object? content, + IEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + throw new AssertException( + $"Expected collection to contain '{content}', but was 'null'.", + details, + localOptions.Gen.InitialSeed + ); + } + + bool found = false; + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + + found |= await localOptions + .Valuer.EqualsAsync(content, item, canceler) + .ConfigureAwait(false); + + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (!found) + { + throw new AssertException( + $"Expected collection to contain '{content}' but didn't.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual void ContainsNot( + object? content, + IEnumerable? collection, + string? details = null + ) + { + ContainsNot(content, collection, Unconfigured, details); + } + + /// + public virtual void ContainsNot( + object? content, + IEnumerable? collection, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + return; + } + + bool notFound = true; + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + + notFound &= !localOptions.Valuer.Equals(content, item); + + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (!notFound) + { + throw new AssertException( + $"Expected collection to not contain '{content}' but did.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public virtual Task ContainsNotAsync( + object? content, + IEnumerable? collection, + CancellationToken canceler, + string? details = null + ) + { + return ContainsNotAsync(content, collection, canceler, Unconfigured, details); + } + + /// + public virtual async Task ContainsNotAsync( + object? content, + IEnumerable? collection, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (collection == null) + { + return; + } + + bool notFound = true; + StringBuilder contents = new(); + + int i = 0; + foreach (object item in collection) + { + ArgumentGuard.ThrowUponIterationLimit(i, localOptions.Design.IterationLimit); + + notFound &= !await localOptions + .Valuer.EqualsAsync(content, item, canceler) + .ConfigureAwait(false); + + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + + if (!notFound) + { + throw new AssertException( + $"Expected collection to not contain '{content}' but did.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } +} diff --git a/src/Toolbox/AsserterTool/Implementation/Asserter.Error.cs b/src/Toolbox/AsserterTool/Implementation/Asserter.Error.cs new file mode 100644 index 00000000..33c417a6 --- /dev/null +++ b/src/Toolbox/AsserterTool/Implementation/Asserter.Error.cs @@ -0,0 +1,52 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.AsserterTool.Categories; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterError +{ + /// + [DoesNotReturn, ExcludeFromCodeCoverage] + public virtual void Fail(Exception? exception, string? details = null) + { + Fail(exception, Unconfigured, details); + } + + /// + [DoesNotReturn] + public virtual void Fail( + Exception? exception, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + throw new AssertException("Test failed.", details, localOptions.Gen.InitialSeed, exception); + } + + /// + public void Debug(Exception? exception, string? details = null) + { + Debug(exception, Unconfigured, details); + } + + /// + public void Debug( + Exception? exception, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (localOptions.TriggerFailureForDebugAsserts) + { + throw new AssertException( + $"{nameof(AsserterOptions.TriggerFailureForDebugAsserts)} set to '{true}'.", + details, + localOptions.Gen.InitialSeed, + exception + ); + } + } +} diff --git a/src/Toolbox/AsserterTool/Implementation/Asserter.Func.cs b/src/Toolbox/AsserterTool/Implementation/Asserter.Func.cs new file mode 100644 index 00000000..9b371378 --- /dev/null +++ b/src/Toolbox/AsserterTool/Implementation/Asserter.Func.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.AsserterTool.Categories; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterFunc +{ + /// + public virtual T HasResult(Func? behavior, string? details = null) + { + return HasResult(behavior, Unconfigured, details); + } + + /// + public virtual T HasResult( + Func? behavior, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return HasResult((Delegate?)behavior, optionConfiguration, details); + } +} diff --git a/src/Toolbox/AsserterTool/Implementation/Asserter.Object.cs b/src/Toolbox/AsserterTool/Implementation/Asserter.Object.cs new file mode 100644 index 00000000..9c86c3f9 --- /dev/null +++ b/src/Toolbox/AsserterTool/Implementation/Asserter.Object.cs @@ -0,0 +1,405 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterObject +{ + /// + public void Is(object? expected, object? actual, string? details = null) + { + Is(expected, actual, Unconfigured, details); + } + + /// + public void Is( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ValuesEqual(expected, actual, optionConfiguration, details); + } + + /// + public void IsNull(object? actual, string? details = null) + { + IsNull(actual, Unconfigured, details); + } + + /// + public void IsNull(object? actual, AsserterMod? optionConfiguration, string? details = null) + { + ReferenceEqual(null, actual, optionConfiguration, details); + } + + /// + public void IsNot(object? expected, object? actual, string? details = null) + { + IsNot(expected, actual, Unconfigured, details); + } + + /// + public void IsNot( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ValuesNotEqual(expected, actual, optionConfiguration, details); + } + + /// + public void IsNotNull([NotNull] object? actual, string? details = null) + { + IsNotNull(actual, Unconfigured, details); + } + +#pragma warning disable CS8777 // Is accounted for. + + /// + public void IsNotNull( + [NotNull] object? actual, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ReferenceNotEqual(null, actual, optionConfiguration, details); + } + +#pragma warning restore CS8777 + + /// + public virtual void ReferenceEqual(object? expected, object? actual, string? details = null) + { + ReferenceEqual(expected, actual, Unconfigured, details); + } + + /// + public virtual void ReferenceEqual( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (!ReferenceEquals(expected, actual)) + { + throw new AssertException( + "References failed to equal.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public virtual void ReferenceNotEqual(object? expected, object? actual, string? details = null) + { + ReferenceNotEqual(expected, actual, Unconfigured, details); + } + + /// + public virtual void ReferenceNotEqual( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (ReferenceEquals(expected, actual)) + { + throw new AssertException( + "References failed to not equal.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public virtual void ValuesEqual(object? expected, object? actual, string? details = null) + { + ValuesEqual(expected, actual, Unconfigured, details); + } + + /// + public virtual void ValuesEqual( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + Difference[] differences = [.. localOptions.Valuer.Compare(expected, actual)]; + if (differences.Length > 0) + { + throw new AssertException( + $"Value equality failed for type '{GetTypeName(expected, actual)}'.", + details, + localOptions.Gen.InitialSeed, + string.Join(Environment.NewLine, differences) + ); + } + } + + /// + public virtual void ValuesNotEqual(object? expected, object? actual, string? details = null) + { + ValuesNotEqual(expected, actual, Unconfigured, details); + } + + /// + public virtual void ValuesNotEqual( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (localOptions.Valuer.Equals(expected, actual)) + { + throw new AssertException( + $"Value inequality failed for type '{GetTypeName(expected, actual)}'.", + details, + localOptions.Gen.InitialSeed, + expected?.ToString() + ); + } + } + + /// + public virtual void AreUnique(object? expected, object? actual, string? details = null) + { + AreUnique(expected, actual, Unconfigured, details); + } + + /// + public virtual void AreUnique( + object? expected, + object? actual, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + ReferenceNotEqual(expected, actual, details); + + int i = 0; + StringBuilder contents = new(); + foreach ( + object value in localOptions + .Extractor.Extract(actual) + .FindSharedContent(localOptions.Extractor.Extract(expected)) + ) + { + _ = contents.Append('#').Append(i++).Append(':').Append(value).AppendLine(); + } + + if (i != 0) + { + throw new AssertException( + $"Expected no shared content, but had '{i}' shared items.", + details, + localOptions.Gen.InitialSeed, + contents.ToString() + ); + } + } + + /// + public void Inherits(object? instance, string? details = null) + { + Inherits(instance, Unconfigured, details); + } + + /// + public void Inherits( + object? instance, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + Type? type = instance is Type asType ? asType : instance?.GetType(); + + if (!type.Inherits()) + { + throw new AssertException( + $"'{GenericConverter.ExpandName(type)}' does not inherit '{GenericConverter.ExpandName()}'.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public void Inherits(Type? parent, object? instance, string? details = null) + { + Inherits(parent, instance, Unconfigured, details); + } + + /// + public void Inherits( + Type? parent, + object? instance, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + Type? type = instance is Type asType ? asType : instance?.GetType(); + + if (!type.Inherits(parent)) + { + throw new AssertException( + $"'{GenericConverter.ExpandName(type)}' does not inherit '{GenericConverter.ExpandName(parent)}'.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public void InheritedBy(object? instance, string? details = null) + { + InheritedBy(instance, Unconfigured, details); + } + + /// + public void InheritedBy( + object? instance, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + Type? type = instance is Type asType ? asType : instance?.GetType(); + + if (!type.IsInheritedBy()) + { + throw new AssertException( + $"'{GenericConverter.ExpandName()}' does not inherit '{GenericConverter.ExpandName(type)}'.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public void InheritedBy(Type? child, object? instance, string? details = null) + { + InheritedBy(child, instance, Unconfigured, details); + } + + /// + public void InheritedBy( + Type? child, + object? instance, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + Type? type = instance is Type asType ? asType : instance?.GetType(); + + if (!type.IsInheritedBy(child)) + { + throw new AssertException( + $"'{GenericConverter.ExpandName(child)}' does not inherit '{GenericConverter.ExpandName(type)}'.", + details, + localOptions.Gen.InitialSeed + ); + } + } + + /// + public virtual void Called(object? fake, AsserterMod? optionConfiguration = null) + { + Called(fake, Times.AtLeast(1), Unconfigured); + } + + /// + public virtual void Called(object? fake, Times total, AsserterMod? optionConfiguration = null) + { + ReferenceNotEqual(null, fake); + if (fake is IFaked actualFake) + { + new Fake(actualFake).Verify(total); + } + else + { + throw new ToolException( + $"{nameof(Called)} assertion can only be used on {nameof(IFaked)} " + + $"instances and not the provided {GenericConverter.ExpandName(fake)}." + ); + } + } + + /// + [DoesNotReturn, ExcludeFromCodeCoverage] + public virtual void Fail(object? content, string? details = null) + { + Fail(content, Unconfigured, details); + } + + /// + [DoesNotReturn] + public virtual void Fail( + object? content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + throw new AssertException( + "Test failed.", + details, + localOptions.Gen.InitialSeed, + content?.ToString() + ); + } + + /// + public void Debug(object? content, string? details = null) + { + Debug(content, Unconfigured, details); + } + + /// + public void Debug(object? content, AsserterMod? optionConfiguration, string? details = null) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + + string? text = content?.ToString(); + + if (localOptions.TriggerFailureForDebugAsserts) + { + throw new AssertException( + $"{nameof(AsserterOptions.TriggerFailureForDebugAsserts)} set to '{true}'.", + details, + localOptions.Gen.InitialSeed, + text + ); + } + } +} diff --git a/src/Toolbox/AsserterTool/Implementation/Asserter.String.cs b/src/Toolbox/AsserterTool/Implementation/Asserter.String.cs new file mode 100644 index 00000000..46fb6f5d --- /dev/null +++ b/src/Toolbox/AsserterTool/Implementation/Asserter.String.cs @@ -0,0 +1,234 @@ +using Werecodent.CreateAndFake.AsserterTool.Categories; + +namespace Werecodent.CreateAndFake.AsserterTool; + +/// +public partial class Asserter : IAsserterString +{ + /// + public virtual void Contains(string content, string? text, string? details = null) + { + Contains(content, text, Unconfigured, details); + } + + /// + public virtual void Contains( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if ( + text == null + || text.IndexOf(content, localOptions.ComparisonModeForStringAsserts) == -1 + ) + { + throw new AssertException( + $"Text was missing '{content}'.", + details, + localOptions.Gen.InitialSeed, + text + ); + } + } + + /// + public virtual void ContainsNot(string content, string? text, string? details = null) + { + ContainsNot(content, text, Unconfigured, details); + } + + /// + public virtual void ContainsNot( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (text?.IndexOf(content, localOptions.ComparisonModeForStringAsserts) >= 0) + { + throw new AssertException( + $"Text contained '{content}'.", + details, + localOptions.Gen.InitialSeed, + text + ); + } + } + + /// + public void StartsWith(char content, string? text, string? details = null) + { + StartsWith(content, text, Unconfigured, details); + } + + /// + public void StartsWith( + char content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + StartsWith(content.ToString(), text, optionConfiguration, details); + } + + /// + public virtual void StartsWith(string content, string? text, string? details = null) + { + StartsWith(content, text, Unconfigured, details); + } + + /// + public virtual void StartsWith( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (text?.StartsWith(content, localOptions.ComparisonModeForStringAsserts) != true) + { + throw new AssertException( + $"Text did not start with '{content}'.", + details, + localOptions.Gen.InitialSeed, + text + ); + } + } + + /// + public void StartsNotWith(char content, string? text, string? details = null) + { + StartsNotWith(content, text, Unconfigured, details); + } + + /// + public void StartsNotWith( + char content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + StartsNotWith(content.ToString(), text, optionConfiguration, details); + } + + /// + public virtual void StartsNotWith(string content, string? text, string? details = null) + { + StartsNotWith(content, text, Unconfigured, details); + } + + /// + public virtual void StartsNotWith( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (text?.StartsWith(content, localOptions.ComparisonModeForStringAsserts) == true) + { + throw new AssertException( + $"Text started with '{content}'.", + details, + localOptions.Gen.InitialSeed, + text + ); + } + } + + /// + public void EndsWith(char content, string? text, string? details = null) + { + EndsWith(content, text, Unconfigured, details); + } + + /// + public void EndsWith( + char content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + EndsWith(content.ToString(), text, optionConfiguration, details); + } + + /// + public virtual void EndsWith(string content, string? text, string? details = null) + { + EndsWith(content, text, Unconfigured, details); + } + + /// + public virtual void EndsWith( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (text?.EndsWith(content, localOptions.ComparisonModeForStringAsserts) != true) + { + throw new AssertException( + $"Text did not end with '{content}'.", + details, + localOptions.Gen.InitialSeed, + text + ); + } + } + + /// + public void EndsNotWith(char content, string? text, string? details = null) + { + EndsNotWith(content, text, Unconfigured, details); + } + + /// + public void EndsNotWith( + char content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + EndsNotWith(content.ToString(), text, optionConfiguration, details); + } + + /// + public virtual void EndsNotWith(string content, string? text, string? details = null) + { + EndsNotWith(content, text, Unconfigured, details); + } + + /// + public virtual void EndsNotWith( + string content, + string? text, + AsserterMod? optionConfiguration, + string? details = null + ) + { + AsserterOptions localOptions = ApplyConfiguration(optionConfiguration); + if (text?.EndsWith(content, localOptions.ComparisonModeForStringAsserts) == true) + { + throw new AssertException( + $"Text ended with '{content}'.", + details, + localOptions.Gen.InitialSeed, + text + ); + } + } +} diff --git a/src/Toolbox/ConfiguredDesignOptions.cs b/src/Toolbox/ConfiguredDesignOptions.cs new file mode 100644 index 00000000..fe645c00 --- /dev/null +++ b/src/Toolbox/ConfiguredDesignOptions.cs @@ -0,0 +1,34 @@ +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Properties; + +namespace Werecodent.CreateAndFake; + +/// +public sealed record ConfiguredDesignOptions : DesignOptions +{ + /// Identifies the configuration section containing these settings. + internal static string ConfigSectionName { get; } = "Design"; + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal ConfiguredDesignOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + Seed = Config.GetValue(section, Seed), + IterationLimit = Config.GetValue(section, IterationLimit), + IncludeInfinityAndNaNGeneration = Config.GetValue( + section, + IncludeInfinityAndNaNGeneration + ), + }; + } +} diff --git a/src/Toolbox/CreateAndFake.csproj b/src/Toolbox/CreateAndFake.csproj new file mode 100644 index 00000000..1373efb3 --- /dev/null +++ b/src/Toolbox/CreateAndFake.csproj @@ -0,0 +1,26 @@ + + + + net11.0;net10.0;netstandard2.0 + + + + LEGACY + + + + A C# class library that handles mocking, test data generation, and validation. + + + + + + + + + + + + + + diff --git a/src/Toolbox/DuplicatorTool/Duplicator.cs b/src/Toolbox/DuplicatorTool/Duplicator.cs new file mode 100644 index 00000000..9bae026d --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Duplicator.cs @@ -0,0 +1,57 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool; + +/// +/// +/// If given a parameter. +public sealed class Duplicator(DuplicatorOptions options) : IDuplicator +{ + /// Handles hint based duplication. + private static readonly DuplicatorEngine _Engine = new(); + + /// + public DuplicatorOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public IEnumerable SupportedTypes => _Engine.SupportedTypes; + + /// + [return: NotNullIfNotNull(nameof(source))] + public T Copy(T source, DuplicatorMod? optionConfiguration = null) + { + DuplicatorOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + T result = new DuplicatorChainer(localOptions, _Engine).Copy(source); + if (localOptions.VerifyEqualityForClones) + { + Options.Asserter.ValuesEqual( + source, + result, + opt => + opt with + { + Valuer = opt.Valuer.WithOptions(valuer => + valuer with + { + SkipAsyncValues = true, + } + ), + }, + $"Type '{source?.GetType()}' did not clone properly and was unequal. " + + "Verify/create a hint to generate the type and pass it to the duplicator." + ); + } + return result; + } + + /// + public IDuplicator WithOptions(DuplicatorMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Duplicator(optionConfiguration.Invoke(Options)); + } +} diff --git a/src/Toolbox/DuplicatorTool/DuplicatorOptions.cs b/src/Toolbox/DuplicatorTool/DuplicatorOptions.cs new file mode 100644 index 00000000..b2b504e1 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/DuplicatorOptions.cs @@ -0,0 +1,53 @@ +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.DuplicatorTool; + +/// Settings for manipulating behavior. +public sealed record DuplicatorOptions : ToolHintOptions +{ + /// Identifier for the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Duplicator); + + /// + public required IAsserter Asserter { get; init; } + + /// + public required IExtractor Extractor { get; init; } + + /// If generated clones are compared to their original source before being returned. + /// + /// Useful for ensuring cloning is successfully accomplished by the . + /// is overridden to + /// for this verification in order to prevent s. + /// + /// + [ConfigurableOption] + public bool VerifyEqualityForClones { get; init; } = true; + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal DuplicatorOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + VerifyEqualityForClones = Config.GetValue(section, VerifyEqualityForClones), + IncludeFrameworkHints = Config.GetValue(section, IncludeFrameworkHints), + IncludeFoundHints = Config.GetValue(section, IncludeFoundHints), + MaxRecursionDepth = Config.GetValue(section, MaxRecursionDepth), + }; + } +} diff --git a/src/Toolbox/DuplicatorTool/Engine/CopyHint.cs b/src/Toolbox/DuplicatorTool/Engine/CopyHint.cs new file mode 100644 index 00000000..76321b82 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/CopyHint.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +/// +public abstract class CopyHint : ICopyHint +{ + /// + public abstract int EnginePriority { get; } + + /// + public abstract IEnumerable SupportedTypes { get; } + + /// + public abstract CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator); + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/DuplicatorTool/Engine/CopyHintResult.cs b/src/Toolbox/DuplicatorTool/Engine/CopyHintResult.cs new file mode 100644 index 00000000..415706a5 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/CopyHintResult.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +/// +public sealed class CopyHintResult : HintResult +{ + /// For when a hint doesn't support a type or fails to copy it. + public static CopyHintResult None { get; } = new(false, null); + + /// + private CopyHintResult(bool hasData, object? data) + : base(hasData, data) { } + + /// + public CopyHintResult(object? data) + : this(true, data) { } +} diff --git a/src/Toolbox/DuplicatorTool/Engine/CopyHint{T}.cs b/src/Toolbox/DuplicatorTool/Engine/CopyHint{T}.cs new file mode 100644 index 00000000..e6e2c7d2 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/CopyHint{T}.cs @@ -0,0 +1,28 @@ +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +/// being supported for cloning. +/// +public abstract class CopyHint : CopyHint +{ + /// + public override IEnumerable SupportedTypes => [typeof(T)]; + + /// + public sealed override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + if (source is T data) + { + return new(Copy(data, duplicator)); + } + else + { + return CopyHintResult.None; + } + } + + /// Deep clones . + /// Object to clone. + /// Handles cloning child values. + /// Clone of . + protected abstract T Copy(T source, IDuplicatorChainer duplicator); +} diff --git a/src/Toolbox/DuplicatorTool/Engine/CopyPriority.cs b/src/Toolbox/DuplicatorTool/Engine/CopyPriority.cs new file mode 100644 index 00000000..86e2f682 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/CopyPriority.cs @@ -0,0 +1,65 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +/// Priorities for s. +public enum CopyPriority +{ + /// Priority for hints that won't automatically execute. + /// Such hints only work if given to the tool via . + Disabled = int.MinValue, + + /// Priority for custom hints that'll execute last. + /// Subtract from this priority for even lower priorities. + None = 0, + + /// Priority for . + ObjectHint = 1, + + /// Priority for . + SerializableHint = 2, + + /// Priority for . + CloneableHint = 3, + + /// Priority for . + StreamHint = 4, + + /// Priority for . + CollectionHint = 5, + + /// Priority for . + ImmutableCollectionHint = 6, + + /// Priority for . + FrozenCollectionHint = 7, + + /// Priority for . + AsyncCollectionHint = 8, + + /// Priority for . + AsyncDesignHint = 9, + + /// Priority for . + BasicHint = 10, + + /// Priority for . + DuplicatableHint = 11, + + /// Priority for . + DeepCloneableHint = 12, + + /// Priority for . + ValueTaskHint = 13, + + /// Priority for . + TaskHint = 14, + + /// Priority for . + HandlerHint = 15, + + /// Starting priority for custom hints that'll execute first. + /// Add to this priority for even higher priorities. + Highest = 16, +} diff --git a/src/Toolbox/DuplicatorTool/Engine/DuplicatorChainer.cs b/src/Toolbox/DuplicatorTool/Engine/DuplicatorChainer.cs new file mode 100644 index 00000000..28acb540 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/DuplicatorChainer.cs @@ -0,0 +1,97 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +#pragma warning disable IDE0028 // Invalid because it's not constructible. + +/// Provides a callback into to create child values. +public sealed class DuplicatorChainer + : ToolChainer, + IDuplicatorChainer +{ + /// History of clones to match up references. + private readonly ConditionalWeakTable _history; + + /// + public DuplicatorChainer(DuplicatorOptions options, IDuplicatorEngine engine) + : base(options, engine) + { + _history = new ConditionalWeakTable(); + } + + /// + private DuplicatorChainer(DuplicatorOptions options, DuplicatorChainer prevChainer) + : base(options, prevChainer) + { + _history = prevChainer._history; + } + + /// + protected override DuplicatorChainer CreateSubChainer(DuplicatorOptions subOptions) + { + return new DuplicatorChainer(subOptions, this); + } + + /// + public object? AddToHistory(object source, object clone) + { + if (CanTrack(source)) + { + if (_history.TryGetValue(source, out object? existingClone)) + { + return existingClone; + } + _history.Add(source, clone); + } + return null; + } + + /// + [return: NotNullIfNotNull(nameof(source))] + public T Copy(T source, DuplicatorMod? optionConfiguration = null) + { + return (T?)Copy((object?)source, optionConfiguration)!; + } + + /// + [return: NotNullIfNotNull(nameof(source))] + public object? Copy(object? source, DuplicatorMod? optionConfiguration = null) + { + if (!CanTrack(source)) + { + return Engine.Copy(source, GetSubChainer(optionConfiguration)); + } + + if (_history.TryGetValue(source, out object? clone)) + { + return clone!; + } + + object? result = Engine.Copy(source, GetSubChainer(optionConfiguration)); + if (!_history.TryGetValue(source, out _)) + { + _history.Add(source, result); + } + return result; + } + + /// If can be tracked in history. + /// Item to check. + /// if possible, otherwise. + private static bool CanTrack([NotNullWhen(true)] object? source) + { + return source?.GetType().IsValueType == false; + } + + /// + public IDuplicator WithOptions(DuplicatorMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new DuplicatorChainer(optionConfiguration.Invoke(Options), this); + } +} + +#pragma warning restore diff --git a/src/Toolbox/DuplicatorTool/Engine/DuplicatorEngine.cs b/src/Toolbox/DuplicatorTool/Engine/DuplicatorEngine.cs new file mode 100644 index 00000000..370659c6 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/DuplicatorEngine.cs @@ -0,0 +1,54 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +#pragma warning disable RCS1165, S2955 // Checking for only null specifically. + +/// +public sealed class DuplicatorEngine : ToolEngine, IDuplicatorEngine +{ + /// + [return: NotNullIfNotNull(nameof(source))] + public T Copy(T source, IDuplicatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (source == null) + { + return default!; + } + + CopyHintResult? result; + try + { + result = SelectHints(chainer) + .Select(h => h.TryCopy(source, chainer)) + .FirstOrDefault(r => r?.HasData ?? false); + } + catch (Exception e) + { + throw new ToolException( + $"Issue duplicating type '{GenericConverter.ExpandName(source)}'.", + e + ); + } + + if (result != null) + { + return (T)result.Data!; + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(source)}' not supported by the duplicator. " + + "Create a hint to generate the type and pass it to the duplicator." + ); + } + } +} + +#pragma warning restore diff --git a/src/Toolbox/DuplicatorTool/Engine/ICopyHandler.cs b/src/Toolbox/DuplicatorTool/Engine/ICopyHandler.cs new file mode 100644 index 00000000..16b5e393 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/ICopyHandler.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +/// Handles cloning of the . +internal interface ICopyHandler : ITypeSupporter +{ + /// Copies an instance of the specific type. + /// Object to clone. + /// Handles cloning child values. + /// The clone. + object? CopySupported(object source, IDuplicatorChainer duplicator); +} diff --git a/src/Toolbox/DuplicatorTool/Engine/ICopyHint.cs b/src/Toolbox/DuplicatorTool/Engine/ICopyHint.cs new file mode 100644 index 00000000..97fd4246 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/ICopyHint.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +/// Handles cloning of the . +public interface ICopyHint : IToolHint +{ + /// Tries to deep clone . + /// Object to clone. + /// Handles cloning child values. + /// Possible result. + CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator); +} diff --git a/src/Toolbox/DuplicatorTool/Engine/IDuplicatorChainer.cs b/src/Toolbox/DuplicatorTool/Engine/IDuplicatorChainer.cs new file mode 100644 index 00000000..082cae4a --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/IDuplicatorChainer.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +/// +public interface IDuplicatorChainer : IDuplicator, IToolChainer +{ + /// Adds successful clone details to history. + /// Object cloned. + /// The clone. + /// Existing clone if there already was one created for . + object? AddToHistory(object source, object clone); +} diff --git a/src/Toolbox/DuplicatorTool/Engine/IDuplicatorEngine.cs b/src/Toolbox/DuplicatorTool/Engine/IDuplicatorEngine.cs new file mode 100644 index 00000000..eb0e73e9 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Engine/IDuplicatorEngine.cs @@ -0,0 +1,13 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Engine; + +/// +public interface IDuplicatorEngine : IToolEngine +{ + /// Handles cloning child values. + /// + [return: NotNullIfNotNull(nameof(source))] + T Copy(T source, IDuplicatorChainer chainer); +} diff --git a/src/Toolbox/DuplicatorTool/Handlers/FactoryCopyHandler.cs b/src/Toolbox/DuplicatorTool/Handlers/FactoryCopyHandler.cs new file mode 100644 index 00000000..f8ed3557 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Handlers/FactoryCopyHandler.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +/// +/// Handles cloning via the . +/// +/// +/// Behavior handling cloning. +internal sealed class FactoryCopyHandler(Func factory) : ICopyHandler +{ + /// + public Type SupportedType { get; } = typeof(T); + + /// + public object? CopySupported(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(factory, source); + + return factory.Invoke((T)source, duplicator); + } +} diff --git a/src/Toolbox/DuplicatorTool/Handlers/LegacyCollectionCopyHandlers.cs b/src/Toolbox/DuplicatorTool/Handlers/LegacyCollectionCopyHandlers.cs new file mode 100644 index 00000000..e5fd440c --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Handlers/LegacyCollectionCopyHandlers.cs @@ -0,0 +1,90 @@ +using System.Collections; +using System.Collections.Specialized; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class LegacyCollectionCopyHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + [ + new FactoryCopyHandler(CreateAndCopyList), + new FactoryCopyHandler(CreateAndCopyDictionary), + new FactoryCopyHandler(CreateAndCopyDictionary), + new FactoryCopyHandler((data, _) => [.. data]), + new FactoryCopyHandler((data, _) => new BitArray(data)), + new FactoryCopyHandler(CreateAndCopyDictionary), + new FactoryCopyHandler(CreateAndCopyDictionary), + new FactoryCopyHandler((data, _) => [with(data)]), + new FactoryCopyHandler( + (data, copier) => new Queue(data.Cast().Select(d => copier.Copy(d)).ToArray()) + ), + new FactoryCopyHandler( + (data, copier) => + new Stack(data.Cast().Select(d => copier.Copy(d)).Reverse().ToArray()) + ), + new FactoryCopyHandler( + (data, _) => + { + StringDictionary result = []; + foreach (DictionaryEntry entry in data) + { + result.Add((string)entry.Key, (string?)entry.Value); + } + return result; + } + ), + new FactoryCopyHandler( + (data, duplicator) => + { + OrderedDictionary result = []; + + Dictionary transfer = []; + foreach (DictionaryEntry entry in data) + { + transfer.Add(entry.Key, entry.Value); + } + + for (int i = 0; i < data.Count; i++) + { + object? value = data[i]; + object key = transfer.First(entry => ReferenceEquals(entry.Value, value)).Key; + _ = transfer.Remove(key); + + result.Add(duplicator.Copy(key), duplicator.Copy(value)); + } + return result; + } + ), + ]; + + /// Clones . + /// Collection type being cloned. + /// Collection to clone. + /// Handles callback behavior for child values. + /// Clone of . + private static T CreateAndCopyList(T source, IDuplicatorChainer duplicator) + where T : IList, new() + { + T result = new(); + foreach (object item in source) + { + _ = result.Add(duplicator.Copy(item)); + } + return result; + } + + /// + private static T CreateAndCopyDictionary(T source, IDuplicatorChainer duplicator) + where T : IDictionary, new() + { + T result = new(); + foreach (DictionaryEntry entry in source) + { + result.Add(duplicator.Copy(entry.Key), duplicator.Copy(entry.Value)); + } + return result; + } +} diff --git a/src/Toolbox/DuplicatorTool/Handlers/RefCopyHandler.cs b/src/Toolbox/DuplicatorTool/Handlers/RefCopyHandler.cs new file mode 100644 index 00000000..1a207617 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Handlers/RefCopyHandler.cs @@ -0,0 +1,17 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +/// Prevents cloning of the . +/// Specific to prevent cloning of. +internal sealed class RefCopyHandler(Type supportedType) : ICopyHandler +{ + /// + public Type SupportedType { get; } = supportedType; + + /// + public object? CopySupported(object source, IDuplicatorChainer duplicator) + { + return source; + } +} diff --git a/src/Toolbox/DuplicatorTool/Handlers/ReflectionCopyHandlers.cs b/src/Toolbox/DuplicatorTool/Handlers/ReflectionCopyHandlers.cs new file mode 100644 index 00000000..56489c4f --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Handlers/ReflectionCopyHandlers.cs @@ -0,0 +1,15 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class ReflectionCopyHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + RuntimeDetails + .RuntimeTypes.Select(t => new RefCopyHandler(t)) + .Concat([new RefCopyHandler(typeof(AssemblyName))]); +} diff --git a/src/Toolbox/DuplicatorTool/Handlers/SelfCopyHandlers.cs b/src/Toolbox/DuplicatorTool/Handlers/SelfCopyHandlers.cs new file mode 100644 index 00000000..0170c850 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Handlers/SelfCopyHandlers.cs @@ -0,0 +1,41 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class SelfCopyHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + [ + new RefCopyHandler(typeof(AsserterOptions)), + new RefCopyHandler(typeof(DuplicatorOptions)), + new RefCopyHandler(typeof(ExtractorOptions)), + new RefCopyHandler(typeof(FakerOptions)), + new RefCopyHandler(typeof(MutatorOptions)), + new RefCopyHandler(typeof(RandomizerOptions)), + new RefCopyHandler(typeof(RunnerOptions)), + new RefCopyHandler(typeof(TesterOptions)), + new RefCopyHandler(typeof(ValuerOptions)), + new RefCopyHandler(typeof(ToolSet)), + new RefCopyHandler(typeof(Asserter)), + new RefCopyHandler(typeof(Duplicator)), + new RefCopyHandler(typeof(Extractor)), + new RefCopyHandler(typeof(Faker)), + new RefCopyHandler(typeof(Mutator)), + new RefCopyHandler(typeof(Randomizer)), + new RefCopyHandler(typeof(Runner)), + new RefCopyHandler(typeof(Tester)), + new RefCopyHandler(typeof(Valuer)), + new RefCopyHandler(typeof(DataRandom)), + ]; +} diff --git a/src/Toolbox/DuplicatorTool/Handlers/SystemCopyHandlers.cs b/src/Toolbox/DuplicatorTool/Handlers/SystemCopyHandlers.cs new file mode 100644 index 00000000..e185b13e --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Handlers/SystemCopyHandlers.cs @@ -0,0 +1,84 @@ +using System.Globalization; +using System.Numerics; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.Primitives; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class SystemCopyHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + [ + new FactoryCopyHandler((source, _) => new StringBuilder(source.ToString())), + new FactoryCopyHandler((source, _) => new Uri(source.OriginalString)), + new RefCopyHandler(typeof(TimeZoneInfo)), + new RefCopyHandler(typeof(ECCurve)), + new RefCopyHandler(typeof(string)), + new RefCopyHandler(typeof(object)), + new RefCopyHandler(typeof(StringSegmentComparer)), + new RefCopyHandler(typeof(RuntimeMethodHandle)), + new FactoryCopyHandler((source, _) => new Vector2(source.X, source.Y)), + new FactoryCopyHandler((source, _) => new Vector3(source.X, source.Y, source.Z)), + new FactoryCopyHandler( + (source, _) => new Vector4(source.X, source.Y, source.Z, source.W) + ), + new FactoryCopyHandler((source, _) => new UriBuilder(source.Uri)), + new FactoryCopyHandler( + (source, _) => source.IsReadOnly ? source : (DateTimeFormatInfo)source.Clone() + ), + new FactoryCopyHandler( + (source, _) => source.IsReadOnly ? source : (NumberFormatInfo)source.Clone() + ), + new FactoryCopyHandler( + (source, _) => source.IsReadOnly ? source : (CultureInfo)source.Clone() + ), + new FactoryCopyHandler( + (source, duplicator) => new StreamReader(duplicator.Copy(source.BaseStream)) + ), + new FactoryCopyHandler( + (source, duplicator) => + { + source.Flush(); + return new StreamWriter(duplicator.Copy(source.BaseStream)); + } + ), + new FactoryCopyHandler( + (source, _) => + { + CancellationTokenSource result = new(); + if (source.IsCancellationRequested) + { + result.Cancel(); + } + return result; + } + ), +#pragma warning disable S2930 // Must remain undisposed to last the life of the token. + new FactoryCopyHandler( + (source, _) => + { + if (source.CanBeCanceled) + { + CancellationTokenSource tokenSource = new(); + if (source.IsCancellationRequested) + { + tokenSource.Cancel(); + } + return tokenSource.Token; + } + else + { + return new CancellationToken(source.IsCancellationRequested); + } + } + ), +#pragma warning restore S2930 +#if NET9_0_OR_GREATER + new RefCopyHandler(typeof(Lock)), +#endif + ]; +} diff --git a/src/Toolbox/DuplicatorTool/Handlers/ValueCopyHandlers.cs b/src/Toolbox/DuplicatorTool/Handlers/ValueCopyHandlers.cs new file mode 100644 index 00000000..d438b818 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Handlers/ValueCopyHandlers.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class ValueCopyHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + ValueRandom.SupportedTypes.Select(t => new RefCopyHandler(t)); +} diff --git a/src/Toolbox/DuplicatorTool/Hints/AsyncCollectionCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/AsyncCollectionCopyHint.cs new file mode 100644 index 00000000..60feea98 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/AsyncCollectionCopyHint.cs @@ -0,0 +1,57 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +#pragma warning disable MA0079 // Should not cancel the source while canceling the clone. + +/// Handles cloning collections for . +public sealed class AsyncCollectionCopyHint : CopyHint +{ + /// + public override int EnginePriority => (int)CopyPriority.AsyncCollectionHint; + + /// + public override IEnumerable SupportedTypes => [typeof(IAsyncEnumerable<>)]; + + /// + public override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source, duplicator); + + if (source.GetType().Inherits(typeof(IAsyncEnumerable<>))) + { + return new(CopyAsync((dynamic)source, duplicator)); + } + else + { + return CopyHintResult.None; + } + } + + /// Item type being copied. + /// Aborts execution if triggered. + /// Iteration of cloned values. + /// + [ExcludeFromCodeCoverage] // Generated EnumeratorCancellation code can only be partially covered. + private static async IAsyncEnumerable CopyAsync( + IAsyncEnumerable source, + IDuplicatorChainer duplicator, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + int index = 0; + await foreach (T item in source.WithCancellation(canceler).ConfigureAwait(false)) + { + ArgumentGuard.ThrowUponIterationLimit( + index++, + duplicator.Options.Design.IterationLimit + ); + yield return duplicator.Copy(item); + } + } +} + +#pragma warning restore diff --git a/src/Toolbox/DuplicatorTool/Hints/AsyncDesignCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/AsyncDesignCopyHint.cs new file mode 100644 index 00000000..77b94aa9 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/AsyncDesignCopyHint.cs @@ -0,0 +1,61 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning collections for . +public sealed class AsyncDesignCopyHint : CopyHint +{ + /// + public override int EnginePriority => (int)CopyPriority.AsyncDesignHint; + + /// + public override IEnumerable SupportedTypes => [typeof(AsyncList<>)]; + + /// + public override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source, duplicator); + + Type type = source.GetType(); + Type? asGeneric = GenericConverter.AsGenericBase(type); + + if (asGeneric == typeof(AsyncList<>)) + { + return new(CopyListAsync((dynamic)source, duplicator)); + } + else if (asGeneric == typeof(AsyncHashSet<>)) + { + return new(CopySetAsync((dynamic)source, duplicator)); + } + else + { + return CopyHintResult.None; + } + } + + /// Item type being copied. + /// Iteration of cloned values. + /// + private static AsyncList CopyListAsync(AsyncList source, IDuplicatorChainer duplicator) + { + // Beware that 'duplicator.Copy' does not work in dynamic context for legacy .NET. + return new AsyncList(duplicator.Copy(source.Content), int.MaxValue); + } + + /// + private static AsyncHashSet CopySetAsync( + AsyncHashSet source, + IDuplicatorChainer duplicator + ) + { + return AsyncHashSet.CreateFromAsync( + duplicator.Copy(source.ByHashesAsync(CancellationToken.None)), + source.Comparer, + duplicator.Options.Design.IterationLimit, + CancellationToken.None + ); + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/BasicCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/BasicCopyHint.cs new file mode 100644 index 00000000..2a73798b --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/BasicCopyHint.cs @@ -0,0 +1,35 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +#pragma warning disable SYSLIB0050 // 'IObjectReference' is obsolete: Still needed for compatibility. + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning basic types for . +public sealed class BasicCopyHint : CopyHint +{ + /// + public override int EnginePriority => (int)CopyPriority.BasicHint; + + /// + public override IEnumerable SupportedTypes => []; + + /// + public sealed override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source); + + Type type = source.GetType(); + if (type.IsEnum || type.IsPrimitive || type.Inherits()) + { + return new(source); + } + else + { + return CopyHintResult.None; + } + } +} + +#pragma warning restore diff --git a/src/Toolbox/DuplicatorTool/Hints/CloneableCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/CloneableCopyHint.cs new file mode 100644 index 00000000..306dde2f --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/CloneableCopyHint.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning instances for . +public sealed class CloneableCopyHint : CopyHint +{ + /// + public override int EnginePriority => (int)CopyPriority.CloneableHint; + + /// + protected override ICloneable Copy(ICloneable source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source); + + return (ICloneable)source.Clone(); + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/CollectionCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/CollectionCopyHint.cs new file mode 100644 index 00000000..bf228328 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/CollectionCopyHint.cs @@ -0,0 +1,131 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning collections for . +public sealed class CollectionCopyHint : CopyHint +{ + /// Special cases where the data needs to be reversed. + private static readonly FrozenSet _ReverseCases = FrozenSet.ToFrozenSet([ + typeof(ConcurrentStack<>), + typeof(Stack<>), + typeof(Stack), + ]); + + /// + public override int EnginePriority => (int)CopyPriority.CollectionHint; + + /// + public override IEnumerable SupportedTypes => [typeof(IEnumerable)]; + + /// + public sealed override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(duplicator); + + if (source is IEnumerable collection) + { + IEnumerable? result = Copy(collection, duplicator); + if (result != null) + { + return new(result); + } + } + return CopyHintResult.None; + } + + private static IEnumerable? Copy(IEnumerable source, IDuplicatorChainer duplicator) + { + Type type = source.GetType(); + + Type itemType = + GenericConverter.AsConcreteType(type, typeof(IEnumerable<>))?.GetGenericArguments()[0] + ?? type.GetElementType() + ?? typeof(object); + + Array contents = CopyContents( + source, + itemType, + duplicator, + _ReverseCases.Contains(GenericConverter.AsGenericBase(type) ?? type) + ); + + return MakeCollection(contents, type); + } + + private static IEnumerable? MakeCollection(Array contents, Type collectionType) + { + if (collectionType.IsArray) + { + return contents; + } + else if (GenericConverter.AsGenericBase(collectionType) == typeof(Dictionary<,>)) + { + // Constructor missing in .NET 4.8. + dynamic result = Activator.CreateInstance(collectionType)!; + foreach (dynamic item in contents) + { + result.Add(item.Key, item.Value); + } + return result; + } + + foreach ( + ConstructorInfo constructor in TypeDescriber + .For(collectionType) + .Constructors.OnlyPublic.Where(c => c.GetParameters().Length == 1) + .Where(c => c.GetParameters()[0].ParameterType.IsInstanceOfType(contents)) + ) + { + return (IEnumerable)constructor.Invoke([contents]); + } + + return null; + } + + /// Copies the contents of . + /// Collection with contents to copy. + /// Collection item type. + /// Handles callback behavior for child values. + /// If the copy process should reverse the order of items from the enumerator. + /// The duplicate object. + /// + private static Array CopyContents( + IEnumerable source, + Type itemType, + IDuplicatorChainer duplicator, + bool reverse + ) + { + List copy = []; + + int index = 0; + foreach (object item in source) + { + ArgumentGuard.ThrowUponIterationLimit( + index++, + duplicator.Options.Design.IterationLimit + ); + copy.Add(duplicator.Copy(item)); + } + + if (reverse) + { + copy.Reverse(); + } + + Array result = Array.CreateInstance(itemType, copy.Count); + for (int i = 0; i < copy.Count; i++) + { + result.SetValue(copy[i], i); + } + return result; + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/DeepCloneableCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/DeepCloneableCopyHint.cs new file mode 100644 index 00000000..7ca9d4b0 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/DeepCloneableCopyHint.cs @@ -0,0 +1,41 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning instances for . +public sealed class DeepCloneableCopyHint : CopyHint +{ + /// + public override int EnginePriority => (int)CopyPriority.DeepCloneableHint; + + /// + public override IEnumerable SupportedTypes => [typeof(IDeepCloneable<>)]; + + /// + public override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source); + + Type sourceType = source.GetType(); + if (sourceType.Inherits(typeof(IDeepCloneable<>))) + { + Type cloneType; + try + { + cloneType = typeof(IDeepCloneable<>).MakeGenericType(sourceType); + } + catch (ArgumentException) + { + return CopyHintResult.None; + } + + return new(cloneType.GetMethod(nameof(IDeepCloneable<>.DeepClone))!.Invoke(source, [])); + } + else + { + return CopyHintResult.None; + } + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/DuplicatableCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/DuplicatableCopyHint.cs new file mode 100644 index 00000000..be6542ee --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/DuplicatableCopyHint.cs @@ -0,0 +1,42 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning instances for . +public sealed class DuplicatableCopyHint : CopyHint +{ + /// + public override int EnginePriority => (int)CopyPriority.DuplicatableHint; + + /// + public override IEnumerable SupportedTypes => [typeof(IDuplicatable<>)]; + + /// + public override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source); + + Type sourceType = source.GetType(); + if (sourceType.Inherits(typeof(IDuplicatable<>))) + { + Type cloneType; + try + { + cloneType = typeof(IDuplicatable<>).MakeGenericType(sourceType); + } + catch (ArgumentException) + { + return CopyHintResult.None; + } + + return new( + cloneType.GetMethod(nameof(IDuplicatable<>.DeepClone))!.Invoke(source, [duplicator]) + ); + } + else + { + return CopyHintResult.None; + } + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/FrozenCollectionCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/FrozenCollectionCopyHint.cs new file mode 100644 index 00000000..5ae4873a --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/FrozenCollectionCopyHint.cs @@ -0,0 +1,112 @@ +using System.Collections.Frozen; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning immutable collection types for . +public class FrozenCollectionCopyHint : CopyHint +{ + /// Constructs frozen sets. + private static readonly MethodInfo _SetMaker = typeof(FrozenSet).GetMethod( + nameof(FrozenSet.ToFrozenSet), + BindingFlags.Public | BindingFlags.Static + )!; + + /// Constructs frozen dictionaries. + private static readonly MethodInfo _DictionaryMaker = typeof(FrozenDictionary) + .GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(m => m.Name == nameof(FrozenDictionary.ToFrozenDictionary)) + .Single(m => m.GetParameters().Length == 2); + + /// Copies generic item data. + private static readonly MethodInfo _CopyContentsHelper = + typeof(FrozenCollectionCopyHint).GetMethod( + nameof(CopyContentsHelper), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + /// + public override int EnginePriority => (int)CopyPriority.FrozenCollectionHint; + + /// + public override IEnumerable SupportedTypes => + [typeof(FrozenSet<>), typeof(FrozenDictionary<,>)]; + + /// + public override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source); + + Type type = source.GetType(); + + if (type.Inherits(typeof(FrozenSet<>))) + { + Type itemType = type.GetInterfaces() + .Single(i => + i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>) + ) + .GetGenericArguments() + .Single(); + + return new( + _SetMaker + .MakeGenericMethod(itemType) + .Invoke( + null, + [ + _CopyContentsHelper + .MakeGenericMethod(itemType) + .Invoke(null, [source, duplicator]), + null, + ] + ) + ); + } + else if (type.Inherits(typeof(FrozenDictionary<,>))) + { + Type itemType = type.GetInterfaces() + .Single(i => + i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>) + ) + .GetGenericArguments() + .Single(); + + return new( + _DictionaryMaker + .MakeGenericMethod(itemType.GetGenericArguments()) + .Invoke( + null, + [ + _CopyContentsHelper + .MakeGenericMethod(itemType) + .Invoke(null, [source, duplicator]), + null, + ] + ) + ); + } + else + { + return CopyHintResult.None; + } + } + + /// Copies the contents of . + /// Content type being copied. + /// Collection with contents to copy. + /// Handles callback behavior for child values. + /// The duplicate object. + private static T?[] CopyContentsHelper(IEnumerable source, IDuplicatorChainer duplicator) + { + List copy = []; + + foreach (T? item in source) + { + copy.Add(duplicator.Copy(item)); + } + + return [.. copy]; + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/HandlerCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/HandlerCopyHint.cs new file mode 100644 index 00000000..37a025ec --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/HandlerCopyHint.cs @@ -0,0 +1,47 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning common types for . +public sealed class HandlerCopyHint : CopyHint +{ + /// Supported types and the methods used to generate them. + private static readonly ICopyHandler[] _Copiers = [new RefCopyHandler(typeof(TypeDescriber))]; + + private static readonly IDictionary _CopiersByType = + TypeSupporter.GroupBySupportedType( + _Copiers + .Concat(SelfCopyHandlers.Handlers) + .Concat(ValueCopyHandlers.Handlers) + .Concat(SystemCopyHandlers.Handlers) + .Concat(ReflectionCopyHandlers.Handlers) + .Concat(LegacyCollectionCopyHandlers.Handlers) + ); + + /// + public override int EnginePriority => (int)CopyPriority.HandlerHint; + + /// + public override IEnumerable SupportedTypes => _CopiersByType.Keys; + + /// + public sealed override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(duplicator); + + if ( + source != null + && _CopiersByType.TryGetValue(source.GetType(), out ICopyHandler? copier) + ) + { + return new(copier.CopySupported(source, duplicator)); + } + else + { + return CopyHintResult.None; + } + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/ImmutableCollectionCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/ImmutableCollectionCopyHint.cs new file mode 100644 index 00000000..2bbc28c8 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/ImmutableCollectionCopyHint.cs @@ -0,0 +1,120 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning immutable collection types for . +public class ImmutableCollectionCopyHint : CopyHint +{ + /// Collections able to be randomized. + private static readonly FrozenDictionary _Collections = new Dictionary< + Type, + MethodInfo + >() + { + { typeof(ImmutableList<>), FindCreateRangeBuilder(typeof(ImmutableList)) }, + { typeof(ImmutableArray<>), FindCreateRangeBuilder(typeof(ImmutableArray)) }, + { typeof(ImmutableQueue<>), FindCreateRangeBuilder(typeof(ImmutableQueue)) }, + { typeof(ImmutableStack<>), FindCreateRangeBuilder(typeof(ImmutableStack)) }, + { typeof(ImmutableHashSet<>), FindCreateRangeBuilder(typeof(ImmutableHashSet)) }, + { typeof(ImmutableSortedSet<>), FindCreateRangeBuilder(typeof(ImmutableSortedSet)) }, + { typeof(ImmutableDictionary<,>), FindCreateRangeBuilder(typeof(ImmutableDictionary)) }, + { + typeof(ImmutableSortedDictionary<,>), + FindCreateRangeBuilder(typeof(ImmutableSortedDictionary)) + }, + }.ToFrozenDictionary(); + + /// Finds the static CreateRange method for a collection. + /// Collection type to create. + /// Found create method. + private static MethodInfo FindCreateRangeBuilder(Type type) + { + return type.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Single(m => + m.Name == "CreateRange" + && m.GetParameters().Length == 1 + && m.GetParameters()[0].ParameterType.Inherits(typeof(IEnumerable<>)) + ); + } + + /// Copies generic item data. + private static readonly MethodInfo _CopyContentsHelper = + typeof(ImmutableCollectionCopyHint).GetMethod( + nameof(CopyContentsHelper), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + /// + public override int EnginePriority => (int)CopyPriority.ImmutableCollectionHint; + + /// + public override IEnumerable SupportedTypes => _Collections.Keys; + + /// + public override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source); + + Type type = source.GetType(); + Type? genericType = GenericConverter.AsGenericBase(type); + + if (genericType != null && _Collections.TryGetValue(genericType, out MethodInfo? match)) + { + Type[] args = type.GetGenericArguments(); + Type itemType = + (args.Length != 1) ? typeof(KeyValuePair<,>).MakeGenericType(args) : args.Single(); + + return new( + match + .MakeGenericMethod(args) + .Invoke( + null, + [ + _CopyContentsHelper + .MakeGenericMethod(itemType) + .Invoke( + null, + [source, duplicator, genericType == typeof(ImmutableStack<>)] + ), + ] + ) + ); + } + else + { + return CopyHintResult.None; + } + } + + /// Copies the contents of . + /// Content type being copied. + /// Collection with contents to copy. + /// Handles callback behavior for child values. + /// If the copy process should reverse the order of items from the enumerator. + /// The duplicate object. + private static T?[] CopyContentsHelper( + IEnumerable source, + IDuplicatorChainer duplicator, + bool reverse + ) + { + List copy = []; + + foreach (T? item in source) + { + copy.Add(duplicator.Copy(item)); + } + + if (reverse) + { + copy.Reverse(); + } + + return [.. copy]; + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/ObjectCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/ObjectCopyHint.cs new file mode 100644 index 00000000..d6d80758 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/ObjectCopyHint.cs @@ -0,0 +1,189 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning objects for . +public sealed class ObjectCopyHint : CopyHint +{ + /// + public override int EnginePriority => (int)CopyPriority.ObjectHint; + + /// + public override IEnumerable SupportedTypes => []; + + /// + public sealed override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source, duplicator); + + object? result = Copy(source, duplicator); + return (result != null) ? new(result) : CopyHintResult.None; + } + + /// + private static object? Copy(object source, IDuplicatorChainer duplicator) + { + object? dupe = CreateNew(source, duplicator); + if (dupe == null) + { + return dupe; + } + object? existing = duplicator.AddToHistory(source, dupe); + if (existing != null) + { + return existing; + } + + foreach ( + FieldInfo field in TypeDescriber + .For(source.GetType()) + .Fields.Visible.Where(f => !f.IsInitOnly && !f.IsLiteral) + ) + { + object? value = field.GetValue(source); + field.SetValue(dupe, duplicator.Copy(value)); + } + + foreach ( + PropertyInfo property in TypeDescriber + .For(source.GetType()) + .Properties.Visible.Where(p => p.CanRead && p.CanWrite) + .Where(p => p.GetIndexParameters().Length == 0) + ) + { + object? value = property.GetValue(source); + + try + { + property.SetValue(dupe, duplicator.Copy(value)); + } + catch (Exception) + { + // Bad setter. + } + } + + return dupe; + } + + /// Creates an instance of 's . + /// Object whose is to be created. + /// Handles callback behavior for child values. + /// The created instance. + private static object? CreateNew(object source, IDuplicatorChainer duplicator) + { + TypeDescriber describer = TypeDescriber.For(source); + + return describer + .Constructors.Visible.OrderByDescending(c => c.GetParameters().Length) + .Cast() + .Concat(describer.Factories.Visible.OrderByDescending(c => c.GetParameters().Length)) + .Select(m => + TryToCreate(source, duplicator, m, describer.Properties.All, describer.Fields.All) + ) + .FirstOrDefault(o => o != null); + } + + /// Attempts to create an instance using a . + /// Object being cloned. + /// Handles callback behavior for child values. + /// Constructor/factory on to use. + /// Properties on . + /// Fields on . + /// Null if failed; created instance otherwise. + private static object? TryToCreate( + object source, + IDuplicatorChainer duplicator, + MethodBase maker, + IEnumerable props, + IEnumerable fields + ) + { + List propList = [.. props]; + List fieldList = [.. fields]; + + // Attempts to match members with parameters in the constructor. + List matchedMembers = []; + foreach (ParameterInfo param in maker.GetParameters()) + { + PropertyInfo[] potentialProps = + [ + .. propList.Where(p => p.PropertyType.Inherits(param.ParameterType)), + ]; + if (potentialProps.Length != 0) + { + PropertyInfo? directPropMatch = potentialProps.FirstOrDefault(p => + p.Name.Equals(param.Name, StringComparison.OrdinalIgnoreCase) + ); + if (directPropMatch != null) + { + _ = propList.Remove(directPropMatch); + matchedMembers.Add(directPropMatch); + } + else + { + _ = propList.Remove(potentialProps[0]); + matchedMembers.Add(potentialProps[0]); + } + continue; + } + + FieldInfo[] potentialFields = + [ + .. fieldList.Where(f => f.FieldType.Inherits(param.ParameterType)), + ]; + if (potentialFields.Length != 0) + { + FieldInfo? directFieldMatch = potentialFields.FirstOrDefault(f => + f.Name.Trim('_').Equals(param.Name, StringComparison.OrdinalIgnoreCase) + ); + if (directFieldMatch != null) + { + _ = fieldList.Remove(directFieldMatch); + matchedMembers.Add(directFieldMatch); + } + else + { + _ = fieldList.Remove(potentialFields[0]); + matchedMembers.Add(potentialFields[0]); + } + continue; + } + + return null; + } + + object?[] finalParameters = + [ + .. matchedMembers.Select(m => CopyMember(m, source, duplicator)), + ]; + + return (maker is ConstructorInfo constructor) + ? constructor.Invoke(finalParameters) + : maker.Invoke(null, finalParameters); + } + + /// Copies the value of on . + /// Property or field to copy. + /// Instance containing the member. + /// Duplicator handling the cloning. + /// The duplicate object. + private static object? CopyMember( + MemberInfo member, + object source, + IDuplicatorChainer duplicator + ) + { + if (member is PropertyInfo prop) + { + return duplicator.Copy(prop.GetValue(source)); + } + else + { + return duplicator.Copy(((FieldInfo)member).GetValue(source)); + } + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/SerializableCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/SerializableCopyHint.cs new file mode 100644 index 00000000..a7633092 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/SerializableCopyHint.cs @@ -0,0 +1,74 @@ +using System.Collections; +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.ExtractorTool; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +#pragma warning disable CS0252 // Intended. + +/// Handles cloning instances for . +public sealed class SerializableCopyHint : CopyHint +{ + /// Internal type needed for AggregateException serialization. + private static readonly Type _ListDictionaryInternalType = typeof(IDictionary).Assembly.GetType( + "System.Collections.ListDictionaryInternal" + )!; + + /// + public override int EnginePriority => (int)CopyPriority.SerializableHint; + + /// + public override IEnumerable SupportedTypes => [typeof(ISerializable)]; + + /// + public override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(duplicator); + + if (source is ISerializable) + { + IContentMap contents = duplicator.Options.Extractor.Extract(source); + + DataContractSerializer serializer = new( + source.GetType(), + contents.Select(d => d.GetType()).Concat(FindExtraKnownTypes(source)).Distinct() + ); + + using MemoryStream stream = new(); + try + { + serializer.WriteObject(stream, source); + _ = stream.Seek(0, SeekOrigin.Begin); + return new(serializer.ReadObject(stream)); + } + catch (Exception e) when (e is SerializationException or InvalidDataContractException) + { + throw new SerializationException( + $"Ran into problem trying to serialize type '{source.GetType()}'.", + e + ); + } + } + else + { + return CopyHintResult.None; + } + } + + /// Finds known types needed for specific types. + /// Object being serialized. + /// Known types to add. + private static IEnumerable FindExtraKnownTypes(object source) + { + if (source is Exception) + { + yield return typeof(Exception[]); + yield return _ListDictionaryInternalType; + } + yield return typeof(string[]); + } +} + +#pragma warning restore diff --git a/src/Toolbox/DuplicatorTool/Hints/StreamCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/StreamCopyHint.cs new file mode 100644 index 00000000..6728df86 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/StreamCopyHint.cs @@ -0,0 +1,30 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// +public sealed class StreamCopyHint : CopyHint +{ + /// + public override int EnginePriority => (int)CopyPriority.StreamHint; + + /// + protected override Stream Copy(Stream source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source); + + source.Flush(); + + long startingPosition = source.Position; + source.Position = 0; + + MemoryStream stream = new(); + source.CopyTo(stream); + stream.Flush(); + + source.Position = startingPosition; + stream.Position = startingPosition; + return stream; + } +} diff --git a/src/Toolbox/DuplicatorTool/Hints/TaskCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/TaskCopyHint.cs new file mode 100644 index 00000000..aded9b32 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/TaskCopyHint.cs @@ -0,0 +1,97 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +/// Handles cloning instances for . +public sealed class TaskCopyHint : CopyHint +{ + private static readonly MethodInfo _GenericCloner = typeof(TaskCopyHint).GetMethod( + nameof(WrapTaskAsync), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + /// + public override int EnginePriority => (int)CopyPriority.TaskHint; + + /// + public override IEnumerable SupportedTypes => [typeof(Task), typeof(Task<>)]; + + /// + public sealed override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(duplicator); + + if (source is Task task) + { + Type? asGeneric = GenericConverter.AsConcreteType(source.GetType(), typeof(Task<>)); + if ( + asGeneric + ?.GetGenericArguments() + .Single() + .Name.Contains("VoidTaskResult", StringComparison.Ordinal) == false + ) + { + return new( + _GenericCloner + .MakeGenericMethod(asGeneric.GetGenericArguments()) + .Invoke(null, [task, duplicator]) + ); + } + else + { + return new(WrapPlainTaskAsync(task, duplicator)); + } + } + else + { + return CopyHintResult.None; + } + } + + private static Task WrapPlainTaskAsync(Task task, IDuplicatorChainer duplicator) + { + if (task.IsCanceled) + { + return Task.FromCanceled(new CancellationToken(true)); + } + else if (task.IsFaulted) + { + return Task.FromException(duplicator.Copy(task.Exception.InnerException!)); + } + else if (task.IsCompleted) + { + return Task.CompletedTask; + } + else + { + return Task.Run(() => task); + } + } + +#pragma warning disable CA1849, MA0042, VSTHRD103 // Completion verified. + + private static Task WrapTaskAsync(Task task, IDuplicatorChainer duplicator) + { + if (task.IsCanceled) + { + return Task.FromCanceled(new CancellationToken(true)); + } + else if (task.IsFaulted) + { + return Task.FromException(duplicator.Copy(task.Exception.InnerException!)); + } + else if (task.IsCompleted) + { + return Task.FromResult(duplicator.Copy(task.Result)); + } + else + { + return Task.Run(async () => duplicator.Copy(await task.ConfigureAwait(false))); + } + } + +#pragma warning restore CA1849, MA0042, VSTHRD103 +} diff --git a/src/Toolbox/DuplicatorTool/Hints/ValueTaskCopyHint.cs b/src/Toolbox/DuplicatorTool/Hints/ValueTaskCopyHint.cs new file mode 100644 index 00000000..8e4be740 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/Hints/ValueTaskCopyHint.cs @@ -0,0 +1,111 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool.Hints; + +#pragma warning disable CA2012 // Intended and not a bug. + +/// Handles cloning instances for . +public sealed class ValueTaskCopyHint : CopyHint +{ + private const string _ErrorMessage = + $"{nameof(ValueTask)} instances can't be duplicated unless generated by the {nameof(CreateAndFake)} framework," + + " as resolving a ValueTask multiple times results in undefined behavior."; + + private static readonly MethodInfo _GenericTaskCloner = typeof(ValueTaskCopyHint).GetMethod( + nameof(CloneTaskAsync), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + private static readonly MethodInfo _GenericSourceCloner = typeof(ValueTaskCopyHint).GetMethod( + nameof(CloneSource), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + /// + public override int EnginePriority => (int)CopyPriority.ValueTaskHint; + + /// + public override IEnumerable SupportedTypes => + [typeof(ValueTask), typeof(ValueTask<>), typeof(SingleCallValueTaskSource<>)]; + + /// + public sealed override CopyHintResult TryCopy(object source, IDuplicatorChainer duplicator) + { + ArgumentGuard.ThrowIfNull(source, duplicator); + + Type type = source.GetType(); + Type? genericType = GenericConverter.AsGenericBase(type); + + if (source is ValueTask task) + { + return new(ClonePlainTaskAsync(task)); + } + else if (genericType == typeof(ValueTask<>)) + { + return new( + _GenericTaskCloner + .MakeGenericMethod(type.GetGenericArguments()) + .Invoke(null, [source, duplicator]) + ); + } + else if (genericType == typeof(SingleCallValueTaskSource<>)) + { + return new( + _GenericSourceCloner + .MakeGenericMethod(type.GetGenericArguments()) + .Invoke(null, [source, duplicator]) + ); + } + else + { + return CopyHintResult.None; + } + } + + private static ValueTask ClonePlainTaskAsync(ValueTask task) + { + SingleCallValueTaskSource? source = SingleCallValueTaskSource.ExtractFrom(task); + if (source != null) + { + return new ValueTask( + source.DeepClone(), + SingleCallValueTaskSource.ExtractTokenFrom(task) + ); + } + else + { + throw new UnsupportedException(_ErrorMessage); + } + } + + private static ValueTask CloneTaskAsync(ValueTask task, IDuplicatorChainer duplicator) + { + SingleCallValueTaskSource? source = SingleCallValueTaskSource.ExtractFrom(task); + if (source != null) + { + return new ValueTask( + CloneSource(source, duplicator), + SingleCallValueTaskSource.ExtractTokenFrom(task) + ); + } + else + { + throw new UnsupportedException(_ErrorMessage); + } + } + + private static SingleCallValueTaskSource CloneSource( + SingleCallValueTaskSource source, + IDuplicatorChainer duplicator + ) + { + return new SingleCallValueTaskSource(duplicator.Copy(source.RawResult)); + } +} + +#pragma warning restore diff --git a/src/Toolbox/DuplicatorTool/IDuplicatable.cs b/src/Toolbox/DuplicatorTool/IDuplicatable.cs new file mode 100644 index 00000000..5a208ecb --- /dev/null +++ b/src/Toolbox/DuplicatorTool/IDuplicatable.cs @@ -0,0 +1,16 @@ +namespace Werecodent.CreateAndFake.DuplicatorTool; + +/// Enables deep copies with the aid of the duplicator. +/// Self-reference . +/// Should only be inherited by s. +public interface IDuplicatable + where T : IDuplicatable +{ + /// + /// Makes a clone such that any mutation to the source + /// or copy only affects that object and not the other. + /// + /// Duplicator to clone child values. + /// Created clone that is equal in value to the instance. + T DeepClone(IDuplicator duplicator); +} diff --git a/src/Toolbox/DuplicatorTool/IDuplicator.cs b/src/Toolbox/DuplicatorTool/IDuplicator.cs new file mode 100644 index 00000000..fc468439 --- /dev/null +++ b/src/Toolbox/DuplicatorTool/IDuplicator.cs @@ -0,0 +1,33 @@ +global using DuplicatorMod = System.Func< + Werecodent.CreateAndFake.DuplicatorTool.DuplicatorOptions, + Werecodent.CreateAndFake.DuplicatorTool.DuplicatorOptions +>; +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.DuplicatorTool; + +/// Tool to deep clone s. +/// Useful for tracking mutations by comparing against the created clones. +public interface IDuplicator : IHintTool +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + IDuplicator WithOptions(DuplicatorMod optionConfiguration); + + /// Deep clones . + /// being cloned. + /// Object to clone. + /// Modifications of this tool's options to apply for this call. + /// Clone of . + /// + /// Depending upon the , this may just return if not cloneable. + /// Important relevant options: + /// + /// + /// + [return: NotNullIfNotNull(nameof(source))] + T Copy(T source, DuplicatorMod? optionConfiguration = null); +} diff --git a/src/Toolbox/ExtractorTool/AsyncContentMap.cs b/src/Toolbox/ExtractorTool/AsyncContentMap.cs new file mode 100644 index 00000000..0b29edba --- /dev/null +++ b/src/Toolbox/ExtractorTool/AsyncContentMap.cs @@ -0,0 +1,245 @@ +using System.Collections; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.ExtractorTool; + +/// Extracted content of an object. +/// +/// +public sealed class AsyncContentMap(IAsyncSet content, ExtractorOptions options) + : IAsyncContentMap, + IDuplicatable +{ + /// Flattened object data. + private readonly IAsyncSet _content = content + ?? throw new ArgumentNullException(nameof(content)); + + /// Configured options used to extract the contents. + private readonly ExtractorOptions _options = options + ?? throw new ArgumentNullException(nameof(options)); + + /// + public IAsyncEnumerator GetAsyncEnumerator( + CancellationToken cancellationToken = default + ) + { + return _content.GetAsyncEnumerator(cancellationToken); + } + + /// + public Task HasContentAsync(object? item, CancellationToken canceler) + { + return item == null ? Task.FromResult(false) : _content.ContainsAsync(item, canceler); + } + + /// + public Task HasSharedContentAsync(IAsyncContentMap map, CancellationToken canceler) + { + return HasSharedContentAsync([map], canceler); + } + + /// + public async Task HasSharedContentAsync( + IEnumerable maps, + CancellationToken canceler + ) + { + await foreach (object _ in FindSharedContentAsync(maps, canceler).ConfigureAwait(false)) + { + return true; + } + return false; + } + + /// + public IAsyncEnumerable FindSharedContentAsync( + IAsyncContentMap map, + CancellationToken canceler + ) + { + return FindSharedContentAsync([map], canceler); + } + + /// + public IAsyncEnumerable FindSharedContentAsync( + IEnumerable maps, + CancellationToken canceler + ) + { + return GetSharedContentAsync(maps, canceler); + } + + /// + private async IAsyncEnumerable GetSharedContentAsync( + IEnumerable maps, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + if (maps == null) + { + yield break; + } + + int count = 0; + await foreach (object item in GetAllIntersectsAsync(maps, canceler).ConfigureAwait(false)) + { + Type itemType = item.GetType(); + + if (!_options.IgnoredTypesForUniques.Contains(itemType) && !itemType.IsEnum) + { + if (item is IEnumerable series) + { + foreach (object _ in series) + { + ArgumentGuard.ThrowUponIterationLimit( + count++, + options.Design.IterationLimit + ); + yield return item; + } + } + else + { + ArgumentGuard.ThrowUponIterationLimit(count++, options.Design.IterationLimit); + yield return item; + } + } + } + } + + /// + private async IAsyncEnumerable GetAllIntersectsAsync( + IEnumerable maps, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + await foreach ( + KeyValuePair entry in _content + .ByHashesAsync(canceler) + .ConfigureAwait(false) + ) + { + foreach (IAsyncContentMap map in maps) + { + if (map == null) + { + continue; + } + + if (await map.HasContentAsync(entry.Value, canceler).ConfigureAwait(false)) + { + yield return entry.Value; + } + } + } + } + + /// + public IAsyncEnumerable FindAllAsync(CancellationToken canceler) + { + return GetAllAsync(canceler); + } + + /// + public IAsyncEnumerable FindAllAsync(Type type, CancellationToken canceler) + { + return GetAllAsync(type, canceler); + } + + /// + private async IAsyncEnumerable GetAllAsync( + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + await foreach (object item in _content.WithCancellation(canceler).ConfigureAwait(false)) + { + if (item is T valid) + { + yield return valid; + } + } + } + + /// + private async IAsyncEnumerable GetAllAsync( + Type type, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + if (type == typeof(Type)) + { + await foreach (object item in _content.WithCancellation(canceler).ConfigureAwait(false)) + { + if (item is Type valid) + { + yield return valid; + } + } + } + else + { + await foreach (object item in _content.WithCancellation(canceler).ConfigureAwait(false)) + { + if (TypeDescriber.For(item).Inherits(type)) + { + yield return item; + } + } + } + } + + /// + public AsyncContentMap DeepClone(IDuplicator duplicator) + { + ArgumentGuard.ThrowIfNull(duplicator); + return new AsyncContentMap(duplicator.Copy(_content), duplicator.Copy(_options)); + } + + /// + public IAsyncEnumerable CompareAsync( + object? other, + IValuer valuer, + CancellationToken canceler = default + ) + { + ArgumentGuard.ThrowIfNull(valuer); + + if (other is AsyncContentMap map) + { + return valuer.CompareAsync( + (_content, _options), + (map._content, map._options), + canceler, + opt => opt with { UseEquatableComparisons = false } + ); + } + else + { + return valuer.CompareAsync(GetType(), other?.GetType(), canceler); + } + } + + /// + public Task GetValueHashAsync(IValuer valuer, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(valuer); + + return valuer.GetHashCodeAsync((_content, _options), canceler, opt => + opt with + { + UseEquatableComparisons = false, + } + ); + } + + /// + public override string ToString() + { + return $"ContentMap: {_content}"; + } +} diff --git a/src/Toolbox/ExtractorTool/ContentMap.cs b/src/Toolbox/ExtractorTool/ContentMap.cs new file mode 100644 index 00000000..b4f7afea --- /dev/null +++ b/src/Toolbox/ExtractorTool/ContentMap.cs @@ -0,0 +1,125 @@ +using System.Collections; +using System.Text; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.ExtractorTool; + +/// Extracted content of an object. +/// +/// +public sealed class ContentMap(ISet content, ExtractorOptions options) : IContentMap +{ + /// Flattened object data. + private readonly ISet _content = content + ?? throw new ArgumentNullException(nameof(content)); + + /// Configured options used to extract the contents. + private readonly ExtractorOptions _options = options + ?? throw new ArgumentNullException(nameof(options)); + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + public IEnumerator GetEnumerator() + { + return _content.GetEnumerator(); + } + + /// + public bool HasContent(object? item) + { + if (item == null) + { + return false; + } + + return _content.Contains(item); + } + + /// + public bool HasSharedContent(params IEnumerable maps) + { + return FindSharedContent(maps).Any(); + } + + /// + public IEnumerable FindSharedContent(params IEnumerable maps) + { + return maps.SelectMany(m => m) + .Intersect(this, _options.Valuer) + .Where(d => !_options.IgnoredTypesForUniques.Contains(d.GetType())) + .Where(d => !d.GetType().IsEnum) + .Where(d => + { + if (d is IEnumerable series) + { + foreach (object item in series) + { + return true; + } + return false; + } + return true; + }); + } + + /// + public IEnumerable FindAll() + { + return _content.OfType(); + } + + /// + public IEnumerable FindAll(Type type) + { + return _content.Where(t => t.GetType().Inherits(type)); + } + + /// + public IEnumerable Compare(object? other, IValuer valuer) + { + ArgumentGuard.ThrowIfNull(valuer); + + if (other is ContentMap map) + { + return valuer.Compare((_content, _options), (map._content, map._options)); + } + else + { + return valuer.Compare(GetType(), other?.GetType()); + } + } + + /// + public bool ValuesEqual(object? other, IValuer valuer) + { + return !Compare(other, valuer).Any(); + } + + /// + public int GetValueHash(IValuer valuer) + { + ArgumentGuard.ThrowIfNull(valuer); + return valuer.GetHashCode((_content, _options)); + } + + /// + public override string ToString() + { + StringBuilder text = new(); + + text.AppendLine("ContentMap: {"); + foreach (object item in _content) + { + text.Append(" ").Append(item).AppendLine(); + } + text.Append('}'); + + return text.ToString(); + } +} diff --git a/src/Toolbox/ExtractorTool/Engine/ExtractHint.cs b/src/Toolbox/ExtractorTool/Engine/ExtractHint.cs new file mode 100644 index 00000000..ed5331b3 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/ExtractHint.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// +public abstract class ExtractHint : IExtractHint +{ + /// + public abstract int EnginePriority { get; } + + /// + public abstract IEnumerable SupportedTypes { get; } + + /// + public abstract ExtractHintResult TryToExtract(object? source, IExtractorChainer chainer); + + /// + public abstract Task TryToExtractAsync( + object? source, + IExtractorChainer chainer, + CancellationToken canceler + ); + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/ExtractorTool/Engine/ExtractHintResult.cs b/src/Toolbox/ExtractorTool/Engine/ExtractHintResult.cs new file mode 100644 index 00000000..06c5a64d --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/ExtractHintResult.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// +public sealed class ExtractHintResult : HintResult +{ + /// For when a hint doesn't support a type or fails to extract from it. + public static ExtractHintResult None { get; } = new(false, false); + + /// + private ExtractHintResult(bool hasData, bool data) + : base(hasData, data) { } + + /// + public ExtractHintResult(bool data) + : this(true, data) { } +} diff --git a/src/Toolbox/ExtractorTool/Engine/ExtractHint{T}.cs b/src/Toolbox/ExtractorTool/Engine/ExtractHint{T}.cs new file mode 100644 index 00000000..986c1ae5 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/ExtractHint{T}.cs @@ -0,0 +1,55 @@ +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// Handles extracting instances for . +/// being supported for extraction. +public abstract class ExtractHint : ExtractHint +{ + /// + public override IEnumerable SupportedTypes { get; } = [typeof(T)]; + + /// + public sealed override ExtractHintResult TryToExtract(object? source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (source is T supported) + { + return new(Extract(supported, chainer)); + } + else + { + return ExtractHintResult.None; + } + } + + /// + public sealed override async Task TryToExtractAsync( + object? source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (source is T supported) + { + return new(await ExtractAsync(supported, chainer, canceler).ConfigureAwait(false)); + } + else + { + return ExtractHintResult.None; + } + } + + /// + protected abstract bool Extract(T source, IExtractorChainer chainer); + + /// + protected abstract Task ExtractAsync( + T source, + IExtractorChainer chainer, + CancellationToken canceler + ); +} diff --git a/src/Toolbox/ExtractorTool/Engine/ExtractPriority.cs b/src/Toolbox/ExtractorTool/Engine/ExtractPriority.cs new file mode 100644 index 00000000..b17d5804 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/ExtractPriority.cs @@ -0,0 +1,50 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// Priorities for s. +public enum ExtractPriority +{ + /// Priority for hints that won't automatically execute. + /// Such hints only work if given to the tool via . + Disabled = int.MinValue, + + /// Priority for custom hints that'll execute last. + /// Subtract from this priority for even lower priorities. + None = 0, + + /// Priority for . + ObjectHint = 1, + + /// Priority for . + FakedHint = 2, + + /// Priority for . + StreamHint = 3, + + /// Priority for . + TaskHint = 4, + + /// Priority for . + DelegateHint = 5, + + /// Priority for . + EnumerableHint = 6, + + /// Priority for . + DictionaryHint = 7, + + /// Priority for . + ExtractableHint = 8, + + /// Priority for . + EndingHint = 9, + + /// Priority for . + HandlerHint = 10, + + /// Starting priority for custom hints that'll execute first. + /// Add to this priority for even higher priorities. + Highest = 11, +} diff --git a/src/Toolbox/ExtractorTool/Engine/ExtractorChainer.cs b/src/Toolbox/ExtractorTool/Engine/ExtractorChainer.cs new file mode 100644 index 00000000..527764f2 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/ExtractorChainer.cs @@ -0,0 +1,134 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// Provides a callback into to extract child values. +public sealed class ExtractorChainer + : ToolChainer, + IExtractorChainer +{ + /// Flattened internal data. + private readonly ISet _foundContents; + + /// Flattened internal data. + private readonly IAsyncSet _asyncFoundContents; + + /// First context used. + private bool? _isSync; + + /// + public ExtractorChainer(ExtractorOptions options, IExtractorEngine engine) + : base(options, engine) + { + _foundContents = new HashSet(Options.Valuer); + _asyncFoundContents = new AsyncHashSet(Options.Valuer); + _isSync = null; + } + + /// + private ExtractorChainer(ExtractorOptions options, ExtractorChainer prevChainer) + : base(options, prevChainer) + { + _foundContents = prevChainer._foundContents; + _asyncFoundContents = prevChainer._asyncFoundContents; + _isSync = prevChainer._isSync; + } + + /// + protected override ExtractorChainer CreateSubChainer(ExtractorOptions subOptions) + { + return new ExtractorChainer(subOptions, this); + } + + /// + public IContentMap Extract(object? source, ExtractorMod? optionConfiguration = null) + { + _ = InnerExtract(source, optionConfiguration); + return new ContentMap(_foundContents, optionConfiguration?.Invoke(Options) ?? Options); + } + + /// + public async Task ExtractAsync( + object? source, + CancellationToken canceler, + ExtractorMod? optionConfiguration = null + ) + { + _ = await InnerExtractAsync(source, canceler, optionConfiguration).ConfigureAwait(false); + + return new AsyncContentMap( + _asyncFoundContents, + optionConfiguration?.Invoke(Options) ?? Options + ); + } + + /// + public bool InnerExtract(object? value, ExtractorMod? optionConfiguration = null) + { + return Engine.Extract(value, GetSubChainer(optionConfiguration)); + } + + /// + public Task InnerExtractAsync( + object? value, + CancellationToken canceler, + ExtractorMod? optionConfiguration = null + ) + { + return Engine.ExtractAsync(value, GetSubChainer(optionConfiguration), canceler); + } + + /// + public bool AddFoundValue(object value, ExtractorMod? optionConfiguration = null) + { + if (value == null) + { + return false; + } + + if (_isSync == false) + { + throw new MismatchedAccessException( + value, + "Cannot add values in synchronous context once asynchronous content has been established." + ); + } + _isSync = true; + + return _foundContents.Add(value); + } + + /// + public Task AddFoundValueAsync( + object value, + CancellationToken canceler, + ExtractorMod? optionConfiguration = null + ) + { + if (value == null) + { + return Task.FromResult(false); + } + + if (_isSync == true) + { + throw new MismatchedAccessException( + value, + "Cannot add values in asynchronous context once synchronous content has been established." + ); + } + _isSync = false; + + return _asyncFoundContents.AddAsync(value, canceler); + } + + /// + public IExtractor WithOptions(ExtractorMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new ExtractorChainer(optionConfiguration.Invoke(Options), this); + } +} diff --git a/src/Toolbox/ExtractorTool/Engine/ExtractorEngine.cs b/src/Toolbox/ExtractorTool/Engine/ExtractorEngine.cs new file mode 100644 index 00000000..0cf6ec72 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/ExtractorEngine.cs @@ -0,0 +1,96 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// +public sealed class ExtractorEngine : ToolEngine, IExtractorEngine +{ + /// + public bool Extract(object? value, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + if (value == null) + { + return false; + } + + ExtractHintResult? result; + try + { + result = SelectHints(chainer) + .Select(h => h.TryToExtract(value, chainer)) + .FirstOrDefault(r => r?.HasData ?? false); + } + catch (Exception e) + { + throw new ToolException( + $"Issue extracting type '{GenericConverter.ExpandName(value)}'.", + e + ); + } + + if (result != null) + { + return result.Data; + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(value)}' not supported by the extractor. " + + "Create a hint to extract the type." + ); + } + } + + /// + public async Task ExtractAsync( + object? value, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + if (value == null) + { + return false; + } + + ExtractHintResult? result = null; + try + { + foreach (IExtractHint hint in SelectHints(chainer)) + { + ExtractHintResult? current = await hint.TryToExtractAsync(value, chainer, canceler) + .ConfigureAwait(false); + + if (current?.HasData ?? false) + { + result = current; + break; + } + } + } + catch (Exception e) + { + throw new ToolException( + $"Issue extracting type '{GenericConverter.ExpandName(value)}'.", + e + ); + } + + if (result != null) + { + return result.Data; + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(value)}' not supported by the extractor. " + + "Create a hint to extract the type." + ); + } + } +} diff --git a/src/Toolbox/ExtractorTool/Engine/IExtractHandler.cs b/src/Toolbox/ExtractorTool/Engine/IExtractHandler.cs new file mode 100644 index 00000000..ce62f878 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/IExtractHandler.cs @@ -0,0 +1,17 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// Handles extraction of the . +public interface IExtractHandler : ITypeSupporter +{ + /// + bool ExtractSupported(object source, IExtractorChainer chainer); + + /// + Task ExtractSupportedAsync( + object source, + IExtractorChainer chainer, + CancellationToken canceler + ); +} diff --git a/src/Toolbox/ExtractorTool/Engine/IExtractHint.cs b/src/Toolbox/ExtractorTool/Engine/IExtractHint.cs new file mode 100644 index 00000000..19938b8e --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/IExtractHint.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// Handles extracting specific types for . +public interface IExtractHint : IToolHint +{ + /// + ExtractHintResult TryToExtract(object? source, IExtractorChainer chainer); + + /// Tries to extract content. + /// Instance to extract content from. + /// Extractor to use. + /// Aborts execution if triggered. + /// Hint result. + Task TryToExtractAsync( + object? source, + IExtractorChainer chainer, + CancellationToken canceler + ); +} diff --git a/src/Toolbox/ExtractorTool/Engine/IExtractorChainer.cs b/src/Toolbox/ExtractorTool/Engine/IExtractorChainer.cs new file mode 100644 index 00000000..64befc79 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/IExtractorChainer.cs @@ -0,0 +1,37 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// Provides a callback into to extract child values. +public interface IExtractorChainer : IExtractor, IToolChainer +{ + /// + bool AddFoundValue(object value, ExtractorMod? optionConfiguration = null); + + /// Adds the as an extracted instance. + /// Instance to add. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// + /// if the was added, otherwise. + /// + Task AddFoundValueAsync( + object value, + CancellationToken canceler, + ExtractorMod? optionConfiguration = null + ); + + /// + bool InnerExtract(object? value, ExtractorMod? optionConfiguration = null); + + /// Extracts the members of the given . + /// Instance to extract members from. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// if data was extracted, otherwise. + Task InnerExtractAsync( + object? value, + CancellationToken canceler, + ExtractorMod? optionConfiguration = null + ); +} diff --git a/src/Toolbox/ExtractorTool/Engine/IExtractorEngine.cs b/src/Toolbox/ExtractorTool/Engine/IExtractorEngine.cs new file mode 100644 index 00000000..145025bd --- /dev/null +++ b/src/Toolbox/ExtractorTool/Engine/IExtractorEngine.cs @@ -0,0 +1,17 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ExtractorTool.Engine; + +/// Extracts the contents of objects. +public interface IExtractorEngine : IToolEngine +{ + /// + bool Extract(object? value, IExtractorChainer chainer); + + /// Attempts to extract data from the . + /// Instance to extract data from. + /// Handles extracting child values. + /// Aborts execution if triggered. + /// if data was extracted, otherwise. + Task ExtractAsync(object? value, IExtractorChainer chainer, CancellationToken canceler); +} diff --git a/src/Toolbox/ExtractorTool/Extractor.cs b/src/Toolbox/ExtractorTool/Extractor.cs new file mode 100644 index 00000000..4b0663d6 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Extractor.cs @@ -0,0 +1,67 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool; + +/// +/// +/// If given a parameter. +public sealed class Extractor(ExtractorOptions options) : IExtractor +{ + /// Handles hint based extraction. + private static readonly ExtractorEngine _Engine = new(); + + /// + public ExtractorOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public IEnumerable SupportedTypes => _Engine.SupportedTypes; + + /// + public IContentMap Extract(object? source, ExtractorMod? optionConfiguration = null) + { + try + { + return new ExtractorChainer(Options, _Engine).Extract(source, optionConfiguration); + } + catch (Exception e) + { + throw new ToolException( + $"Issue extracting type '{GenericConverter.ExpandName(source)}'.", + e + ); + } + } + + /// + public async Task ExtractAsync( + object? source, + CancellationToken canceler, + ExtractorMod? optionConfiguration = null + ) + { + try + { + return await new ExtractorChainer(Options, _Engine) + .ExtractAsync(source, canceler, optionConfiguration) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new ToolException( + $"Issue extracting type '{GenericConverter.ExpandName(source)}'.", + e + ); + } + } + + /// + public IExtractor WithOptions(ExtractorMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Extractor(optionConfiguration.Invoke(Options)); + } +} diff --git a/src/Toolbox/ExtractorTool/ExtractorOptions.cs b/src/Toolbox/ExtractorTool/ExtractorOptions.cs new file mode 100644 index 00000000..cc488460 --- /dev/null +++ b/src/Toolbox/ExtractorTool/ExtractorOptions.cs @@ -0,0 +1,66 @@ +using System.Collections.Frozen; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.ExtractorTool.Engine; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.ExtractorTool; + +/// Settings for manipulating behavior. +public sealed record ExtractorOptions : ToolHintOptions +{ + /// Identifies the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Extractor); + + /// + public required IValuer Valuer { get; init; } + + /// + /// If non- properties/fields should be included while extracting contents. + /// + /// + /// Only properties/fields are extracted when not set to . + /// + /// + [ConfigurableOption] + public bool ExtractPrivateMembers { get; init; } = false; + + /// s to exclude when determining shared content among extracted content maps. + /// Represents s with too small of a range for unique randomization. + /// [typeof(bool), typeof(byte), typeof(char)] + [ConfigurableOption] + public FrozenSet IgnoredTypesForUniques { get; init; } = + FrozenSet.ToFrozenSet([typeof(bool), typeof(byte), typeof(char)]); + + /// s that are extracted as-is when extracting contents. + /// + /// No internal members ( nor ) + /// are included when extracting these s. + /// + /// [] + [ConfigurableOption] + public FrozenSet NonExtractableTypes { get; init; } = FrozenSet.ToFrozenSet([]); + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal ExtractorOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + IgnoredTypesForUniques = Config.GetTypes(section, IgnoredTypesForUniques), + ExtractPrivateMembers = Config.GetValue(section, ExtractPrivateMembers), + IncludeFrameworkHints = Config.GetValue(section, IncludeFrameworkHints), + NonExtractableTypes = Config.GetTypes(section, NonExtractableTypes), + IncludeFoundHints = Config.GetValue(section, IncludeFoundHints), + MaxRecursionDepth = Config.GetValue(section, MaxRecursionDepth), + }; + } +} diff --git a/src/Toolbox/ExtractorTool/Handlers/ConvertExtractHandler.cs b/src/Toolbox/ExtractorTool/Handlers/ConvertExtractHandler.cs new file mode 100644 index 00000000..64927aa9 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Handlers/ConvertExtractHandler.cs @@ -0,0 +1,62 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Handlers; + +/// +/// +/// Behavior handling extraction of the supported type. +internal class ConvertExtractHandler(Type type, Func> factory) + : IExtractHandler +{ + /// + public Type? SupportedType { get; } = type; + + /// + public bool ExtractSupported(object source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(factory, chainer); + + if (chainer.AddFoundValue(source)) + { + foreach (object? item in factory.Invoke(source)) + { + if (item != null) + { + _ = chainer.InnerExtract(item); + } + } + return true; + } + else + { + return false; + } + } + + /// + public async Task ExtractSupportedAsync( + object source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(factory, chainer); + + if (await chainer.AddFoundValueAsync(source, canceler).ConfigureAwait(false)) + { + foreach (object? item in factory.Invoke(source)) + { + if (item != null) + { + _ = await chainer.InnerExtractAsync(item, canceler).ConfigureAwait(false); + } + } + return true; + } + else + { + return false; + } + } +} diff --git a/src/Toolbox/ExtractorTool/Handlers/ConvertExtractHandler{T}.cs b/src/Toolbox/ExtractorTool/Handlers/ConvertExtractHandler{T}.cs new file mode 100644 index 00000000..15fa9475 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Handlers/ConvertExtractHandler{T}.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.ExtractorTool.Handlers; + +/// +/// +internal sealed class ConvertExtractHandler(Func> factory) + : ConvertExtractHandler(typeof(T), value => + { + ArgumentGuard.ThrowIfNull(factory); + return factory.Invoke((T)value); + }); diff --git a/src/Toolbox/ExtractorTool/Handlers/ReflectionExtractHandlers.cs b/src/Toolbox/ExtractorTool/Handlers/ReflectionExtractHandlers.cs new file mode 100644 index 00000000..b864be3b --- /dev/null +++ b/src/Toolbox/ExtractorTool/Handlers/ReflectionExtractHandlers.cs @@ -0,0 +1,71 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class ReflectionExtractHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + [ + new SelfExtractHandler(RuntimeDetails.RuntimeType), + new ConvertExtractHandler( + RuntimeDetails.RuntimeConstructorInfoType, + data => + { + ConstructorInfo info = (ConstructorInfo)data; + return [info.Name, info.DeclaringType, info.GetParameters()]; + } + ), + new ConvertExtractHandler( + RuntimeDetails.RuntimeMethodInfoType, + data => + { + MethodInfo info = (MethodInfo)data; + return [info.Name, info.DeclaringType, info.ReturnType, info.GetParameters()]; + } + ), + new ConvertExtractHandler( + RuntimeDetails.RuntimePropertyInfoType, + data => + { + PropertyInfo info = (PropertyInfo)data; + return [info.Name, info.DeclaringType, info.PropertyType]; + } + ), + new ConvertExtractHandler( + RuntimeDetails.RtFieldInfoType, + data => + { + FieldInfo info = (FieldInfo)data; + return [info.Name, info.DeclaringType, info.FieldType]; + } + ), + new ConvertExtractHandler( + RuntimeDetails.MdFieldInfoType, + data => + { + FieldInfo info = (FieldInfo)data; + return [info.Name, info.DeclaringType, info.FieldType]; + } + ), + new ConvertExtractHandler( + RuntimeDetails.RuntimeParameterInfoType, + data => + { + ParameterInfo info = (ParameterInfo)data; + return [info.Name, info.ParameterType]; + } + ), + new ConvertExtractHandler( + RuntimeDetails.RuntimeAssemblyType, + data => + { + Assembly info = (Assembly)data; + return [info.FullName]; + } + ), + ]; +} diff --git a/src/Toolbox/ExtractorTool/Handlers/SelfExtractHandler.cs b/src/Toolbox/ExtractorTool/Handlers/SelfExtractHandler.cs new file mode 100644 index 00000000..0aa257d9 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Handlers/SelfExtractHandler.cs @@ -0,0 +1,32 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Handlers; + +/// Prevents further extraction of the . +/// +internal sealed class SelfExtractHandler(Type supportedType) : IExtractHandler +{ + /// + public Type? SupportedType => supportedType; + + /// + public bool ExtractSupported(object source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + return chainer.AddFoundValue(source); + } + + /// + public Task ExtractSupportedAsync( + object source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + return chainer.AddFoundValueAsync(source, canceler); + } +} diff --git a/src/Toolbox/ExtractorTool/Handlers/SystemExtractHandlers.cs b/src/Toolbox/ExtractorTool/Handlers/SystemExtractHandlers.cs new file mode 100644 index 00000000..c4555bfc --- /dev/null +++ b/src/Toolbox/ExtractorTool/Handlers/SystemExtractHandlers.cs @@ -0,0 +1,30 @@ +using System.Numerics; +using System.Reflection; +using System.Text; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class SystemExtractHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + [ + new SelfExtractHandler(typeof(Lock)), + new SelfExtractHandler(typeof(string)), + new SelfExtractHandler(typeof(AssemblyName)), + new SelfExtractHandler(typeof(StringBuilder)), + new SelfExtractHandler(typeof(CancellationToken)), + new SelfExtractHandler(typeof(RuntimeMethodHandle)), + new ConvertExtractHandler(x => [x.X, x.Y]), + new ConvertExtractHandler(x => [x.X, x.Y, x.Z]), + new ConvertExtractHandler(x => [x.X, x.Y, x.Z, x.W]), + new ConvertExtractHandler(x => [x.BaseStream]), + new ConvertExtractHandler(x => + { + x.Flush(); + return [x.BaseStream]; + }), + ]; +} diff --git a/src/Toolbox/ExtractorTool/Handlers/ValueExtractHandlers.cs b/src/Toolbox/ExtractorTool/Handlers/ValueExtractHandlers.cs new file mode 100644 index 00000000..9a7be4b1 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Handlers/ValueExtractHandlers.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class ValueExtractHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + ValueRandom.SupportedTypes.Select(t => new SelfExtractHandler(t)); +} diff --git a/src/Toolbox/ExtractorTool/Hints/DelegateExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/DelegateExtractHint.cs new file mode 100644 index 00000000..fa2d9c9b --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/DelegateExtractHint.cs @@ -0,0 +1,31 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +/// Handles extracting delegates for . +public sealed class DelegateExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.DelegateHint; + + /// + protected override bool Extract(Delegate source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + return chainer.AddFoundValue(source); + } + + /// + protected override Task ExtractAsync( + Delegate source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + return chainer.AddFoundValueAsync(source, canceler); + } +} diff --git a/src/Toolbox/ExtractorTool/Hints/DictionaryExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/DictionaryExtractHint.cs new file mode 100644 index 00000000..2da2f1a1 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/DictionaryExtractHint.cs @@ -0,0 +1,56 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +/// Handles extracting dictionaries for . +public sealed class DictionaryExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.DictionaryHint; + + /// + protected override bool Extract(IDictionary source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (chainer.AddFoundValue(source)) + { + foreach (DictionaryEntry item in source) + { + _ = chainer.InnerExtract(item.Key); + _ = chainer.InnerExtract(item.Value); + } + return true; + } + else + { + return false; + } + } + + /// + protected override async Task ExtractAsync( + IDictionary source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (await chainer.AddFoundValueAsync(source, canceler).ConfigureAwait(false)) + { + foreach (DictionaryEntry item in source) + { + _ = await chainer.InnerExtractAsync(item.Key, canceler).ConfigureAwait(false); + _ = await chainer.InnerExtractAsync(item.Value, canceler).ConfigureAwait(false); + } + return true; + } + else + { + return false; + } + } +} diff --git a/src/Toolbox/ExtractorTool/Hints/EndingExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/EndingExtractHint.cs new file mode 100644 index 00000000..e7b09098 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/EndingExtractHint.cs @@ -0,0 +1,71 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +#pragma warning disable MA0042 // Using sync behavior for async versions. + +/// Handles extracting final values for . +public sealed class EndingExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.EndingHint; + + /// + public override IEnumerable SupportedTypes { get; } = ValueRandom.SupportedTypes; + + /// + public override ExtractHintResult TryToExtract(object? source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + Type? type = source?.GetType(); + if ( + source != null + && type != null + && ( + ValueRandom.SupportedTypes.Contains(type) + || type.IsEnum + || chainer.Options.NonExtractableTypes.Contains(type) + ) + ) + { + return new(chainer.AddFoundValue(source)); + } + else + { + return ExtractHintResult.None; + } + } + + /// + public override async Task TryToExtractAsync( + object? source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + Type? type = source?.GetType(); + if ( + source != null + && type != null + && ( + ValueRandom.SupportedTypes.Contains(type) + || type.IsEnum + || chainer.Options.NonExtractableTypes.Contains(type) + ) + ) + { + return new(await chainer.AddFoundValueAsync(source, canceler).ConfigureAwait(false)); + } + else + { + return ExtractHintResult.None; + } + } +} + +#pragma warning restore diff --git a/src/Toolbox/ExtractorTool/Hints/EnumerableExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/EnumerableExtractHint.cs new file mode 100644 index 00000000..235d5657 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/EnumerableExtractHint.cs @@ -0,0 +1,58 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +/// Handles extracting enumerables for . +public sealed class EnumerableExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.EnumerableHint; + + /// + protected override bool Extract(IEnumerable source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (chainer.AddFoundValue(source)) + { + int i = 0; + foreach (object item in source) + { + ArgumentGuard.ThrowUponIterationLimit(i++, chainer.Options.Design.IterationLimit); + _ = chainer.InnerExtract(item); + } + return true; + } + else + { + return false; + } + } + + /// + protected override async Task ExtractAsync( + IEnumerable source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (await chainer.AddFoundValueAsync(source, canceler).ConfigureAwait(false)) + { + int i = 0; + foreach (object item in source) + { + ArgumentGuard.ThrowUponIterationLimit(i++, chainer.Options.Design.IterationLimit); + _ = await chainer.InnerExtractAsync(item, canceler).ConfigureAwait(false); + } + return true; + } + else + { + return false; + } + } +} diff --git a/src/Toolbox/ExtractorTool/Hints/ExtractableExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/ExtractableExtractHint.cs new file mode 100644 index 00000000..bd8d6537 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/ExtractableExtractHint.cs @@ -0,0 +1,60 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +/// +public sealed class ExtractableExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.ExtractableHint; + + /// + protected override bool Extract(IExtractable source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (chainer.AddFoundValue(source)) + { + foreach (object? item in source.ExtractContents()) + { + if (item != null) + { + _ = chainer.InnerExtract(item); + } + } + return true; + } + else + { + return false; + } + } + + /// + protected override async Task ExtractAsync( + IExtractable source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (await chainer.AddFoundValueAsync(source, canceler).ConfigureAwait(false)) + { + foreach (object? item in source.ExtractContents()) + { + if (item != null) + { + _ = await chainer.InnerExtractAsync(item, canceler).ConfigureAwait(false); + } + } + return true; + } + else + { + return false; + } + } +} diff --git a/src/Toolbox/ExtractorTool/Hints/FakedExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/FakedExtractHint.cs new file mode 100644 index 00000000..e3a8257b --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/FakedExtractHint.cs @@ -0,0 +1,48 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ExtractorTool.Engine; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +/// +public sealed class FakedExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.FakedHint; + + /// + protected override bool Extract(IFaked source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (chainer.AddFoundValue(source)) + { + _ = chainer.InnerExtract(source.FakeMeta); + return true; + } + else + { + return false; + } + } + + /// + protected override async Task ExtractAsync( + IFaked source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (await chainer.AddFoundValueAsync(source, canceler).ConfigureAwait(false)) + { + _ = await chainer.InnerExtractAsync(source.FakeMeta, canceler).ConfigureAwait(false); + return true; + } + else + { + return false; + } + } +} diff --git a/src/Toolbox/ExtractorTool/Hints/HandlerExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/HandlerExtractHint.cs new file mode 100644 index 00000000..0ef26cfa --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/HandlerExtractHint.cs @@ -0,0 +1,85 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ExtractorTool.Engine; +using Werecodent.CreateAndFake.ExtractorTool.Handlers; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +#pragma warning disable MA0042 // Using sync behavior for async versions. + +/// Combines and utilizes available handlers for mutations. +public sealed class HandlerExtractHint : IExtractHint +{ + /// Handlers to use that haven't already been specified. + private static readonly IExtractHandler[] _Creators = + [ + new ConvertExtractHandler(x => [x.SupportedType]), + new ConvertExtractHandler(x => [x.Identifier]), + ]; + + /// All handlers by their supported type. + private static readonly IDictionary _MutatorsByType = + TypeSupporter.GroupBySupportedType( + _Creators + .Concat(ReflectionExtractHandlers.Handlers) + .Concat(SystemExtractHandlers.Handlers) + .Concat(ValueExtractHandlers.Handlers) + ); + + /// + public int EnginePriority => (int)ExtractPriority.HandlerHint; + + /// + public IEnumerable SupportedTypes => _MutatorsByType.Keys; + + /// + public ExtractHintResult TryToExtract(object? source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if ( + source != null + && _MutatorsByType.TryGetValue(source.GetType(), out IExtractHandler? handler) + ) + { + return new(handler.ExtractSupported(source, chainer)); + } + else + { + return ExtractHintResult.None; + } + } + + /// + public async Task TryToExtractAsync( + object? source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + if ( + source != null + && _MutatorsByType.TryGetValue(source.GetType(), out IExtractHandler? handler) + ) + { + return new( + await handler.ExtractSupportedAsync(source, chainer, canceler).ConfigureAwait(false) + ); + } + else + { + return ExtractHintResult.None; + } + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} + +#pragma warning restore diff --git a/src/Toolbox/ExtractorTool/Hints/ObjectExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/ObjectExtractHint.cs new file mode 100644 index 00000000..4725a84e --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/ObjectExtractHint.cs @@ -0,0 +1,93 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +/// Handles extracting objects for . +public sealed class ObjectExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.ObjectHint; + + /// + protected override bool Extract(object source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (chainer.AddFoundValue(source)) + { + Type type = source.GetType(); + foreach ( + PropertyInfo property in ( + chainer.Options.ExtractPrivateMembers + ? TypeDescriber.For(type).Properties.All + : TypeDescriber.For(type).Properties.OnlyPublic + ) + .Where(p => p.CanRead) + .Where(p => source is not Exception || p.Name != "HResult") + ) + { + _ = chainer.InnerExtract(property.GetValue(source)); + } + foreach ( + FieldInfo field in chainer.Options.ExtractPrivateMembers + ? TypeDescriber.For(type).Fields.All + : TypeDescriber.For(type).Fields.OnlyPublic + ) + { + _ = chainer.InnerExtract(field.GetValue(source)); + } + return true; + } + else + { + return false; + } + } + + /// + protected override async Task ExtractAsync( + object source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (await chainer.AddFoundValueAsync(source, canceler).ConfigureAwait(false)) + { + Type type = source.GetType(); + foreach ( + PropertyInfo property in ( + chainer.Options.ExtractPrivateMembers + ? TypeDescriber.For(type).Properties.All + : TypeDescriber.For(type).Properties.OnlyPublic + ) + .Where(p => p.CanRead) + .Where(p => source is not Exception || p.Name != "HResult") + ) + { + _ = await chainer + .InnerExtractAsync(property.GetValue(source), canceler) + .ConfigureAwait(false); + } + foreach ( + FieldInfo field in chainer.Options.ExtractPrivateMembers + ? TypeDescriber.For(type).Fields.All + : TypeDescriber.For(type).Fields.OnlyPublic + ) + { + _ = await chainer + .InnerExtractAsync(field.GetValue(source), canceler) + .ConfigureAwait(false); + } + return true; + } + else + { + return false; + } + } +} diff --git a/src/Toolbox/ExtractorTool/Hints/StreamExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/StreamExtractHint.cs new file mode 100644 index 00000000..b7a5f535 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/StreamExtractHint.cs @@ -0,0 +1,50 @@ +using System.Text; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +/// Handles extracting enumerables for . +public sealed class StreamExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.StreamHint; + + /// + protected override bool Extract(Stream source, IExtractorChainer chainer) + { + return chainer.InnerExtract(ReadContents(source, chainer)); + } + + /// + protected override Task ExtractAsync( + Stream source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + return chainer.InnerExtractAsync(ReadContents(source, chainer), canceler); + } + + private static IEnumerable ReadContents(Stream stream, IExtractorChainer chainer) + { + stream.Flush(); + + long startingPosition = stream.Position; + stream.Position = 0; + + using StreamReader reader = new(stream, Encoding.UTF8, true, 1024, true); + for (int i = 0; !reader.EndOfStream; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i, chainer.Options.Design.IterationLimit); + + string? line = reader.ReadLine(); + if (!string.IsNullOrWhiteSpace(line)) + { + yield return line; + } + } + + stream.Position = startingPosition; + } +} diff --git a/src/Toolbox/ExtractorTool/Hints/TaskExtractHint.cs b/src/Toolbox/ExtractorTool/Hints/TaskExtractHint.cs new file mode 100644 index 00000000..3c53ed31 --- /dev/null +++ b/src/Toolbox/ExtractorTool/Hints/TaskExtractHint.cs @@ -0,0 +1,31 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool.Hints; + +/// Handles extracting tasks for . +public sealed class TaskExtractHint : ExtractHint +{ + /// + public override int EnginePriority => (int)ExtractPriority.TaskHint; + + /// + protected override bool Extract(Task source, IExtractorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + return chainer.AddFoundValue(source); + } + + /// + protected override Task ExtractAsync( + Task source, + IExtractorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + return chainer.AddFoundValueAsync(source, canceler); + } +} diff --git a/src/Toolbox/ExtractorTool/IAsyncContentMap.cs b/src/Toolbox/ExtractorTool/IAsyncContentMap.cs new file mode 100644 index 00000000..0fcfa9fb --- /dev/null +++ b/src/Toolbox/ExtractorTool/IAsyncContentMap.cs @@ -0,0 +1,70 @@ +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.ExtractorTool; + +/// Extracted content of an . +public interface IAsyncContentMap : IAsyncEnumerable, IValuerAsyncComparable +{ + /// Determines if the map has the given in it. + /// Content to check for. + /// Aborts execution if triggered. + /// + /// if has the item, + /// otherwise. + /// + Task HasContentAsync(object? item, CancellationToken canceler); + + /// Determines if has any content from the in it. + /// Content to compare with. + /// Aborts execution if triggered. + /// + /// if has content shared with the maps, + /// otherwise. + /// + /// + /// Ignores types with too small of range for unique randomization + /// (). + /// + Task HasSharedContentAsync(IAsyncContentMap map, CancellationToken canceler); + + /// Determines if has any content from the in it. + /// Content to compare with. + /// + Task HasSharedContentAsync( + IEnumerable maps, + CancellationToken canceler + ); + + /// Finds content shares with the . + /// Content to compare with. + /// Aborts execution if triggered. + /// All shared content found. + /// + /// Ignores types with too small of range for unique randomization + /// (). + /// + IAsyncEnumerable FindSharedContentAsync( + IAsyncContentMap map, + CancellationToken canceler + ); + + /// Finds content shares with . + /// Content to compare with. + /// + IAsyncEnumerable FindSharedContentAsync( + IEnumerable maps, + CancellationToken canceler + ); + + /// Returns all possible instances. + /// Content to find. + /// Aborts execution if triggered. + /// All instances (including subclasses). + IAsyncEnumerable FindAllAsync(CancellationToken canceler); + + /// Returns all possible instances of the . + /// Content to find. + /// Aborts execution if triggered. + /// All instances or the (including subclasses). + IAsyncEnumerable FindAllAsync(Type type, CancellationToken canceler); +} diff --git a/src/Toolbox/ExtractorTool/IContentMap.cs b/src/Toolbox/ExtractorTool/IContentMap.cs new file mode 100644 index 00000000..a5daca33 --- /dev/null +++ b/src/Toolbox/ExtractorTool/IContentMap.cs @@ -0,0 +1,46 @@ +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.ExtractorTool; + +/// Extracted content of an . +public interface IContentMap : IEnumerable, IValuerComparable +{ + /// Determines if the map has the given in it. + /// Content to check for. + /// + /// if has the , + /// otherwise. + /// + bool HasContent(object? item); + + /// Determines if has any content from the in it. + /// Content to compare with. + /// + /// if has content from any of the other , + /// otherwise. + /// + /// + /// Ignores types with too small of range for unique randomization + /// (). + /// + bool HasSharedContent(params IEnumerable maps); + + /// Finds content shares with . + /// Content to compare with. + /// All shared content found. + /// + /// Ignores types with too small of range for unique randomization + /// (). + /// + IEnumerable FindSharedContent(params IEnumerable maps); + + /// Returns all possible instances. + /// Content to find. + /// All instances (including subclasses). + IEnumerable FindAll(); + + /// Returns all possible instances of the . + /// Content to find. + /// All instances of the (including subclasses). + IEnumerable FindAll(Type type); +} diff --git a/src/Toolbox/ExtractorTool/IExtractor.cs b/src/Toolbox/ExtractorTool/IExtractor.cs new file mode 100644 index 00000000..ad77a08a --- /dev/null +++ b/src/Toolbox/ExtractorTool/IExtractor.cs @@ -0,0 +1,41 @@ +global using ExtractorMod = System.Func< + Werecodent.CreateAndFake.ExtractorTool.ExtractorOptions, + Werecodent.CreateAndFake.ExtractorTool.ExtractorOptions +>; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.ExtractorTool; + +/// Tool to flatten the contents of s. +/// Useful for determining what data is shared among s. +public interface IExtractor : IHintTool +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + IExtractor WithOptions(ExtractorMod optionConfiguration); + + /// + IContentMap Extract(object? source, ExtractorMod? optionConfiguration = null); + + /// Finds all data contained by the instance. + /// Instance being deconstructed. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A mapping for the extracted content of . + /// + /// The resulting map instance provides a means of searching all the content + /// or comparing with the extracted results of other s. + /// Important relevant options: + /// + /// + /// + /// + /// + Task ExtractAsync( + object? source, + CancellationToken canceler, + ExtractorMod? optionConfiguration = null + ); +} diff --git a/src/CreateAndFake/Toolbox/FakerTool/AnyGeneric.cs b/src/Toolbox/FakerTool/AnyGeneric.cs similarity index 79% rename from src/CreateAndFake/Toolbox/FakerTool/AnyGeneric.cs rename to src/Toolbox/FakerTool/AnyGeneric.cs index 492dde3e..10d6f9a9 100644 --- a/src/CreateAndFake/Toolbox/FakerTool/AnyGeneric.cs +++ b/src/Toolbox/FakerTool/AnyGeneric.cs @@ -1,10 +1,9 @@ - -namespace CreateAndFake.Toolbox.FakerTool; - -/// Represents any generic for mock matching. -public sealed class AnyGeneric -{ - /// - /// Prevents instantiation. - private AnyGeneric() { } -} +namespace Werecodent.CreateAndFake.FakerTool; + +/// Represents any generic for mock matching. +public sealed class AnyGeneric +{ + /// + /// Prevents instantiation. + private AnyGeneric() { } +} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Arg.cs b/src/Toolbox/FakerTool/Arg.cs similarity index 88% rename from src/CreateAndFake/Toolbox/FakerTool/Arg.cs rename to src/Toolbox/FakerTool/Arg.cs index c80cae25..cd22521a 100644 --- a/src/CreateAndFake/Toolbox/FakerTool/Arg.cs +++ b/src/Toolbox/FakerTool/Arg.cs @@ -1,145 +1,148 @@ -using System.Diagnostics.CodeAnalysis; -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// Provides the ability to match arguments based upon conditions. -public sealed class Arg : IDeepCloneable -{ - /// Current setup args. - private static readonly ThreadLocal>> _ArgCache = new(() => []); - - /// Condition to compare with. - private readonly Func _matcher; - - /// - /// Condition to compare with. - private Arg(Func matcher) - { - _matcher = matcher; - } - - /// - public IDeepCloneable DeepClone() - { - return new Arg(_matcher); - } - - /// Determines if the condition is matched. - /// Argument to compare with. - /// True if matched; false otherwise. - internal bool Matches(object? arg) - { - return _matcher(arg); - } - - /// Grabs created args and restarts arg tracking. - /// Previously created args and associated values. - internal static Tuple[] CaptureSetArgs() - { - Tuple[] result = [.. _ArgCache.Value]; - _ArgCache.Value!.Clear(); - return result; - } - - /// Matches any instance. - /// Type to match. - /// Random instance of for the fake setup. - /// Use when matching via method names. - public static T? Any() - { - T? value = Tools.Randomizer.Create(); - _ArgCache.Value!.Add(Tuple.Create(LambdaAny(), (object?)value)); - return value; - } - - /// Matches any reference. - /// Type to match. - /// Container for the reference. - /// Use when matching via method names. - public static OutRef AnyRef() - { - return new OutRef(); - } - - /// Matches any instance except null. - /// Type to match. - /// Random instance of for the fake setup. - /// Use when matching via method names. - public static T? NotNull() where T : class - { - T? value = Tools.Randomizer.Create(); - _ArgCache.Value!.Add(Tuple.Create(LambdaNotNull(), (object?)value)); - return value; - } - - /// Matches any instance that fulfills . - /// Type to match. - /// Condition to verify. - /// Random instance of for the fake setup. - /// Use when matching via method names. - public static T? Where(Func condition) - { - T? value = Tools.Randomizer.Create(); - _ArgCache.Value!.Add(Tuple.Create(LambdaWhere(condition), (object?)value)); - return value; - } - - /// - /// Matches any reference that fulfills . - /// - /// Type to match. - /// Condition to verify. - /// Container for the reference. - /// Use when matching via method names. - [SuppressMessage("IDE", "IDE0060:RemoveUnusedParameters", - Justification = "Taken and used through lambdas for setup replacement behavior.")] - public static OutRef WhereRef(Func condition) - { - return new OutRef(); - } - - /// Matches any instance. - /// Type to match. - /// Arg for the fake provider to match with. - public static Arg LambdaAny() - { - return new Arg(o => o is T or null); - } - - /// Matches any reference. - /// Type to match. - /// Arg for the fake provider to match with. - public static Arg LambdaAnyRef() - { - return LambdaWhere>(null); - } - - /// Matches any instance except null. - /// Type to match. - /// Arg for the fake provider to match with. - public static Arg LambdaNotNull() where T : class - { - return LambdaWhere(o => o != null); - } - - /// Matches any instance that fulfills . - /// Type to match. - /// Condition to verify. - /// Arg for the fake provider to match with. - public static Arg LambdaWhere(Func? condition) - { - return new Arg(o => o is T value && (condition?.Invoke(value) ?? true)); - } - - /// - /// Matches any reference that fulfills . - /// - /// Type to match. - /// Condition to verify. - /// Container for the reference. - public static Arg LambdaWhereRef(Func? condition) - { - return LambdaWhere>(o => condition?.Invoke(o.Var!) ?? true); - } -} +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// Provides the ability to match arguments based upon conditions. +public sealed class Arg : IDeepCloneable +{ + /// Current setup args. + private static readonly ThreadLocal>> _ArgCache = new(() => []); + + /// Condition to compare with. + private readonly Func _matcher; + + /// + /// Condition to compare with. + private Arg(Func matcher) + { + _matcher = matcher; + } + + /// + public Arg DeepClone() + { + return new Arg(_matcher); + } + + /// Determines if the condition is matched. + /// Argument to compare with. + /// True if matched; false otherwise. + internal bool Matches(object? arg) + { + return _matcher(arg); + } + + /// Grabs created args and restarts arg tracking. + /// Previously created args and associated values. + internal static Tuple[] CaptureSetArgs() + { + Tuple[] result = [.. _ArgCache.Value!]; + _ArgCache.Value!.Clear(); + return result; + } + + /// Matches any instance. + /// Type to match. + /// Random instance of for the fake setup. + /// Use when matching via method names. + public static T? Any() + { + T? value = Tools.Randomizer.Create(); + _ArgCache.Value!.Add(Tuple.Create(LambdaAny(), (object?)value)); + return value; + } + + /// Matches any reference. + /// Type to match. + /// Container for the reference. + /// Use when matching via method names. + public static OutRef AnyRef() + { + return new OutRef(); + } + + /// Matches any instance except . + /// Type to match. + /// Random instance of for the fake setup. + /// Use when matching via method names. + public static T? NotNull() + where T : class + { + T? value = Tools.Randomizer.Create(); + _ArgCache.Value!.Add(Tuple.Create(LambdaNotNull(), (object?)value)); + return value; + } + + /// Matches any instance that fulfills . + /// Type to match. + /// Condition to verify. + /// Random instance of for the fake setup. + /// Use when matching via method names. + public static T? Where(Func condition) + { + T? value = Tools.Randomizer.Create(); + _ArgCache.Value!.Add(Tuple.Create(LambdaWhere(condition), (object?)value)); + return value; + } + +#pragma warning disable IDE0060, RCS1163 // Used via lambdas for setup replacement behavior. + + /// + /// Matches any reference that fulfills . + /// + /// Type to match. + /// Condition to verify. + /// Container for the reference. + /// Use when matching via method names. + public static OutRef WhereRef(Func condition) + { + return new OutRef(); + } + +#pragma warning restore IDE0060, RCS1163 + + /// Matches any instance. + /// Type to match. + /// Arg for the fake provider to match with. + public static Arg LambdaAny() + { + return new Arg(o => o is T or null); + } + + /// Matches any reference. + /// Type to match. + /// Arg for the fake provider to match with. + public static Arg LambdaAnyRef() + { + return LambdaWhere>(null); + } + + /// Matches any instance except . + /// Type to match. + /// Arg for the fake provider to match with. + public static Arg LambdaNotNull() + where T : class + { + return LambdaWhere(o => o != null); + } + + /// Matches any instance that fulfills . + /// Type to match. + /// Condition to verify. + /// Arg for the fake provider to match with. + public static Arg LambdaWhere(Func? condition) + { + return new Arg(o => o is T value && (condition?.Invoke(value) ?? true)); + } + + /// + /// Matches any reference that fulfills . + /// + /// Type to match. + /// Condition to verify. + /// Container for the reference. + public static Arg LambdaWhereRef(Func? condition) + { + return LambdaWhere>(o => condition?.Invoke(o.Var!) ?? true); + } +} diff --git a/src/Toolbox/FakerTool/Behavior.cs b/src/Toolbox/FakerTool/Behavior.cs new file mode 100644 index 00000000..db196283 --- /dev/null +++ b/src/Toolbox/FakerTool/Behavior.cs @@ -0,0 +1,628 @@ +using System.Reflection; +using System.Runtime.ExceptionServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// Mock behavior for fakes. +/// +/// +/// Starting number of calls. +public abstract class Behavior(Delegate implementation, Times? times, int calls) +{ + /// Set behavior to run. + protected Delegate Implementation { get; } = implementation; + + /// Behavior call limit. + protected Times Limit { get; } = times ?? Times.AtLeast(1); + + /// Times the fake behavior was called. + protected internal int Calls { get; private set; } = calls; + + /// Triggers calling the base method of the given type instead. + public bool CallBase { get; private set; } = false; + + /// Runs the behavior. + /// Expected args for the behavior. + /// Result of the call. + internal object? Invoke(object[] args) + { + return Invoke(Implementation, args); + } + + /// Runs the behavior. + /// Delegate to run. + /// Expected args for the behavior. + /// Result of the call. + internal object? Invoke(Delegate implementation, object[] args) + { + ArgumentGuard.ThrowIfNull(implementation); + + Calls++; + try + { + if (implementation.Method.GetParameters().Length == 0) + { + return implementation.DynamicInvoke(); + } + else + { + return implementation.DynamicInvoke(args); + } + } + catch (Exception e) + { + ExceptionDispatchInfo? info = + (e is TargetInvocationException) + ? ExceptionDispatchInfo.Capture(e.InnerException!) + : null; + + info?.Throw(); + throw; + } + } + + /// Checks if call count is in expected range. + /// if in range, otherwise. + internal bool HasExpectedCalls() + { + return Limit?.IsInRange(Calls) ?? true; + } + + /// Converts to the number of expected calls. + /// Text representation of expected calls. + internal string ToExpectedCalls() + { + return Limit?.ToString() ?? ""; + } + + /// Specifies no behavior for a fake. + /// Behavior call limit. + public static Behavior None(Times? times = null) + { + return Call(() => { }, times); + } + + /// Specifies behavior returning null for a fake. + /// Null type to return. + /// Behavior call limit. + /// Instance to set up the mock with. + public static Behavior Null(Times? times = null) + where T : class? + { + return Returns(null, times); + } + + /// Specifies behavior returning the default for a fake. + /// Default value type to return. + /// Behavior call limit. + /// Instance to set up the mock with. + public static Behavior Default(Times? times = null) + { + return Returns(default(T), times); + } + + /// + public static Behavior Base(Times? times = null) + { + return Base(times); + } + + /// Specifies behavior calling the base implementation. + /// Expected value type to return. + /// Behavior call limit. + /// Instance to set up the mock with. + public static Behavior Base(Times? times = null) + { + Behavior result = Default(times); + result.CallBase = true; + return result; + } + + /// Specifies exception behavior for a fake. + /// Behavior call limit. + public static Behavior Throw(Times? times = null) + { + return Throw(new BehaviorDefaultThrowException("Thrown as configured."), times); + } + + /// + public static Behavior Throw(Times? times = null) + where T : Exception, new() + { + return Throw(new T(), times); + } + + /// Specifies a specific exception behavior for a fake. + /// Exception type to throw if called. + /// Exception to throw. + /// Behavior call limit. + /// Instance to set up the mock with. + public static Behavior Throw(T exception, Times? times = null) + where T : Exception + { + return Call(() => throw exception, times); + } + + /// Specifies behavior returning a value for a fake. + /// Value type to return. + /// Value to return. + /// Behavior call limit. + /// Instance to set up the mock with. + public static Behavior Returns(T? value, Times? times = null) + { + return Call(() => value, times); + } + + /// Specifies behavior returning values for a fake. + /// Value type to return. + /// Sequential values to return. + /// Instance to set up the mock with. + public static Behavior Series(params IEnumerable values) + { + List collected = values?.ToList() ?? []; + + int i = 0; + return Call(() => + { + if (i < collected.Count) + { + return collected[i++]; + } + else + { + return default; + } + }); + } + + /// + public static Behavior Call(Action implementation, Times? times = null) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call(Action implementation, Times? times = null) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14 + >( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15 + >( + Action implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16 + >( + Action< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16 + > implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call(Func implementation, Times? times = null) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call(Func implementation, Times? times = null) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + TOut + >( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// + public static Behavior Call< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + TOut + >( + Func implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } + + /// Specifies mock behavior of for a fake. + /// Type for parameter 1. + /// Type for parameter 2. + /// Type for parameter 3. + /// Type for parameter 4. + /// Type for parameter 5. + /// Type for parameter 6. + /// Type for parameter 7. + /// Type for parameter 8. + /// Type for parameter 9. + /// Type for parameter 10. + /// Type for parameter 11. + /// Type for parameter 12. + /// Type for parameter 13. + /// Type for parameter 14. + /// Type for parameter 15. + /// Type for parameter 16. + /// Type for the return value of . + /// Behavior to invoke for calls. + /// Behavior call limit. + /// Instance to set up the mock with. + public static Behavior Call< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + TOut + >( + Func< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + TOut + > implementation, + Times? times = null + ) + { + return new Behavior(implementation, times); + } +} diff --git a/src/Toolbox/FakerTool/Behavior{T}.cs b/src/Toolbox/FakerTool/Behavior{T}.cs new file mode 100644 index 00000000..e87853bc --- /dev/null +++ b/src/Toolbox/FakerTool/Behavior{T}.cs @@ -0,0 +1,48 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// +/// Return type. +public sealed class Behavior : Behavior, IDeepCloneable> +{ + /// + public Behavior(Delegate implementation, Times? times = null) + : base(implementation, times, 0) { } + + /// + private Behavior(Delegate implementation, Times times, int calls) + : base(implementation, times, calls) { } + + /// + public Behavior DeepClone() + { + return new Behavior(Implementation, Limit, Calls); + } + + /// Specifies exception behavior for a fake. + /// Behavior call limit. + public static new Behavior Throw(Times? times = null) + { + return Throw(new BehaviorDefaultThrowException("Thrown as configured."), times); + } + + /// + public static new Behavior Throw(Times? times = null) + where TException : Exception, new() + { + return Throw(new TException(), times); + } + + /// Specifies a specific exception behavior for a fake. + /// Exception type to throw if called. + /// Exception to throw. + /// Behavior call limit. + /// Instance to set up the mock with. + public static new Behavior Throw(TException exception, Times? times = null) + where TException : Exception + { + return Call(() => throw exception, times); + } +} diff --git a/src/Toolbox/FakerTool/Engine/FakeHintResult.cs b/src/Toolbox/FakerTool/Engine/FakeHintResult.cs new file mode 100644 index 00000000..6704a00b --- /dev/null +++ b/src/Toolbox/FakerTool/Engine/FakeHintResult.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.FakerTool.Engine; + +/// +public sealed class FakeHintResult : HintResult +{ + /// For when a hint doesn't support a type or fails to fake it. + public static FakeHintResult None { get; } = new(false, null); + + /// + private FakeHintResult(bool hasData, IFaked? data) + : base(hasData, data) { } + + /// + public FakeHintResult(IFaked? data) + : this(true, data) { } +} diff --git a/src/Toolbox/FakerTool/Engine/FakePriority.cs b/src/Toolbox/FakerTool/Engine/FakePriority.cs new file mode 100644 index 00000000..197edba7 --- /dev/null +++ b/src/Toolbox/FakerTool/Engine/FakePriority.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.FakerTool.Hints; + +namespace Werecodent.CreateAndFake.FakerTool.Engine; + +/// Priorities for s. +public enum FakePriority +{ + /// Priority for hints that won't automatically execute. + /// Such hints only work if given to the tool via . + Disabled = int.MinValue, + + /// Priority for custom hints that'll execute last. + /// Subtract from this priority for even lower priorities. + None = 0, + + /// Priority for . + ObjectHint = 1, + + /// Priority for . + AsyncDisposableHint = 2, + + /// Priority for . + DisposableHint = 3, + + /// Starting priority for custom hints that'll execute first. + /// Add to this priority for even higher priorities. + Highest = 4, +} diff --git a/src/Toolbox/FakerTool/Engine/FakerChainer.cs b/src/Toolbox/FakerTool/Engine/FakerChainer.cs new file mode 100644 index 00000000..e4a357ea --- /dev/null +++ b/src/Toolbox/FakerTool/Engine/FakerChainer.cs @@ -0,0 +1,123 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.FakerTool.Engine; + +/// Provides a callback into to fake child values. +public sealed class FakerChainer + : ToolChainer, + IFakerChainer +{ + /// + public FakerChainer(FakerOptions options, IFakerEngine engine) + : base(options, engine) { } + + /// + private FakerChainer(FakerOptions options, FakerChainer prevChainer) + : base(options, prevChainer) { } + + /// + protected override FakerChainer CreateSubChainer(FakerOptions subOptions) + { + return new FakerChainer(subOptions, this); + } + + /// + public bool Supports(FakerMod? optionConfiguration = null) + { + return Supports(typeof(T), optionConfiguration); + } + + /// + public bool Supports(Type type, FakerMod? optionConfiguration = null) + { + return Engine.Supports(type, GetSubChainer(optionConfiguration)); + } + + /// + public Fake Mock(params IEnumerable interfaces) + { + return Mock(interfaces, null); + } + + /// + public Fake Mock(IEnumerable interfaces, FakerMod? optionConfiguration) + { + return new Fake(Engine.Mock(typeof(T), interfaces, GetSubChainer(optionConfiguration))); + } + + /// + public Fake Mock(Type parent, params IEnumerable interfaces) + { + return Mock(parent, interfaces, null); + } + + /// + public Fake Mock(Type parent, IEnumerable interfaces, FakerMod? optionConfiguration) + { + return Engine.Mock(parent, interfaces, GetSubChainer(optionConfiguration)); + } + + /// + public Fake Stub(params IEnumerable interfaces) + { + return Stub(interfaces, null); + } + + /// + public Fake Stub(IEnumerable interfaces, FakerMod? optionConfiguration) + { + Fake fake = Mock(interfaces, optionConfiguration); + fake.ThrowByDefault = false; + return fake; + } + + /// + public Fake Stub(Type parent, params IEnumerable interfaces) + { + return Stub(parent, interfaces, null); + } + + /// + public Fake Stub(Type parent, IEnumerable interfaces, FakerMod? optionConfiguration) + { + return Engine.Stub(parent, interfaces, GetSubChainer(optionConfiguration)); + } + + /// + public Injected InjectMocks(FakerMod? optionConfiguration = null) + { + return InjectMocks([], optionConfiguration); + } + + /// + public Injected InjectMocks( + IEnumerable values, + FakerMod? optionConfiguration = null + ) + { + return Engine.InjectMocks(values, GetSubChainer(optionConfiguration)); + } + + /// + public Injected InjectStubs(FakerMod? optionConfiguration = null) + { + return InjectStubs([], optionConfiguration); + } + + /// + public Injected InjectStubs( + IEnumerable values, + FakerMod? optionConfiguration = null + ) + { + return Engine.InjectStubs(values, GetSubChainer(optionConfiguration)); + } + + /// + public IFaker WithOptions(FakerMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Faker(optionConfiguration.Invoke(Options)); + } +} diff --git a/src/Toolbox/FakerTool/Engine/FakerEngine.cs b/src/Toolbox/FakerTool/Engine/FakerEngine.cs new file mode 100644 index 00000000..015d5c2b --- /dev/null +++ b/src/Toolbox/FakerTool/Engine/FakerEngine.cs @@ -0,0 +1,193 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.FakerTool.Engine; + +/// +public sealed class FakerEngine : ToolEngine, IFakerEngine +{ + /// + public bool Supports(Type type, IFakerChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + return chainer.SupportedTypes.Contains(type) || Subclasser.Supports(type); + } + + /// + public Fake Mock(Type parent, IEnumerable interfaces, IFakerChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + FakeHintResult? result; + try + { + result = SelectHints(chainer) + .Select(h => h.TryToFake(parent, interfaces, chainer)) + .FirstOrDefault(r => r?.HasData ?? false); + } + catch (Exception e) + { + throw new ToolException( + "Issue faking type with interfaces " + + $"'{string.Join("|", interfaces.Prepend(parent).Select(GenericConverter.ExpandName))}'.", + e + ); + } + + IFaked instance; + if (result != null) + { + instance = result.Data!; + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(parent)}' not supported by the faker. " + + "Create a hint to fake the type." + ); + } + + try + { + _ = SelectHints(chainer) + .Select(h => h.TryToSetup(instance, chainer)) + .FirstOrDefault(r => r?.HasData ?? false && !r.Data); + } + catch (Exception e) + { + throw new ToolException( + "Issue configuring faked type with interfaces " + + $"'{string.Join("|", interfaces.Prepend(parent).Select(GenericConverter.ExpandName))}'.", + e + ); + } + + return new Fake(instance); + } + + /// + public Fake Stub(Type parent, IEnumerable interfaces, IFakerChainer chainer) + { + Fake fake = Mock(parent, interfaces, chainer); + fake.ThrowByDefault = false; + return fake; + } + + /// + public Injected InjectMocks(IEnumerable values, IFakerChainer chainer) + { + return Inject(values?.ToArray() ?? [], t => Mock(t, [], chainer), chainer); + } + + /// + public Injected InjectStubs(IEnumerable values, IFakerChainer chainer) + { + return Inject(values?.ToArray() ?? [], t => Stub(t, [], chainer), chainer); + } + + /// Creates an instance injected with fakes. + /// Instance to be created. + /// Values to inject instead where possible. + /// Fake creation method to use. + /// Handles callback behavior for child values. + /// The created instance with its fakes. + /// + private Injected Inject( + ICollection values, + Func subclasser, + IFakerChainer chainer + ) + { + Type[] startingTypes = + [ + .. values + .Where(v => v != null) + .Select(v => (v is Fake fake) ? fake.Dummy : v) + .Select(v => v.GetType()), + ]; + + ConstructorInfo? maker = FindBestConstructor(startingTypes); + if (maker != null) + { + object?[] args = CreateInjectArgs(maker, values, subclasser, chainer); + + return new Injected( + (T)maker.Invoke([.. args.Select(v => (v is Fake fake) ? fake.Dummy : v)]), + args.OfType() + ); + } + else + { + throw new InvalidOperationException( + $"No constructors found on type '{typeof(T).Name}'." + ); + } + } + + /// Creates the args to inject an instance with. + /// Constructor to use. + /// Values to inject instead where possible. + /// Fake creation method to use. + /// Handles callback behavior for child values. + /// The created args to inject an instance with. + private object?[] CreateInjectArgs( + ConstructorInfo maker, + IEnumerable values, + Func subclasser, + IFakerChainer chainer + ) + { + List> data = + [ + .. values + .Where(v => v != null) + .Select(v => + Tuple.Create((v is Fake fake) ? fake.Dummy.GetType() : v.GetType(), v) + ), + ]; + + ParameterInfo[] info = maker.GetParameters(); + object?[] args = new object[info.Length]; + + for (int i = 0; i < args.Length; i++) + { + Tuple? match = data.Find(t => t.Item1.Inherits(info[i].ParameterType)); + if (match != default) + { + args[i] = match.Item2; + _ = data.Remove(match); + } + else if (Supports(info[i].ParameterType, chainer)) + { + args[i] = subclasser.Invoke(info[i].ParameterType); + } + else + { + args[i] = null; + } + } + return args; + } + + /// Finds the constructor with the most matches then by most parameters. + /// Type to search. + /// Argument types to search on. + /// The constructor best fitted to the types. + private static ConstructorInfo? FindBestConstructor(Type[] startingTypes) + { + return TypeDescriber + .For() + .Constructors.OnlyPublic.GroupBy(c => + c.GetParameters().Count(p => startingTypes.Any(t => t.Inherits(p.ParameterType))) + ) + .OrderByDescending(g => g.Key) + .FirstOrDefault() + ?.OrderByDescending(c => c.GetParameters()) + .FirstOrDefault(); + } +} diff --git a/src/Toolbox/FakerTool/Engine/IFakeHint.cs b/src/Toolbox/FakerTool/Engine/IFakeHint.cs new file mode 100644 index 00000000..1225b90f --- /dev/null +++ b/src/Toolbox/FakerTool/Engine/IFakeHint.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.FakerTool.Engine; + +/// Handles faking the . +public interface IFakeHint : IToolHint +{ + /// Tries to fake an instance of the given . + /// to generate. + /// Extra interfaces to implement. + /// Handles faking child values. + /// Possible result. + FakeHintResult TryToFake(Type parent, IEnumerable interfaces, IFakerChainer faker); + + /// Tries to configure the fake . + /// Fake to configure. + /// Handles faking child values. + /// Possible result. + SetupHintResult TryToSetup(IFaked instance, IFakerChainer faker); +} diff --git a/src/Toolbox/FakerTool/Engine/IFakerChainer.cs b/src/Toolbox/FakerTool/Engine/IFakerChainer.cs new file mode 100644 index 00000000..5c14ae6e --- /dev/null +++ b/src/Toolbox/FakerTool/Engine/IFakerChainer.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.FakerTool.Engine; + +/// Provides a callback into to fake child values. +public interface IFakerChainer : IFaker, IToolChainer; diff --git a/src/Toolbox/FakerTool/Engine/IFakerEngine.cs b/src/Toolbox/FakerTool/Engine/IFakerEngine.cs new file mode 100644 index 00000000..0ec793cc --- /dev/null +++ b/src/Toolbox/FakerTool/Engine/IFakerEngine.cs @@ -0,0 +1,27 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.FakerTool.Engine; + +/// +public interface IFakerEngine : IToolEngine +{ + /// Handles callback behavior for child values. + /// + bool Supports(Type type, IFakerChainer chainer); + + /// Handles callback behavior for child values. + /// + Fake Mock(Type parent, IEnumerable interfaces, IFakerChainer chainer); + + /// Handles callback behavior for child values. + /// + Fake Stub(Type parent, IEnumerable interfaces, IFakerChainer chainer); + + /// Handles callback behavior for child values. + /// + Injected InjectMocks(IEnumerable values, IFakerChainer chainer); + + /// Handles callback behavior for child values. + /// + Injected InjectStubs(IEnumerable values, IFakerChainer chainer); +} diff --git a/src/Toolbox/FakerTool/Engine/SetupHintResult.cs b/src/Toolbox/FakerTool/Engine/SetupHintResult.cs new file mode 100644 index 00000000..3a1aa4e5 --- /dev/null +++ b/src/Toolbox/FakerTool/Engine/SetupHintResult.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.FakerTool.Engine; + +/// +public sealed class SetupHintResult : HintResult +{ + /// For when a hint doesn't support a type or fails to fake it. + public static SetupHintResult None { get; } = new(false, false); + + /// + private SetupHintResult(bool hasData, bool data) + : base(hasData, data) { } + + /// + public SetupHintResult(bool data) + : this(true, data) { } +} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Fake.cs b/src/Toolbox/FakerTool/Fake.cs similarity index 81% rename from src/CreateAndFake/Toolbox/FakerTool/Fake.cs rename to src/Toolbox/FakerTool/Fake.cs index a3e7e3bf..9adfaeb4 100644 --- a/src/CreateAndFake/Toolbox/FakerTool/Fake.cs +++ b/src/Toolbox/FakerTool/Fake.cs @@ -1,88 +1,87 @@ -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFake.Toolbox.FakerTool; - -/// Manages faking behavior. -/// Faked implementation. -public class Fake(IFaked fake) -{ - /// Faked implementation. - public IFaked Dummy { get; } = fake ?? throw new ArgumentNullException(nameof(fake)); - - /// How to compare call data. - protected IValuer? Valuer => Dummy.FakeMeta.Valuer; - - /// Determines behavior when missing set behavior for a call. - public bool ThrowByDefault - { - get => Dummy.FakeMeta.ThrowByDefault; - set => Dummy.FakeMeta.ThrowByDefault = value; - } - - /// Ties a method call to fake behavior. - /// Method name of the call. - /// Args to match on the call. - /// Fake behavior to invoke. - /// Representation of the call. - public void Setup(string methodName, object[] args, Behavior callback) - { - Setup(methodName, [], args, callback); - } - - /// Ties a method call to fake behavior. - /// Method name of the call. - /// Generics tied to the call. - /// Args to match on the call. - /// Fake behavior to invoke. - /// Representation of the call. - public void Setup(string methodName, Type[] generics, object?[] args, Behavior callback) - { - Dummy.FakeMeta.SetCallBehavior(new CallData(methodName, generics, args, Valuer), callback); - } - - /// Verifies all behaviors with associated times were called as expected. - /// Expected total number of calls to test as well. - public void VerifyAll(Times? total = null) - { - Dummy.FakeMeta.Verify(); - if (total != null) - { - VerifyTotalCalls(total); - } - } - - /// Verifies the number of calls made. - /// Expected number of calls. - /// Method name of the call. - /// Args to match on the call. - public void Verify(Times times, string methodName, object[] args) - { - Verify(times, methodName, [], args); - } - - /// Verifies the number of calls made. - /// Expected number of calls. - /// Method name of the call. - /// Generics tied to the call. - /// Args to match on the call. - public void Verify(Times times, string methodName, Type[] generics, object?[] args) - { - Verify(times, new CallData(methodName, generics, args, Valuer)); - } - - /// Verifies the number of calls made. - /// Expected number of calls. - /// Call to verify. - private void Verify(Times times, CallData call) - { - Dummy.FakeMeta.Verify(times, call); - } - - /// Verifies the total number of calls made. - /// Expected total. - public void VerifyTotalCalls(Times times) - { - Dummy.FakeMeta.VerifyTotalCalls(times); - } -} +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// Manages faking behavior. +/// Faked implementation. +public class Fake(IFaked fake) +{ + /// Faked implementation. + public IFaked Dummy { get; } = fake ?? throw new ArgumentNullException(nameof(fake)); + + /// How to compare call data. + protected FakerOptions? Options => Dummy.FakeMeta.Options; + + /// Determines behavior when missing set behavior for a call. + public bool ThrowByDefault + { + get => Dummy.FakeMeta.ThrowByDefault; + set => Dummy.FakeMeta.ThrowByDefault = value; + } + + /// Ties a method call to fake behavior. + /// Method name of the call. + /// Args to match on the call. + /// Fake behavior to invoke. + /// Representation of the call. + public void Setup(string methodName, object[] args, Behavior callback) + { + Setup(methodName, [], args, callback); + } + + /// Ties a method call to fake behavior. + /// Method name of the call. + /// Generics tied to the call. + /// Args to match on the call. + /// Fake behavior to invoke. + /// Representation of the call. + public void Setup(string methodName, Type[] generics, object?[] args, Behavior callback) + { + Dummy.FakeMeta.SetCallBehavior(new CallData(methodName, generics, args, Options), callback); + } + + /// Verifies all behaviors with associated times were called as expected. + /// Expected total number of calls to test as well. + public void Verify(Times? total = null) + { + Dummy.FakeMeta.Verify(); + if (total != null) + { + Dummy.FakeMeta.VerifyTotalCalls(total); + } + } + + /// Verifies the number of calls made. + /// Expected number of calls. + /// Method name of the call. + /// Args to match on the call. + public void Verify(Times times, string methodName, object[] args) + { + Verify(times, methodName, [], args); + } + + /// Verifies the number of calls made. + /// Expected number of calls. + /// Method name of the call. + /// Generics tied to the call. + /// Args to match on the call. + public void Verify(Times times, string methodName, Type[] generics, object?[] args) + { + Verify(times, new CallData(methodName, generics, args, Options)); + } + + /// Verifies the number of calls made. + /// Expected number of calls. + /// Call to verify. + private void Verify(Times times, CallData call) + { + Dummy.FakeMeta.Verify(times, call); + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/FakerTool/FakeExtensions.cs b/src/Toolbox/FakerTool/FakeExtensions.cs new file mode 100644 index 00000000..5a7651e2 --- /dev/null +++ b/src/Toolbox/FakerTool/FakeExtensions.cs @@ -0,0 +1,21 @@ +namespace Werecodent.CreateAndFake.FakerTool; + +/// Niceties for fakes. +public static class FakeExtensions +{ + /// Switches the fake to a different type. + /// Alternative base to cast to. + /// Created fake with the extra type. + /// Fake to test with. + public static Fake ToFake(this Fake baseFake) + { + if (baseFake is Fake fake) + { + return fake; + } + else + { + return new Fake(baseFake); + } + } +} diff --git a/src/Toolbox/FakerTool/Faker.cs b/src/Toolbox/FakerTool/Faker.cs new file mode 100644 index 00000000..f7db8231 --- /dev/null +++ b/src/Toolbox/FakerTool/Faker.cs @@ -0,0 +1,117 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool.Engine; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// +/// +/// If given a parameter. +public sealed class Faker(FakerOptions options) : IFaker +{ + /// Handles hint based faking. + private static readonly FakerEngine _Engine = new(); + + /// + public FakerOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public IEnumerable SupportedTypes => _Engine.SupportedTypes; + + /// + public bool Supports(FakerMod? optionConfiguration = null) + { + return new FakerChainer(Options, _Engine).Supports(optionConfiguration); + } + + /// + public bool Supports(Type type, FakerMod? optionConfiguration = null) + { + return new FakerChainer(Options, _Engine).Supports(type, optionConfiguration); + } + + /// + public Fake Mock(params IEnumerable interfaces) + { + return new FakerChainer(Options, _Engine).Mock(interfaces); + } + + /// + public Fake Mock(IEnumerable interfaces, FakerMod? optionConfiguration) + { + return new FakerChainer(Options, _Engine).Mock(interfaces, optionConfiguration); + } + + /// + public Fake Mock(Type parent, params IEnumerable interfaces) + { + return new FakerChainer(Options, _Engine).Mock(parent, interfaces); + } + + /// + public Fake Mock(Type parent, IEnumerable interfaces, FakerMod? optionConfiguration) + { + return new FakerChainer(Options, _Engine).Mock(parent, interfaces, optionConfiguration); + } + + /// + public Fake Stub(params IEnumerable interfaces) + { + return new FakerChainer(Options, _Engine).Stub(interfaces); + } + + /// + public Fake Stub(IEnumerable interfaces, FakerMod? optionConfiguration) + { + return new FakerChainer(Options, _Engine).Stub(interfaces, optionConfiguration); + } + + /// + public Fake Stub(Type parent, params IEnumerable interfaces) + { + return new FakerChainer(Options, _Engine).Stub(parent, interfaces); + } + + /// + public Fake Stub(Type parent, IEnumerable interfaces, FakerMod? optionConfiguration) + { + return new FakerChainer(Options, _Engine).Stub(parent, interfaces, optionConfiguration); + } + + /// + public Injected InjectMocks(FakerMod? optionConfiguration = null) + { + return new FakerChainer(Options, _Engine).InjectMocks(optionConfiguration); + } + + /// + public Injected InjectMocks( + IEnumerable values, + FakerMod? optionConfiguration = null + ) + { + return new FakerChainer(Options, _Engine).InjectMocks(values, optionConfiguration); + } + + /// + public Injected InjectStubs(FakerMod? optionConfiguration = null) + { + return new FakerChainer(Options, _Engine).InjectStubs(optionConfiguration); + } + + /// + public Injected InjectStubs( + IEnumerable values, + FakerMod? optionConfiguration = null + ) + { + return new FakerChainer(Options, _Engine).InjectStubs(values, optionConfiguration); + } + + /// + public IFaker WithOptions(FakerMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Faker(optionConfiguration.Invoke(Options)); + } +} diff --git a/src/Toolbox/FakerTool/FakerOptions.cs b/src/Toolbox/FakerTool/FakerOptions.cs new file mode 100644 index 00000000..1193d149 --- /dev/null +++ b/src/Toolbox/FakerTool/FakerOptions.cs @@ -0,0 +1,42 @@ +using System.Reflection; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.FakerTool.Engine; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// Settings for manipulating behavior. +public sealed record FakerOptions : ToolHintOptions +{ + /// Identifies the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Faker); + + /// + public required IValuer Valuer { get; init; } + + /// If set, controls the default behavior for fake calls. + /// + internal Func? FakeDefaultGenerator { get; init; } = null; + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal FakerOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + IncludeFrameworkHints = Config.GetValue(section, IncludeFrameworkHints), + IncludeFoundHints = Config.GetValue(section, IncludeFoundHints), + MaxRecursionDepth = Config.GetValue(section, MaxRecursionDepth), + }; + } +} diff --git a/src/Toolbox/FakerTool/Fake{T}.cs b/src/Toolbox/FakerTool/Fake{T}.cs new file mode 100644 index 00000000..118a3922 --- /dev/null +++ b/src/Toolbox/FakerTool/Fake{T}.cs @@ -0,0 +1,210 @@ +using System.Linq.Expressions; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// being faked. +/// +public sealed class Fake : Fake +{ + /// + public new T Dummy => (T)base.Dummy; + + /// + public Fake(IFaked fake) + : base(fake) { } + + /// + /// Switches the fake to a different type. + public Fake(Fake baseFake) + : base(baseFake?.Dummy ?? throw new ArgumentNullException(nameof(baseFake))) + { + _ = (T)base.Dummy; + } + + /// Ties a set method call to fake behavior. + /// Property type. + /// Expression of property to setup. + /// Set value to match from the call. + /// Fake behavior to invoke. + /// Representation of the call. + public void SetupSet( + Expression> method, + TResult value, + Behavior callback + ) + { + (MethodInfo, Type[], object?[]) call = ExtractCall(method, true); + Setup(call.Item1.Name, call.Item2, [value], callback); + } + + /// Ties a set method call to fake behavior. + /// Property type. + /// Expression of property to setup. + /// Arg expression to match from the call. + /// Fake behavior to invoke. + /// Representation of the call. + public void SetupSet( + Expression> method, + Arg value, + Behavior callback + ) + { + (MethodInfo, Type[], object?[]) call = ExtractCall(method, true); + Setup(call.Item1.Name, call.Item2, [value], callback); + } + + /// Ties a method call to fake behavior. + /// Expression of method to setup. + /// Fake behavior to invoke. + /// Representation of the call. + public void Setup(Expression> method, Behavior callback) + { + (MethodInfo, Type[], object?[]) call = ExtractCall(method, false); + Setup(call.Item1.Name, call.Item2, call.Item3, callback); + } + + /// Ties a method call to fake behavior. + /// Method return type. + /// Expression of method to setup. + /// Fake behavior to invoke. + /// Representation of the call. + public void Setup(Expression> method, Behavior callback) + { + (MethodInfo, Type[], object?[]) call = ExtractCall(method, false); + Setup(call.Item1.Name, call.Item2, call.Item3, callback); + } + + /// Verifies the number of calls made to the setter. + /// Type to verify. + /// Expected number of calls. + /// Setter to verify. + /// Set value to match from the call. + public void VerifySet(Times times, Expression> method, TResult value) + { + (MethodInfo, Type[], object?[]) call = ExtractCall(method, true); + Verify(times, call.Item1.Name, call.Item2, [value]); + } + + /// Verifies the number of calls made to the setter. + /// Type to verify. + /// Expected number of calls. + /// Setter to verify. + /// Arg expression to match from the call. + public void VerifySet(Times times, Expression> method, Arg value) + { + (MethodInfo, Type[], object?[]) call = ExtractCall(method, true); + Verify(times, call.Item1.Name, call.Item2, [value]); + } + + /// Verifies the number of calls made to . + /// Expected number of calls. + /// Method to verify. + public void Verify(Times times, Expression> method) + { + (MethodInfo, Type[], object?[]) call = ExtractCall(method, false); + Verify(times, call.Item1.Name, call.Item2, call.Item3); + } + + /// Verifies the number of calls made to . + /// Type to verify. + /// Expected number of calls. + /// Method to verify. + public void Verify(Times times, Expression> method) + { + (MethodInfo, Type[], object?[]) call = ExtractCall(method, false); + Verify(times, call.Item1.Name, call.Item2, call.Item3); + } + + /// Changes expression to call data. + /// Expression to convert. + /// If only setter is allowed. + /// Method name, generics, and args. + /// + /// + private static (MethodInfo, Type[], object?[]) ExtractCall( + LambdaExpression method, + bool onlySetter + ) + { + ArgumentGuard.ThrowIfNull(method); + + if (!onlySetter && method.Body is MethodCallExpression methodCall) + { + if (methodCall.Method.IsStatic) + { + throw new UnsupportedException( + $"Method '{methodCall.Method.Name}' is static and not an actual member of '{typeof(T).Name}'." + ); + } + + Type[] generics = methodCall.Method.IsGenericMethod + ? methodCall.Method.GetGenericArguments() + : Type.EmptyTypes; + + return (methodCall.Method, generics, methodCall.Arguments.Select(ConvertArg).ToArray()); + } + else if (method.Body is MemberExpression memberExpression) + { + PropertyInfo info = (PropertyInfo)memberExpression.Member; + return onlySetter + ? (info.GetSetMethod()!, Type.EmptyTypes, []) + : (info.GetGetMethod()!, Type.EmptyTypes, []); + } + else + { + throw new InvalidOperationException($"Unexpected expression type: {method}"); + } + } + + /// Converts arg expressions to actual values. + /// Arg to convert. + /// Value to pass to the call. + private static object? ConvertArg(Expression arg) + { + if ( + arg is MemberExpression memberExpression + && memberExpression.Member.Name == nameof(OutRef<>.Var) + ) + { + return ConvertArg(memberExpression.Expression!); + } + + MethodCallExpression? call = + arg as MethodCallExpression + ?? (arg as UnaryExpression)?.Operand as MethodCallExpression; + if (call?.Method.DeclaringType == typeof(Arg) && call.Method.ReturnType != typeof(Arg)) + { + return ResolveArgLambda(call); + } + else + { + return Expression.Lambda(arg).Compile().DynamicInvoke(); + } + } + +#pragma warning disable IDE0200 // Code coverage issue. + + /// Converts an lambda arg expression to its actual value. + /// Expression of the arg to convert. + /// Value to pass to the call. + private static object ResolveArgLambda(MethodCallExpression call) + { + Type innerType = + (GenericConverter.AsGenericBase(call.Method.ReturnType) == typeof(OutRef<>)) + ? call.Method.ReturnType.GetGenericArguments().Single() + : call.Method.ReturnType; + + return typeof(Arg) + .GetMethod("Lambda" + call.Method.Name)! + .MakeGenericMethod(innerType) + .Invoke(null, [.. call.Arguments.Select(x => ConvertArg(x))])!; + } + +#pragma warning restore IDE0200 // Code coverage issue. +} diff --git a/src/Toolbox/FakerTool/Hints/AsyncDisposableFakeHint.cs b/src/Toolbox/FakerTool/Hints/AsyncDisposableFakeHint.cs new file mode 100644 index 00000000..dfa315ae --- /dev/null +++ b/src/Toolbox/FakerTool/Hints/AsyncDisposableFakeHint.cs @@ -0,0 +1,42 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool.Engine; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent; + +namespace Werecodent.CreateAndFake.FakerTool.Hints; + +/// Handles faking Span collections for . +public sealed class AsyncDisposableFakeHint : IFakeHint +{ + /// + public int EnginePriority => (int)FakePriority.AsyncDisposableHint; + + /// + public IEnumerable SupportedTypes => [typeof(IAsyncDisposable)]; + + /// + public FakeHintResult TryToFake(Type parent, IEnumerable interfaces, IFakerChainer faker) + { + return FakeHintResult.None; + } + + /// + public SetupHintResult TryToSetup(IFaked instance, IFakerChainer faker) + { + ArgumentGuard.ThrowIfNull(instance, faker); + + if (instance.GetType().Inherits()) + { + new Fake(instance).Setup( + f => f.DisposeAsync(), + Behavior.Returns(new ValueTask(Task.CompletedTask), Times.Any) + ); + + return new(true); + } + else + { + return SetupHintResult.None; + } + } +} diff --git a/src/Toolbox/FakerTool/Hints/DisposableFakeHint.cs b/src/Toolbox/FakerTool/Hints/DisposableFakeHint.cs new file mode 100644 index 00000000..313daaa5 --- /dev/null +++ b/src/Toolbox/FakerTool/Hints/DisposableFakeHint.cs @@ -0,0 +1,38 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool.Engine; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent; + +namespace Werecodent.CreateAndFake.FakerTool.Hints; + +/// Handles faking Span collections for . +public sealed class DisposableFakeHint : IFakeHint +{ + /// + public int EnginePriority => (int)FakePriority.DisposableHint; + + /// + public IEnumerable SupportedTypes => [typeof(IDisposable)]; + + /// + public FakeHintResult TryToFake(Type parent, IEnumerable interfaces, IFakerChainer faker) + { + return FakeHintResult.None; + } + + /// + public SetupHintResult TryToSetup(IFaked instance, IFakerChainer faker) + { + ArgumentGuard.ThrowIfNull(instance, faker); + + if (instance.GetType().Inherits()) + { + new Fake(instance).Setup(f => f.Dispose(), Behavior.None(Times.Any)); + return new(true); + } + else + { + return SetupHintResult.None; + } + } +} diff --git a/src/Toolbox/FakerTool/Hints/ObjectFakeHint.cs b/src/Toolbox/FakerTool/Hints/ObjectFakeHint.cs new file mode 100644 index 00000000..e4fdff14 --- /dev/null +++ b/src/Toolbox/FakerTool/Hints/ObjectFakeHint.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool.Engine; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.FakerTool.Hints; + +/// Handles faking Span collections for . +public sealed class ObjectFakeHint : IFakeHint +{ + /// + public int EnginePriority => (int)FakePriority.ObjectHint; + + /// + public IEnumerable SupportedTypes => [typeof(object)]; + + /// + public FakeHintResult TryToFake(Type parent, IEnumerable interfaces, IFakerChainer faker) + { + ArgumentGuard.ThrowIfNull(faker); + + return new(Subclasser.Create(parent, faker.Options, interfaces)); + } + + /// + public SetupHintResult TryToSetup(IFaked instance, IFakerChainer faker) + { + return SetupHintResult.None; + } +} diff --git a/src/Toolbox/FakerTool/IFaker.cs b/src/Toolbox/FakerTool/IFaker.cs new file mode 100644 index 00000000..6b00785d --- /dev/null +++ b/src/Toolbox/FakerTool/IFaker.cs @@ -0,0 +1,77 @@ +global using FakerMod = System.Func< + Werecodent.CreateAndFake.FakerTool.FakerOptions, + Werecodent.CreateAndFake.FakerTool.FakerOptions +>; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.FakerTool.Engine; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// Tool to simulate behavior via stubs/mocks. +/// Useful for testing in isolation from dependencies. +public interface IFaker : IHintTool +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + IFaker WithOptions(FakerMod optionConfiguration); + + /// Determines if can be faked. + /// to check. + /// + bool Supports(FakerMod? optionConfiguration = null); + + /// Determines if the can be faked. + /// to check. + /// Modifications of this tool's options to apply for this call. + /// if possible, otherwise. + bool Supports(Type type, FakerMod? optionConfiguration = null); + + /// /// + Fake Mock(params IEnumerable interfaces); + + /// being faked. + /// + Fake Mock(IEnumerable interfaces, FakerMod? optionConfiguration); + + /// + Fake Mock(Type parent, params IEnumerable interfaces); + + /// Creates a strict fake where calls fail unless set up. + /// + Fake Mock(Type parent, IEnumerable interfaces, FakerMod? optionConfiguration); + + /// /// + Fake Stub(params IEnumerable interfaces); + + /// being faked. + /// + Fake Stub(IEnumerable interfaces, FakerMod? optionConfiguration); + + /// + Fake Stub(Type parent, params IEnumerable interfaces); + + /// Creates a loose fake with a base default implementation. + /// Type being faked. + /// Extra interfaces to implement. + /// Modifications of this tool's options to apply for this call. + /// Handler for the fake behavior. + Fake Stub(Type parent, IEnumerable interfaces, FakerMod? optionConfiguration); + + /// + Injected InjectMocks(FakerMod? optionConfiguration = null); + + /// Creates an instance injected with mocks. + /// + Injected InjectMocks(IEnumerable values, FakerMod? optionConfiguration = null); + + /// + Injected InjectStubs(FakerMod? optionConfiguration = null); + + /// Creates an instance injected with stubs. + /// Instance type to be created. + /// Values to inject instead where possible. + /// Modifications of this tool's options to apply for this call. + /// The created instance with its fakes. + Injected InjectStubs(IEnumerable values, FakerMod? optionConfiguration = null); +} diff --git a/src/Toolbox/FakerTool/Injected.cs b/src/Toolbox/FakerTool/Injected.cs new file mode 100644 index 00000000..cf6db34e --- /dev/null +++ b/src/Toolbox/FakerTool/Injected.cs @@ -0,0 +1,67 @@ +using System.Collections.Immutable; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// Instance with dynamically injected fakes. +/// being injected by fakes. +public sealed class Injected +{ + /// Faked implementation. + public T Dummy { get; } + + /// Fakes injected into the dummy. + public ImmutableArray Fakes { get; } + + /// + /// Faked implementation. + /// Fakes injected into the dummy. + public Injected(T dummy, IEnumerable fakes) + { + ArgumentGuard.ThrowIfNull(dummy, fakes); + + Dummy = dummy; + Fakes = [.. fakes]; + } + + /// Finds the fake. + /// of fake to look for. + /// How many fakes of the to ignore first. + /// The found fake. + public Fake Fake(int skip = 0) + { + Fake? direct = Fakes.OfType>().Skip(skip).FirstOrDefault(); + + return direct + ?? Fakes + .Where(f => f.Dummy.GetType().Inherits()) + .Skip(skip) + .First() + .ToFake(); + } + + /// Finds the fake owner of the given dummy. + /// of fake to look for. + /// Dummy of a fake to search on. + /// The found fake. + public Fake Fake(TInject dummy) + { + return Fakes.First(f => ReferenceEquals(f.Dummy, dummy)).ToFake(); + } + + /// Verifies all behaviors in all fakes were called as expected. + public void Verify() + { + foreach (Fake fake in Fakes) + { + fake.Verify(); + } + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/FakerTool/OutRef.cs b/src/Toolbox/FakerTool/OutRef.cs new file mode 100644 index 00000000..0112c8da --- /dev/null +++ b/src/Toolbox/FakerTool/OutRef.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.FakerTool; + +#pragma warning disable CA1051, S1104 // Required to match out/ref. + +/// For matching and arguments. +/// Argument to match. +public sealed class OutRef : IOutRef +{ + /// Used as the out/ref argument. + public T? Var = default; +} + +#pragma warning restore diff --git a/src/Toolbox/FakerTool/Proxy/CallData.cs b/src/Toolbox/FakerTool/Proxy/CallData.cs new file mode 100644 index 00000000..5a8fe4b4 --- /dev/null +++ b/src/Toolbox/FakerTool/Proxy/CallData.cs @@ -0,0 +1,121 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.FakerTool.Proxy; + +/// Method call details. +/// +/// +/// +/// +internal sealed class CallData( + string methodName, + Type[] generics, + object?[] args, + FakerOptions? options +) : IDeepCloneable +{ + /// Name tied to the call. + private readonly string _methodName = methodName + ?? throw new ArgumentNullException(nameof(methodName)); + + /// Generics tied to the call. + private readonly Type[] _generics = generics + ?? throw new ArgumentNullException(nameof(generics)); + + /// Args tied to the call. + private readonly object?[] _args = args ?? throw new ArgumentNullException(nameof(args)); + + /// How to compare call data. + private readonly FakerOptions? _options = options; + + /// Converts arg values to designated Arg matchers. + /// Created Args to substitute on the given values. + internal void ConvertArgs(Tuple[] argChanges) + { + ArgumentGuard.ThrowIfNull(argChanges); + + List> changes = [.. argChanges]; + for (int i = 0; i < _args.Length; i++) + { + Tuple? change = changes.Find(c => Equals(c.Item2, _args[i])); + if (change != default) + { + _args[i] = change.Item1; + _ = changes.Remove(change); + } + } + } + + /// Determines if behavior is intended for a call. + /// Details of the call. + /// if matched, otherwise. + internal bool MatchesCall(CallData input) + { + ArgumentGuard.ThrowIfNull(input); + + return (_methodName == input._methodName) + && GenericsMatch(input._generics) + && ArgsMatch(input._args); + } + + /// Determines if the call generics match the expected ones. + /// Generics used in the call. + /// if matched, otherwise. + private bool GenericsMatch(Type[] inputGenerics) + { + bool matches = inputGenerics.Length == _generics.Length; + + for (int i = 0; matches && i < inputGenerics.Length; i++) + { + if (_generics[i] != typeof(AnyGeneric)) + { + matches &= _generics[i] == inputGenerics[i]; + } + } + return matches; + } + + /// Determines if the call args match the expected ones. + /// Args used in the call. + /// if matched, otherwise. + private bool ArgsMatch(object?[] inputArgs) + { + bool matches = inputArgs.Length == _args.Length; + + for (int i = 0; matches && i < inputArgs.Length; i++) + { + if (_args[i] is Arg exp) + { + matches &= exp.Matches(inputArgs[i]); + } + else if (_options?.Valuer != null) + { + matches &= _options.Valuer.Equals(inputArgs[i], _args[i]); + } + else + { + matches &= Equals(inputArgs[i], _args[i]); + } + } + return matches; + } + + /// + public CallData DeepClone() + { + return new CallData(_methodName, _generics, [.. _args], _options); + } + + /// Converts to a . + /// representation of . + public override string ToString() + { + string gen = + _generics.Length != 0 + ? $"<{string.Join(",", _generics.Select(GenericConverter.ExpandName))}>" + : ""; + return $"{_methodName}{gen}({string.Join(",", _args.Select(i => i ?? "'NULL'"))})"; + } +} diff --git a/src/Toolbox/FakerTool/Proxy/Emitter.cs b/src/Toolbox/FakerTool/Proxy/Emitter.cs new file mode 100644 index 00000000..f8f24844 --- /dev/null +++ b/src/Toolbox/FakerTool/Proxy/Emitter.cs @@ -0,0 +1,365 @@ +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.FakerTool.Proxy; + +#pragma warning disable S125 // Code comments are documentation here. + +/// Creates dynamic subclasses by IL code. +internal static class Emitter +{ + /// Assembly used to contain the dynamic types. + internal static AssemblyName AssemblyName { get; } = + new AssemblyName("Werecodent.CreateAndFake.FakerTypes"); + + /// Underlying type managing implementation details. + internal static Type FakeType { get; } = typeof(IFaked); + + /// Underlying type managing implementation details. + internal static Type MetaType { get; } = typeof(FakeMetaProvider); + + /// Flags used to find members to implement. + private const BindingFlags _MemberFinder = + BindingFlags.FlattenHierarchy + | BindingFlags.NonPublic + | BindingFlags.Instance + | BindingFlags.Public; + + /// Methods called to chain fake calls. + private static readonly MethodInfo _VoidChainer = + MetaType.GetMethod( + nameof(FakeMetaProvider.CallVoid), + BindingFlags.Instance | BindingFlags.NonPublic + )!, + _ResultChainer = + MetaType.GetMethod( + nameof(FakeMetaProvider.CallRet), + BindingFlags.Instance | BindingFlags.NonPublic + )!, + _TypeResolver = + typeof(Type).GetMethod( + nameof(Type.GetTypeFromHandle), + BindingFlags.Static | BindingFlags.Public + )!, + _CurrentMethodGrabber = + typeof(MethodBase).GetMethod( + nameof(MethodBase.GetCurrentMethod), + BindingFlags.Static | BindingFlags.Public + )!; + + /// Module storing the faked types. + private static readonly ModuleBuilder _Module = AssemblyBuilder + .DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess.RunAndCollect) + .DefineDynamicModule("Werecodent.CreateAndFakeFakerTypesModule"); + + /// Creates a type with the given inheritance. + /// Base class inheriting from. + /// Additional interfaces to inherit. + /// Dynamic type with behavior faked. + internal static TypeInfo BuildType(Type parent, Type[] interfaces) + { + ArgumentGuard.ThrowIfNull(parent, interfaces); + + TypeBuilder newType = _Module.DefineType( + "Fake_" + + string.Join("|", interfaces.Prepend(parent).Select(GenericConverter.ExpandName)) + + "_" + + Guid.NewGuid(), + TypeAttributes.Sealed, + parent, + interfaces + ); + + MethodInfo metaGetter = SetupFakeMetaProvider(newType, SetupConstructor(newType, parent)); + + (PropertyInfo, PropertyBuilder)[] props = + [ + .. FindImplementableProperties(interfaces.Prepend(parent)) + .Select(p => + ( + p, + newType.DefineProperty( + p.DeclaringType!.Name + "." + p.Name, + p.Attributes, + p.PropertyType, + Type.EmptyTypes + ) + ) + ), + ]; + + foreach (MethodInfo method in FindImplementableMethods(interfaces.Prepend(parent))) + { + MethodBuilder fakedMethod = newType.DefineMethod( + method.DeclaringType!.Name + "." + method.Name, + method.Attributes & ~MethodAttributes.Abstract, + method.ReturnType, + [.. method.GetParameters().Select(p => p.ParameterType)] + ); + + if (method.IsGenericMethod) + { + _ = fakedMethod.DefineGenericParameters([ + .. method.GetGenericArguments().Select(a => a.Name), + ]); + } + ImplementFakeBehavior(fakedMethod.GetILGenerator(), method, metaGetter); + newType.DefineMethodOverride(fakedMethod, method); + + foreach ((PropertyInfo, PropertyBuilder) prop in props) + { + if (prop.Item1.GetMethod == method) + { + prop.Item2.SetGetMethod(fakedMethod); + } + else if (prop.Item1.SetMethod == method) + { + prop.Item2.SetSetMethod(fakedMethod); + } + } + } + + return newType.CreateTypeInfo()!; + } + + /// Finds all properties to generate for a type implementing the given interfaces. + /// Interfaces to inherit. + /// Properties to implement for the faked type. + private static IEnumerable FindImplementableProperties( + IEnumerable interfaces + ) + { + return interfaces + .Where(t => t != typeof(IFaked)) + .SelectMany(t => + TypeDescriber + .For(t) + .Properties.Visible.Where(p => IsVisible(p.GetMethod) || IsVisible(p.SetMethod)) + .Concat(FindImplementableProperties(t.GetInterfaces())) + ) + .Distinct(); + } + + /// Finds all methods to generate for a type implementing the given interfaces. + /// Interfaces to inherit. + /// Methods to implement for the faked type. + private static IEnumerable FindImplementableMethods(IEnumerable interfaces) + { + return interfaces + .Where(t => t != typeof(IFaked)) + .SelectMany(i => + i.GetMethods(_MemberFinder) + .Where(m => m.IsAbstract || (m.IsVirtual && !m.IsFinal)) + .Where(m => IsVisible(m)) + .Where(m => m.Name != "Finalize") + .Concat(FindImplementableMethods(i.GetInterfaces())) + ) + .Distinct(); + } + + /// Determines if the method is visible for faking. + /// Method to check. + /// True if visible; false otherwise. + private static bool IsVisible(MethodInfo? method) + { + if (method == null) + { + return true; + } + + return !method.IsPrivate + && ( + !(method.IsAssembly || method.IsFamilyAndAssembly) + || method + .Module.Assembly.GetCustomAttributes() + .Any(a => a.AssemblyName == AssemblyName.Name) + ); + } + + /// Chains the call for a method. + /// Generator for the fake method. + /// Method being implemented. + /// Hook for the meta provider to chain with. + private static void ImplementFakeBehavior( + ILGenerator gen, + MethodInfo method, + MethodInfo metaGetter + ) + { + ParameterInfo[] argInfos = method.GetParameters(); + Type[] generics = method.GetGenericArguments(); + + // object[] args = new object[params.Length]; + LocalBuilder args = gen.DeclareLocal(typeof(object[])); + gen.Emit(OpCodes.Ldc_I4, argInfos.Length); + gen.Emit(OpCodes.Newarr, typeof(object)); + gen.Emit(OpCodes.Stloc, args); + + // args[0..x] = params[0..x]; + for (int i = 0; i < argInfos.Length; i++) + { + gen.Emit(OpCodes.Ldloc, args); + gen.Emit(OpCodes.Ldc_I4, i); + if (!argInfos[i].ParameterType.IsByRef) + { + gen.Emit(OpCodes.Ldarg, i + 1); + gen.Emit(OpCodes.Box, argInfos[i].ParameterType); + gen.Emit(OpCodes.Stelem_Ref); + } + else + { + // args[i] = new OutRef(); + Type outRef = typeof(OutRef<>).MakeGenericType( + argInfos[i].ParameterType.GetElementType()! + ); + gen.Emit(OpCodes.Newobj, outRef.GetConstructor(Type.EmptyTypes)!); + gen.Emit(OpCodes.Stelem_Ref); + if (!argInfos[i].IsOut) + { + // ((OutRef)args[i].Var) = params[i]; + gen.Emit(OpCodes.Ldloc, args); + gen.Emit(OpCodes.Ldc_I4, i); + gen.Emit(OpCodes.Ldelem_Ref); + gen.Emit(OpCodes.Castclass, outRef); + gen.Emit(OpCodes.Ldarg, i + 1); + gen.Emit(OpCodes.Ldind_Ref); + gen.Emit(OpCodes.Stfld, outRef.GetField(nameof(OutRef<>.Var))!); + } + } + } + + // Type[] types = new Type[generics.Length]; + LocalBuilder types = gen.DeclareLocal(typeof(Type[])); + gen.Emit(OpCodes.Ldc_I4, generics.Length); + gen.Emit(OpCodes.Newarr, typeof(Type)); + gen.Emit(OpCodes.Stloc, types); + + // types[0..x] = typeof(generics[0..x]); + for (int i = 0; i < generics.Length; i++) + { + gen.Emit(OpCodes.Ldloc, types); + gen.Emit(OpCodes.Ldc_I4, i); + gen.Emit(OpCodes.Ldtoken, generics[i]); + gen.Emit(OpCodes.Call, _TypeResolver); + gen.Emit(OpCodes.Stelem_Ref); + } + + // this.FakeMeta.Call(this, MethodBase.GetCurrentMethod(), types, args); + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Callvirt, metaGetter); + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Call, _CurrentMethodGrabber); + gen.Emit(OpCodes.Ldloc, types); + gen.Emit(OpCodes.Ldloc, args); + if (method.ReturnType != typeof(void)) + { + gen.Emit(OpCodes.Callvirt, _ResultChainer.MakeGenericMethod(method.ReturnType)); + } + else + { + gen.Emit(OpCodes.Callvirt, _VoidChainer); + } + + // params[0..x] = ((OutRef)args[0..x]).Var; + for (int i = 0; i < argInfos.Length; i++) + { + if (argInfos[i].ParameterType.IsByRef) + { + Type outRef = typeof(OutRef<>).MakeGenericType( + argInfos[i].ParameterType.GetElementType()! + ); + + gen.Emit(OpCodes.Ldarg, i + 1); + gen.Emit(OpCodes.Ldloc, args); + gen.Emit(OpCodes.Ldc_I4, i); + gen.Emit(OpCodes.Ldelem_Ref); + gen.Emit(OpCodes.Castclass, outRef); + gen.Emit(OpCodes.Ldfld, outRef.GetField(nameof(OutRef<>.Var))!); + gen.Emit(OpCodes.Stind_Ref); + } + } + + gen.Emit(OpCodes.Ret); + } + + /// Creates the constructor with the backing field for the meta provider. + /// Dynamic type being created. + /// Base class inheriting from. + /// Info for the meta provider field. + private static FieldBuilder SetupConstructor(TypeBuilder newType, Type parent) + { + ConstructorInfo? baseConstructor = parent + .GetConstructors(_MemberFinder) + .SingleOrDefault(c => c.GetParameters().Length == 0); + + FieldBuilder backingField = newType.DefineField( + "_" + nameof(IFaked.FakeMeta), + MetaType, + FieldAttributes.Private | FieldAttributes.InitOnly + ); + + ConstructorBuilder constructor = newType.DefineConstructor( + MethodAttributes.Public, + CallingConventions.HasThis, + [MetaType] + ); + { + // base(); + ILGenerator gen = constructor.GetILGenerator(); + if (baseConstructor != null) + { + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Call, baseConstructor); + } + + // this.m_FakeMeta = params[0]; + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Ldarg_1); + gen.Emit(OpCodes.Stfld, backingField); + gen.Emit(OpCodes.Ret); + } + + return backingField; + } + + /// Hooks up the fake behavior mechanism for the new type. + /// Dynamic type being created. + /// Field holding the meta provider. + /// Info for the meta provider get hook. + private static MethodInfo SetupFakeMetaProvider(TypeBuilder newType, FieldInfo backingField) + { + PropertyInfo propInfo = FakeType.GetProperty(nameof(IFaked.FakeMeta))!; + MethodInfo getterInfo = propInfo.GetGetMethod()!; + + MethodBuilder getMetaMethod = newType.DefineMethod( + nameof(IFaked) + "." + getterInfo.Name, + getterInfo.Attributes & ~MethodAttributes.Abstract, + MetaType, + Type.EmptyTypes + ); + { + // return this._FakeMeta; + ILGenerator gen = getMetaMethod.GetILGenerator(); + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Ldfld, backingField); + gen.Emit(OpCodes.Ret); + } + + newType + .DefineProperty( + nameof(IFaked) + "." + propInfo.Name, + propInfo.Attributes, + MetaType, + Type.EmptyTypes + ) + .SetGetMethod(getMetaMethod); + + newType.DefineMethodOverride(getMetaMethod, getterInfo); + return getterInfo; + } +} + +#pragma warning restore diff --git a/src/Toolbox/FakerTool/Proxy/FakeCallException.cs b/src/Toolbox/FakerTool/Proxy/FakeCallException.cs new file mode 100644 index 00000000..8024ac52 --- /dev/null +++ b/src/Toolbox/FakerTool/Proxy/FakeCallException.cs @@ -0,0 +1,49 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.FakerTool.Proxy; + +/// Exception for a call lacking behavior. +[Serializable] +public sealed class FakeCallException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private FakeCallException() + : base() { } + + /// + /// Associated call data. + /// Call data with behavior. + internal FakeCallException(CallData data, IEnumerable setup) + : base(BuildMessage(data, setup)) { } + + /// + /// Object data. + /// Additional info. + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private FakeCallException(SerializationInfo info, StreamingContext context) + : base(info, context) { } + + /// Integrates the details into the message. + /// Associated call data. + /// Call data with behavior. + /// Message to use for the exception. + private static string BuildMessage(CallData data, IEnumerable setup) + { + string nl = Environment.NewLine; + + return "Method called without matched behavior." + + ((data == null) ? "" : $"{nl}Call: {data}") + + ((setup == null) ? "" : $"{nl}Calls with behavior set: {BuildMessage(setup)}"); + } + + /// + private static string BuildMessage(IEnumerable setup) + { + return Environment.NewLine + string.Join(Environment.NewLine, setup); + } +} diff --git a/src/Toolbox/FakerTool/Proxy/FakeMetaProvider.cs b/src/Toolbox/FakerTool/Proxy/FakeMetaProvider.cs new file mode 100644 index 00000000..342a62f2 --- /dev/null +++ b/src/Toolbox/FakerTool/Proxy/FakeMetaProvider.cs @@ -0,0 +1,342 @@ +using System.Linq.Expressions; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool; + +namespace Werecodent.CreateAndFake.FakerTool.Proxy; + +#pragma warning disable S2696 // Thread local. + +/// Internal mechanism for faked object behavior. +/// +/// +public sealed class FakeMetaProvider(int identifier, FakerOptions options) + : IDuplicatable +{ + /// Last called method. + [ThreadStatic] + private static Tuple? _LastCall; + + /// Faked behavior. + private readonly Stack<(CallData, Behavior)> _behavior = new(); + + /// Record of calls made. + private readonly List _log = []; + + /// Value assigned to identify the instance. + /// Uniqueness not guaranteed nor verified. + public int Identifier { get; } = identifier; + + /// Determines behavior when missing set behavior for a call. + public bool ThrowByDefault { get; set; } = true; + + /// + internal FakerOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + /// Behavior to pass in. + /// Record of calls to pass in. + /// Copy constructor. + internal FakeMetaProvider( + int identifier, + FakerOptions options, + IEnumerable<(CallData, Behavior)> behavior, + IEnumerable log + ) + : this(identifier, options) + { + ArgumentGuard.ThrowIfNull(behavior, log); + + foreach ((CallData, Behavior) set in behavior) + { + _behavior.Push(set); + } + _log.AddRange(log); + } + + /// + public FakeMetaProvider DeepClone(IDuplicator duplicator) + { + ArgumentGuard.ThrowIfNull(duplicator); + + return new FakeMetaProvider( + Identifier, + duplicator.Copy(Options), + _behavior.Reverse().Select(t => duplicator.Copy(t)), + _log.Select(t => duplicator.Copy(t)) + ) + { + ThrowByDefault = ThrowByDefault, + }; + } + + /// Sets up behavior for the fake method last called. + /// Behavior to tie to the call. + /// + internal static void SetLastCallBehavior(Behavior behavior) + { + if (_LastCall == null) + { + throw new InvalidOperationException( + "Faked method never called to set behavior for. " + + "Verify instance is marked with [Fake] or [Stub], and method is abstract." + ); + } + + _ = _LastCall.Item1._log.Remove(_LastCall.Item2); + _LastCall.Item1.SetCallBehavior(_LastCall.Item2, behavior); + _LastCall.Item2.ConvertArgs(Arg.CaptureSetArgs()); + _LastCall = null; + } + + /// Sets up behavior for the fake. + /// Call to set behavior for. + /// Behavior to tie to the call. + internal void SetCallBehavior(CallData callData, Behavior behavior) + { + ArgumentGuard.ThrowIfNull(callData, behavior); + + _behavior.Push((callData, behavior)); + } + + /// Verifies behavior with associated times were called as expected. + /// + internal void Verify() + { + (CallData, Behavior)[] invalids = [.. _behavior.Where(t => !t.Item2.HasExpectedCalls())]; + if (invalids.Length != 0) + { + throw new FakeVerifyException(invalids, _log); + } + } + + /// Verifies the number of calls made. + /// Expected number of calls. + /// Call to verify. + /// + internal void Verify(Times times, CallData callData) + { + ArgumentGuard.ThrowIfNull(times, callData); + + IEnumerable calls = [.. _log.Where(callData.MatchesCall)]; + if (!times.IsInRange(calls.Count())) + { + throw new FakeVerifyException(callData, times, calls.Count(), _log); + } + } + + /// Verifies the total number of calls made. + /// Expected total. + /// + internal void VerifyTotalCalls(Times times) + { + ArgumentGuard.ThrowIfNull(times); + + if (!times.IsInRange(_log.Count)) + { + throw new FakeVerifyException(times, _log); + } + } + + /// Manager for all action calls. + /// The faked object. + /// Method being called. + /// Generics tied to the call. + /// Provided args to the call. + /// + internal void CallVoid(object instance, MethodInfo calledMethod, Type[] generics, object[] args) + { + object? result = CallBehavior(instance, calledMethod, generics, args); + if (result != null) + { + throw new InvalidOperationException( + $"Method '{GetMethodName(calledMethod)}' expected void but instead returned '{result}'." + ); + } + } + + /// Manager for all func calls. + /// Return type. + /// The faked object. + /// Method being called. + /// Generics tied to the call. + /// Provided args to the call. + /// Faked result previously set up. + /// + internal T? CallRet(object instance, MethodInfo calledMethod, Type[] generics, object[] args) + { + return CallBehavior(instance, calledMethod, generics, args); + } + + /// Manager for all calls. + /// Return type. + /// The faked object. + /// Method being called. + /// Generics tied to the call. + /// Provided args to the call. + /// Faked result previously set up. + /// + private T? CallBehavior( + object instance, + MethodInfo calledMethod, + Type[] generics, + object[] args + ) + { + ArgumentGuard.ThrowIfNull(calledMethod); + + CallData data = new(GetMethodName(calledMethod), generics, args, Options); + _log.Add(data); + _LastCall = Tuple.Create(this, data); + + (CallData, Behavior) match = _behavior.FirstOrDefault(t => t.Item1.MatchesCall(data)); + if (match.Equals(default)) + { + if (ThrowByDefault && GetMethodName(calledMethod) != "Finalizer") + { + throw new FakeCallException(data, _behavior.Select(b => b.Item1)); + } + else if (Options.FakeDefaultGenerator != null) + { + return (T?) + Options + .FakeDefaultGenerator.Invoke( + calledMethod.IsGenericMethod + ? calledMethod.MakeGenericMethod(generics) + : calledMethod, + data + ) + .Invoke(args); + } + else + { + return default; + } + } + + if (match.Item2.CallBase) + { + return CallBase(instance, calledMethod, generics, match, args); + } + else + { + return (T?)match.Item2.Invoke(args); + } + } + + /// Calls the base method for a behavior. + /// Return type. + /// The faked object. + /// Method being called. + /// Generics tied to the call. + /// Behavior details. + /// Provided args to the call. + /// Base method result. + /// + /// + private T? CallBase( + object instance, + MethodInfo calledMethod, + Type[] generics, + (CallData, Behavior) match, + object[] args + ) + { + string specificName = GetMethodName(calledMethod); + Type[] specificParameters = + [ + .. ( + calledMethod.IsGenericMethod + ? calledMethod.MakeGenericMethod(generics) + : calledMethod + ) + .GetParameters() + .Select(p => p.ParameterType), + ]; + + MethodInfo? searchForSourceMethod() + { + Type? currentType = calledMethod.DeclaringType?.BaseType; + for (int i = 0; currentType != null; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i, Options.Design.IterationLimit); + + MethodInfo? method = TypeDescriber + .For(currentType) + .Methods.All.Where(m => m.Name == specificName) + .Where(m => + generics.Length == (m.IsGenericMethod ? m.GetGenericArguments().Length : 0) + ) + .Select(m => m.IsGenericMethod ? m.MakeGenericMethod(generics) : m) + .FirstOrDefault(m => + m.GetParameters() + .Select(p => p.ParameterType) + .SequenceEqual(specificParameters) + ); + + if (method != null) + { + return method; + } + + currentType = currentType.BaseType; + } + return null; + } + + MethodInfo? found = searchForSourceMethod(); + + if (found == null) + { + throw new MissingMethodException( + $"Method '{GetMethodName(calledMethod)}' does not exist on '{calledMethod.DeclaringType?.BaseType}'" + ); + } + else if (found.IsAbstract) + { + throw new InvalidOperationException( + $"Cannot call base '{GetMethodName(calledMethod)}' as it's abstract." + ); + } + else + { + Delegate caller = (Delegate) + Activator.CreateInstance( + FindDelegateType(found), + instance, + found.MethodHandle.GetFunctionPointer() + )!; + + return (T?)match.Item2.Invoke(caller, args); + } + } + +#pragma warning disable CA1307 // Not available for all .NET versions. + private static string GetMethodName(MethodInfo method) + { + return method.Name.Substring(method.Name.LastIndexOf('.') + 1); + } +#pragma warning restore CA1307 + + /// Matches a delegate to the method. + /// Method to call. + /// Found delegate type. + private static Type FindDelegateType(MethodInfo methodInfo) + { + IEnumerable args = methodInfo.GetParameters().Select(p => p.ParameterType); + + return (methodInfo.ReturnType == typeof(void)) + ? Expression.GetActionType([.. args]) + : Expression.GetFuncType([.. args, methodInfo.ReturnType]); + } + + /// + public override string ToString() + { + return $"{GenericConverter.ExpandName(GetType())}({Identifier})"; + } +} + +#pragma warning restore diff --git a/src/Toolbox/FakerTool/Proxy/FakeVerifyException.cs b/src/Toolbox/FakerTool/Proxy/FakeVerifyException.cs new file mode 100644 index 00000000..12b82c09 --- /dev/null +++ b/src/Toolbox/FakerTool/Proxy/FakeVerifyException.cs @@ -0,0 +1,100 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.FakerTool.Proxy; + +/// Exception for call counts not matching expectations. +[Serializable] +public sealed class FakeVerifyException : CreateAndFakeException +{ + /// + /// Serialization constructor. + private FakeVerifyException() + : base() { } + + /// + /// Associated call data. + /// Expected number of calls. + /// Actual number of calls. + /// Log of all made calls. + internal FakeVerifyException( + CallData data, + Times expected, + int actual, + IEnumerable log + ) + : base(BuildMessage(data, expected?.ToString(), actual, log)) { } + + /// + /// Expected number of calls. + /// Log of all made calls. + internal FakeVerifyException(Times expected, IEnumerable log) + : base(BuildMessage(null, expected?.ToString(), log?.Count(), log)) { } + + /// + /// Call data with behavior that aren't valid. + /// Log of all made calls. + internal FakeVerifyException( + IEnumerable<(CallData, Behavior)> invalidCalls, + IEnumerable log + ) + : base(BuildMessage(invalidCalls, log)) { } + + /// + /// Object data. + /// Additional info. + /// Serialization constructor. +#if NET5_0_OR_GREATER + [Obsolete("ISerializable has been disabled.", DiagnosticId = "SYSLIB0051")] +#endif + private FakeVerifyException(SerializationInfo info, StreamingContext context) + : base(info, context) { } + + /// Integrates the details into the message. + /// Call data with behavior that aren't valid. + /// Log of all made calls. + /// Message to use for the exception. + private static string BuildMessage( + IEnumerable<(CallData, Behavior)> invalidCalls, + IEnumerable log + ) + { + return string.Join( + Environment.NewLine, + ( + invalidCalls?.Select(i => + BuildMessage(i.Item1, i.Item2.ToExpectedCalls(), i.Item2.Calls, null) + ) + ?? [] + ).Append((log == null) ? "" : $"Log: {BuildMessage(log)}") + ); + } + + /// Integrates the details into the message. + /// Associated call data. + /// Expected number of calls. + /// Actual number of calls. + /// Log of all made calls. + /// Message to use for the exception. + private static string BuildMessage( + CallData? source, + string? expected, + int? actual, + IEnumerable? log + ) + { + string nl = Environment.NewLine; + + return $"Expected '{expected}', but had '{actual}' calls." + + ((source == null) ? "" : $"{nl}Call: {source}") + + ((log == null) ? "" : $"{nl}Log: {BuildMessage(log)}"); + } + + /// Integrates the details into the message. + /// Log of all made calls. + /// Message to use for the exception. + private static string BuildMessage(IEnumerable log) + { + return Environment.NewLine + string.Join(Environment.NewLine, log); + } +} diff --git a/src/CreateAndFake/Toolbox/FakerTool/Proxy/IFaked.cs b/src/Toolbox/FakerTool/Proxy/IFaked.cs similarity index 76% rename from src/CreateAndFake/Toolbox/FakerTool/Proxy/IFaked.cs rename to src/Toolbox/FakerTool/Proxy/IFaked.cs index 9215cad3..f65ce6ab 100644 --- a/src/CreateAndFake/Toolbox/FakerTool/Proxy/IFaked.cs +++ b/src/Toolbox/FakerTool/Proxy/IFaked.cs @@ -1,8 +1,8 @@ -namespace CreateAndFake.Toolbox.FakerTool.Proxy; - -/// Represents a faked implementation. -public interface IFaked -{ - /// Handles the behavior of the faked object. - FakeMetaProvider FakeMeta { get; } -} +namespace Werecodent.CreateAndFake.FakerTool.Proxy; + +/// Represents a faked implementation. +public interface IFaked +{ + /// Handles the behavior of the faked object. + FakeMetaProvider FakeMeta { get; } +} diff --git a/src/Toolbox/FakerTool/Proxy/IOutRef.cs b/src/Toolbox/FakerTool/Proxy/IOutRef.cs new file mode 100644 index 00000000..3d0b4c4c --- /dev/null +++ b/src/Toolbox/FakerTool/Proxy/IOutRef.cs @@ -0,0 +1,4 @@ +namespace Werecodent.CreateAndFake.FakerTool.Proxy; + +/// Marker for OutRef. +public interface IOutRef; diff --git a/src/Toolbox/FakerTool/Proxy/Subclasser.cs b/src/Toolbox/FakerTool/Proxy/Subclasser.cs new file mode 100644 index 00000000..ba3c90a9 --- /dev/null +++ b/src/Toolbox/FakerTool/Proxy/Subclasser.cs @@ -0,0 +1,253 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.FakerTool.Proxy; + +/// Creates dynamic subclasses. +internal static class Subclasser +{ + /// Prevents concurrency issues for . + private static readonly Lock _Lock = new(); + + /// Cache of already created types. + private static readonly Dictionary _TypeCache = []; + + /// Types not supported with the error message for them. + private static readonly Dictionary _InvalidTypes = new() + { + { typeof(Array), $"Cannot subclass system reserved '{nameof(Array)}' type." }, + { typeof(ObjectDisposedException), $"{typeof(ObjectDisposedException)} not allowed." }, + { typeof(Uri), $"{typeof(Uri)} not supported without a provided constructor." }, + { typeof(Task), $"{typeof(Task)} not supported without a provided constructor." }, + { typeof(ValueTask), $"{typeof(ValueTask)} not supported without a provided constructor." }, + { + typeof(ValueTask?), + $"{typeof(ValueTask?)} not supported without a provided constructor." + }, + { typeof(Task<>), $"{typeof(Task<>)} not supported without a provided constructor." }, + { + typeof(ValueTask<>), + $"{typeof(ValueTask<>)} not supported without a provided constructor." + }, + { + typeof(StreamReader), + $"{typeof(StreamReader)} not supported without a provided constructor." + }, + { + typeof(StreamWriter), + $"{typeof(StreamWriter)} not supported without a provided constructor." + }, +#if NET11_0_OR_GREATER + { typeof(FieldInfo), $"{typeof(FieldInfo)} itself has specific issues being faked." }, +#endif +#if LEGACY // Required feature shipped with C# 14 / .NET 10.0 + { typeof(TypeInfo), $"{typeof(TypeInfo)} itself has specific issues being faked." }, +#endif + }; + + /// Assembly used to contain the dynamic types. + public static AssemblyName AssemblyName => Emitter.AssemblyName; + + /// Determines if the type can be faked. + /// Type to check. + /// True if possible; false otherwise. + public static bool Supports() + { + return Supports(typeof(T)); + } + + /// Determines if the type can be faked. + /// Type to check. + /// True if possible; false otherwise. + public static bool Supports(Type type) + { + return CanBeSubclassed(type).Item1; + } + + /// Creates a subclass of the given type. + /// Parent type to inherit from. + /// Configured options being used by the tool. + /// Extra interfaces to implement. + /// An instance of the created child type. + public static T Create(FakerOptions options, params IEnumerable interfaces) + { + return (T)Create(typeof(T), options, interfaces); + } + + /// Creates a subclass of the given type. + /// Parent type to inherit from. + /// Configured options being used by the tool. + /// Extra interfaces to implement. + /// An instance of the created child type. + public static IFaked Create( + Type parent, + FakerOptions options, + params IEnumerable interfaces + ) + { + ArgumentGuard.ThrowIfNull(options); + + return (IFaked) + CreateInfo(parent, interfaces) + .AsType() + .GetConstructor([Emitter.MetaType])! + .Invoke([new FakeMetaProvider(options.Gen.Next(), options)]); + } + + /// Creates a subclass of the given type. + /// Parent type to inherit from. + /// Extra interfaces to implement. + /// The created child type. + /// + internal static TypeInfo CreateInfo(Type parent, params IEnumerable interfaces) + { + List allInterfaces = interfaces?.ToList() ?? []; + allInterfaces.Add(Emitter.FakeType); + + Type realParent = parent ?? typeof(object); + if (realParent.IsInterface) + { + allInterfaces.Add(realParent); + realParent = typeof(object); + } + + (bool, Exception?) possible = CanBeSubclassed(realParent); + if (!possible.Item1) + { + throw possible.Item2!; + } + + IEnumerable invalidInterfaces = allInterfaces.Where(t => !t.IsInterface); + if (invalidInterfaces.Any()) + { + throw new ArgumentException( + "Given interfaces not actually interfaces: '" + + string.Join("', '", invalidInterfaces.Select(t => t.Name)) + + "'.", + nameof(interfaces) + ); + } + + return FindOrBuildType(realParent, [.. allInterfaces.Distinct()]); + } + + /// Determines if type can be subclassed. + /// Type to check. + /// True if possible; false if not with exception to throw. + private static (bool, Exception?) CanBeSubclassed(Type parent) + { + TypeDescriber info = TypeDescriber.For(parent); + + if (parent == null) + { + return (true, null); + } + else if ( + _InvalidTypes.TryGetValue( + GenericConverter.AsGenericBase(parent) ?? parent, + out string? error + ) + ) + { + return (false, new ArgumentException(error, nameof(parent))); + } + else if (parent.IsSealed) + { + return ( + false, + new ArgumentException( + $"Cannot subclass the sealed type '{parent.Name}'.", + nameof(parent) + ) + ); + } + else if (parent.IsPointer) + { + return ( + false, + new ArgumentException( + $"Cannot subclass the pointer '{parent.Name}'.", + nameof(parent) + ) + ); + } + else if (parent.ContainsGenericParameters) + { + return ( + false, + new ArgumentException( + $"Cannot subclass with unspecified generics '{parent.Name}'.", + nameof(parent) + ) + ); + } + else if (!ScopeChecker.IsVisible(parent, AssemblyName)) + { + return ( + false, + new ArgumentException( + $"Cannot subclass with nonpublic type '{parent.Name}'. Think about adding " + + $"'InternalsVisibleTo(\"{AssemblyName.Name}\")' to the type's assembly.", + nameof(parent) + ) + ); + } + else if (info.Inherits()) + { + return ( + false, + new ArgumentException($"Cannot subclass delegate '{parent}' type.", nameof(parent)) + ); + } + else if (info.StaticMethods.All.Any(m => m.IsAbstract)) + { + return ( + false, + new ArgumentException("Static virtual members not yet supported.", nameof(parent)) + ); + } + else if (parent.Namespace == "System.Numerics") + { + return ( + false, + new ArgumentException( + "Numerics private static virtual members not supported.", + nameof(parent) + ) + ); + } + else + { + return (true, null); + } + } + + /// Finds or creates a type with the given hierarchy. + /// Parent type to inherit from. + /// Extra interfaces to implement. + /// The cached or created child type. + private static TypeInfo FindOrBuildType(Type parent, Type[] interfaces) + { + lock (_Lock) + { + TypeInfo cachedType = _TypeCache + .Where(t => t.Key.BaseType == parent) + .SingleOrDefault(t => + !t.Value.Except(interfaces).Union(interfaces.Except(t.Value)).Any() + ) + .Key; + + if (cachedType != null) + { + return cachedType; + } + else + { + TypeInfo newType = Emitter.BuildType(parent, interfaces); + _TypeCache.Add(newType, interfaces); + return newType; + } + } + } +} diff --git a/src/Toolbox/FakerTool/Times.cs b/src/Toolbox/FakerTool/Times.cs new file mode 100644 index 00000000..1fc2fe79 --- /dev/null +++ b/src/Toolbox/FakerTool/Times.cs @@ -0,0 +1,142 @@ +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.FakerTool; + +/// Tracks number of calls. +public sealed class Times : IEquatable, IDeepCloneable, IValueEquatable +{ + /// Expected bounds. + private readonly int _min, + _max; + + /// + /// Inclusive upper and lower bound. + /// Sets the expected bounds to a single value. + private Times(int count) + : this(count, count) { } + + /// + /// Inclusive lower bound. + /// Inclusive upper bound. + private Times(int min, int max) + { + _min = min; + _max = max; + } + + /// + public Times DeepClone() + { + return new Times(_min, _max); + } + + /// Checks if is in the expected range. + /// Value to verify. + /// + /// if is in range, otherwise. + /// + internal bool IsInRange(int count) + { + return _min <= count && count <= _max; + } + + /// Compares to by value. + /// Instance to compare with. + /// + /// if is equal to by value, + /// otherwise. + /// + public override bool Equals(object? obj) + { + return Equals(obj as Times); + } + + /// + public bool Equals(Times? other) + { + return other != null && _min == other._min && _max == other._max; + } + + /// Computes an identifying hash code based upon value. + /// The computed hash code. + public override int GetHashCode() + { + return ValueComparer.Use.GetHashCode(_min, _max); + } + + /// + public bool ValuesEqual(object? other) + { + return Equals(other); + } + + /// + public int GetValueHash() + { + return GetHashCode(); + } + + /// Converts to a . + /// representation of . + public override string ToString() + { + string maxValue = (_max != int.MaxValue) ? $"{_max}" : "*"; + return (_min != _max) ? $"[{_min}-{maxValue}]" : maxValue; + } + + /// Sets the expected bounds to a single value. + /// Upper and lower bound. + public static implicit operator Times(int count) + { + return ToTimes(count); + } + + /// Sets the expected bounds to a single value. + /// Upper and lower bound. + public static Times ToTimes(int count) + { + return new Times(count); + } + + /// Represents 0 allowed calls. + public static Times Never { get; } = Exactly(0); + + /// Represents 1 allowed calls. + public static Times Once { get; } = Exactly(1); + + /// Represents any number of allowed calls. + public static Times Any { get; } = AtLeast(0); + + /// Sets the expected bounds to exactly . + /// Upper and lower bound. + /// Representation of the bounds. + public static Times Exactly(int count) + { + return new Times(count); + } + + /// Sets the bounds to and . + /// Lower bound. + /// Upper bound. + /// Representation of the bounds. + public static Times Between(int min, int max) + { + return new Times(min, max); + } + + /// Sets the expected bounds to be greater than or equal to the . + /// Inclusive lower bound. + /// Representation of the bounds. + public static Times AtLeast(int count) + { + return Between(count, int.MaxValue); + } + + /// Sets the expected bounds to anything less than or equal to the . + /// Inclusive upper bound. + /// Representation of the bounds. + public static Times AtMost(int count) + { + return Between(0, count); + } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncEnumerable.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncEnumerable.cs new file mode 100644 index 00000000..c1c37920 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncEnumerable.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +/// +public sealed class AssertAsyncEnumerable + : AssertAsyncEnumerableBase> +{ + /// + internal AssertAsyncEnumerable(IAsserter asserter, IAsyncEnumerable? collection) + : base(asserter, collection) { } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncEnumerableBase.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncEnumerableBase.cs new file mode 100644 index 00000000..64d6c2e0 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncEnumerableBase.cs @@ -0,0 +1,382 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +#pragma warning disable CA1068 // Cleaner calls. + +/// Handles common collection assertion calls. +/// +/// +public abstract class AssertAsyncEnumerableBase( + IAsserter asserter, + IAsyncEnumerable? collection +) : AssertAsyncObjectBase(asserter, collection) + where TSelf : AssertAsyncEnumerableBase +{ + /// Collection to run assertion checks with. + protected IAsyncEnumerable? Collection { get; } = collection; + + /// + /// + public virtual async Task> IsEmptyAsync( + CancellationToken canceler, + string? details = null + ) + { + await Asserter.IsEmptyAsync(Collection, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> IsEmptyAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .IsEmptyAsync(Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> IsNotEmptyAsync( + CancellationToken canceler, + string? details = null + ) + { + await Asserter.IsNotEmptyAsync(Collection, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> IsNotEmptyAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .IsNotEmptyAsync(Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountAsync( + int count, + CancellationToken canceler, + string? details = null + ) + { + await Asserter.HasCountAsync(count, Collection, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountAsync( + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .HasCountAsync(count, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountLessThanAsync( + int count, + CancellationToken canceler, + string? details = null + ) + { + await Asserter + .HasCountLessThanAsync(count, Collection, canceler, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountLessThanAsync( + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .HasCountLessThanAsync(count, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountLessOrExactlyAsync( + int count, + CancellationToken canceler, + string? details = null + ) + { + await Asserter + .HasCountLessOrExactlyAsync(count, Collection, canceler, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountLessOrExactlyAsync( + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .HasCountLessOrExactlyAsync(count, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountMoreThanAsync( + int count, + CancellationToken canceler, + string? details = null + ) + { + await Asserter + .HasCountMoreThanAsync(count, Collection, canceler, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountMoreThanAsync( + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .HasCountMoreThanAsync(count, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountMoreOrExactlyAsync( + int count, + CancellationToken canceler, + string? details = null + ) + { + await Asserter + .HasCountMoreOrExactlyAsync(count, Collection, canceler, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> HasCountMoreOrExactlyAsync( + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .HasCountMoreOrExactlyAsync(count, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ContainsAsync( + TItem? content, + CancellationToken canceler, + string? details = null + ) + { + await Asserter.ContainsAsync(content, Collection, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ContainsAsync( + TItem? content, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ContainsAsync(content, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ContainsNotAsync( + TItem? content, + CancellationToken canceler, + string? details = null + ) + { + await Asserter + .ContainsNotAsync(content, Collection, canceler, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ContainsNotAsync( + TItem? content, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ContainsNotAsync(content, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> FailAsync( + CancellationToken canceler, + string? details = null + ) + { + await Asserter.FailAsync(Collection, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> FailAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .FailAsync(Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> DebugAsync( + CancellationToken canceler, + string? details = null + ) + { + await Asserter.DebugAsync(Collection, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> DebugAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .DebugAsync(Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + public virtual async Task> ThrowsAsync( + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + await Asserter + .ThrowsAsync(Collection, canceler, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + await Asserter + .ThrowsAsync(Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsExceptionAsync( + CancellationToken canceler, + string? details = null + ) + { + return new ExceptionChainer( + await Asserter + .ThrowsExceptionAsync(Collection, canceler, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsExceptionAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ExceptionChainer( + await Asserter + .ThrowsExceptionAsync(Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncObject.cs.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncObject.cs.cs new file mode 100644 index 00000000..488e5242 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncObject.cs.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +/// +public sealed class AssertAsyncObject : AssertAsyncObjectBase +{ + /// + internal AssertAsyncObject(IAsserter asserter, object? actual) + : base(asserter, actual) { } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncObjectBase.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncObjectBase.cs new file mode 100644 index 00000000..084aba40 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertAsyncObjectBase.cs @@ -0,0 +1,154 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +#pragma warning disable CA1068 // Cleaner calls. + +/// Handles assertion calls for delegates. +/// +public abstract class AssertAsyncObjectBase(IAsserter asserter, object? actual) + : AssertObjectBase(asserter, actual) + where T : AssertAsyncObjectBase +{ + /// + /// + public async Task> IsAsync( + object? expected, + CancellationToken canceler, + string? details = null + ) + { + await Asserter.IsAsync(expected, Actual, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public async Task> IsAsync( + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .IsAsync(expected, Actual, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public async Task> IsNotAsync( + object? expected, + CancellationToken canceler, + string? details = null + ) + { + await Asserter.IsNotAsync(expected, Actual, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public async Task> IsNotAsync( + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .IsNotAsync(expected, Actual, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ValuesEqualAsync( + object? expected, + CancellationToken canceler, + string? details = null + ) + { + await Asserter.ValuesEqualAsync(expected, Actual, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ValuesEqualAsync( + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ValuesEqualAsync(expected, Actual, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ValuesNotEqualAsync( + object? expected, + CancellationToken canceler, + string? details = null + ) + { + await Asserter + .ValuesNotEqualAsync(expected, Actual, canceler, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ValuesNotEqualAsync( + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ValuesNotEqualAsync(expected, Actual, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> UniqueFromAsync( + object? expected, + CancellationToken canceler, + string? details = null + ) + { + await Asserter.AreUniqueAsync(expected, Actual, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> UniqueFromAsync( + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .AreUniqueAsync(expected, Actual, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericTask.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericTask.cs new file mode 100644 index 00000000..3bb9657d --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericTask.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +/// +public sealed class AssertGenericTask : AssertGenericTaskBase> +{ + /// + internal AssertGenericTask(IAsserter asserter, Task? behavior) + : base(asserter, behavior) { } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericTaskBase.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericTaskBase.cs new file mode 100644 index 00000000..0911d015 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericTaskBase.cs @@ -0,0 +1,77 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +#pragma warning disable CA1068 // Cleaner calls. + +/// Handles assertion calls for delegates. +/// Delegate to check. +/// +public abstract class AssertGenericTaskBase(IAsserter asserter, Task? behavior) + : AssertTaskBase(asserter, behavior) + where TSelf : AssertGenericTaskBase +{ + /// Delegate to run assertion checks with. + protected new Task? Behavior { get; } = behavior; + + /// + public virtual async Task> HasResultAsync( + CancellationToken canceler, + string? details = null + ) + { + return new ResultChainer( + await Asserter.HasResultAsync(Behavior, canceler, details).ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> HasResultAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ResultChainer( + await Asserter + .HasResultAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> HasResultAsync( + TItem expected, + CancellationToken canceler, + string? details = null + ) + { + return new ResultChainer( + await Asserter + .HasResultAsync(expected, Behavior, canceler, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> HasResultAsync( + TItem expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ResultChainer( + await Asserter + .HasResultAsync(expected, Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericValueTask.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericValueTask.cs new file mode 100644 index 00000000..0a48df7d --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericValueTask.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +/// +public sealed class AssertGenericValueTask + : AssertGenericValueTaskBase> +{ + /// + internal AssertGenericValueTask(IAsserter asserter, ValueTask? operation) + : base(asserter, operation) { } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericValueTaskBase.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericValueTaskBase.cs new file mode 100644 index 00000000..bc5836ae --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertGenericValueTaskBase.cs @@ -0,0 +1,191 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +#pragma warning disable CA1068 // Cleaner calls. + +/// Handles assertion calls for delegates. +/// Delegate to check. +/// +public abstract class AssertGenericValueTaskBase( + IAsserter asserter, + ValueTask? behavior +) : AssertAsyncObjectBase(asserter, behavior) + where TSelf : AssertGenericValueTaskBase +{ + /// Delegate to run assertion checks with. + protected ValueTask? Behavior { get; } = behavior; + + /// + public virtual async Task> HasResultAsync( + CancellationToken canceler, + string? details = null + ) + { + return new ResultChainer( + await Asserter.HasResultAsync(Behavior, canceler, details).ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> HasResultAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ResultChainer( + await Asserter + .HasResultAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> HasResultAsync( + TItem expected, + CancellationToken canceler, + string? details = null + ) + { + return new ResultChainer( + await Asserter + .HasResultAsync(expected, Behavior, canceler, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> HasResultAsync( + TItem expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ResultChainer( + await Asserter + .HasResultAsync(expected, Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsAsync( + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + await Asserter + .ThrowsAsync(Behavior, canceler, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + await Asserter + .ThrowsAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsExceptionAsync( + CancellationToken canceler, + string? details = null + ) + { + return new ExceptionChainer( + await Asserter.ThrowsExceptionAsync(Behavior, canceler, details).ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsExceptionAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ExceptionChainer( + await Asserter + .ThrowsExceptionAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + /// + public virtual async Task ThrowsNoAsync( + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + await Asserter + .ThrowsNoAsync(Behavior, canceler, details) + .ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + await Asserter + .ThrowsNoAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoExceptionAsync( + CancellationToken canceler, + string? details = null + ) + { + await Asserter.ThrowsNoExceptionAsync(Behavior, canceler, details).ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoExceptionAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ThrowsNoExceptionAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return new AlsoChainer(Asserter); + } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertTask.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertTask.cs new file mode 100644 index 00000000..b10d0eb8 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertTask.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +/// +public sealed class AssertTask : AssertTaskBase +{ + /// + internal AssertTask(IAsserter asserter, Task? operation) + : base(asserter, operation) { } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertTaskBase.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertTaskBase.cs new file mode 100644 index 00000000..453ee7f6 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertTaskBase.cs @@ -0,0 +1,131 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +#pragma warning disable CA1068 // Cleaner calls. + +/// Handles assertion calls for delegates. +/// Delegate to check. +/// +public abstract class AssertTaskBase(IAsserter asserter, Task? behavior) + : AssertAsyncObjectBase(asserter, behavior) + where T : AssertTaskBase +{ + /// Delegate to run assertion checks with. + protected Task? Behavior { get; } = behavior; + + /// + public virtual async Task> ThrowsAsync( + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + await Asserter + .ThrowsAsync(Behavior, canceler, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + await Asserter + .ThrowsAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsExceptionAsync( + CancellationToken canceler, + string? details = null + ) + { + return new ExceptionChainer( + await Asserter.ThrowsExceptionAsync(Behavior, canceler, details).ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsExceptionAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ExceptionChainer( + await Asserter + .ThrowsExceptionAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + /// + public virtual async Task ThrowsNoAsync( + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + await Asserter.ThrowsNoAsync(Behavior, canceler, details).ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + await Asserter + .ThrowsNoAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoExceptionAsync( + CancellationToken canceler, + string? details = null + ) + { + await Asserter.ThrowsNoExceptionAsync(Behavior, canceler, details).ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoExceptionAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ThrowsNoExceptionAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return new AlsoChainer(Asserter); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertValueTask.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertValueTask.cs new file mode 100644 index 00000000..0052e9c0 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertValueTask.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +/// +public sealed class AssertValueTask : AssertValueTaskBase +{ + /// + internal AssertValueTask(IAsserter asserter, ValueTask? operation) + : base(asserter, operation) { } +} diff --git a/src/Toolbox/Fluent/AssertAsyncCalls/AssertValueTaskBase.cs b/src/Toolbox/Fluent/AssertAsyncCalls/AssertValueTaskBase.cs new file mode 100644 index 00000000..56e887b9 --- /dev/null +++ b/src/Toolbox/Fluent/AssertAsyncCalls/AssertValueTaskBase.cs @@ -0,0 +1,131 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.AsyncCategories; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +#pragma warning disable CA1068 // Cleaner calls. + +/// Handles assertion calls for delegates. +/// Delegate to check. +/// +public abstract class AssertValueTaskBase(IAsserter asserter, ValueTask? behavior) + : AssertAsyncObjectBase(asserter, behavior) + where T : AssertValueTaskBase +{ + /// Delegate to run assertion checks with. + protected ValueTask? Behavior { get; } = behavior; + + /// + public virtual async Task> ThrowsAsync( + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + await Asserter + .ThrowsAsync(Behavior, canceler, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + await Asserter + .ThrowsAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsExceptionAsync( + CancellationToken canceler, + string? details = null + ) + { + return new ExceptionChainer( + await Asserter.ThrowsExceptionAsync(Behavior, canceler, details).ConfigureAwait(false), + Asserter + ); + } + + /// + public virtual async Task> ThrowsExceptionAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ExceptionChainer( + await Asserter + .ThrowsExceptionAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// + /// + public virtual async Task ThrowsNoAsync( + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + await Asserter.ThrowsNoAsync(Behavior, canceler, details).ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + await Asserter + .ThrowsNoAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoExceptionAsync( + CancellationToken canceler, + string? details = null + ) + { + await Asserter.ThrowsNoExceptionAsync(Behavior, canceler, details).ConfigureAwait(false); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual async Task ThrowsNoExceptionAsync( + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ThrowsNoExceptionAsync(Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return new AlsoChainer(Asserter); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/AssertCalls/AssertAction.cs b/src/Toolbox/Fluent/AssertCalls/AssertAction.cs new file mode 100644 index 00000000..592e3f22 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertAction.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// +public sealed class AssertAction : AssertActionBase +{ + /// + internal AssertAction(IAsserter asserter, Action? behavior) + : base(asserter, behavior) { } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertActionBase.cs b/src/Toolbox/Fluent/AssertCalls/AssertActionBase.cs new file mode 100644 index 00000000..46df3ae0 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertActionBase.cs @@ -0,0 +1,100 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// Handles assertion calls for delegates. +/// Delegate to check. +/// +public abstract class AssertActionBase(IAsserter asserter, Action? behavior) + : AssertObjectBase(asserter, behavior) + where T : AssertActionBase +{ + /// Delegate to run assertion checks with. + protected Action? Behavior { get; } = behavior; + + /// + public virtual ExceptionChainer Throws(string? details = null) + where TException : Exception + { + return new ExceptionChainer( + Asserter.Throws(Behavior, details), + Asserter + ); + } + + /// + public virtual ExceptionChainer Throws( + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + Asserter.Throws(Behavior, optionConfiguration, details), + Asserter + ); + } + + /// + public virtual ExceptionChainer ThrowsException(string? details = null) + { + return new ExceptionChainer( + Asserter.ThrowsException(Behavior, details), + Asserter + ); + } + + /// + public virtual ExceptionChainer ThrowsException( + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ExceptionChainer( + Asserter.ThrowsException(Behavior, optionConfiguration, details), + Asserter + ); + } + + /// + /// + public virtual AlsoChainer ThrowsNo(string? details = null) + where TException : Exception + { + Asserter.ThrowsNo(Behavior, details); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual AlsoChainer ThrowsNo( + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + Asserter.ThrowsNo(Behavior, optionConfiguration, details); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual AlsoChainer ThrowsNoException(string? details = null) + { + Asserter.ThrowsNoException(Behavior, details); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual AlsoChainer ThrowsNoException( + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.ThrowsNoException(Behavior, optionConfiguration, details); + return new AlsoChainer(Asserter); + } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertComparable.cs b/src/Toolbox/Fluent/AssertCalls/AssertComparable.cs new file mode 100644 index 00000000..dc87dc0c --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertComparable.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// +public sealed class AssertComparable : AssertComparableBase +{ + /// + internal AssertComparable(IAsserter asserter, IComparable? value) + : base(asserter, value) { } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertComparableBase.cs b/src/Toolbox/Fluent/AssertCalls/AssertComparableBase.cs new file mode 100644 index 00000000..249e2342 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertComparableBase.cs @@ -0,0 +1,161 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// Handles common comparables assertion calls. +/// +/// +public abstract class AssertComparableBase(IAsserter asserter, IComparable? value) + : AssertObjectBase(asserter, value) + where T : AssertComparableBase +{ + /// Value to run assertion checks with. + protected IComparable? Value { get; } = value; + + /// + /// + public virtual AssertChainer GreaterThan(IComparable target, string? details = null) + { + Asserter.GreaterThan(target, Value, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer GreaterThan( + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.GreaterThan(target, Value, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer GreaterThanOrEqualTo(IComparable target, string? details = null) + { + Asserter.GreaterThanOrEqualTo(target, Value, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer GreaterThanOrEqualTo( + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.GreaterThanOrEqualTo(target, Value, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer GreaterThanOrIs(IComparable target, string? details = null) + { + Asserter.GreaterThanOrIs(target, Value, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer GreaterThanOrIs( + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.GreaterThanOrIs(target, Value, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer LessThan(IComparable target, string? details = null) + { + Asserter.LessThan(target, Value, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer LessThan( + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.LessThan(target, Value, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer LessThanOrEqualTo(IComparable target, string? details = null) + { + Asserter.LessThanOrEqualTo(target, Value, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer LessThanOrEqualTo( + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.LessThanOrEqualTo(target, Value, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer LessThanOrIs(IComparable target, string? details = null) + { + Asserter.LessThanOrIs(target, Value, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer LessThanOrIs( + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.LessThanOrIs(target, Value, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer InRange( + IComparable min, + IComparable max, + string? details = null + ) + { + Asserter.InRange(min, max, Value, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer InRange( + IComparable min, + IComparable max, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.InRange(min, max, Value, optionConfiguration, details); + return ToChainer(); + } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertDelegate.cs b/src/Toolbox/Fluent/AssertCalls/AssertDelegate.cs new file mode 100644 index 00000000..61943461 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertDelegate.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +#pragma warning disable CA1711 // Follows existing pattern. + +/// +public sealed class AssertDelegate : AssertDelegateBase +{ + /// + internal AssertDelegate(IAsserter asserter, Delegate? behavior) + : base(asserter, behavior) { } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/AssertCalls/AssertDelegateBase.cs b/src/Toolbox/Fluent/AssertCalls/AssertDelegateBase.cs new file mode 100644 index 00000000..034ac693 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertDelegateBase.cs @@ -0,0 +1,175 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +#pragma warning disable CA1068 // Cleaner calls. + +/// Handles assertion calls for delegates. +/// Delegate to check. +/// +public abstract class AssertDelegateBase(IAsserter asserter, Delegate? behavior) + : AssertObjectBase(asserter, behavior) + where T : AssertDelegateBase +{ + /// Delegate to run assertion checks with. + protected Delegate? Behavior { get; } = behavior; + + /// + public virtual ExceptionChainer Throws(string? details = null) + where TException : Exception + { + return new ExceptionChainer( + Asserter.Throws(Behavior, details), + Asserter + ); + } + + /// + public virtual ExceptionChainer Throws( + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + return new ExceptionChainer( + Asserter.Throws(Behavior, optionConfiguration, details), + Asserter + ); + } + + /// + public virtual ExceptionChainer ThrowsException(string? details = null) + { + return new ExceptionChainer( + Asserter.ThrowsException(Behavior, details), + Asserter + ); + } + + /// + public virtual ExceptionChainer ThrowsException( + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ExceptionChainer( + Asserter.ThrowsException(Behavior, optionConfiguration, details), + Asserter + ); + } + + /// + /// + public virtual AlsoChainer ThrowsNo(string? details = null) + where TException : Exception + { + Asserter.ThrowsNo(Behavior, details); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual AlsoChainer ThrowsNo( + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + Asserter.ThrowsNo(Behavior, optionConfiguration, details); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual AlsoChainer ThrowsNoException(string? details = null) + { + Asserter.ThrowsNoException(Behavior, details); + return new AlsoChainer(Asserter); + } + + /// + /// + public virtual AlsoChainer ThrowsNoException( + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.ThrowsNoException(Behavior, optionConfiguration, details); + return new AlsoChainer(Asserter); + } + + /// + public virtual ResultChainer HasResult(string? details = null) + { + return new ResultChainer(Asserter.HasResult(Behavior, details), Asserter); + } + + /// Expected return of the behavior. + /// + public virtual ResultChainer HasResult( + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ResultChainer( + Asserter.HasResult(Behavior, optionConfiguration, details), + Asserter + ); + } + + /// + public virtual ResultChainer HasResult(TItem expected, string? details = null) + { + return new ResultChainer(Asserter.HasResult(expected, Behavior, details), Asserter); + } + + /// Expected return of the behavior. + /// + public virtual ResultChainer HasResult( + TItem expected, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ResultChainer( + Asserter.HasResult(expected, Behavior, optionConfiguration, details), + Asserter + ); + } + + /// + public virtual async Task> HasResultAsync( + TItem expected, + CancellationToken canceler, + string? details = null + ) + { + return new ResultChainer( + await Asserter + .HasResultAsync(expected, Behavior, canceler, details) + .ConfigureAwait(false), + Asserter + ); + } + + /// Expected return of the behavior. + /// + public virtual async Task> HasResultAsync( + TItem expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ResultChainer( + await Asserter + .HasResultAsync(expected, Behavior, canceler, optionConfiguration, details) + .ConfigureAwait(false), + Asserter + ); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/AssertCalls/AssertEnumerable.cs b/src/Toolbox/Fluent/AssertCalls/AssertEnumerable.cs new file mode 100644 index 00000000..f260326a --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertEnumerable.cs @@ -0,0 +1,12 @@ +using System.Collections; +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// +public sealed class AssertEnumerable : AssertEnumerableBase +{ + /// + internal AssertEnumerable(IAsserter asserter, IEnumerable? collection) + : base(asserter, collection) { } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertEnumerableBase.cs b/src/Toolbox/Fluent/AssertCalls/AssertEnumerableBase.cs new file mode 100644 index 00000000..8699e684 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertEnumerableBase.cs @@ -0,0 +1,285 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +#pragma warning disable CA1068 // Cleaner calls. + +/// Handles common collection assertion calls. +/// +/// +public abstract class AssertEnumerableBase(IAsserter asserter, IEnumerable? collection) + : AssertAsyncObjectBase(asserter, collection) + where T : AssertEnumerableBase +{ + /// Collection to run assertion checks with. + protected IEnumerable? Collection { get; } = collection; + + /// + /// + public virtual AssertChainer IsEmpty(string? details = null) + { + Asserter.IsEmpty(Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer IsEmpty( + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.IsEmpty(Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer IsNotEmpty(string? details = null) + { + Asserter.IsNotEmpty(Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer IsNotEmpty( + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.IsNotEmpty(Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCount(int count, string? details = null) + { + Asserter.HasCount(count, Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCount( + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.HasCount(count, Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCountLessThan(int count, string? details = null) + { + Asserter.HasCountLessThan(count, Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCountLessThan( + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.HasCountLessThan(count, Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCountLessOrExactly(int count, string? details = null) + { + Asserter.HasCountLessOrExactly(count, Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCountLessOrExactly( + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.HasCountLessOrExactly(count, Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCountMoreThan(int count, string? details = null) + { + Asserter.HasCountMoreThan(count, Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCountMoreThan( + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.HasCountMoreThan(count, Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCountMoreOrExactly(int count, string? details = null) + { + Asserter.HasCountMoreOrExactly(count, Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer HasCountMoreOrExactly( + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.HasCountMoreOrExactly(count, Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Contains(object? content, string? details = null) + { + Asserter.Contains(content, Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Contains( + object? content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.Contains(content, Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual async Task> ContainsAsync( + object? content, + CancellationToken canceler, + string? details = null + ) + { + await Asserter.ContainsAsync(content, Collection, canceler, details).ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ContainsAsync( + object? content, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ContainsAsync(content, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ContainsNot(object? content, string? details = null) + { + Asserter.ContainsNot(content, Collection, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ContainsNot( + object? content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.ContainsNot(content, Collection, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual async Task> ContainsNotAsync( + object? content, + CancellationToken canceler, + string? details = null + ) + { + await Asserter + .ContainsNotAsync(content, Collection, canceler, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + /// + public virtual async Task> ContainsNotAsync( + object? content, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + await Asserter + .ContainsNotAsync(content, Collection, canceler, optionConfiguration, details) + .ConfigureAwait(false); + return ToChainer(); + } + + /// + [DoesNotReturn] + public override void Fail(string? details = null) + { + Asserter.Fail(Collection, details); + } + + /// + [DoesNotReturn] + public override void Fail(AsserterMod? optionConfiguration, string? details = null) + { + Asserter.Fail(Collection, optionConfiguration, details); + } + + /// + public override AssertChainer Debug(string? details = null) + { + Asserter.Debug(Collection, details); + return ToChainer(); + } + + /// + public override AssertChainer Debug(AsserterMod? optionConfiguration, string? details = null) + { + Asserter.Debug(Collection, optionConfiguration, details); + return ToChainer(); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/AssertCalls/AssertError.cs b/src/Toolbox/Fluent/AssertCalls/AssertError.cs new file mode 100644 index 00000000..738fddae --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertError.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// +public sealed class AssertError : AssertErrorBase +{ + /// + internal AssertError(IAsserter asserter, Exception? exception) + : base(asserter, exception) { } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertErrorBase.cs b/src/Toolbox/Fluent/AssertCalls/AssertErrorBase.cs new file mode 100644 index 00000000..b5e4df0b --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertErrorBase.cs @@ -0,0 +1,45 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// Handles common assertion calls. +/// +/// +public abstract class AssertErrorBase(IAsserter asserter, Exception? exception) + : AssertObjectBase(asserter, exception) + where T : AssertErrorBase +{ + /// Exception to run assertion checks with. + protected Exception? Error { get; } = exception; + + /// + [DoesNotReturn] + public override void Fail(string? details = null) + { + Asserter.Fail(Error, details); + } + + /// + [DoesNotReturn] + public override void Fail(AsserterMod? optionConfiguration, string? details = null) + { + Asserter.Fail(Error, optionConfiguration, details); + } + + /// + public override AssertChainer Debug(string? details = null) + { + Asserter.Debug(Error, details); + return ToChainer(); + } + + /// + public override AssertChainer Debug(AsserterMod? optionConfiguration, string? details = null) + { + Asserter.Debug(Error, optionConfiguration, details); + return ToChainer(); + } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertFunc.cs b/src/Toolbox/Fluent/AssertCalls/AssertFunc.cs new file mode 100644 index 00000000..69dfbd3f --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertFunc.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// +public sealed class AssertFunc : AssertFuncBase> +{ + /// + internal AssertFunc(IAsserter asserter, Func? behavior) + : base(asserter, behavior) { } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertFuncBase.cs b/src/Toolbox/Fluent/AssertCalls/AssertFuncBase.cs new file mode 100644 index 00000000..6bd0b4d6 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertFuncBase.cs @@ -0,0 +1,35 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// Handles assertion calls for delegates. +/// Delegate to check. +/// +public abstract class AssertFuncBase(IAsserter asserter, Func? behavior) + : AssertDelegateBase(asserter, behavior) + where TSelf : AssertFuncBase +{ + /// Delegate to run assertion checks with. + protected new Func? Behavior { get; } = behavior; + + /// + /// + public virtual ResultChainer HasResult(string? details = null) + { + return new ResultChainer(Asserter.HasResult(Behavior, details), Asserter); + } + + /// + public virtual ResultChainer HasResult( + AsserterMod? optionConfiguration, + string? details = null + ) + { + return new ResultChainer( + Asserter.HasResult(Behavior, optionConfiguration, details), + Asserter + ); + } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertObject.cs b/src/Toolbox/Fluent/AssertCalls/AssertObject.cs new file mode 100644 index 00000000..01f50568 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertObject.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// +public sealed class AssertObject : AssertObjectBase +{ + /// + internal AssertObject(IAsserter asserter, object? actual) + : base(asserter, actual) { } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertObjectBase.cs b/src/Toolbox/Fluent/AssertCalls/AssertObjectBase.cs new file mode 100644 index 00000000..3c591b22 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertObjectBase.cs @@ -0,0 +1,372 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// Handles common assertion calls. +/// Type to verify. +/// +/// +public abstract class AssertObjectBase(IAsserter asserter, object? actual) + where T : AssertObjectBase +{ + /// Handles the actual assert behavior. + protected IAsserter Asserter { get; } = + asserter ?? throw new ArgumentNullException(nameof(asserter)); + + /// Instance to run assertion checks with. + protected object? Actual { get; } = actual; + + /// + /// + public AssertChainer Is(object? expected, string? details = null) + { + asserter.Is(expected, Actual, details); + return ToChainer(); + } + + /// + /// + public AssertChainer Is( + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + { + asserter.Is(expected, Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public AssertChainer IsNull(string? details = null) + { + asserter.IsNull(Actual, details); + return ToChainer(); + } + + /// + /// + public AssertChainer IsNull(AsserterMod? optionConfiguration, string? details = null) + { + asserter.IsNull(Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public AssertChainer IsNot(object? expected, string? details = null) + { + asserter.IsNot(expected, Actual, details); + return ToChainer(); + } + + /// + /// + public AssertChainer IsNot( + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + { + asserter.IsNot(expected, Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public AssertChainer IsNotNull(string? details = null) + { + asserter.IsNotNull(Actual, details); + return ToChainer(); + } + + /// + /// + public AssertChainer IsNotNull(AsserterMod? optionConfiguration, string? details = null) + { + asserter.IsNotNull(Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ReferenceEqual(object? expected, string? details = null) + { + asserter.ReferenceEqual(expected, Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ReferenceEqual( + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + { + asserter.ReferenceEqual(expected, Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ReferenceNotEqual(object? expected, string? details = null) + { + asserter.ReferenceNotEqual(expected, Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ReferenceNotEqual( + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + { + asserter.ReferenceNotEqual(expected, Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ValuesEqual(object? expected, string? details = null) + { + asserter.ValuesEqual(expected, Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ValuesEqual( + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + { + asserter.ValuesEqual(expected, Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ValuesNotEqual(object? expected, string? details = null) + { + asserter.ValuesNotEqual(expected, Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ValuesNotEqual( + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + { + asserter.ValuesNotEqual(expected, Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer UniqueFrom(object? expected, string? details = null) + { + asserter.AreUnique(expected, Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer UniqueFrom( + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + { + asserter.AreUnique(expected, Actual, optionConfiguration, details); + return ToChainer(); + } + + /// Chained assertion calls use instance as a value. + /// + /// + public virtual ResultChainer IsA(string? details = null) + { + Asserter.Inherits(Actual, details); + return new ResultChainer((TParent)Actual!, Asserter); + } + + /// + /// + public virtual ResultChainer IsA( + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.Inherits(Actual, optionConfiguration, details); + return new ResultChainer((TParent)Actual!, Asserter); + } + +#pragma warning disable CA1716 // Overriding here should be a rarity. + + /// + /// + public virtual AssertChainer Inherits(string? details = null) + { + Asserter.Inherits(Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Inherits( + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.Inherits(Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Inherits(Type? parent, string? details = null) + { + Asserter.Inherits(parent, Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Inherits( + Type? parent, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.Inherits(parent, Actual, optionConfiguration, details); + return ToChainer(); + } + +#pragma warning restore CA1716 + + /// + /// + public virtual AssertChainer InheritedBy(string? details = null) + { + Asserter.InheritedBy(Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer InheritedBy( + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.InheritedBy(Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer InheritedBy(Type? child, string? details = null) + { + Asserter.InheritedBy(child, Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer InheritedBy( + Type? child, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.InheritedBy(child, Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + [DoesNotReturn] + public virtual void Fail(string? details = null) + { + asserter.Fail(Actual, details); + } + + /// + [DoesNotReturn] + public virtual void Fail(AsserterMod? optionConfiguration, string? details = null) + { + asserter.Fail(Actual, optionConfiguration, details); + } + + /// + /// + public virtual AssertChainer Debug(string? details = null) + { + asserter.Debug(Actual, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Debug(AsserterMod? optionConfiguration, string? details = null) + { + asserter.Debug(Actual, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Pass() + { + asserter.Pass(); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Pass(AsserterMod? optionConfiguration) + { + asserter.Pass(optionConfiguration); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Called(AsserterMod? optionConfiguration = null) + { + asserter.Called(Actual, optionConfiguration); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Called(Times total, AsserterMod? optionConfiguration = null) + { + asserter.Called(Actual, total, optionConfiguration); + return ToChainer(); + } + + /// Converts to a chainer for additional assertions on actual. + /// Chainer enabling additional assertion calls. + protected internal AssertChainer ToChainer() + { + return new AssertChainer((T)this, Asserter); + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertString.cs b/src/Toolbox/Fluent/AssertCalls/AssertString.cs new file mode 100644 index 00000000..b3a51678 --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertString.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +/// +public sealed class AssertString : AssertStringBase +{ + /// + internal AssertString(IAsserter asserter, string? text) + : base(asserter, text) { } +} diff --git a/src/Toolbox/Fluent/AssertCalls/AssertStringBase.cs b/src/Toolbox/Fluent/AssertCalls/AssertStringBase.cs new file mode 100644 index 00000000..31ee128c --- /dev/null +++ b/src/Toolbox/Fluent/AssertCalls/AssertStringBase.cs @@ -0,0 +1,220 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.AsserterTool.Categories; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent.AssertCalls; + +#pragma warning disable CA1307, CA1310 // Not available for all .NET versions. + +/// Handles common assertion calls. +/// +/// +public abstract class AssertStringBase(IAsserter asserter, string? text) + : AssertEnumerableBase(asserter, text) + where T : AssertStringBase +{ + /// Text to run assertion checks with. + protected string? Text { get; } = text; + + /// + /// + public virtual AssertChainer Contains(string content, string? details = null) + { + Asserter.Contains(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer Contains( + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.Contains(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ContainsNot(string content, string? details = null) + { + Asserter.ContainsNot(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer ContainsNot( + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.ContainsNot(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer StartsWith(char content, string? details = null) + { + Asserter.StartsWith(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer StartsWith( + char content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.StartsWith(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer StartsWith(string content, string? details = null) + { + Asserter.StartsWith(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer StartsWith( + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.StartsWith(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer StartsNotWith(char content, string? details = null) + { + Asserter.StartsNotWith(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer StartsNotWith( + char content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.StartsNotWith(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer StartsNotWith(string content, string? details = null) + { + Asserter.StartsNotWith(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer StartsNotWith( + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.StartsNotWith(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer EndsWith(char content, string? details = null) + { + Asserter.EndsWith(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer EndsWith( + char content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.EndsWith(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer EndsWith(string content, string? details = null) + { + Asserter.EndsWith(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer EndsWith( + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.EndsWith(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer EndsNotWith(char content, string? details = null) + { + Asserter.EndsNotWith(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer EndsNotWith( + char content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.EndsNotWith(content, Text, optionConfiguration, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer EndsNotWith(string content, string? details = null) + { + Asserter.EndsNotWith(content, Text, details); + return ToChainer(); + } + + /// + /// + public virtual AssertChainer EndsNotWith( + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + { + Asserter.EndsNotWith(content, Text, optionConfiguration, details); + return ToChainer(); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/AssertExtensions.cs b/src/Toolbox/Fluent/AssertExtensions.cs new file mode 100644 index 00000000..acd8b197 --- /dev/null +++ b/src/Toolbox/Fluent/AssertExtensions.cs @@ -0,0 +1,186 @@ +using System.Collections; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class AssertExtensions +{ + /// Gets the asserter to use based upon context. + /// Provider for the to use if set. + /// The asserter to test with. + private static IAsserter GetAsserter(IToolSet? tools) + { + return tools?.Asserter ?? Tools.Asserter; + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertAsyncEnumerable Assert( + this IAsyncEnumerable collection, + IToolSet? tools = null + ) + { + return new AssertAsyncEnumerable(GetAsserter(tools), collection); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertAsyncObject Assert(this object? actual, IToolSet? tools = null) + { + return new AssertAsyncObject(GetAsserter(tools), actual); + } + + /// + /// Return of . + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertGenericTask Assert(this Task? behavior, IToolSet? tools = null) + { + return new AssertGenericTask(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertGenericValueTask Assert( + this ValueTask? behavior, + IToolSet? tools = null + ) + { + return new AssertGenericValueTask(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertGenericValueTask Assert( + this ValueTask behavior, + IToolSet? tools = null + ) + { + return new AssertGenericValueTask(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertTask Assert(this Task? behavior, IToolSet? tools = null) + { + return new AssertTask(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertValueTask Assert(this ValueTask behavior, IToolSet? tools = null) + { + return new AssertValueTask(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertValueTask Assert(this ValueTask? behavior, IToolSet? tools = null) + { + return new AssertValueTask(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertAction Assert(this Action? behavior, IToolSet? tools = null) + { + return new AssertAction(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertComparable Assert(this IComparable? value, IToolSet? tools = null) + { + return new AssertComparable(GetAsserter(tools), value); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertDelegate Assert(this Delegate? behavior, IToolSet? tools = null) + { + return new AssertDelegate(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertEnumerable Assert(this IEnumerable? collection, IToolSet? tools = null) + { + return new AssertEnumerable(GetAsserter(tools), collection); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertError Assert(this Exception? exception, IToolSet? tools = null) + { + return new AssertError(GetAsserter(tools), exception); + } + + /// + /// Return of . + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertFunc Assert(this Func? behavior, IToolSet? tools = null) + { + return new AssertFunc(GetAsserter(tools), behavior); + } + + /// + /// + /// Provider for the to use if set. + /// Asserter to test with. + public static AssertString Assert(this string? text, IToolSet? tools = null) + { + return new AssertString(GetAsserter(tools), text); + } + + /// Handles assertion calls for runtime . + /// of . + /// Object with to test. + /// Delegate on to test. + /// Provider for the to use if set. + /// Asserter to test with. + /// Primarily useful for exception testing. + public static AssertAction Assert(this T origin, Action behavior, IToolSet? tools = null) + { + return Assert(() => behavior.Invoke(origin), tools); + } + + /// + public static AssertFunc Assert( + this TSelf origin, + Func behavior, + IToolSet? tools = null + ) + { + return Assert(() => behavior.Invoke(origin), tools); + } +} diff --git a/src/Toolbox/Fluent/Chaining/AlsoChainer.cs b/src/Toolbox/Fluent/Chaining/AlsoChainer.cs new file mode 100644 index 00000000..b85d270e --- /dev/null +++ b/src/Toolbox/Fluent/Chaining/AlsoChainer.cs @@ -0,0 +1,140 @@ +using System.Collections; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Fluent.Chaining; + +/// Chainer enabling additional assertion calls. +/// Handles the actual assert behavior. +public class AlsoChainer(IAsserter asserter) +{ + /// + /// + /// Asserter to test with. + public AssertAsyncEnumerable Also(IAsyncEnumerable collection) + { + return new AssertAsyncEnumerable(asserter, collection); + } + + /// + /// + /// Asserter to test with. + public AssertAsyncObject Also(object? actual) + { + return new AssertAsyncObject(asserter, actual); + } + + /// + /// Return of . + /// + /// Asserter to test with. + public AssertGenericTask Also(Task? behavior) + { + return new AssertGenericTask(asserter, behavior); + } + + /// + /// + /// Asserter to test with. + public AssertGenericValueTask Also(ValueTask? actual) + { + return new AssertGenericValueTask(asserter, actual); + } + + /// + /// + /// Asserter to test with. + public AssertGenericValueTask Also(ValueTask actual) + { + return new AssertGenericValueTask(asserter, actual); + } + + /// + /// + /// Asserter to test with. + public AssertTask Also(Task? behavior) + { + return new AssertTask(asserter, behavior); + } + + /// + /// + /// Asserter to test with. + public AssertValueTask Also(ValueTask actual) + { + return new AssertValueTask(asserter, actual); + } + + /// + /// + /// Asserter to test with. + public AssertValueTask Also(ValueTask? actual) + { + return new AssertValueTask(asserter, actual); + } + + /// + /// + /// Asserter to test with. + public AssertAction Also(Action? behavior) + { + return new AssertAction(asserter, behavior); + } + + /// + /// + /// Asserter to test with. + public AssertComparable Also(IComparable? value) + { + return new AssertComparable(asserter, value); + } + + /// + /// + /// Asserter to test with. + public AssertDelegate Also(Delegate? behavior) + { + return new AssertDelegate(asserter, behavior); + } + + /// + /// + /// Asserter to test with. + public AssertEnumerable Also(IEnumerable? collection) + { + return new AssertEnumerable(asserter, collection); + } + + /// + /// + /// Asserter to test with. + public AssertError Also(Exception? error) + { + return new AssertError(asserter, error); + } + + /// + /// Return of . + /// + /// Asserter to test with. + public AssertFunc Also(Func? behavior) + { + return new AssertFunc(asserter, behavior); + } + + /// + /// + /// Asserter to test with. + public AssertString Also(string? text) + { + return new AssertString(asserter, text); + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/Fluent/Chaining/AssertChainer.cs b/src/Toolbox/Fluent/Chaining/AssertChainer.cs new file mode 100644 index 00000000..ad319e60 --- /dev/null +++ b/src/Toolbox/Fluent/Chaining/AssertChainer.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.Chaining; + +/// Chainer enabling additional assertion calls. +/// Assertion base to chain. +/// Assertion base instance to chain. +/// +public sealed class AssertChainer(T chain, IAsserter asserter) : AlsoChainer(asserter) +{ + /// Provides additional assertions to test the instance. + public T And() + { + return chain; + } +} diff --git a/src/Toolbox/Fluent/Chaining/ExceptionChainer.cs b/src/Toolbox/Fluent/Chaining/ExceptionChainer.cs new file mode 100644 index 00000000..030d5df9 --- /dev/null +++ b/src/Toolbox/Fluent/Chaining/ExceptionChainer.cs @@ -0,0 +1,27 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Fluent.Chaining; + +#pragma warning disable CA1024 // Hurts readability. + +/// Chainer enabling additional assertion calls on the exception. +/// +public sealed class ExceptionChainer(T result, IAsserter asserter) + : WithChainer(result, asserter) + where T : Exception +{ + /// Provides assertions to test the exception. + public AssertError That() + { + return Also(Result); + } + + /// Result exception to chain with more assertions. + public T GetCaughtException() + { + return Result; + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/Chaining/ResultChainer.cs b/src/Toolbox/Fluent/Chaining/ResultChainer.cs new file mode 100644 index 00000000..e9cc825c --- /dev/null +++ b/src/Toolbox/Fluent/Chaining/ResultChainer.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Fluent.Chaining; + +#pragma warning disable CA1024 // Hurts readability. + +/// Chainer enabling additional assertion calls on the result. +/// +public sealed class ResultChainer(T result, IAsserter asserter) + : WithChainer(result, asserter) +{ + /// Result instance to chain with more assertions. + public T GetResultValue() + { + return Result; + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/Chaining/ResultChainerExtensions.cs b/src/Toolbox/Fluent/Chaining/ResultChainerExtensions.cs new file mode 100644 index 00000000..f9f02d5d --- /dev/null +++ b/src/Toolbox/Fluent/Chaining/ResultChainerExtensions.cs @@ -0,0 +1,754 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Collections.Specialized; +using System.Numerics; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +#pragma warning disable IDE0130 // Cleaner project organization. + +namespace Werecodent.CreateAndFake.Fluent; + +#pragma warning restore IDE0130 + +/// Provides fluent assertions. +public static class ResultChainerExtensions +{ + /// + public static AssertAsyncEnumerable That(this ResultChainer> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertAsyncEnumerable That(this ResultChainer> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertAsyncEnumerable That(this ResultChainer> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertAsyncEnumerable That(this ResultChainer> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertAsyncObject That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertGenericTask That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertGenericValueTask That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertGenericValueTask That(this ResultChainer> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertTask That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertValueTask That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertValueTask That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertAction That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertDelegate That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That( + this ResultChainer?> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That( + this ResultChainer?> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That( + this ResultChainer?> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That( + this ResultChainer?> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That( + this ResultChainer?> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That( + this ResultChainer?> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertEnumerable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertError That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + /// Assert provider. + public static AssertFunc That(this ResultChainer?> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertString That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } + + /// + public static AssertComparable That(this ResultChainer origin) + { + ArgumentGuard.ThrowIfNull(origin); + return origin.Also(origin.GetResultValue()); + } +} diff --git a/src/Toolbox/Fluent/Chaining/WithChainer.cs b/src/Toolbox/Fluent/Chaining/WithChainer.cs new file mode 100644 index 00000000..a2b34e3f --- /dev/null +++ b/src/Toolbox/Fluent/Chaining/WithChainer.cs @@ -0,0 +1,133 @@ +using System.Collections; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Fluent.Chaining; + +/// +/// Result to chain. +/// +public abstract class WithChainer(T result, IAsserter asserter) : AlsoChainer(asserter) +{ + /// Base instance to chain with more assertions. + protected T Result { get; } = result; + + /// + public AssertAsyncEnumerable With( + Func> selector + ) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertAsyncObject With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertGenericTask With(Func?> selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertGenericValueTask With(Func?> selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertGenericValueTask With(Func> selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertTask With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertValueTask With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertValueTask With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertAction With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertAction With(Action? selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(() => selector.Invoke(Result)); + } + + /// + public AssertComparable With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertDelegate With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertEnumerable With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertError With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// Begins assertions on an associated value. + /// Associated content . + /// How to retrieve the value to test on. + /// Asserter to test the selected value. + public AssertFunc With(Func?> selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } + + /// + public AssertString With(Func selector) + { + ArgumentGuard.ThrowIfNull(selector); + return Also(selector.Invoke(Result)); + } +} diff --git a/src/Toolbox/Fluent/FakedExtensions.cs b/src/Toolbox/Fluent/FakedExtensions.cs new file mode 100644 index 00000000..c2379673 --- /dev/null +++ b/src/Toolbox/Fluent/FakedExtensions.cs @@ -0,0 +1,55 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.Fluent; + +#pragma warning disable IDE0060, RCS1175 // Provides fluent attachment. + +/// Provides fluent handling of fakes. +public static class FakedExtensions +{ + /// Ties a method call to fake behavior. + /// Type to return. + /// Result from the fake method to setup. + /// Value to set the call behavior with. + /// Expected number of calls for the behavior. + /// + /// For use on stubs from the tool only. + /// + /// T db = Tools.Faker.Stub{T}().Dummy; + /// db.Find(id).SetupReturn(data); + /// + /// + public static void SetupReturn(this T fakeCallResult, T returnValue, Times? times = null) + { + SetupReturn(fakeCallResult, Behavior.Returns(returnValue, times)); + } + + /// Ties a method call to . + /// Type to return. + /// Result from the fake method to setup. + /// Behavior to set the call behavior with. + /// For use on stubs from the tool only. + public static void SetupReturn(this T fakeCallResult, Behavior behavior) + { + FakeMetaProvider.SetLastCallBehavior(behavior ?? Behavior.Default()); + } + + /// Ties a method call to . + /// Type to return. + /// Fake being configured. + /// Method to configure. + /// Behavior to set the call behavior with. + /// For use on stubs from the tool only. + public static void SetupReturn(this T fake, Action call, Behavior behavior) + { + ArgumentGuard.ThrowIfNull(fake, call); + + call.Invoke(fake); + FakeMetaProvider.SetLastCallBehavior(behavior); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/.editorconfig b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/.editorconfig new file mode 100644 index 00000000..1381d0bf --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/.editorconfig @@ -0,0 +1,7 @@ +[*.cs] + +# Cleaner calls. +dotnet_diagnostic.CA1068.severity = None + +# Cleaner project organization. +dotnet_diagnostic.IDE0130.severity = None diff --git a/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncEnumerableExtensions.cs b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncEnumerableExtensions.cs new file mode 100644 index 00000000..6e7ee401 --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncEnumerableExtensions.cs @@ -0,0 +1,371 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertAsyncEnumerableExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task>> IsEmptyAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .IsEmptyAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> IsEmptyAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .IsEmptyAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> IsNotEmptyAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .IsNotEmptyAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> IsNotEmptyAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .IsNotEmptyAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountAsync( + this Task> origin, + int count, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountAsync(count, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountAsync( + this Task> origin, + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountAsync(count, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountLessThanAsync( + this Task> origin, + int count, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountLessThanAsync(count, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountLessThanAsync( + this Task> origin, + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountLessThanAsync(count, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountLessOrExactlyAsync( + this Task> origin, + int count, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountLessOrExactlyAsync(count, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountLessOrExactlyAsync( + this Task> origin, + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountLessOrExactlyAsync(count, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountMoreThanAsync( + this Task> origin, + int count, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountMoreThanAsync(count, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountMoreThanAsync( + this Task> origin, + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountMoreThanAsync(count, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountMoreOrExactlyAsync( + this Task> origin, + int count, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountMoreOrExactlyAsync(count, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> HasCountMoreOrExactlyAsync( + this Task> origin, + int count, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasCountMoreOrExactlyAsync(count, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> ContainsAsync( + this Task> origin, + T? content, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ContainsAsync(content, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> ContainsAsync( + this Task> origin, + T? content, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ContainsAsync(content, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> ContainsNotAsync( + this Task> origin, + T? content, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ContainsNotAsync(content, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> ContainsNotAsync( + this Task> origin, + T? content, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ContainsNotAsync(content, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> FailAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .FailAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> FailAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .FailAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> DebugAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .DebugAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task>> DebugAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .DebugAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsExceptionAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsExceptionAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsExceptionAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsExceptionAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncObjectExtensions.cs b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncObjectExtensions.cs new file mode 100644 index 00000000..93b8d134 --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncObjectExtensions.cs @@ -0,0 +1,251 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertAsyncObjectExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> IsAsync( + this Task origin, + object? expected, + CancellationToken canceler, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .IsAsync(expected, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsAsync( + this Task origin, + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .IsAsync(expected, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNotAsync( + this Task origin, + object? expected, + CancellationToken canceler, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .IsNotAsync(expected, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNotAsync( + this Task origin, + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .IsNotAsync(expected, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ValuesEqualAsync( + this Task origin, + object? expected, + CancellationToken canceler, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ValuesEqualAsync(expected, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ValuesEqualAsync( + this Task origin, + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ValuesEqualAsync(expected, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ValuesNotEqualAsync( + this Task origin, + object? expected, + CancellationToken canceler, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ValuesNotEqualAsync(expected, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ValuesNotEqualAsync( + this Task origin, + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ValuesNotEqualAsync(expected, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> UniqueFromAsync( + this Task origin, + object? expected, + CancellationToken canceler, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .UniqueFromAsync(expected, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> UniqueFromAsync( + this Task origin, + object? expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertAsyncObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .UniqueFromAsync(expected, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + +#pragma warning disable VSTHRD200 // Matches underlying method. + + /// + /// Assert provider in asynchronous context. + public static async Task> IsA( + this Task origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsA(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsA( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsA(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Inherits( + this Task origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Inherits(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Inherits( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Inherits(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> InheritedBy( + this Task origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).InheritedBy(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> InheritedBy( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).InheritedBy( + optionConfiguration, + details + ); + } + +#pragma warning restore VSTHRD200 +} diff --git a/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericTaskExtensions.cs b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericTaskExtensions.cs new file mode 100644 index 00000000..97c115be --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericTaskExtensions.cs @@ -0,0 +1,69 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertGenericTaskExtensions +{ + /// + /// + public static async Task> HasResultAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> HasResultAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> HasResultAsync( + this Task> origin, + T expected, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(expected, canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> HasResultAsync( + this Task> origin, + T expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(expected, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericValueTaskExtensions.cs b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericValueTaskExtensions.cs new file mode 100644 index 00000000..50adaa51 --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericValueTaskExtensions.cs @@ -0,0 +1,127 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertGenericValueTaskExtensions +{ + /// + /// + public static async Task> HasResultAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> HasResultAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> HasResultAsync( + this Task> origin, + T expected, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(expected, canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> HasResultAsync( + this Task> origin, + T expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(expected, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> ThrowsExceptionAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsExceptionAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> ThrowsExceptionAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsExceptionAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task ThrowsNoExceptionAsync( + this Task> origin, + CancellationToken canceler, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoExceptionAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task ThrowsNoExceptionAsync( + this Task> origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoExceptionAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertTaskExtensions.cs b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertTaskExtensions.cs new file mode 100644 index 00000000..97a22b2d --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertTaskExtensions.cs @@ -0,0 +1,133 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertTaskExtensions +{ + /// + /// + public static async Task> ThrowsAsync( + this Task origin, + CancellationToken canceler, + string? details = null + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> ThrowsAsync( + this Task origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> ThrowsExceptionAsync( + this Task origin, + CancellationToken canceler, + string? details = null + ) + where T : AssertTaskBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsExceptionAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task> ThrowsExceptionAsync( + this Task origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertTaskBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsExceptionAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task ThrowsNoAsync( + this Task origin, + CancellationToken canceler, + string? details = null + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task ThrowsNoAsync( + this Task origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task ThrowsNoExceptionAsync( + this Task origin, + CancellationToken canceler, + string? details = null + ) + where T : AssertTaskBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoExceptionAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// + public static async Task ThrowsNoExceptionAsync( + this Task origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertTaskBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoExceptionAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertValueTaskExtensions.cs b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertValueTaskExtensions.cs new file mode 100644 index 00000000..a177316f --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertAsyncUnwrapping/TaskAssertValueTaskExtensions.cs @@ -0,0 +1,133 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertValueTaskExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsAsync( + this Task origin, + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsAsync( + this Task origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsExceptionAsync( + this Task origin, + CancellationToken canceler, + string? details = null + ) + where T : AssertValueTaskBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsExceptionAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsExceptionAsync( + this Task origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertValueTaskBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsExceptionAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNoAsync( + this Task origin, + CancellationToken canceler, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNoAsync( + this Task origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNoExceptionAsync( + this Task origin, + CancellationToken canceler, + string? details = null + ) + where T : AssertValueTaskBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoExceptionAsync(canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNoExceptionAsync( + this Task origin, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertValueTaskBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ThrowsNoExceptionAsync(canceler, optionConfiguration, details) + .ConfigureAwait(false); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/.editorconfig b/src/Toolbox/Fluent/TaskAssertUnwrapping/.editorconfig new file mode 100644 index 00000000..8df32379 --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/.editorconfig @@ -0,0 +1,11 @@ +[*.cs] + +# Cleaner calls. +dotnet_diagnostic.CA1068.severity = None +dotnet_diagnostic.VSTHRD200.severity = None + +# Cleaner project organization. +dotnet_diagnostic.IDE0130.severity = None + +# Matches underlying method and override available. +dotnet_diagnostic.VSTHRD103.severity = None diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertActionExtensions.cs b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertActionExtensions.cs new file mode 100644 index 00000000..32c22ad5 --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertActionExtensions.cs @@ -0,0 +1,115 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertActionExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> Throws( + this Task origin, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Throws(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Throws( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Throws( + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsException( + this Task origin, + string? details = null + ) + where T : AssertActionBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsException(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsException( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertActionBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsException(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNo( + this Task origin, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsNo(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNo( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsNo( + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNoException( + this Task origin, + string? details = null + ) + where T : AssertActionBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsNoException(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNoException( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertActionBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsNoException(optionConfiguration, details); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertComparableExtensions.cs b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertComparableExtensions.cs new file mode 100644 index 00000000..75bca08a --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertComparableExtensions.cs @@ -0,0 +1,220 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertComparableExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> GreaterThan( + this Task origin, + IComparable target, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).GreaterThan(target, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> GreaterThan( + this Task origin, + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).GreaterThan( + target, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> GreaterThanOrEqualTo( + this Task origin, + IComparable target, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).GreaterThanOrEqualTo(target, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> GreaterThanOrEqualTo( + this Task origin, + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).GreaterThanOrEqualTo( + target, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> GreaterThanOrIs( + this Task origin, + IComparable target, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).GreaterThanOrIs(target, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> GreaterThanOrIs( + this Task origin, + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).GreaterThanOrIs( + target, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> LessThan( + this Task origin, + IComparable target, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).LessThan(target, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> LessThan( + this Task origin, + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).LessThan(target, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> LessThanOrEqualTo( + this Task origin, + IComparable target, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).LessThanOrEqualTo(target, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> LessThanOrEqualTo( + this Task origin, + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).LessThanOrEqualTo( + target, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> LessThanOrIs( + this Task origin, + IComparable target, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).LessThanOrIs(target, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> LessThanOrIs( + this Task origin, + IComparable target, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).LessThanOrIs( + target, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> InRange( + this Task origin, + IComparable min, + IComparable max, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).InRange(min, max, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> InRange( + this Task origin, + IComparable min, + IComparable max, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertComparableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).InRange(min, max, optionConfiguration, details); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertDelegateExtensions.cs b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertDelegateExtensions.cs new file mode 100644 index 00000000..5e7025e0 --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertDelegateExtensions.cs @@ -0,0 +1,209 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +#pragma warning disable MA0042 // Following the pattern. + +/// Provides fluent assertions. +public static class TaskAssertDelegateExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> Throws( + this Task origin, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Throws(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Throws( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Throws( + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsException( + this Task origin, + string? details = null + ) + where T : AssertDelegateBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsException(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ThrowsException( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertDelegateBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsException(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNo( + this Task origin, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsNo(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNo( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where TException : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsNo( + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNoException( + this Task origin, + string? details = null + ) + where T : AssertDelegateBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsNoException(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task ThrowsNoException( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertDelegateBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ThrowsNoException(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasResult( + this Task origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasResult(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasResult( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasResult( + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasResult( + this Task origin, + TItem expected, + string? details = null + ) + where T : AssertDelegateBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasResult(expected, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasResult( + this Task origin, + TItem expected, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertDelegateBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasResult( + expected, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasResultAsync( + this Task origin, + TItem expected, + CancellationToken canceler, + string? details = null + ) + where T : AssertDelegateBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(expected, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasResultAsync( + this Task origin, + TItem expected, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertDelegateBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .HasResultAsync(expected, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertEnumerableExtensions.cs b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertEnumerableExtensions.cs new file mode 100644 index 00000000..40c24d2f --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertEnumerableExtensions.cs @@ -0,0 +1,381 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +#pragma warning disable MA0042 // Following the pattern. + +/// Provides fluent assertions. +public static class TaskAssertEnumerableExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> IsEmpty( + this Task origin, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsEmpty(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsEmpty( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsEmpty(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNotEmpty( + this Task origin, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsNotEmpty(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNotEmpty( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsNotEmpty(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCount( + this Task origin, + int count, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCount(count, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCount( + this Task origin, + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCount(count, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCountLessThan( + this Task origin, + int count, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCountLessThan(count, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCountLessThan( + this Task origin, + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCountLessThan( + count, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCountLessOrExactly( + this Task origin, + int count, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCountLessOrExactly(count, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCountLessOrExactly( + this Task origin, + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCountLessOrExactly( + count, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCountMoreThan( + this Task origin, + int count, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCountMoreThan(count, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCountMoreThan( + this Task origin, + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCountMoreThan( + count, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCountMoreOrExactly( + this Task origin, + int count, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCountMoreOrExactly(count, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasCountMoreOrExactly( + this Task origin, + int count, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasCountMoreOrExactly( + count, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Contains( + this Task origin, + object? content, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Contains(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Contains( + this Task origin, + object? content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Contains(content, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ContainsAsync( + this Task origin, + object? content, + CancellationToken canceler, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ContainsAsync(content, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ContainsAsync( + this Task origin, + object? content, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ContainsAsync(content, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ContainsNot( + this Task origin, + object? content, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ContainsNot(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ContainsNot( + this Task origin, + object? content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ContainsNot( + content, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ContainsNotAsync( + this Task origin, + object? content, + CancellationToken canceler, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ContainsNotAsync(content, canceler, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ContainsNotAsync( + this Task origin, + object? content, + CancellationToken canceler, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertEnumerableBase + { + ArgumentGuard.ThrowIfNull(origin); + return await (await origin.ConfigureAwait(false)) + .ContainsNotAsync(content, canceler, optionConfiguration, details) + .ConfigureAwait(false); + } + + /// + /// Assert provider in asynchronous context. + public static async Task Fail(this Task origin, string? details = null) + { + ArgumentGuard.ThrowIfNull(origin); + (await origin.ConfigureAwait(false)).Fail(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task Fail( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + (await origin.ConfigureAwait(false)).Fail(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Debug( + this Task origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Debug(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Debug( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Debug(optionConfiguration, details); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertErrorExtensions.cs b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertErrorExtensions.cs new file mode 100644 index 00000000..d94014fe --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertErrorExtensions.cs @@ -0,0 +1,79 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertErrorExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task Fail(this Task origin, string? details = null) + { + ArgumentGuard.ThrowIfNull(origin); + (await origin.ConfigureAwait(false)).Fail(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task Fail( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + (await origin.ConfigureAwait(false)).Fail(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Debug( + this Task origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Debug(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Debug( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Debug(optionConfiguration, details); + } + +#pragma warning disable VSTHRD200 // Matches underlying method. + + /// + /// Assert provider in asynchronous context. + public static async Task> Inherits( + this Task origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Inherits(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Inherits( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Inherits(optionConfiguration, details); + } + +#pragma warning restore VSTHRD200 +} diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertFuncExtensions.cs b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertFuncExtensions.cs new file mode 100644 index 00000000..edd73992 --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertFuncExtensions.cs @@ -0,0 +1,32 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertFuncExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> HasResult( + this Task> origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasResult(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> HasResult( + this Task> origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).HasResult(optionConfiguration, details); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertObjectExtensions.cs b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertObjectExtensions.cs new file mode 100644 index 00000000..1c04aa2b --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertObjectExtensions.cs @@ -0,0 +1,440 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertObjectExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> Is( + this Task origin, + object? expected, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Is(expected, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Is( + this Task origin, + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Is(expected, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNull( + this Task origin, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsNull(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNull( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsNull(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNot( + this Task origin, + object? expected, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsNot(expected, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNot( + this Task origin, + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsNot(expected, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNotNull( + this Task origin, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsNotNull(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsNotNull( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsNotNull(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ReferenceEqual( + this Task origin, + object? expected, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ReferenceEqual(expected, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ReferenceEqual( + this Task origin, + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ReferenceEqual( + expected, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ReferenceNotEqual( + this Task origin, + object? expected, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ReferenceNotEqual(expected, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ReferenceNotEqual( + this Task origin, + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ReferenceNotEqual( + expected, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ValuesEqual( + this Task origin, + object? expected, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ValuesEqual(expected, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ValuesEqual( + this Task origin, + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ValuesEqual( + expected, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ValuesNotEqual( + this Task origin, + object? expected, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ValuesNotEqual(expected, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ValuesNotEqual( + this Task origin, + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ValuesNotEqual( + expected, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> UniqueFrom( + this Task origin, + object? expected, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).UniqueFrom(expected, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> UniqueFrom( + this Task origin, + object? expected, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).UniqueFrom( + expected, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsA( + this Task origin, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsA(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> IsA( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).IsA(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Inherits( + this Task origin, + Type? child, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Inherits(child, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Inherits( + this Task origin, + Type? child, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Inherits(child, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> InheritedBy( + this Task origin, + Type? parent, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).InheritedBy(parent, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> InheritedBy( + this Task origin, + Type? parent, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).InheritedBy( + parent, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task Fail(this Task origin, string? details = null) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + (await origin.ConfigureAwait(false)).Fail(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task Fail( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + (await origin.ConfigureAwait(false)).Fail(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Debug(this Task origin, string? details = null) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Debug(details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Debug( + this Task origin, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Debug(optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Pass(this Task origin) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Pass(); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Pass( + this Task origin, + AsserterMod? optionConfiguration + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Pass(optionConfiguration); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Called( + this Task origin, + AsserterMod? optionConfiguration = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Called(optionConfiguration); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Called( + this Task origin, + Times total, + AsserterMod? optionConfiguration = null + ) + where T : AssertObjectBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Called(total, optionConfiguration); + } +} diff --git a/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertStringExtensions.cs b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertStringExtensions.cs new file mode 100644 index 00000000..f23eaf46 --- /dev/null +++ b/src/Toolbox/Fluent/TaskAssertUnwrapping/TaskAssertStringExtensions.cs @@ -0,0 +1,311 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +#pragma warning disable MA0042 // Following the pattern. + +/// Provides fluent assertions. +public static class TaskAssertStringExtensions +{ + /// + /// Assert provider in asynchronous context. + public static async Task> Contains( + this Task origin, + string content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Contains(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> Contains( + this Task origin, + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Contains(content, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ContainsNot( + this Task origin, + string content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ContainsNot(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> ContainsNot( + this Task origin, + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).ContainsNot( + content, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> StartsWith( + this Task origin, + char content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).StartsWith(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> StartsWith( + this Task origin, + char content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).StartsWith( + content, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> StartsWith( + this Task origin, + string content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).StartsWith(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> StartsWith( + this Task origin, + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).StartsWith( + content, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> StartsNotWith( + this Task origin, + char content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).StartsNotWith(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> StartsNotWith( + this Task origin, + char content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).StartsNotWith( + content, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> StartsNotWith( + this Task origin, + string content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).StartsNotWith(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> StartsNotWith( + this Task origin, + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).StartsNotWith( + content, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> EndsWith( + this Task origin, + char content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).EndsWith(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> EndsWith( + this Task origin, + char content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).EndsWith(content, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> EndsWith( + this Task origin, + string content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).EndsWith(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> EndsWith( + this Task origin, + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).EndsWith(content, optionConfiguration, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> EndsNotWith( + this Task origin, + char content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).EndsNotWith(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> EndsNotWith( + this Task origin, + char content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).EndsNotWith( + content, + optionConfiguration, + details + ); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> EndsNotWith( + this Task origin, + string content, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).EndsNotWith(content, details); + } + + /// + /// Assert provider in asynchronous context. + public static async Task> EndsNotWith( + this Task origin, + string content, + AsserterMod? optionConfiguration, + string? details = null + ) + where T : AssertStringBase + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).EndsNotWith( + content, + optionConfiguration, + details + ); + } +} + +#pragma warning restore diff --git a/src/Toolbox/Fluent/TaskChainingUnwrapping/.editorconfig b/src/Toolbox/Fluent/TaskChainingUnwrapping/.editorconfig new file mode 100644 index 00000000..e1879cd6 --- /dev/null +++ b/src/Toolbox/Fluent/TaskChainingUnwrapping/.editorconfig @@ -0,0 +1,8 @@ +[*.cs] + +# Cleaner calls. +dotnet_diagnostic.CA1068.severity = None +dotnet_diagnostic.VSTHRD200.severity = None + +# Cleaner project organization. +dotnet_diagnostic.IDE0130.severity = None diff --git a/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskAlsoChainerExtensions.cs b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskAlsoChainerExtensions.cs new file mode 100644 index 00000000..5abd378a --- /dev/null +++ b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskAlsoChainerExtensions.cs @@ -0,0 +1,191 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAlsoChainerExtensions +{ + /// + /// + /// Asserter to test with. + public static async Task> Also( + this Task origin, + Func> collection + ) + where TSelf : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, collection); + return (await origin.ConfigureAwait(false)).Also(collection.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also(this Task origin, Func actual) + where T : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, actual); + return (await origin.ConfigureAwait(false)).Also(actual.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task> Also( + this Task origin, + Func?> behavior + ) + where TSelf : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, behavior); + return (await origin.ConfigureAwait(false)).Also(behavior.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task> Also( + this Task origin, + Func?> behavior + ) + where TSelf : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, behavior); + return (await origin.ConfigureAwait(false)).Also(behavior.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task> Also( + this Task origin, + Func> behavior + ) + where TSelf : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, behavior); + return (await origin.ConfigureAwait(false)).Also(behavior.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also(this Task origin, Func behavior) + where T : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, behavior); + return (await origin.ConfigureAwait(false)).Also(behavior.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also(this Task origin, Func behavior) + where T : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, behavior); + return (await origin.ConfigureAwait(false)).Also(behavior.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also( + this Task origin, + Func behavior + ) + where T : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, behavior); + return (await origin.ConfigureAwait(false)).Also(behavior.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also(this Task origin, Func behavior) + where T : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, behavior); + return (await origin.ConfigureAwait(false)).Also(behavior.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also(this Task origin, Action? behavior) + where T : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).Also(behavior); + } + + /// + /// + /// Asserter to test with. + public static async Task Also( + this Task origin, + Func value + ) + where T : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, value); + return (await origin.ConfigureAwait(false)).Also(value.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also( + this Task origin, + Func collection + ) + where T : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, collection); + return (await origin.ConfigureAwait(false)).Also(collection.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also( + this Task origin, + Func exception + ) + where TOrigin : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, exception); + return (await origin.ConfigureAwait(false)).Also(exception.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task> Also( + this Task origin, + Func>? behavior + ) + where TSelf : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, behavior); + return (await origin.ConfigureAwait(false)).Also(behavior.Invoke()); + } + + /// + /// + /// Asserter to test with. + public static async Task Also( + this Task origin, + Func text + ) + where TOrigin : AlsoChainer + { + ArgumentGuard.ThrowIfNull(origin, text); + return (await origin.ConfigureAwait(false)).Also(text.Invoke()); + } +} diff --git a/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskAssertChainerExtensions.cs b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskAssertChainerExtensions.cs new file mode 100644 index 00000000..8962a506 --- /dev/null +++ b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskAssertChainerExtensions.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskAssertChainerExtensions +{ + /// + public static async Task And(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).And(); + } +} diff --git a/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskExceptionChainerExtensions.cs b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskExceptionChainerExtensions.cs new file mode 100644 index 00000000..9e9e8260 --- /dev/null +++ b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskExceptionChainerExtensions.cs @@ -0,0 +1,194 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskExceptionChainerExtensions +{ + /// + public static async Task That(this Task> origin) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task GetCaughtException(this Task> origin) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).GetCaughtException(); + } + + /// + public static async Task> With( + this Task> origin, + Func> selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task> With( + this Task> origin, + Func?> selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task> With( + this Task> origin, + Func?> selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task> With( + this Task> origin, + Func> selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Action? selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// Assert provider in asynchronous context. + /// + /// + public static async Task> With( + this Task> origin, + Func?> selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + where T : Exception + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } +} diff --git a/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskResultChainerExtensions.cs b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskResultChainerExtensions.cs new file mode 100644 index 00000000..b64b2470 --- /dev/null +++ b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskResultChainerExtensions.cs @@ -0,0 +1,833 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Collections.Specialized; +using System.Numerics; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskResultChainerExtensions +{ + /// + public static async Task GetResultValue(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).GetResultValue(); + } + + /// + public static async Task> That( + this Task>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task> That( + this Task>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task> That( + this Task>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task> That( + this Task>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task> That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task> That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task> That( + this Task>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task?>> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task?>> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task?>> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task?>> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task?>> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task?>> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task?>> origin + ) + where TKey : notnull + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + /// Assert provider. + public static async Task> That(this Task?>> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That( + this Task> origin + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } + + /// + public static async Task That(this Task> origin) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).That(); + } +} diff --git a/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskWithChainerExtensions.cs b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskWithChainerExtensions.cs new file mode 100644 index 00000000..ade5ab2c --- /dev/null +++ b/src/Toolbox/Fluent/TaskChainingUnwrapping/TaskWithChainerExtensions.cs @@ -0,0 +1,173 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent assertions. +public static class TaskWithChainerExtensions +{ + /// + public static async Task> With( + this Task> origin, + Func> selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task> With( + this Task> origin, + Func?> selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task> With( + this Task> origin, + Func?> selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task> With( + this Task> origin, + Func> selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Action? selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// Assert provider in asynchronous context. + /// + /// + public static async Task> With( + this Task> origin, + Func?> selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } + + /// + public static async Task With( + this Task> origin, + Func selector + ) + { + ArgumentGuard.ThrowIfNull(origin); + return (await origin.ConfigureAwait(false)).With(selector); + } +} diff --git a/src/Toolbox/Fluent/Tooling/AsyncObjectTools.cs b/src/Toolbox/Fluent/Tooling/AsyncObjectTools.cs new file mode 100644 index 00000000..2433e8c7 --- /dev/null +++ b/src/Toolbox/Fluent/Tooling/AsyncObjectTools.cs @@ -0,0 +1,49 @@ +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Fluent.Tooling; + +/// +public class AsyncObjectTools(T source, IToolSet? tools) : ObjectTools(source, tools) +{ + /// + public Task ExtractAsync( + CancellationToken canceler, + ExtractorMod? optionConfiguration = null + ) + { + return Tools.Extractor.ExtractAsync(Source, canceler, optionConfiguration); + } + + /// + public Task VariantAsync(CancellationToken canceler, MutatorMod? optionConfiguration = null) + { + return Tools.Mutator.VariantAsync(Source, canceler, optionConfiguration); + } + + /// + public Task UniqueAsync(CancellationToken canceler, MutatorMod? optionConfiguration = null) + { + return Tools.Mutator.UniqueAsync(Source, canceler, optionConfiguration); + } + + /// + public Task EqualsAsync( + object? y, + CancellationToken canceler, + ValuerMod? optionConfiguration = null + ) + { + return Tools.Valuer.EqualsAsync(Source, y, canceler, optionConfiguration); + } + + /// + public Task GetHashCodeAsync( + CancellationToken canceler, + ValuerMod? optionConfiguration = null + ) + { + return Tools.Valuer.GetHashCodeAsync(Source, canceler, optionConfiguration); + } +} diff --git a/src/Toolbox/Fluent/Tooling/ObjectTools.cs b/src/Toolbox/Fluent/Tooling/ObjectTools.cs new file mode 100644 index 00000000..cebc58e5 --- /dev/null +++ b/src/Toolbox/Fluent/Tooling/ObjectTools.cs @@ -0,0 +1,102 @@ +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Fluent.Tooling; + +/// Provides fluent randomization options. +/// Target type for the tools. +/// +/// +public class ObjectTools(T source, IToolSet? tools) +{ + /// Origin. + protected T Source { get; } = source; + + /// Tools to use. + protected IToolSet Tools { get; } = tools ?? CreateAndFake.Tools.Source; + + /// Accesses the raw fake wrapper. + /// Fake to test with. + /// For use on stubs from the tool only. + public Fake ToFake() + { + return new((IFaked)Source!); + } + + /// Accesses the raw fake wrapper. + /// Type to convert to. + /// Fake to test with. + /// For use on stubs from the tool only. + public Fake ToFake() + { + return new((IFaked)Source!); + } + + /// + public T Copy(DuplicatorMod? optionConfiguration = null) + { + return Tools.Duplicator.Copy(Source, optionConfiguration); + } + + /// + public IContentMap Extract(ExtractorMod? optionConfiguration = null) + { + return Tools.Extractor.Extract(Source, optionConfiguration); + } + + /// + public T Variant(MutatorMod? optionConfiguration = null) + { + return Tools.Mutator.Variant(Source, optionConfiguration); + } + + /// + public T Unique(MutatorMod? optionConfiguration = null) + { + return Tools.Mutator.Unique(Source, optionConfiguration); + } + + /// + public bool Modify(MutatorMod? optionConfiguration = null) + { + return Tools.Mutator.Modify(Source, optionConfiguration); + } + + /// + public Task CallMethodsAsync( + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ) + { + return Tools.Runner.CallMethodsOnAsync(Source!, canceler, optionConfiguration); + } + + /// + public override bool Equals(object? obj) + { + return Tools.Valuer.Equals(Source, obj); + } + + /// + public bool Equals(object? y, ValuerMod? optionConfiguration) + { + return Tools.Valuer.Equals(Source, y, optionConfiguration); + } + + /// + public override int GetHashCode() + { + return Tools.Valuer.GetHashCode(Source); + } + + /// + public int GetHashCode(ValuerMod? optionConfiguration) + { + return Tools.Valuer.GetHashCode(Source, optionConfiguration); + } +} diff --git a/src/Toolbox/Fluent/Tooling/TypeTools.cs b/src/Toolbox/Fluent/Tooling/TypeTools.cs new file mode 100644 index 00000000..cb768e4d --- /dev/null +++ b/src/Toolbox/Fluent/Tooling/TypeTools.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.RandomizerTool; + +namespace Werecodent.CreateAndFake.Fluent.Tooling; + +/// +public sealed class TypeTools(Type source, IToolSet? tools) : ObjectTools(source, tools) +{ + /// + public object CreateRandomInstance(RandomizerMod? optionConfiguration = null) + { + return Tools.Randomizer.Create(Source, optionConfiguration); + } + + /// + public object CreateRandomSizedInstance(int size, RandomizerMod? optionConfiguration = null) + { + return Tools.Randomizer.CreateSized(size, Source, optionConfiguration); + } +} diff --git a/src/Toolbox/Fluent/ToolingExtensions.cs b/src/Toolbox/Fluent/ToolingExtensions.cs new file mode 100644 index 00000000..edad943c --- /dev/null +++ b/src/Toolbox/Fluent/ToolingExtensions.cs @@ -0,0 +1,105 @@ +using System.Numerics; +using Werecodent.CreateAndFake.Fluent.Tooling; + +namespace Werecodent.CreateAndFake.Fluent; + +/// Provides fluent tool actions. +public static class ToolingExtensions +{ + /// Accesses available tool behavior for the instance. + /// Type being used. + /// Instance to act upon. + /// Custom tools to potentially use. + /// Tool functions to run. + public static AsyncObjectTools Tools(this T instance, IToolSet? tools = null) + { + return new AsyncObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this string instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static TypeTools Tools(this Type instance, IToolSet? tools = null) + { + return new TypeTools(instance, tools); + } + + /// + public static ObjectTools Tools(this float instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this double instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this decimal instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this TimeSpan instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this DateTime instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this BigInteger instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools( + this DateTimeOffset instance, + IToolSet? tools = null + ) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this char instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this int instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this long instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this short instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } + + /// + public static ObjectTools Tools(this byte instance, IToolSet? tools = null) + { + return new ObjectTools(instance, tools); + } +} diff --git a/src/Toolbox/IToolSet.cs b/src/Toolbox/IToolSet.cs new file mode 100644 index 00000000..3a2e2a35 --- /dev/null +++ b/src/Toolbox/IToolSet.cs @@ -0,0 +1,46 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake; + +/// Holds implementations of all reflection tools. +public interface IToolSet +{ + /// + IRandom Gen { get; } + + /// + IValuer Valuer { get; } + + /// + IFaker Faker { get; } + + /// + IRandomizer Randomizer { get; } + + /// + IExtractor Extractor { get; } + + /// + IMutator Mutator { get; } + + /// + IAsserter Asserter { get; } + + /// + IDuplicator Duplicator { get; } + + /// + IRunner Runner { get; } + + /// + ITester Tester { get; } +} diff --git a/src/Toolbox/MutatorTool/Engine/IMutateHandler.cs b/src/Toolbox/MutatorTool/Engine/IMutateHandler.cs new file mode 100644 index 00000000..5bae5096 --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/IMutateHandler.cs @@ -0,0 +1,10 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// Handles mutation of the . +public interface IMutateHandler : ITypeSupporter +{ + /// + bool ModifySupported(object instance, IMutatorChainer chainer); +} diff --git a/src/Toolbox/MutatorTool/Engine/IMutateHint.cs b/src/Toolbox/MutatorTool/Engine/IMutateHint.cs new file mode 100644 index 00000000..7b0b703a --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/IMutateHint.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// Handles mutation of the . +public interface IMutateHint : IToolHint +{ + /// If the hint supported the operation with the attempt result if so. + /// + MutateHintResult TryToModify(object instance, IMutatorChainer chainer); +} diff --git a/src/Toolbox/MutatorTool/Engine/IMutatorChainer.cs b/src/Toolbox/MutatorTool/Engine/IMutatorChainer.cs new file mode 100644 index 00000000..f38c7c29 --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/IMutatorChainer.cs @@ -0,0 +1,7 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// +/// Provides a callback into to mutate child values. +public interface IMutatorChainer : IMutator, IToolChainer; diff --git a/src/Toolbox/MutatorTool/Engine/IMutatorEngine.cs b/src/Toolbox/MutatorTool/Engine/IMutatorEngine.cs new file mode 100644 index 00000000..42fb2810 --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/IMutatorEngine.cs @@ -0,0 +1,63 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// +public interface IMutatorEngine : IToolEngine +{ + /// + /// + object Variant(Type type, object? instance, IMutatorChainer chainer); + + /// + /// Aborts execution if triggered. + Task VariantAsync( + Type type, + object? instance, + IMutatorChainer chainer, + CancellationToken canceler + ); + + /// + /// + object VariantOf(Type type, IEnumerable instances, IMutatorChainer chainer); + + /// + /// Aborts execution if triggered. + Task VariantOfAsync( + Type type, + IEnumerable instances, + IMutatorChainer chainer, + CancellationToken canceler + ); + + /// + /// + object Unique(Type type, object? instance, IMutatorChainer chainer); + + /// + /// Aborts execution if triggered. + Task UniqueAsync( + Type type, + object? instance, + IMutatorChainer chainer, + CancellationToken canceler + ); + + /// + /// + object UniqueOf(Type type, IEnumerable instances, IMutatorChainer chainer); + + /// + /// Aborts execution if triggered. + Task UniqueOfAsync( + Type type, + IEnumerable instances, + IMutatorChainer chainer, + CancellationToken canceler + ); + + /// Handles callback behavior for child values. + /// + bool Modify(object? instance, IMutatorChainer chainer); +} diff --git a/src/Toolbox/MutatorTool/Engine/MutateHint.cs b/src/Toolbox/MutatorTool/Engine/MutateHint.cs new file mode 100644 index 00000000..ff93eaa0 --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/MutateHint.cs @@ -0,0 +1,37 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// +public abstract class MutateHint : IMutateHint +{ + /// + public abstract int EnginePriority { get; } + + /// + public abstract IEnumerable SupportedTypes { get; } + + /// + public MutateHintResult TryToModify(object instance, IMutatorChainer chainer) + { + return Supports(instance) ? new(Modify(instance, chainer)) : MutateHintResult.None; + } + + /// If the hint supports modifying the . + /// if supported, otherwise. + /// + protected abstract bool Supports(object instance); + + /// + /// if the has been mutated, + /// otherwise. + /// + /// + protected abstract bool Modify(object instance, IMutatorChainer chainer); + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/MutatorTool/Engine/MutateHintResult.cs b/src/Toolbox/MutatorTool/Engine/MutateHintResult.cs new file mode 100644 index 00000000..0c0bd5a2 --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/MutateHintResult.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// Contains whether or not the modified the instance. +public sealed class MutateHintResult : HintResult +{ + /// Result for when a hint doesn't support a . + public static MutateHintResult None { get; } = new(false, default); + + /// + private MutateHintResult(bool hasData, bool data) + : base(hasData, data) { } + + /// + public MutateHintResult(bool data) + : this(true, data) { } +} diff --git a/src/Toolbox/MutatorTool/Engine/MutateHint{T}.cs b/src/Toolbox/MutatorTool/Engine/MutateHint{T}.cs new file mode 100644 index 00000000..a9dba5c4 --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/MutateHint{T}.cs @@ -0,0 +1,24 @@ +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// Handles mutations. +/// Specific the hint supports. +public abstract class MutateHint : MutateHint +{ + /// + public override IEnumerable SupportedTypes { get; } = [typeof(T)]; + + /// + protected override bool Supports(object instance) + { + return instance is T; + } + + /// + protected sealed override bool Modify(object instance, IMutatorChainer chainer) + { + return Modify((T)instance, chainer); + } + + /// + protected abstract bool Modify(T instance, IMutatorChainer chainer); +} diff --git a/src/Toolbox/MutatorTool/Engine/MutatePriority.cs b/src/Toolbox/MutatorTool/Engine/MutatePriority.cs new file mode 100644 index 00000000..1b4e5992 --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/MutatePriority.cs @@ -0,0 +1,47 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.MutatorTool.Hints; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// Priorities for s. +public enum MutatePriority +{ + /// Priority for hints that won't automatically execute. + /// Such hints only work if given to the tool via . + Disabled = int.MinValue, + + /// Priority for custom hints that'll execute last. + /// Subtract from this priority for even lower priorities. + None = 0, + + /// Priority for . + ObjectHint = 1, + + /// Priority for . + StreamHint = 2, + + /// Priority for . + ImmutableEnumerableHint = 3, + + /// Priority for . + LegacyCollectionHint = 4, + + /// Priority for . + CollectionHint = 5, + + /// Priority for . + ListHint = 6, + + /// Priority for . + DictionaryHint = 7, + + /// Priority for . + UnmodifiableHint = 8, + + /// Priority for . + HandlerHint = 9, + + /// Starting priority for custom hints that'll execute first. + /// Add to this priority for even higher priorities. + Highest = 10, +} diff --git a/src/Toolbox/MutatorTool/Engine/MutatorChainer.cs b/src/Toolbox/MutatorTool/Engine/MutatorChainer.cs new file mode 100644 index 00000000..5027a0bb --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/MutatorChainer.cs @@ -0,0 +1,209 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// +public sealed class MutatorChainer + : ToolChainer, + IMutatorChainer +{ + /// Tracks recursion stack to prevent infinite loops. + private readonly ISet _modifyHistory; + + /// + public MutatorChainer(MutatorOptions options, IMutatorEngine engine) + : base(options, engine) + { + _modifyHistory = new HashSet(ReferenceComparer.Use); + } + + /// + private MutatorChainer(MutatorOptions options, MutatorChainer prevChainer) + : base(options, prevChainer) + { + _modifyHistory = prevChainer._modifyHistory; + } + + /// + protected override MutatorChainer CreateSubChainer(MutatorOptions subOptions) + { + return new MutatorChainer(subOptions, this); + } + + /// + public T Variant(T instance, MutatorMod? optionConfiguration = null) + { + return (T)Variant(typeof(T), instance, optionConfiguration); + } + + /// + public object Variant(Type type, object? instance, MutatorMod? optionConfiguration = null) + { + return Engine.Variant(type, instance, GetSubChainer(optionConfiguration)); + } + + /// + public async Task VariantAsync( + T instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return (T) + await VariantAsync(typeof(T), instance, canceler, optionConfiguration) + .ConfigureAwait(false); + } + + /// + public Task VariantAsync( + Type type, + object? instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return Engine.VariantAsync(type, instance, GetSubChainer(optionConfiguration), canceler); + } + + /// + public T VariantOf(IEnumerable instances, MutatorMod? optionConfiguration = null) + { + return (T)VariantOf(typeof(T), instances.Cast(), optionConfiguration); + } + + /// + public object VariantOf( + Type type, + IEnumerable instances, + MutatorMod? optionConfiguration = null + ) + { + return Engine.VariantOf(type, instances, GetSubChainer(optionConfiguration)); + } + + /// + public async Task VariantOfAsync( + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return (T) + await VariantOfAsync(typeof(T), instances.Cast(), canceler, optionConfiguration) + .ConfigureAwait(false); + } + + /// + public Task VariantOfAsync( + Type type, + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return Engine.VariantOfAsync(type, instances, GetSubChainer(optionConfiguration), canceler); + } + + /// + public T Unique(T instance, MutatorMod? optionConfiguration = null) + { + return (T)Unique(typeof(T), instance, optionConfiguration); + } + + /// + public object Unique(Type type, object? instance, MutatorMod? optionConfiguration = null) + { + return Engine.Unique(type, instance, GetSubChainer(optionConfiguration)); + } + + /// + public async Task UniqueAsync( + T instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return (T) + await UniqueAsync(typeof(T), instance, canceler, optionConfiguration) + .ConfigureAwait(false); + } + + /// + public Task UniqueAsync( + Type type, + object? instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return Engine.UniqueAsync(type, instance, GetSubChainer(optionConfiguration), canceler); + } + + /// + public T UniqueOf(IEnumerable instances, MutatorMod? optionConfiguration = null) + { + return (T)UniqueOf(typeof(T), instances.Cast(), optionConfiguration); + } + + /// + public object UniqueOf( + Type type, + IEnumerable instances, + MutatorMod? optionConfiguration = null + ) + { + return Engine.UniqueOf(type, instances, GetSubChainer(optionConfiguration)); + } + + /// + public async Task UniqueOfAsync( + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return (T) + await UniqueOfAsync(typeof(T), instances.Cast(), canceler, optionConfiguration) + .ConfigureAwait(false); + } + + /// + public Task UniqueOfAsync( + Type type, + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return Engine.UniqueOfAsync(type, instances, GetSubChainer(optionConfiguration), canceler); + } + + /// + public bool Modify(object? instance, MutatorMod? optionConfiguration = null) + { + if (_modifyHistory.Add(instance)) + { + try + { + return Engine.Modify(instance, GetSubChainer(optionConfiguration)); + } + finally + { + _ = _modifyHistory.Remove(instance); + } + } + else + { + return false; + } + } + + /// + public IMutator WithOptions(MutatorMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new MutatorChainer(optionConfiguration.Invoke(Options), this); + } +} diff --git a/src/Toolbox/MutatorTool/Engine/MutatorEngine.cs b/src/Toolbox/MutatorTool/Engine/MutatorEngine.cs new file mode 100644 index 00000000..6da6194d --- /dev/null +++ b/src/Toolbox/MutatorTool/Engine/MutatorEngine.cs @@ -0,0 +1,290 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.MutatorTool.Engine; + +/// +public sealed class MutatorEngine : ToolEngine, IMutatorEngine +{ + /// + public object Variant(Type type, object? instance, IMutatorChainer chainer) + { + return VariantOf(type, [instance], chainer); + } + + /// + public Task VariantAsync( + Type type, + object? instance, + IMutatorChainer chainer, + CancellationToken canceler + ) + { + return VariantOfAsync(type, [instance], chainer, canceler); + } + + /// + public object VariantOf(Type type, IEnumerable instances, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(type, instances, chainer); + + ValuerOptions compareOptions = chainer.Options.Valuer.Options with + { + SkipAsyncValues = true, + }; + + bool isVariantCheck(object result) + { + if ( + ArgumentGuard.IsAsynchronous(result) + || result is IValuerAsyncComparable + || instances.All(o => + ArgumentGuard.IsAsynchronous(o) + || o is IValuerAsyncComparable + || !chainer.Options.Valuer.Equals(result, o, _ => compareOptions) + ) + ) + { + return true; + } + else + { + Disposer.Cleanup(result); + return false; + } + } + + try + { + return chainer + .Options.AttemptLimitForVariants.StallUntil( + $"Create variant of type '{GenericConverter.ExpandName(type)}'", + () => chainer.Options.Randomizer.Create(type), + isVariantCheck + ) + .Last(); + } + catch (Exception e) + { + throw new ToolException( + $"Error creating a variant instance of type '{GenericConverter.ExpandName(type)}'. " + + "Current instance types: " + + string.Join(",", instances.Select(GenericConverter.ExpandName)), + e + ); + } + } + + /// + public async Task VariantOfAsync( + Type type, + IEnumerable instances, + IMutatorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(type, instances, chainer); + + async Task isVariantCheckAsync(object result) + { + foreach (object? item in instances) + { + if ( + await chainer + .Options.Valuer.EqualsAsync(result, item, canceler) + .ConfigureAwait(false) + ) + { + await Disposer.CleanupAsync(result).ConfigureAwait(false); + return false; + } + } + return true; + } + + try + { + return ( + await chainer + .Options.AttemptLimitForVariants.StallUntilAsync( + $"Create variant of type '{GenericConverter.ExpandName(type)}'", + () => chainer.Options.Randomizer.Create(type), + isVariantCheckAsync, + canceler + ) + .ConfigureAwait(false) + ).Last(); + } + catch (Exception e) + { + throw new ToolException( + $"Error creating a variant instance of type '{GenericConverter.ExpandName(type)}'. " + + "Current instance types: " + + string.Join(",", instances.Select(GenericConverter.ExpandName)), + e + ); + } + } + + /// + public object Unique(Type type, object? instance, IMutatorChainer chainer) + { + return UniqueOf(type, [instance], chainer); + } + + /// + public Task UniqueAsync( + Type type, + object? instance, + IMutatorChainer chainer, + CancellationToken canceler + ) + { + return UniqueOfAsync(type, [instance], chainer, canceler); + } + + /// + public object UniqueOf(Type type, IEnumerable instances, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(type, instances, chainer); + + IContentMap[] maps = + [ + .. instances.Where(e => e != null).Select(e => chainer.Options.Extractor.Extract(e)), + ]; + + bool isUniqueCheck(object result) + { + if (!chainer.Options.Extractor.Extract(result).HasSharedContent(maps)) + { + return true; + } + else + { + Disposer.Cleanup(result); + return false; + } + } + + try + { + return chainer + .Options.AttemptLimitForUniques.StallUntil( + $"Create unique of type '{GenericConverter.ExpandName(type)}'", + () => chainer.Options.Randomizer.Create(type), + isUniqueCheck + ) + .Last(); + } + catch (Exception e) + { + throw new ToolException( + $"Error creating a unique instance of type '{GenericConverter.ExpandName(type)}'. " + + "Current instance types: " + + string.Join(",", instances.Select(GenericConverter.ExpandName)), + e + ); + } + } + + /// + public async Task UniqueOfAsync( + Type type, + IEnumerable instances, + IMutatorChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(type, instances, chainer); + + List maps = []; + foreach (object? item in instances) + { + maps.Add( + await chainer.Options.Extractor.ExtractAsync(item, canceler).ConfigureAwait(false) + ); + } + + async Task isUniqueCheckAsync(object result) + { + IAsyncContentMap map = await chainer + .Options.Extractor.ExtractAsync(result, canceler) + .ConfigureAwait(false); + + if (await map.HasSharedContentAsync(maps, canceler).ConfigureAwait(false)) + { + await Disposer.CleanupAsync(result).ConfigureAwait(false); + return false; + } + else + { + return true; + } + } + + try + { + return ( + await chainer + .Options.AttemptLimitForUniques.StallUntilAsync( + $"Create unique of type '{GenericConverter.ExpandName(type)}'", + () => chainer.Options.Randomizer.Create(type), + isUniqueCheckAsync, + canceler + ) + .ConfigureAwait(false) + ).Last(); + } + catch (Exception e) + { + throw new ToolException( + $"Error creating a unique instance of type '{GenericConverter.ExpandName(type)}'. " + + "Current instance types: " + + string.Join(",", instances.Select(GenericConverter.ExpandName)), + e + ); + } + } + + /// + public bool Modify(object? instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + if (instance == null) + { + return false; + } + + MutateHintResult? result; + try + { + result = SelectHints(chainer) + .Select(h => h.TryToModify(instance, chainer)) + .FirstOrDefault(r => r?.HasData ?? false); + } + catch (Exception e) + { + throw new ToolException( + $"Error modifying instance of type '{GenericConverter.ExpandName(instance)}'.", + e + ); + } + + if (result != null) + { + return result.Data; + } + else + { + throw new UnsupportedException( + $"Type '{instance.GetType()}' not supported by the {nameof(IMutator)}." + + $" Create an {nameof(IMutateHint)} to handle the {nameof(Type)}." + ); + } + } +} diff --git a/src/Toolbox/MutatorTool/Handlers/CollectionInternalsMutateHandler.cs b/src/Toolbox/MutatorTool/Handlers/CollectionInternalsMutateHandler.cs new file mode 100644 index 00000000..1d22aa2c --- /dev/null +++ b/src/Toolbox/MutatorTool/Handlers/CollectionInternalsMutateHandler.cs @@ -0,0 +1,36 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Hints; + +namespace Werecodent.CreateAndFake.MutatorTool.Handlers; + +/// Handles mutating the individual contents of s. +/// Not for ; intended to help other hints. +internal sealed class CollectionInternalsMutateHandler : IMutateHandler +{ + /// + public Type? SupportedType => null; + + /// + public bool ModifySupported(object instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + bool modified = false; + + foreach ( + object item in chainer.Options.Gen.NextSequence(((ICollection)instance).Cast()) + ) + { + if (modified && chainer.Options.Gen.Next()) + { + break; + } + + modified |= chainer.Modify(item); + } + + return modified; + } +} diff --git a/src/Toolbox/MutatorTool/Handlers/FactoryMutateHandler.cs b/src/Toolbox/MutatorTool/Handlers/FactoryMutateHandler.cs new file mode 100644 index 00000000..d1c889c3 --- /dev/null +++ b/src/Toolbox/MutatorTool/Handlers/FactoryMutateHandler.cs @@ -0,0 +1,24 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Handlers; + +/// +/// Handles mutations via the . +/// +/// +/// Behavior handling mutations. +internal sealed class FactoryMutateHandler(Action factory) : IMutateHandler +{ + /// + public Type? SupportedType { get; } = typeof(T); + + /// + public bool ModifySupported(object instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(factory, instance); + + factory.Invoke((T)instance, chainer); + return true; + } +} diff --git a/src/Toolbox/MutatorTool/Handlers/NoMutateHandler.cs b/src/Toolbox/MutatorTool/Handlers/NoMutateHandler.cs new file mode 100644 index 00000000..7b14271b --- /dev/null +++ b/src/Toolbox/MutatorTool/Handlers/NoMutateHandler.cs @@ -0,0 +1,17 @@ +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Handlers; + +/// Prevents mutations of the . +/// Specific to prevent mutations of. +internal sealed class NoMutateHandler(Type supportedType) : IMutateHandler +{ + /// + public Type? SupportedType { get; } = supportedType; + + /// + public bool ModifySupported(object instance, IMutatorChainer chainer) + { + return false; + } +} diff --git a/src/Toolbox/MutatorTool/Handlers/ReflectionMutateHandlers.cs b/src/Toolbox/MutatorTool/Handlers/ReflectionMutateHandlers.cs new file mode 100644 index 00000000..dfd4e239 --- /dev/null +++ b/src/Toolbox/MutatorTool/Handlers/ReflectionMutateHandlers.cs @@ -0,0 +1,15 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Handlers; + +/// Holds a collection of related handlers. +internal static class ReflectionMutateHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + RuntimeDetails + .RuntimeTypes.Select(t => new NoMutateHandler(t)) + .Concat([new NoMutateHandler(typeof(AssemblyName))]); +} diff --git a/src/Toolbox/MutatorTool/Handlers/StringDictionaryMutateHandler.cs b/src/Toolbox/MutatorTool/Handlers/StringDictionaryMutateHandler.cs new file mode 100644 index 00000000..37795959 --- /dev/null +++ b/src/Toolbox/MutatorTool/Handlers/StringDictionaryMutateHandler.cs @@ -0,0 +1,29 @@ +using System.Collections.Specialized; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Handlers; + +/// +internal sealed class StringDictionaryMutateHandler : IMutateHandler +{ + /// + public Type? SupportedType => typeof(StringDictionary); + + /// + public bool ModifySupported(object instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(instance, chainer); + + StringDictionary dict = (StringDictionary)instance; + + IEnumerable keys = dict.Keys.Cast(); + if (dict.Count > 0) + { + dict[chainer.Options.Gen.NextItem(keys)] = chainer.Options.Randomizer.Create(); + } + + dict.Add(chainer.VariantOf(keys), chainer.Options.Randomizer.Create()); + return true; + } +} diff --git a/src/Toolbox/MutatorTool/Hints/CollectionMutateHint.cs b/src/Toolbox/MutatorTool/Hints/CollectionMutateHint.cs new file mode 100644 index 00000000..990348e4 --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/CollectionMutateHint.cs @@ -0,0 +1,73 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +/// Handles the mutation of s. +public sealed class CollectionMutateHint : MutateHint +{ + /// Handles modifying behavior once generics are specified. + private static readonly MethodInfo _Modifier = typeof(CollectionMutateHint).GetMethod( + nameof(Alter), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + /// + public override int EnginePriority => (int)MutatePriority.CollectionHint; + + /// + public override IEnumerable SupportedTypes { get; } = [typeof(ICollection<>)]; + + /// + protected override bool Supports(object instance) + { + return TypeDescriber.For(instance?.GetType()).Inherits(typeof(ICollection<>)); + } + + /// + protected override bool Modify(object instance, IMutatorChainer chainer) + { + return (bool) + _Modifier + .MakeGenericMethod( + GenericConverter + .FindConcreteType(instance.GetType(), typeof(ICollection<>)) + .GetGenericArguments() + ) + .Invoke(null, [instance, chainer])!; + } + + /// + private static bool Alter(ICollection instance, IMutatorChainer chainer) + { + bool modified = false; + if (!instance.IsReadOnly) + { + if (instance is ISet set) + { + for (int i = 0; i < chainer.Options.MaxAttemptsForMutatingSets && !modified; i++) + { + modified = set.Add(chainer.Options.Randomizer.Create()); + } + } + else + { + instance.Add(chainer.Options.Randomizer.Create()); + modified = true; + } + } + + foreach (T item in chainer.Options.Gen.NextSequence(instance)) + { + if (modified && chainer.Options.Gen.Next()) + { + break; + } + + modified |= chainer.Modify(item); + } + + return modified; + } +} diff --git a/src/Toolbox/MutatorTool/Hints/DictionaryMutateHint.cs b/src/Toolbox/MutatorTool/Hints/DictionaryMutateHint.cs new file mode 100644 index 00000000..a93ce9f9 --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/DictionaryMutateHint.cs @@ -0,0 +1,59 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +/// +public sealed class DictionaryMutateHint : MutateHint +{ + /// Handles mutating the collection's contents. + private static readonly CollectionInternalsMutateHandler _Handler = new(); + + /// + public override int EnginePriority => (int)MutatePriority.DictionaryHint; + + /// + protected override bool Modify(IDictionary instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (instance.IsReadOnly || (instance.Count == 0 && instance.IsFixedSize)) + { + return _Handler.ModifySupported(instance, chainer); + } + + Type? pairType = GenericConverter.AsConcreteType( + instance.GetType(), + typeof(IDictionary<,>) + ); + + Type keyType = + pairType?.GetGenericArguments()[0] + ?? instance.Keys.Cast().Select(d => d.GetType()).FirstOrDefault() + ?? typeof(string); + + Type valueType = + pairType?.GetGenericArguments()[1] + ?? instance + .Values.Cast() + .Select(d => d?.GetType()) + .FirstOrDefault(t => t != null) + ?? typeof(string); + + object key = + instance.IsFixedSize || (instance.Count > 0 && chainer.Options.Gen.Next()) + ? chainer.Options.Gen.NextItem(instance.Keys.Cast()) + : chainer.VariantOf(keyType, instance.Keys.Cast()); + + instance[key] = chainer.Options.Randomizer.Create(valueType); + + if (chainer.Options.Gen.Next()) + { + _ = _Handler.ModifySupported(instance, chainer); + } + return true; + } +} diff --git a/src/Toolbox/MutatorTool/Hints/HandlerMutateHint.cs b/src/Toolbox/MutatorTool/Hints/HandlerMutateHint.cs new file mode 100644 index 00000000..d745b354 --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/HandlerMutateHint.cs @@ -0,0 +1,73 @@ +using System.Security.Cryptography; +using System.Text; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +#pragma warning disable CA1308 // Uri support for .NET 4.8 is lowercase. + +/// Combines and utilizes available handlers for mutations. +public sealed class HandlerMutateHint : IMutateHint +{ + /// Handlers to use that haven't already been specified. + private static readonly IMutateHandler[] _Creators = + [ + new StringDictionaryMutateHandler(), + new NoMutateHandler(typeof(string)), + new NoMutateHandler(typeof(ECCurve)), + new NoMutateHandler(typeof(RuntimeMethodHandle)), + new FactoryMutateHandler( + (instance, mutator) => + instance.Host = mutator.Options.Randomizer.Create().ToLowerInvariant() + ), + new FactoryMutateHandler( + (instance, mutator) => instance.Append(mutator.Options.Randomizer.Create()) + ), + new FactoryMutateHandler( + (instance, mutator) => + { + instance.WriteLine(mutator.Options.Randomizer.Create()); + instance.Flush(); + } + ), + new FactoryMutateHandler( + (instance, mutator) => mutator.Modify(instance.BaseStream) + ), + ]; + + /// All handlers by their supported type. + private static readonly IDictionary _MutatorsByType = + TypeSupporter.GroupBySupportedType(_Creators.Concat(ReflectionMutateHandlers.Handlers)); + + /// + public int EnginePriority => (int)MutatePriority.HandlerHint; + + /// + public IEnumerable SupportedTypes => _MutatorsByType.Keys; + + /// + public MutateHintResult TryToModify(object instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(instance, chainer); + + if (_MutatorsByType.TryGetValue(instance.GetType(), out IMutateHandler? handler)) + { + return new(handler.ModifySupported(instance, chainer)); + } + else + { + return MutateHintResult.None; + } + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} + +#pragma warning restore diff --git a/src/Toolbox/MutatorTool/Hints/ImmutableEnumerableMutateHint.cs b/src/Toolbox/MutatorTool/Hints/ImmutableEnumerableMutateHint.cs new file mode 100644 index 00000000..85991d1d --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/ImmutableEnumerableMutateHint.cs @@ -0,0 +1,50 @@ +using System.Collections; +using System.Collections.Immutable; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +/// +/// Handles the mutation of collections that don't support s. +/// +public sealed class ImmutableEnumerableMutateHint : MutateHint +{ + /// + public override int EnginePriority => (int)MutatePriority.ImmutableEnumerableHint; + + /// + public override IEnumerable SupportedTypes => + [typeof(ImmutableQueue<>), typeof(ImmutableStack<>)]; + + /// + protected override bool Supports(object instance) + { + TypeDescriber inheritance = TypeDescriber.For(instance?.GetType()); + + return inheritance.Inherits(typeof(ImmutableQueue<>)) + || inheritance.Inherits(typeof(ImmutableStack<>)); + } + + /// + protected override bool Modify(object instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + bool modified = false; + + foreach ( + object item in chainer.Options.Gen.NextSequence(((IEnumerable)instance).Cast()) + ) + { + if (modified && chainer.Options.Gen.Next()) + { + break; + } + + modified |= chainer.Modify(item); + } + + return modified; + } +} diff --git a/src/Toolbox/MutatorTool/Hints/LegacyCollectionMutateHint.cs b/src/Toolbox/MutatorTool/Hints/LegacyCollectionMutateHint.cs new file mode 100644 index 00000000..61f1f95e --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/LegacyCollectionMutateHint.cs @@ -0,0 +1,23 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +/// +public class LegacyCollectionMutateHint : MutateHint +{ + /// Handles mutating the collection's contents. + private static readonly CollectionInternalsMutateHandler _Handler = new(); + + /// + public override int EnginePriority => (int)MutatePriority.LegacyCollectionHint; + + /// + protected override bool Modify(ICollection instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + return _Handler.ModifySupported(instance, chainer); + } +} diff --git a/src/Toolbox/MutatorTool/Hints/ListMutateHint.cs b/src/Toolbox/MutatorTool/Hints/ListMutateHint.cs new file mode 100644 index 00000000..84d9133b --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/ListMutateHint.cs @@ -0,0 +1,55 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +/// +public sealed class ListMutateHint : MutateHint +{ + /// Handles mutating the collection's contents. + private static readonly CollectionInternalsMutateHandler _Handler = new(); + + /// + public override int EnginePriority => (int)MutatePriority.ListHint; + + /// + protected override bool Modify(IList instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + + if (instance.IsReadOnly || (instance.Count == 0 && instance.IsFixedSize)) + { + return _Handler.ModifySupported(instance, chainer); + } + + Type itemType = + GenericConverter + .AsConcreteType(instance.GetType(), typeof(IEnumerable<>)) + ?.GetGenericArguments()[0] + ?? instance.Cast().Select(d => d?.GetType()).FirstOrDefault(t => t != null) + ?? typeof(string); + + object newValue = chainer.Options.Randomizer.Create(itemType); + + bool modified = false; + if (!instance.IsFixedSize && (instance.Count == 0 || chainer.Options.Gen.Next())) + { + modified = instance.Add(newValue) != -1; + } + + if (!modified && instance.Count > 0) + { + instance[chainer.Options.Gen.Next(instance.Count)] = newValue; + modified = true; + } + + if (chainer.Options.Gen.Next()) + { + modified |= _Handler.ModifySupported(instance, chainer); + } + return modified; + } +} diff --git a/src/Toolbox/MutatorTool/Hints/ObjectMutateHint.cs b/src/Toolbox/MutatorTool/Hints/ObjectMutateHint.cs new file mode 100644 index 00000000..6c664867 --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/ObjectMutateHint.cs @@ -0,0 +1,91 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +/// Handles the mutation of data classes. +public sealed class ObjectMutateHint : MutateHint +{ + /// + public override int EnginePriority => (int)MutatePriority.ObjectHint; + + /// + public override IEnumerable SupportedTypes { get; } = [typeof(object)]; + + /// + protected override bool Supports(object instance) + { + return true; + } + + /// + protected override bool Modify(object instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(instance, chainer); + + Type type = instance.GetType(); + DataRandom data = chainer.Options.Gen.NextData(); + bool modified = false; + + object getNewValue(Type memberType, object? originalValue, string? smartValue) + { + return (smartValue?.Equals(originalValue as string, StringComparison.Ordinal) != false) + ? chainer.Variant(memberType, originalValue) + : smartValue; + } + + foreach ( + PropertyInfo prop in chainer.Options.Gen.NextSequence( + TypeDescriber + .For(type) + .Properties.SetAndGetable.Where(p => + p.GetSetMethod() + ?.ReturnParameter.GetRequiredCustomModifiers() + .Contains(typeof(IsExternalInit)) == false + ) + ) + ) + { + if (modified && chainer.Options.Gen.Next()) + { + break; + } + try + { + prop.SetValue( + instance, + getNewValue(prop.PropertyType, prop.GetValue(instance), data.Find(prop)) + ); + modified = true; + } + catch (Exception) + { + // Failed to modify. + } + } + + foreach ( + FieldInfo field in chainer.Options.Gen.NextSequence( + TypeDescriber.For(type).Fields.Writable + ) + ) + { + if (modified && chainer.Options.Gen.Next()) + { + break; + } + + field.SetValue( + instance, + getNewValue(field.FieldType, field.GetValue(instance), data.Find(field)) + ); + modified = true; + } + + return modified; + } +} diff --git a/src/Toolbox/MutatorTool/Hints/StreamMutateHint.cs b/src/Toolbox/MutatorTool/Hints/StreamMutateHint.cs new file mode 100644 index 00000000..ba7bd247 --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/StreamMutateHint.cs @@ -0,0 +1,26 @@ +using System.Text; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +/// +public class StreamMutateHint : MutateHint +{ + /// + public override int EnginePriority => (int)MutatePriority.StreamHint; + + /// + protected override bool Modify(Stream instance, IMutatorChainer chainer) + { + ArgumentGuard.ThrowIfNull(instance, chainer); + + instance.Flush(); + + using StreamWriter writer = new(instance, Encoding.UTF8, 1024, true); + writer.WriteLine(chainer.Options.Randomizer.Create()); + writer.Flush(); + + return true; + } +} diff --git a/src/Toolbox/MutatorTool/Hints/UnmodifiableMutateHint.cs b/src/Toolbox/MutatorTool/Hints/UnmodifiableMutateHint.cs new file mode 100644 index 00000000..68d0369e --- /dev/null +++ b/src/Toolbox/MutatorTool/Hints/UnmodifiableMutateHint.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool.Hints; + +/// +public sealed class UnmodifiableMutateHint : MutateHint +{ + /// + public override int EnginePriority => (int)MutatePriority.UnmodifiableHint; + + /// + public override IEnumerable SupportedTypes => [typeof(IAsyncEnumerable<>)]; + + /// + protected override bool Supports(object instance) + { + ArgumentGuard.ThrowIfNull(instance); + + Type type = instance.GetType(); + return type.IsEnum || type.Inherits(typeof(IAsyncEnumerable<>)); + } + + /// + protected override bool Modify(object instance, IMutatorChainer chainer) + { + return false; + } +} diff --git a/src/Toolbox/MutatorTool/IMutator.cs b/src/Toolbox/MutatorTool/IMutator.cs new file mode 100644 index 00000000..4b671878 --- /dev/null +++ b/src/Toolbox/MutatorTool/IMutator.cs @@ -0,0 +1,174 @@ +global using MutatorMod = System.Func< + Werecodent.CreateAndFake.MutatorTool.MutatorOptions, + Werecodent.CreateAndFake.MutatorTool.MutatorOptions +>; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool; + +/// Tool to modify the state of s or create variants. +/// Useful for testing behavior under various states. +public interface IMutator : IHintTool +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + IMutator WithOptions(MutatorMod optionConfiguration); + + /// Creates a unequal by value with the . + /// The to differentiate from. + /// + T Variant(T instance, MutatorMod? optionConfiguration = null); + + /// Creates an unequal by value with the . + /// The to differentiate from. + /// + object Variant(Type type, object? instance, MutatorMod? optionConfiguration = null); + + /// + /// Aborts execution if triggered. + Task VariantAsync( + T instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ); + + /// + /// Aborts execution if triggered. + Task VariantAsync( + Type type, + object? instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ); + + /// + T VariantOf(IEnumerable instances, MutatorMod? optionConfiguration = null); + + /// + object VariantOf( + Type type, + IEnumerable instances, + MutatorMod? optionConfiguration = null + ); + + /// Creates a unequal by value with the . + /// The to create. + /// The created unequal . + /// + Task VariantOfAsync( + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ); + + /// Creates an unequal by value with the . + /// The to create. + /// The s to differ from. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// The created unequal . + /// + /// Important relevant options: + /// + /// + /// + Task VariantOfAsync( + Type type, + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ); + + /// + /// Creates a that shares no values with the . + /// + /// The to share no values with. + /// + T Unique(T instance, MutatorMod? optionConfiguration = null); + + /// + /// Creates an that shares no values with the . + /// + /// The to share no values with. + /// + object Unique(Type type, object? instance, MutatorMod? optionConfiguration = null); + + /// + /// Aborts execution if triggered. + Task UniqueAsync( + T instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ); + + /// + /// Aborts execution if triggered. + Task UniqueAsync( + Type type, + object? instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ); + + /// + T UniqueOf(IEnumerable instances, MutatorMod? optionConfiguration = null); + + /// + object UniqueOf( + Type type, + IEnumerable instances, + MutatorMod? optionConfiguration = null + ); + + /// + /// Creates a that shares no values with the . + /// + /// The to create. + /// The created . + /// + Task UniqueOfAsync( + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ); + + /// + /// Creates an that shares no values with the . + /// + /// The s to share no values with. + /// Aborts execution if triggered. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + Task UniqueOfAsync( + Type type, + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ); + + /// Attempts to mutate the . + /// The to try modifying. + /// Modifications of this tool's options to apply for this call. + /// + /// if the + /// has been modified, otherwise. + /// + /// + /// Important relevant options: + /// + /// + /// + /// + /// + bool Modify(object? instance, MutatorMod? optionConfiguration = null); +} diff --git a/src/Toolbox/MutatorTool/Mutator.cs b/src/Toolbox/MutatorTool/Mutator.cs new file mode 100644 index 00000000..daf27bbb --- /dev/null +++ b/src/Toolbox/MutatorTool/Mutator.cs @@ -0,0 +1,252 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.MutatorTool; + +/// +/// +public sealed class Mutator(MutatorOptions options) : IMutator +{ + /// + private static readonly MutatorEngine _Engine = new(); + + /// + public MutatorOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public IEnumerable SupportedTypes => _Engine.SupportedTypes; + + /// + public T Variant(T instance, MutatorMod? optionConfiguration = null) + { + return new MutatorChainer(Options, _Engine).Variant(instance, optionConfiguration); + } + + /// + public object Variant(Type type, object? instance, MutatorMod? optionConfiguration = null) + { + return new MutatorChainer(Options, _Engine).Variant(type, instance, optionConfiguration); + } + + /// + public Task VariantAsync( + T instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).VariantAsync( + instance, + canceler, + optionConfiguration + ); + } + + /// + public Task VariantAsync( + Type type, + object? instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).VariantAsync( + type, + instance, + canceler, + optionConfiguration + ); + } + + /// + public T VariantOf(IEnumerable instances, MutatorMod? optionConfiguration = null) + { + return new MutatorChainer(Options, _Engine).VariantOf(instances, optionConfiguration); + } + + /// + public object VariantOf( + Type type, + IEnumerable instances, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).VariantOf(type, instances, optionConfiguration); + } + + /// + public Task VariantOfAsync( + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).VariantOfAsync( + instances, + canceler, + optionConfiguration + ); + } + + /// + public Task VariantOfAsync( + Type type, + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).VariantOfAsync( + type, + instances, + canceler, + optionConfiguration + ); + } + + /// + public T Unique(T instance, MutatorMod? optionConfiguration = null) + { + return new MutatorChainer(Options, _Engine).Unique(instance, optionConfiguration); + } + + /// + public object Unique(Type type, object? instance, MutatorMod? optionConfiguration = null) + { + return new MutatorChainer(Options, _Engine).Unique(type, instance, optionConfiguration); + } + + /// + public Task UniqueAsync( + T instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).UniqueAsync( + instance, + canceler, + optionConfiguration + ); + } + + /// + public Task UniqueAsync( + Type type, + object? instance, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).UniqueAsync( + type, + instance, + canceler, + optionConfiguration + ); + } + + /// + public T UniqueOf(IEnumerable instances, MutatorMod? optionConfiguration = null) + { + return new MutatorChainer(Options, _Engine).UniqueOf(instances, optionConfiguration); + } + + /// + public object UniqueOf( + Type type, + IEnumerable instances, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).UniqueOf(type, instances, optionConfiguration); + } + + /// + public Task UniqueOfAsync( + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).UniqueOfAsync( + instances, + canceler, + optionConfiguration + ); + } + + /// + public Task UniqueOfAsync( + Type type, + IEnumerable instances, + CancellationToken canceler, + MutatorMod? optionConfiguration = null + ) + { + return new MutatorChainer(Options, _Engine).UniqueOfAsync( + type, + instances, + canceler, + optionConfiguration + ); + } + + /// + public bool Modify(object? instance, MutatorMod? optionConfiguration = null) + { + MutatorOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + if (localOptions.VerifyModifyViaValueHashes) + { + int hash = localOptions.Valuer.GetHashCode( + instance, + opt => opt with { SkipAsyncValues = true } + ); + + int i = 1; + do + { + bool modified = new MutatorChainer(Options, _Engine).Modify( + instance, + (optionConfiguration != null) ? _ => localOptions : null + ); + + if (modified) + { + if ( + hash + != localOptions.Valuer.GetHashCode( + instance, + opt => opt with { SkipAsyncValues = true } + ) + ) + { + return true; + } + } + else + { + break; + } + } while (i++ < localOptions.MaxAttemptsForModify); + + return false; + } + else + { + return new MutatorChainer(Options, _Engine).Modify( + instance, + (optionConfiguration != null) ? _ => localOptions : null + ); + } + } + + /// + public IMutator WithOptions(MutatorMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Mutator(optionConfiguration.Invoke(Options)); + } +} diff --git a/src/Toolbox/MutatorTool/MutatorOptions.cs b/src/Toolbox/MutatorTool/MutatorOptions.cs new file mode 100644 index 00000000..c9f2f023 --- /dev/null +++ b/src/Toolbox/MutatorTool/MutatorOptions.cs @@ -0,0 +1,83 @@ +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.MutatorTool; + +/// Configuration for manipulating behavior. +public sealed record MutatorOptions : ToolHintOptions +{ + /// Identifies the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Mutator); + + /// + public required IRandomizer Randomizer { get; init; } + + /// + public required IValuer Valuer { get; init; } + + /// + public required IExtractor Extractor { get; init; } + + /// Limits attempts at creating variants. + /// Attempts fail due to the expected variant actually being equal to the original. + /// Limiter.Score + [ConfigurableOption] + public ILimiter AttemptLimitForVariants { get; init; } = Limiter.Score; + + /// Limits attempts at creating uniques. + /// Attempts fail due to the expected unique actually sharing data with the original. + /// Limiter.Score + [ConfigurableOption] + public ILimiter AttemptLimitForUniques { get; init; } = Limiter.Score; + + /// Limits attempts at mutating sets. + /// Attempts fail due to randomized values already existing in the set. + /// 6 + [ConfigurableOption] + public int MaxAttemptsForMutatingSets { get; init; } = 6; + + /// Limits attempts at mutating s. + /// Only useful when is set. + /// 12 + [ConfigurableOption] + public int MaxAttemptsForModify { get; init; } = 12; + + /// If modification attempts are verified via a change in an instance's value hash. + /// + /// Prevents false positives when using the to modify s. + /// Gives up if not achieved within the limit set by . + /// + /// + [ConfigurableOption] + public bool VerifyModifyViaValueHashes { get; init; } = true; + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal MutatorOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + VerifyModifyViaValueHashes = Config.GetValue(section, VerifyModifyViaValueHashes), + MaxAttemptsForMutatingSets = Config.GetValue(section, MaxAttemptsForMutatingSets), + AttemptLimitForVariants = Config.GetValue(section, AttemptLimitForVariants), + AttemptLimitForUniques = Config.GetValue(section, AttemptLimitForUniques), + IncludeFrameworkHints = Config.GetValue(section, IncludeFrameworkHints), + MaxAttemptsForModify = Config.GetValue(section, MaxAttemptsForModify), + IncludeFoundHints = Config.GetValue(section, IncludeFoundHints), + MaxRecursionDepth = Config.GetValue(section, MaxRecursionDepth), + }; + } +} diff --git a/src/Toolbox/Properties/AssemblyInfo.cs b/src/Toolbox/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..3005fd51 --- /dev/null +++ b/src/Toolbox/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: CLSCompliant(true)] +[assembly: InternalsVisibleTo("Werecodent.CreateAndFake.FakerTypes")] +[assembly: InternalsVisibleTo("CreateAndFake.Tests")] +[assembly: InternalsVisibleTo("CreateAndFake.Configuration.Tests")] diff --git a/src/Toolbox/Properties/Config.cs b/src/Toolbox/Properties/Config.cs new file mode 100644 index 00000000..f28f0b62 --- /dev/null +++ b/src/Toolbox/Properties/Config.cs @@ -0,0 +1,100 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.Properties; + +/// Handles deserializing configuration values. +internal static class Config +{ + /// Loads a configured value from the . + /// of the value to retrieve. + /// Section potentially containing the value. + /// Property to contain the value. + /// Configuration name for the value to retrieve. + /// + /// The deserialized value if present, the otherwise. + /// + internal static T GetValue( + IConfigurationSection section, + T property, + [CallerArgumentExpression(nameof(property))] string? name = null + ) + { + ArgumentGuard.ThrowIfNull(name, section); + return section.GetValue(name, property); + } + + /// + /// The deserialized collection if present, the otherwise. + /// + /// + /// + internal static FrozenSet GetSet( + IConfigurationSection section, + FrozenSet property, + [CallerArgumentExpression(nameof(property))] string? name = null + ) + { + return GetList(section, name)?.ToFrozenSet() ?? property; + } + + /// + internal static ImmutableArray GetArray( + IConfigurationSection section, + ImmutableArray property, + [CallerArgumentExpression(nameof(property))] string? name = null + ) + { + return GetList(section, name)?.ToImmutableArray() ?? property; + } + + /// + internal static FrozenSet GetChars( + IConfigurationSection section, + FrozenSet property, + [CallerArgumentExpression(nameof(property))] string? name = null + ) + { + ArgumentGuard.ThrowIfNull(property); + + return GetValue(section, string.Join("", property), name).ToCharArray().ToFrozenSet(); + } + + /// + internal static FrozenSet GetTypes( + IConfigurationSection section, + FrozenSet property, + [CallerArgumentExpression(nameof(property))] string? name = null + ) + { + return GetList(section, name) + ?.Select(typeName => Type.GetType(typeName, true)!) + .ToFrozenSet() + ?? property; + } + + /// Deserializes a collection from the configuration. + /// Item for the collection. + /// Root configuration section for the options. + /// Name of the subsection representing the collection. + /// The deserialized collection if present, otherwise. + private static List? GetList(IConfigurationSection config, string? sectionName) + { + ArgumentGuard.ThrowIfNull(sectionName, config); + + IConfigurationSection section = config.GetSection(sectionName); + if (section.Exists()) + { + List bindResult = []; + section.Bind(bindResult); + return bindResult; + } + else + { + return null; + } + } +} diff --git a/src/Toolbox/Properties/Globals.cs b/src/Toolbox/Properties/Globals.cs new file mode 100644 index 00000000..fa0ed0c0 --- /dev/null +++ b/src/Toolbox/Properties/Globals.cs @@ -0,0 +1,5 @@ +#if NET9_0_OR_GREATER +global using Lock = System.Threading.Lock; +#else +global using Lock = Werecodent.CreateAndFake.Design.Content.CustomLock; +#endif diff --git a/src/Toolbox/RandomizerTool/Engine/CreateHint.cs b/src/Toolbox/RandomizerTool/Engine/CreateHint.cs new file mode 100644 index 00000000..41b4c69c --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/CreateHint.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// +public abstract class CreateHint : ICreateHint +{ + /// + public abstract int EnginePriority { get; } + + /// + public abstract IEnumerable SupportedTypes { get; } + + /// + public abstract CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer); + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/RandomizerTool/Engine/CreateHintResult.cs b/src/Toolbox/RandomizerTool/Engine/CreateHintResult.cs new file mode 100644 index 00000000..f0e0b680 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/CreateHintResult.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// +public sealed class CreateHintResult : HintResult +{ + /// For when a hint doesn't support a type or fails to create it. + public static CreateHintResult None { get; } = new(false, null); + + /// + private CreateHintResult(bool hasData, object? data) + : base(hasData, data) { } + + /// + public CreateHintResult(object? data) + : this(true, data) { } +} diff --git a/src/Toolbox/RandomizerTool/Engine/CreateHint{T}.cs b/src/Toolbox/RandomizerTool/Engine/CreateHint{T}.cs new file mode 100644 index 00000000..6a2f3d9f --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/CreateHint{T}.cs @@ -0,0 +1,31 @@ +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// being supported for randomization. +/// +public abstract class CreateHint : CreateHint +{ + /// + public override IEnumerable SupportedTypes { get; } = [typeof(T)]; + + /// + public sealed override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + if (type.IsInheritedBy() && !randomizer.AlreadyCreated()) + { + return new(Create(randomizer)); + } + else + { + return CreateHintResult.None; + } + } + + /// Creates a random instance. + /// Handles randomizing child values. + /// The created instance. + protected abstract T Create(IRandomizerChainer randomizer); +} diff --git a/src/Toolbox/RandomizerTool/Engine/CreatePriority.cs b/src/Toolbox/RandomizerTool/Engine/CreatePriority.cs new file mode 100644 index 00000000..afbadae0 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/CreatePriority.cs @@ -0,0 +1,65 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// Priorities for s. +public enum CreatePriority +{ + /// Priority for hints that won't automatically execute. + /// Such hints only work if given to the tool via . + Disabled = int.MinValue, + + /// Priority for custom hints that'll execute last. + /// Subtract from this priority for even lower priorities. + None = 0, + + /// Priority for . + ObjectHint = 1, + + /// Priority for . + NullableHint = 2, + + /// Priority for . + SubclassHint = 3, + + /// Priority for . + FakeHint = 4, + + /// Priority for . + InjectedHint = 5, + + /// Priority for . + ComparerHint = 6, + + /// Priority for . + AsyncCollectionHint = 7, + + /// Priority for . + TaskHint = 8, + + /// Priority for . + DelegateHint = 9, + + /// Priority for . + SpanHint = 10, + + /// Priority for . + LegacyCollectionHint = 11, + + /// Priority for . + CollectionHint = 12, + + /// Priority for . + GenericHint = 13, + + /// Priority for . + EnumHint = 14, + + /// Priority for . + HandlerHint = 15, + + /// Starting priority for custom hints that'll execute first. + /// Add to this priority for even higher priorities. + Highest = 16, +} diff --git a/src/Toolbox/RandomizerTool/Engine/ICreateHandler.cs b/src/Toolbox/RandomizerTool/Engine/ICreateHandler.cs new file mode 100644 index 00000000..c0ca7f89 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/ICreateHandler.cs @@ -0,0 +1,14 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// Handles creation of a specific type. +internal interface ICreateHandler : ITypeSupporter +{ + /// + /// Creates a random instance of the . + /// + /// Handles randomizing supporting values. + /// The created instance. + object? CreateSupported(IRandomizerChainer randomizer); +} diff --git a/src/Toolbox/RandomizerTool/Engine/ICreateHint.cs b/src/Toolbox/RandomizerTool/Engine/ICreateHint.cs new file mode 100644 index 00000000..4d75985f --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/ICreateHint.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// Handles randomizing specific types for . +public interface ICreateHint : IToolHint +{ + /// Tries to create a random instance of the given . + /// to generate. + /// Handles randomizing child values. + /// Possible result. + CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer); +} diff --git a/src/Toolbox/RandomizerTool/Engine/IRandomizerChainer.cs b/src/Toolbox/RandomizerTool/Engine/IRandomizerChainer.cs new file mode 100644 index 00000000..e89bbd64 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/IRandomizerChainer.cs @@ -0,0 +1,31 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// Provides a callback into to create child values. +public interface IRandomizerChainer : IRandomizer, IToolChainer +{ + /// Checks if has already been created by the randomizer. + /// to check. + /// if already created, otherwise. + bool AlreadyCreated(); + + /// Checks if has already been created by the randomizer. + /// to check. + /// if already created, otherwise. + bool AlreadyCreated(Type type); + + /// Calls the randomizer to create a random instance of the given . + /// Type to create. + /// Container of the instance to create. + /// Modifications of this tool's options to apply for this call. + /// The created instance. + object CreateInternal(Type type, object parent, RandomizerMod? optionConfiguration = null); + + /// Calls the randomizer to create a random instance of the given . + /// Type to create. + /// Container of the instance to create. + /// Modifications of this tool's options to apply for this call. + /// The created instance. + object CreateSpecific(Type type, Type parent, RandomizerMod? optionConfiguration = null); +} diff --git a/src/Toolbox/RandomizerTool/Engine/IRandomizerEngine.cs b/src/Toolbox/RandomizerTool/Engine/IRandomizerEngine.cs new file mode 100644 index 00000000..94075414 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/IRandomizerEngine.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// +public interface IRandomizerEngine : IToolEngine +{ + /// Handles callback behavior for child values. + /// + object Create(Type type, IRandomizerChainer chainer); + + /// Handles callback behavior for child values. + /// + object Inject(Type type, IEnumerable? values, IRandomizerChainer chainer); +} diff --git a/src/Toolbox/RandomizerTool/Engine/RandomizerChainer.cs b/src/Toolbox/RandomizerTool/Engine/RandomizerChainer.cs new file mode 100644 index 00000000..62848290 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/RandomizerChainer.cs @@ -0,0 +1,171 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// Provides a callback into to create child values. +public sealed class RandomizerChainer + : ToolChainer, + IRandomizerChainer +{ + /// Types not to create as to prevent infinite recursion. + private readonly IDictionary _createHistory; + + private readonly ISet _attemptHistory; + + /// + public RandomizerChainer(RandomizerOptions options, IRandomizerEngine engine) + : base(options, engine) + { + _createHistory = new Dictionary(); + _attemptHistory = new HashSet(); + } + + /// + private RandomizerChainer(RandomizerOptions options, RandomizerChainer prevChainer) + : base(options, prevChainer) + { + _createHistory = prevChainer._createHistory; + _attemptHistory = prevChainer._attemptHistory; + } + + /// + protected override RandomizerChainer CreateSubChainer(RandomizerOptions subOptions) + { + return new RandomizerChainer(subOptions, this); + } + + /// + public bool AlreadyCreated() + { + return AlreadyCreated(typeof(T)); + } + + /// + public bool AlreadyCreated(Type type) + { + return _createHistory.ContainsKey(type) || _attemptHistory.Contains(type); + } + + /// + public object CreateSpecific(Type type, Type parent, RandomizerMod? optionConfiguration = null) + { + if (_attemptHistory.Add(type)) + { + try + { + return Engine.Create(type, GetSubChainer(optionConfiguration)); + } + finally + { + _ = _attemptHistory.Remove(type); + } + } + else + { + throw new EngineException( + $"Type '{GenericConverter.ExpandName(type)}' already created." + ); + } + } + + /// + public object CreateInternal( + Type type, + object parent, + RandomizerMod? optionConfiguration = null + ) + { + ArgumentGuard.ThrowIfNull(type, parent); + + if (_createHistory.TryGetValue(type, out object? previous)) + { + return previous; + } + else if (parent.GetType() == type) + { + return parent; + } + + if (!_createHistory.ContainsKey(parent.GetType())) + { + _createHistory.Add(parent.GetType(), parent); + try + { + return Engine.Create(type, GetSubChainer(optionConfiguration)); + } + finally + { + _ = _createHistory.Remove(parent.GetType()); + } + } + else + { + throw new EngineException( + $"Type '{GenericConverter.ExpandName(parent)}' already created." + ); + } + } + + /// + public T Create(RandomizerMod? optionConfiguration = null) + { + return (T)Engine.Create(typeof(T), GetSubChainer(optionConfiguration)); + } + + /// + public object Create(Type type, RandomizerMod? optionConfiguration = null) + { + return Engine.Create(type, GetSubChainer(optionConfiguration)); + } + + /// + public T CreateSized(int size, RandomizerMod? optionConfiguration = null) + { + return (T)CreateSized(size, typeof(T), optionConfiguration); + } + + /// + public object CreateSized(int size, Type type, RandomizerMod? optionConfiguration = null) + { + RandomizerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + return Create( + type, + _ => + localOptions with + { + CollectionMinSize = size, + CollectionMaxSize = size, + StringMinSize = size, + StringMaxSize = size, + NestedOptions = localOptions, + } + ); + } + + /// + public T Inject(IEnumerable? values, RandomizerMod? optionConfiguration = null) + { + return (T)Inject(typeof(T), values); + } + + /// + public object Inject( + Type type, + IEnumerable? values, + RandomizerMod? optionConfiguration = null + ) + { + return Engine.Inject(type, values, GetSubChainer(optionConfiguration)); + } + + /// + public IRandomizer WithOptions(RandomizerMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new RandomizerChainer(optionConfiguration.Invoke(Options), this); + } +} diff --git a/src/Toolbox/RandomizerTool/Engine/RandomizerEngine.cs b/src/Toolbox/RandomizerTool/Engine/RandomizerEngine.cs new file mode 100644 index 00000000..21ed53fb --- /dev/null +++ b/src/Toolbox/RandomizerTool/Engine/RandomizerEngine.cs @@ -0,0 +1,153 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.RandomizerTool.Engine; + +/// +public sealed class RandomizerEngine : ToolEngine, IRandomizerEngine +{ + /// Handles callback behavior for child values. + /// + public object Create(Type type, IRandomizerChainer chainer) + { + ArgumentGuard.ThrowIfNull(type, chainer); + + CreateHintResult? result = SelectHints(chainer) + .Select(h => h.TryToCreate(type, chainer)) + .FirstOrDefault(r => r?.HasData ?? false); + + if (result != null) + { + return result.Data!; + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(type)}' not supported by the randomizer. " + + "Create a hint to generate the type." + ); + } + } + + /// Handles callback behavior for child values. + /// + public object Inject(Type type, IEnumerable? values, IRandomizerChainer chainer) + { + ArgumentGuard.ThrowIfNull(type); + + if (type.IsGenericTypeDefinition) + { + int i = 0; + foreach (Type defined in GenericResolver.CreateConcreteGenerics(type, chainer)) + { + ArgumentGuard.ThrowUponIterationLimit(i++, chainer.Options.Design.IterationLimit); + try + { + return HandleInject(defined, values, chainer); + } + catch (Exception) + { + // Try next type. + } + } + throw new UnsupportedException( + $"Could not create generic '{GenericConverter.ExpandName(type)}'." + ); + } + else + { + return HandleInject(type, values, chainer); + } + } + + /// + private object HandleInject(Type type, IEnumerable? values, IRandomizerChainer chainer) + { + TypeDescriber describer = TypeDescriber.For(type); + + List> data = + [ + .. (values ?? []) + .Where(v => v != null) + .Select(v => (v is Fake fake) ? fake.Dummy : v) + .Where(v => v != null) + .Select(v => Tuple.Create(v!.GetType(), v)), + ]; + + MethodBase? maker = FindBestConstructor(describer.Constructors.Visible, data) + ?? FindBestConstructor(describer.Factories.Visible, data); + + if ( + maker == null + || describer.Inherits() + || describer.Inherits(typeof(Injected<>)) + || describer.Inherits() + ) + { + return Create(type, chainer); + } + else if (maker is ConstructorInfo constructor) + { + return constructor.Invoke(CreateInjectArgs(maker, data, chainer)); + } + else + { + return maker.Invoke(null, CreateInjectArgs(maker, data, chainer))!; + } + } + + /// Creates the args to inject an instance with. + /// Constructor to use. + /// Canned data to prefer. + /// Handles callback behavior for child values. + /// The created args to inject an instance with. + private object?[] CreateInjectArgs( + MethodBase maker, + List> data, + IRandomizerChainer chainer + ) + { + ParameterInfo[] info = maker.GetParameters(); + object?[] args = new object[info.Length]; + + for (int i = 0; i < args.Length; i++) + { + Tuple? match = data.Find(t => t.Item1.Inherits(info[i].ParameterType)); + if (match != default) + { + args[i] = match.Item2; + _ = data.Remove(match); + } + else + { + args[i] = Create(info[i].ParameterType, chainer); + } + } + return args; + } + + /// Finds the constructor with the most matches then by fewest parameters. + /// Potential constructors/factories to analyze. + /// Injection data to use. + /// Compatible constructor if found, null otherwise. + private static MethodBase? FindBestConstructor( + IEnumerable potentialMakers, + List> data + ) + { + return potentialMakers + .Where(c => !c.IsGenericMethodDefinition) + .GroupBy(c => + c.GetParameters().Count(p => data.Exists(t => t.Item1.Inherits(p.ParameterType))) + ) + .Where(g => g.Key > 0) + .OrderByDescending(g => g.Key) + .FirstOrDefault() + ?.OrderBy(c => c.GetParameters().Length) + .FirstOrDefault(); + } +} diff --git a/src/Toolbox/RandomizerTool/GenericResolver.cs b/src/Toolbox/RandomizerTool/GenericResolver.cs new file mode 100644 index 00000000..d4366d48 --- /dev/null +++ b/src/Toolbox/RandomizerTool/GenericResolver.cs @@ -0,0 +1,307 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Threading.Tasks.Sources; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.RandomizerTool.Handlers; +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.RandomizerTool; + +/// Fulfills generics for generic type definitions. +public static class GenericResolver +{ + /// All possible s that have default constructors. + private static readonly FrozenSet _HasDefaultConstructor = TypeDescriber + .For() + .FindLoadedSubclasses() + .Where(t => t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null) + .ToFrozenSet(); + + /// Generic choices when there are no constraints. + private static readonly ImmutableArray _DefaultGenerics = + [ + typeof(int), + typeof(double), + typeof(string), + typeof(TimeSpan), + ]; + + /// Types to not use found direct implementations. + private static readonly FrozenSet _CraftOnlyTypes = + [ + .. CollectionCreateHint.PotentialCollections, + typeof(IEnumerable<>), + typeof(IAsyncEnumerable<>), + typeof(IValueTaskSource<>), + ]; + + /// Defines the with randomized generics. + /// Potential generic method definition to concretely define. + /// Handles randomization + /// The with generics specified. + /// If no possible generics are found. + [ExcludeFromCodeCoverage] // Any known fail cases are to be fixed. + [return: NotNullIfNotNull(nameof(method))] + public static MethodInfo? OfConcrete(MethodInfo? method, IRandomizer randomizer) + { + if (method?.IsGenericMethodDefinition ?? false) + { + return CreateConcreteGenerics(method, randomizer).FirstOrDefault() + ?? throw new UnsupportedException($"Could not craft generic '{method}'."); + } + else + { + return method; + } + } + + /// Defines the with randomized generics. + /// Potential generic type definition to concretely define. + /// Handles randomization. + /// The with generics specified. + /// If no possible generics are found. + [ExcludeFromCodeCoverage] // Any known fail cases are to be fixed. + [return: NotNullIfNotNull(nameof(type))] + public static Type? OfConcrete(Type? type, IRandomizerChainer randomizer) + { + if (type?.IsGenericTypeDefinition ?? false) + { + return CreateConcreteGenerics(type, randomizer).FirstOrDefault() + ?? throw new UnsupportedException( + $"Could not craft generic '{GenericConverter.ExpandName(type)}'." + ); + } + else + { + return type; + } + } + + /// Generic method definition to concretely define. + /// + /// If is not a generic definition. + /// + /// + [return: NotNullIfNotNull(nameof(method))] + public static IEnumerable CreateConcreteGenerics( + MethodInfo method, + IRandomizer randomizer + ) + { + ArgumentGuard.ThrowIfNull(method, randomizer); + + if (!method.IsGenericMethodDefinition) + { + throw new ArgumentException( + $"Type '{method}' was not a generic method definition.", + nameof(method) + ); + } + + return CraftGenerics( + method.GetGenericArguments(), + _ => true, + method.MakeGenericMethod, + randomizer + ); + } + + /// Generic type definition to concretely define. + /// + /// If is not a generic definition. + /// + /// + public static IEnumerable CreateConcreteGenerics(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(type, randomizer); + + if (!type.IsGenericTypeDefinition) + { + throw new ArgumentException( + $"Type '{GenericConverter.ExpandName(type)}' was not a generic type definition.", + nameof(type) + ); + } + + if (!_CraftOnlyTypes.Contains(type)) + { + List directImplementations = + [ + .. randomizer.Options.Gen.NextSequence( + FindSubclasses(type).Where(t => !randomizer.AlreadyCreated(t)) + ), + ]; + + if (directImplementations.Count != 0) + { + return directImplementations; + } + } + + return CraftGenerics( + type.GetGenericArguments(), + t => !randomizer.AlreadyCreated(t), + type.MakeGenericType, + randomizer + ); + } + + /// Generates possible generics. + /// of generics to generate. + /// Generic arguments to populate. + /// Condition to force all arguments to fulfill. + /// Method to generate a generic from specified arguments. + /// Handles sequence randomization. + /// The generated generics. + /// Initial generic arguments are randomized, then sequentially applied. + private static IEnumerable CraftGenerics( + Type[] genericArguments, + Func argValidityCheck, + Func maker, + IRandomizer randomizer + ) + where T : class + { + List> possibleArgsPerArg = + [ + .. genericArguments.Select(t => + randomizer + .Options.Gen.NextSequence(FindPossibleArgs(t).Where(argValidityCheck)) + .ToList() + ), + ]; + + int current = 0; + foreach (int[] indexes in FindAllIndexes(possibleArgsPerArg)) + { + ArgumentGuard.ThrowUponIterationLimit( + current++, + Tools.Runner.Options.Design.IterationLimit + ); + + Type[] nextArgSet = new Type[genericArguments.Length]; + for (int i = 0; i < nextArgSet.Length; i++) + { + nextArgSet[i] = possibleArgsPerArg[i][indexes[i]]; + } + + T? nextGeneric = null; + try + { + nextGeneric = maker.Invoke(nextArgSet); + } + catch + { + // Try next generic upon failure. + } + + if (nextGeneric != null) + { + yield return nextGeneric; + } + } + } + + /// + /// Finds all possible index combinations for the . + /// + /// Collection of possible items for each position. + /// Every possible index combination. + /// Performance optimized: Returned array is reused for each yielded result. + private static IEnumerable FindAllIndexes(IEnumerable> possibleArgsPerArg) + { + int[] argLengths = [.. possibleArgsPerArg.Select(a => a.Count)]; + int[] currentIndexes = [.. Enumerable.Repeat(0, argLengths.Length)]; + + if (argLengths.Any(v => v == 0)) + { + yield break; + } + + int lastAddedIndex = currentIndexes.Length; + while (lastAddedIndex >= 0) + { + yield return currentIndexes; + + for (int i = currentIndexes.Length - 1; i >= 0; i--) + { + currentIndexes[i] += 1; + if (currentIndexes[i] < argLengths[i]) + { + break; + } + else + { + lastAddedIndex = i - 1; + currentIndexes[i] = 0; + } + } + } + } + + /// Finds possible s to fulfill a generic argument. + /// Generic argument to match. + /// The possible s. + private static IEnumerable FindPossibleArgs(Type type) + { + ArgumentGuard.ThrowIfNull(type); + + IEnumerable possibleTypes = _DefaultGenerics; + + Type[] constraints = + [ + .. type.GetGenericParameterConstraints() + .Where(t => t != typeof(ValueType)) + .Select(t => GenericConverter.AsGenericBase(t) ?? t), + ]; + if (constraints.Length != 0) + { + HashSet constraintCompatibles = [.. FindSubclasses(constraints[0])]; + foreach (IEnumerable set in constraints.Skip(1).Select(FindSubclasses)) + { + constraintCompatibles.IntersectWith(set); + } + possibleTypes = constraintCompatibles; + } + + if ( + type.GenericParameterAttributes.HasFlag( + GenericParameterAttributes.NotNullableValueTypeConstraint + ) + ) + { + possibleTypes = possibleTypes.Where(t => t.IsValueType); + } + + if ( + type.GenericParameterAttributes.HasFlag( + GenericParameterAttributes.DefaultConstructorConstraint + ) + ) + { + possibleTypes = possibleTypes.Where(_HasDefaultConstructor.Contains); + } + + return possibleTypes; + } + + /// Finds usable subclasses for the . + /// to find subclasses for. + /// The found subclasses. + private static IEnumerable FindSubclasses(Type type) + { + if (type == typeof(Exception)) + { + return ExceptionCreateHandlers.PotentialExceptions; + } + else + { + return TypeDescriber.For(type).FindLoadedSubclasses(); + } + } +} diff --git a/src/Toolbox/RandomizerTool/Handlers/ConfigurationSectionCreateHandler.cs b/src/Toolbox/RandomizerTool/Handlers/ConfigurationSectionCreateHandler.cs new file mode 100644 index 00000000..c833917f --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/ConfigurationSectionCreateHandler.cs @@ -0,0 +1,39 @@ +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +internal sealed class ConfigurationSectionCreateHandler : ICreateHandler +{ + public Type? SupportedType => typeof(IConfigurationSection); + + public object? CreateSupported(IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + Fake config = randomizer.Create>(); + Behavior nullSection = Behavior.Returns(null); + + config.Setup(c => c.GetSection("Design"), nullSection); + config.Setup(c => c.GetSection(nameof(Asserter)), nullSection); + config.Setup(c => c.GetSection(nameof(Duplicator)), nullSection); + config.Setup(c => c.GetSection(nameof(Extractor)), nullSection); + config.Setup(c => c.GetSection(nameof(Faker)), nullSection); + config.Setup(c => c.GetSection(nameof(Mutator)), nullSection); + config.Setup(c => c.GetSection(nameof(Randomizer)), nullSection); + config.Setup(c => c.GetSection(nameof(Runner)), nullSection); + config.Setup(c => c.GetSection(nameof(Tester)), nullSection); + config.Setup(c => c.GetSection(nameof(Valuer)), nullSection); + + return config.Dummy; + } +} diff --git a/src/Toolbox/RandomizerTool/Handlers/ExceptionCreateHandlers.cs b/src/Toolbox/RandomizerTool/Handlers/ExceptionCreateHandlers.cs new file mode 100644 index 00000000..4b726773 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/ExceptionCreateHandlers.cs @@ -0,0 +1,92 @@ +using System.Collections.Frozen; +using System.Reflection; +using System.Runtime.InteropServices; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +#pragma warning disable CS0618, SYSLIB0050 // Needed for backwards compatibility. + +internal static class ExceptionCreateHandlers +{ + /// Exceptions that have issues in legacy .NET. + private static readonly FrozenSet _UnsupportedExceptions = + [ + "System.DirectoryServices.ActiveDirectory.SyncFromAllServersOperationException", + "System.DirectoryServices.ActiveDirectory.ForestTrustCollisionException", + "System.Diagnostics.Eventing.Reader.EventLogProviderDisabledException", + "System.Deployment.Application.CompatibleFrameworkMissingException", + "System.Diagnostics.Eventing.Reader.EventLogInvalidDataException", + "System.Deployment.Application.DependentPlatformMissingException", + "System.Deployment.Application.SupportedRuntimeMissingException", + "System.Diagnostics.Eventing.Reader.EventLogNotFoundException", + "System.Diagnostics.Eventing.Reader.EventLogReadingException", + "System.ComponentModel.Composition.ChangeRejectedException", + "System.ComponentModel.DataAnnotations.ValidationException", + "System.Deployment.Application.DeploymentDownloadException", + "System.Deployment.Application.InvalidDeploymentException", + "System.Deployment.Application.TrustNotGrantedException", + "System.ComponentModel.Composition.CompositionException", + "System.Security.Principal.IdentityNotMappedException", + "System.Diagnostics.Eventing.Reader.EventLogException", + "System.Runtime.Serialization.SerializationException", + "System.Configuration.ConfigurationErrorsException", + "System.Deployment.Application.DeploymentException", + "System.DirectoryServices.Protocols.LdapException", + "System.Net.Mail.SmtpFailedRecipientsException", + "System.Net.NetworkInformation.PingException", + "System.Xaml.XamlDuplicateMemberException", + "System.Net.Http.HttpRequestException", + "System.Security.SecurityException", + "System.Web.HttpParseException", + ]; + + /// Exceptions that shouldn't be registered as supported. + private static readonly FrozenSet _FatalExceptions = + [ + typeof(AppDomainUnloadedException), + typeof(AccessViolationException), + typeof(ExecutionEngineException), + typeof(BadImageFormatException), + typeof(StackOverflowException), + typeof(OutOfMemoryException), + typeof(ThreadAbortException), + typeof(ExternalException), + typeof(COMException), + typeof(SEHException), + ]; + + /// Exception that the handlers can create. + internal static IEnumerable PotentialExceptions { get; } = + TypeDescriber + .For() + .FindLoadedSubclasses() + .Where(t => t.IsVisible) + .Where(t => t.IsSerializable) + .Where(t => t.Namespace!.StartsWith("System", StringComparison.Ordinal)) + .Where(t => !_UnsupportedExceptions.Contains(t.FullName!)) + .Where(t => !_FatalExceptions.Contains(t)) + .Where(t => t.GetConstructor([typeof(string)]) != null) + .ToFrozenSet(); + + internal static IEnumerable Handlers { get; } = + PotentialExceptions + .Select(t => t.GetConstructor([typeof(string)])) + .Select(c => new ExceptionCreateHandler(c!)); + + /// + private sealed class ExceptionCreateHandler(ConstructorInfo constructor) : ICreateHandler + { + /// + public Type? SupportedType => constructor.ReflectedType; + + /// + public object? CreateSupported(IRandomizerChainer randomizer) + { + return constructor.Invoke([randomizer.Create()]); + } + } +} + +#pragma warning restore diff --git a/src/Toolbox/RandomizerTool/Handlers/FactoryCreateHandler.cs b/src/Toolbox/RandomizerTool/Handlers/FactoryCreateHandler.cs new file mode 100644 index 00000000..58e34125 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/FactoryCreateHandler.cs @@ -0,0 +1,27 @@ +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +/// +/// Behavior handling creation of the supported type. +internal sealed class FactoryCreateHandler( + Type supportedType, + Func factory +) : ICreateHandler +{ + /// + public Type SupportedType { get; } = supportedType; + + /// + public object? CreateSupported(IRandomizerChainer randomizer) + { + return factory?.Invoke(randomizer); + } + + /// + public override string ToString() + { + return $"{nameof(FactoryCreateHandler)}({GenericConverter.ExpandName(SupportedType)})"; + } +} diff --git a/src/Toolbox/RandomizerTool/Handlers/FactoryCreateHandler{T}.cs b/src/Toolbox/RandomizerTool/Handlers/FactoryCreateHandler{T}.cs new file mode 100644 index 00000000..477fc8b0 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/FactoryCreateHandler{T}.cs @@ -0,0 +1,27 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +/// +/// +/// Behavior handling creation of the supported type. +internal sealed class FactoryCreateHandler(Func factory) : ICreateHandler +{ + /// + public Type SupportedType { get; } = typeof(T); + + /// + public object? CreateSupported(IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(factory); + return factory.Invoke(randomizer); + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} diff --git a/src/Toolbox/RandomizerTool/Handlers/ReflectionCreateHandlers.cs b/src/Toolbox/RandomizerTool/Handlers/ReflectionCreateHandlers.cs new file mode 100644 index 00000000..74c695cd --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/ReflectionCreateHandlers.cs @@ -0,0 +1,123 @@ +using System.Collections; +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +internal static class ReflectionCreateHandlers +{ + /// Ignored due being performance heavy to call under certain circumstances. + private static readonly ImmutableHashSet _MethodsToExclude = ["Parse"]; + + /// Potential types to randomize. + internal static FrozenSet PossibleTypes { get; } = + [ + typeof(int), + typeof(Guid), + typeof(long), + typeof(long?), + typeof(int[]), + typeof(double), + typeof(object), + typeof(List), + typeof(ISet), + typeof(AggregateException), + typeof(IEnumerable), + typeof(KeyValuePair), + typeof(InvalidOperationException), + ]; + + /// Potential constructors to randomize. + internal static FrozenSet PossibleConstructors { get; } = + PossibleTypes + .Select(TypeDescriber.For) + .Where(t => !t.Inherits()) + .SelectMany(t => t.Constructors.OnlyPublic) + .ToFrozenSet(); + + /// Potential methods to randomize. + internal static FrozenSet PossibleMethods { get; } = + PossibleTypes + .SelectMany(t => t.GetMethods()) + .Where(m => m.GetParameters().All(p => !p.ParameterType.IsByRef)) + .Where(m => !m.ReturnType.Inherits(typeof(ValueTuple<,>))) + .Where(m => !m.IsGenericMethodDefinition) + .Where(m => !_MethodsToExclude.Contains(m.Name)) + .ToFrozenSet(); + + /// Potential properties to randomize. + internal static FrozenSet PossibleProperties { get; } = + PossibleTypes.SelectMany(t => t.GetProperties()).ToFrozenSet(); + + /// Potential fields to randomize. + internal static FrozenSet PossibleFields { get; } = + PossibleTypes + .SelectMany(t => + t.GetFields( + BindingFlags.Instance + | BindingFlags.Static + | BindingFlags.Public + | BindingFlags.NonPublic + ) + ) + .Where(f => f.IsPublic || f.IsAssembly) + .ToFrozenSet(); + + /// Potential constants to randomize. + internal static FrozenSet PossibleConstants { get; } = + PossibleTypes + .SelectMany(t => t.GetFields()) + .Where(f => f.IsLiteral && !f.IsInitOnly) + .ToFrozenSet(); + + /// Potential parameters to randomize. + internal static FrozenSet PossibleParameters { get; } = + PossibleTypes + .SelectMany(t => t.GetMethods()) + .SelectMany(m => m.GetParameters()) + .ToFrozenSet(); + + /// Supported types and the methods used to generate them. + internal static IEnumerable Handlers { get; } = + [ + new FactoryCreateHandler( + RuntimeDetails.RuntimeType, + rand => rand.Options.Gen.NextItem(PossibleTypes) + ), + new FactoryCreateHandler( + RuntimeDetails.RuntimeConstructorInfoType, + rand => rand.Options.Gen.NextItem(PossibleConstructors) + ), + new FactoryCreateHandler( + RuntimeDetails.RuntimeMethodInfoType, + rand => rand.Options.Gen.NextItem(PossibleMethods) + ), + new FactoryCreateHandler( + RuntimeDetails.RuntimePropertyInfoType, + rand => rand.Options.Gen.NextItem(PossibleProperties) + ), + new FactoryCreateHandler( + RuntimeDetails.RtFieldInfoType, + rand => rand.Options.Gen.NextItem(PossibleFields) + ), + new FactoryCreateHandler( + RuntimeDetails.MdFieldInfoType, + rand => rand.Options.Gen.NextItem(PossibleConstants) + ), + new FactoryCreateHandler( + RuntimeDetails.RuntimeParameterInfoType, + rand => rand.Options.Gen.NextItem(PossibleParameters) + ), + new FactoryCreateHandler( + RuntimeDetails.RuntimeAssemblyType, + rand => + rand.Options.Gen.NextItem( + AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic) + ) + ), + new FactoryCreateHandler(rand => rand.Create().GetName()), + ]; +} diff --git a/src/Toolbox/RandomizerTool/Handlers/SelfCreateHandlers.cs b/src/Toolbox/RandomizerTool/Handlers/SelfCreateHandlers.cs new file mode 100644 index 00000000..29cd65f6 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/SelfCreateHandlers.cs @@ -0,0 +1,194 @@ +using System.Collections.Frozen; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +internal static class SelfCreateHandlers +{ + private static readonly ObjectCreateHint _SubHint = new(); + + /// Supported types and the methods used to generate them. + internal static IEnumerable Handlers { get; } = + [ + new FactoryCreateHandler(rand => new SingleCallValueTaskSource( + rand.Create() + )), + new FactoryCreateHandler(rand => new ContentMap( + new HashSet(rand.Create>(), rand.Options.Valuer), + rand.Create() + )), + new FactoryCreateHandler(rand => (IFaked)rand.Options.Faker.Stub().Dummy), + new FactoryCreateHandler(rand => + ToolSet.CreateViaSeed(rand.Options.Gen.Next()) + ), + new FactoryCreateHandler(rand => new SeededRandom( + rand.Options.Gen.Next(7000, 8000), + false, + rand.Options.Gen.Next() + )), + new FactoryCreateHandler(rand => + rand.Options.Gen.NextItem([Limiter.Few, Limiter.Dozen, Limiter.Score]) + ), + new FactoryCreateHandler(rand => rand.Create().Asserter), + new FactoryCreateHandler(rand => rand.Create().Duplicator), + new FactoryCreateHandler(rand => rand.Create().Extractor), + new FactoryCreateHandler(rand => rand.Create().Mutator), + new FactoryCreateHandler(rand => rand.Create().Randomizer), + new FactoryCreateHandler(rand => rand.Create().Runner), + new FactoryCreateHandler(rand => rand.Create().Tester), + new FactoryCreateHandler(rand => rand.Create().Valuer), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + Seed = null, + IterationLimit = rand.Options.Gen.Next(2900, 2960), + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + DisableCatchingForThrowAsserts = false, + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + Hints = [], + NestedOptions = null, + IncludeFoundHints = false, + IncludeFrameworkHints = true, + MaxRecursionDepth = rand.Options.Gen.Next(18, 22), + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + Hints = [], + NestedOptions = null, + IncludeFoundHints = false, + IncludeFrameworkHints = true, + ExtractPrivateMembers = false, + MaxRecursionDepth = rand.Options.Gen.Next(18, 22), + IgnoredTypesForUniques = [typeof(bool), typeof(byte), typeof(char)], + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + Hints = [], + NestedOptions = null, + IncludeFoundHints = false, + FakeDefaultGenerator = null, + IncludeFrameworkHints = true, + MaxRecursionDepth = rand.Options.Gen.Next(18, 22), + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + Hints = [], + NestedOptions = null, + IncludeFoundHints = false, + IncludeFrameworkHints = true, + MaxRecursionDepth = rand.Options.Gen.Next(18, 22), + MaxAttemptsForModify = rand.Options.Gen.Next(8, 14), + MaxAttemptsForMutatingSets = rand.Options.Gen.Next(5, 9), + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + Hints = [], + NestedOptions = null, + IncludeFoundHints = false, + IncludeFrameworkHints = true, + MaxRecursionDepth = rand.Options.Gen.Next(18, 22), + CollectionMinSize = rand.Options.Gen.Next(0, 2), + CollectionMaxSize = rand.Options.Gen.Next(1, 4), + StringMinSize = rand.Options.Gen.Next(0, 3), + StringMaxSize = rand.Options.Gen.Next(2, 9), + FinalCondition = null, + CreateCollectionAttemptLimit = rand.Options.Gen.NextItem([ + Limiter.Dozen, + Limiter.Score, + ]), + StringCharacterSet = FrozenSet.ToFrozenSet( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" + ), + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + RunTimeout = rand.Options.Gen.Next(new TimeSpan(0, 0, 20), new TimeSpan(0, 0, 25)), + InjectionValues = [], + MethodsToIgnore = + [ + "Close", + "Dispose", + "Finalize", + "DisposeAsync", + "PrintMembers", + "GetObjectData", + ], + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + IgnoreObsoleteMethods = true, + InjectionValues = [], + MethodsToIgnore = + [ + "Close", + "Dispose", + "Finalize", + "DisposeAsync", + "PrintMembers", + "GetObjectData", + ], + } + ), + new FactoryCreateHandler(rand => + CreateRandomOptionsBase(rand) with + { + Hints = [], + NestedOptions = null, + IncludeFoundHints = false, + IncludeFrameworkHints = true, + MaxRecursionDepth = rand.Options.Gen.Next(18, 22), + AsyncTimeout = rand.Options.Gen.Next(new TimeSpan(0, 0, 50), new TimeSpan(0, 1, 0)), + } + ), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => _ => rand.Create()), + new FactoryCreateHandler(rand => new PlainAsyncDisposable( + rand.Create() + )), + ]; + + private static T CreateRandomOptionsBase(IRandomizerChainer randomizer) + { + return (T)_SubHint.TryToCreate(typeof(T), randomizer).Data!; + } +} diff --git a/src/Toolbox/RandomizerTool/Handlers/StringCreateHandler.cs b/src/Toolbox/RandomizerTool/Handlers/StringCreateHandler.cs new file mode 100644 index 00000000..56843f2a --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/StringCreateHandler.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +internal sealed class StringCreateHandler : ICreateHandler +{ + public Type? SupportedType => typeof(string); + + public object? CreateSupported(IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + char[] data = new char[randomizer.Options.NextStringSize()]; + for (int i = 0; i < data.Length; i++) + { + data[i] = randomizer.Options.Gen.NextItem(randomizer.Options.StringCharacterSet); + } + return new string(data); + } +} diff --git a/src/Toolbox/RandomizerTool/Handlers/SystemCreateHandlers.cs b/src/Toolbox/RandomizerTool/Handlers/SystemCreateHandlers.cs new file mode 100644 index 00000000..cb92e6a3 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/SystemCreateHandlers.cs @@ -0,0 +1,133 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Numerics; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using static System.TimeZoneInfo; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +#pragma warning disable CA1308 // Uri support for .NET 4.8 is lowercase. + +internal static class SystemCreateHandlers +{ + private static readonly ImmutableArray _PossibleCultureInfos = + [ + .. CultureInfo.GetCultures(CultureTypes.AllCultures), + ]; + + private static readonly ImmutableArray _PossibleTimeZoneInfos = + [ + .. GetSystemTimeZones(), + ]; + + private static readonly ImmutableArray _PossibleTransitionTimes = + [ + .. _PossibleTimeZoneInfos + .SelectMany(d => d.GetAdjustmentRules()) + .SelectMany(d => new[] { d.DaylightTransitionStart, d.DaylightTransitionEnd }), + ]; + + private static readonly ECCurve[] _SupportedECDsaCurves = + [ + ECCurve.NamedCurves.nistP256, + ECCurve.NamedCurves.nistP384, + ECCurve.NamedCurves.nistP521, + ]; + + /// Supported types and the methods used to generate them. + internal static IEnumerable Handlers { get; } = + [ + new FactoryCreateHandler(rand => rand.Create().Uri), + new FactoryCreateHandler(rand => new StringBuilder(rand.Create())), + new FactoryCreateHandler(rand => rand.Create().NumberFormat), + new FactoryCreateHandler(rand => rand.Options.Gen.NextItem(_SupportedECDsaCurves)), + new FactoryCreateHandler>(rand => ValueTuple.Create(rand.Create())), + new FactoryCreateHandler>(rand => + ValueTuple.Create(rand.Create()) + ), + new FactoryCreateHandler>(rand => + ValueTuple.Create(rand.Create()) + ), + new FactoryCreateHandler(rand => + rand.Options.Gen.NextItem(_PossibleTimeZoneInfos) + ), + new FactoryCreateHandler(rand => + rand.Options.Gen.NextItem(_PossibleTransitionTimes) + ), + new FactoryCreateHandler(rand => + rand.Create().MethodHandle + ), + new FactoryCreateHandler(rand => + rand.Options.Gen.NextItem(_PossibleCultureInfos) + ), + new FactoryCreateHandler(rand => + rand.Create().DateTimeFormat + ), + new FactoryCreateHandler(rand => new DateTimeOffset( + rand.Create() + )), + new FactoryCreateHandler(rand => new ValueTask( + rand.Create(), + rand.Create() + )), + new FactoryCreateHandler(rand => new UriBuilder( + rand.Create() ? "http" : "https", + rand.Create().ToLowerInvariant(), + rand.Options.Gen.Next(-1, 65535) + )), + new FactoryCreateHandler(rand => new StreamWriter( + rand.Create() + )), + new FactoryCreateHandler(rand => new StreamReader( + rand.Create() + )), + new FactoryCreateHandler(rand => + rand.Options.Gen.Next() + ? rand.Create().Token + : CancellationToken.None + ), + new FactoryCreateHandler(rand => + { + CancellationTokenSource source = new(); + if (rand.Options.Gen.Next()) + { + source.Cancel(); + } + return source; + }), + new FactoryCreateHandler(rand => + { + MemoryStream stream = new(); + + using StreamWriter writer = new(stream, Encoding.UTF8, 1024, true); + foreach (string line in rand.Create>()) + { + writer.WriteLine(line); + } + writer.Flush(); + + return stream; + }), + new FactoryCreateHandler(rand => new Vector2( + rand.Options.Gen.Next(), + rand.Options.Gen.Next() + )), + new FactoryCreateHandler(rand => new Vector3( + rand.Options.Gen.Next(), + rand.Options.Gen.Next(), + rand.Options.Gen.Next() + )), + new FactoryCreateHandler(rand => new Vector4( + rand.Options.Gen.Next(), + rand.Options.Gen.Next(), + rand.Options.Gen.Next(), + rand.Options.Gen.Next() + )), + ]; +} + +#pragma warning restore diff --git a/src/Toolbox/RandomizerTool/Handlers/ValueCreateHandlers.cs b/src/Toolbox/RandomizerTool/Handlers/ValueCreateHandlers.cs new file mode 100644 index 00000000..b1e1a01d --- /dev/null +++ b/src/Toolbox/RandomizerTool/Handlers/ValueCreateHandlers.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Handlers; + +internal static class ValueCreateHandlers +{ + internal static IEnumerable Handlers => + ValueRandom.SupportedTypes.SelectMany(t => + [ + new FactoryCreateHandler(t, rand => rand.Options.Gen.Next(t)), + new FactoryCreateHandler( + typeof(Nullable<>).MakeGenericType(t), + rand => rand.Options.Gen.Next(t) + ), + ] + ); +} diff --git a/src/Toolbox/RandomizerTool/Hints/AsyncCollectionCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/AsyncCollectionCreateHint.cs new file mode 100644 index 00000000..8854f849 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/AsyncCollectionCreateHint.cs @@ -0,0 +1,82 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing async collection instances for . +public sealed class AsyncCollectionCreateHint : CreateHint +{ + /// Method used to create collection contents. + private static readonly MethodInfo _TaskMaker = typeof(AsyncCollectionCreateHint).GetMethod( + nameof(CreateContentItem), + BindingFlags.Static | BindingFlags.NonPublic + )!; + + /// + public override int EnginePriority => (int)CreatePriority.AsyncCollectionHint; + + /// + public override IEnumerable SupportedTypes => + [ + typeof(AsyncHashSet<>), + typeof(IAsyncSet<>), + typeof(AsyncList<>), + typeof(IAsyncEnumerable<>), + ]; + + private static T CreateContentItem(IRandomizerChainer randomizer) + { + return randomizer.Create(); + } + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + Type? asGeneric = GenericConverter.AsGenericBase(type); + + if (asGeneric == typeof(AsyncHashSet<>) || asGeneric == typeof(IAsyncSet<>)) + { + Type contentType = type.GetGenericArguments().Single(); + + MethodInfo genericMaker = _TaskMaker.MakeGenericMethod(contentType); + object contentFactory() + { + return genericMaker.Invoke(null, [randomizer])!; + } + + return new( + AsyncHashSet.CreateViaGeneratorAsync( + randomizer.Options.NextCollectionSize(), + (Func)contentFactory, + (dynamic) + randomizer.Create( + typeof(IAsyncEqualityComparer<>).MakeGenericType(contentType) + ), + randomizer.Options.Design.IterationLimit, + CancellationToken.None + ) + ); + } + else if (asGeneric == typeof(AsyncList<>) || asGeneric == typeof(IAsyncEnumerable<>)) + { + Type contentType = type.GetGenericArguments().Single(); + + dynamic backingData = randomizer.Create( + typeof(List<>).MakeGenericType(contentType), + _ => randomizer.Options + ); + + return new(AsyncSeriesHelper.CreateFromAsync(backingData, int.MaxValue)); + } + else + { + return CreateHintResult.None; + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/CollectionCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/CollectionCreateHint.cs new file mode 100644 index 00000000..c3b52d9a --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/CollectionCreateHint.cs @@ -0,0 +1,215 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Collections.Immutable; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing collections for . +public sealed class CollectionCreateHint : CreateHint +{ + /// Collections able to be randomized. + private static readonly FrozenDictionary> _Collections = + new Dictionary>() + { + { typeof(List<>), (type, data) => Activator.CreateInstance(type, data)! }, + { typeof(Queue<>), (type, data) => Activator.CreateInstance(type, data)! }, + { typeof(Stack<>), (type, data) => Activator.CreateInstance(type, data)! }, + { typeof(HashSet<>), (type, data) => Activator.CreateInstance(type, data)! }, + { typeof(LinkedList<>), (type, data) => Activator.CreateInstance(type, data)! }, + { typeof(ConcurrentQueue<>), (type, data) => Activator.CreateInstance(type, data)! }, + { typeof(ConcurrentStack<>), (type, data) => Activator.CreateInstance(type, data)! }, + { typeof(FrozenSet<>), (_, data) => FrozenSet.ToFrozenSet((dynamic)data) }, + { typeof(ImmutableList<>), (_, data) => ImmutableList.CreateRange((dynamic)data) }, + { typeof(ImmutableArray<>), (_, data) => ImmutableArray.CreateRange((dynamic)data) }, + { typeof(ImmutableQueue<>), (_, data) => ImmutableQueue.CreateRange((dynamic)data) }, + { typeof(ImmutableStack<>), (_, data) => ImmutableStack.CreateRange((dynamic)data) }, + { + typeof(ConcurrentDictionary<,>), + (type, data) => Activator.CreateInstance(type, data)! + }, + { + typeof(FrozenDictionary<,>), + (_, data) => FrozenDictionary.ToFrozenDictionary((dynamic)data) + }, + { + typeof(ImmutableHashSet<>), + (_, data) => ImmutableHashSet.CreateRange((dynamic)data) + }, + { + typeof(ImmutableSortedSet<>), + (_, data) => ImmutableSortedSet.CreateRange((dynamic)data) + }, + { + typeof(ImmutableDictionary<,>), + (_, data) => ImmutableDictionary.CreateRange((dynamic)data) + }, + { + typeof(ImmutableSortedDictionary<,>), + (_, data) => ImmutableSortedDictionary.CreateRange((dynamic)data) + }, + { + typeof(Dictionary<,>), + (type, data) => + { +#if LEGACY // Constructor missing in .NET 4.8. + dynamic result = Activator.CreateInstance(type); + foreach (dynamic item in data) + { + result.Add(item.Key, item.Value); + } + return result; +#else + return Activator.CreateInstance(type, data)!; +#endif + } + }, + }.ToFrozenDictionary(); + + /// Collections that the hint can create. + internal static IEnumerable PotentialCollections { get; } = + _Collections + .Keys.SelectMany(t => TypeDescriber.For(t).InheritedTypes) + .Where(t => t.Inherits(typeof(IEnumerable<>))) + .Select(t => GenericConverter.AsGenericBase(t)!) + .Where(t => t != null) + .Distinct() + .ToFrozenSet(); + + /// + public override int EnginePriority => (int)CreatePriority.CollectionHint; + + /// + public override IEnumerable SupportedTypes => PotentialCollections; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer? randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + if (type == null) + { + return CreateHintResult.None; + } + + Type? itemType = GenericConverter + .AsConcreteType(type, typeof(IEnumerable<>)) + ?.GetGenericArguments()[0]; + + itemType ??= GenericConverter + .AsConcreteType(type, typeof(IAsyncEnumerable<>)) + ?.GetGenericArguments()[0]; + + if (itemType != null && FindMatches(type, itemType).Any()) + { + return randomizer.Options.CreateCollectionAttemptLimit.Retry( + $"Generating '{GenericConverter.ExpandName(type)}' collection.", + () => + { + IEnumerable result = (IEnumerable)Create(type, itemType, randomizer); + if ( + result.Cast().Take(randomizer.Options.CollectionMinSize).Count() + >= randomizer.Options.CollectionMinSize + ) + { + return new CreateHintResult(result); + } + else + { + throw new ToolException( + $"Failed to create an appropriately sized '{GenericConverter.ExpandName(type)}'" + + $" collection with a min size of: '{randomizer.Options.CollectionMinSize}'" + ); + } + } + ); + } + else + { + return CreateHintResult.None; + } + } + + /// Item to be contained in the collection. + /// The randomized instance. + /// + private static object Create(Type type, Type itemType, IRandomizerChainer randomizer) + { + Array internalData = CreateInternalData(itemType, randomizer); + + Type collection = randomizer.Options.Gen.NextItem(FindMatches(type, itemType)); + Type newType = MakeNewType(collection, itemType); + + if (newType == typeof(Array) || newType == internalData.GetType()) + { + return internalData; + } + else + { + return _Collections[collection].Invoke(newType, internalData); + } + } + + /// Finds potential collection matches for . + /// to find matches for. + /// Item to be contained in the collection. + /// All possible matches. + private static IEnumerable FindMatches(Type type, Type itemType) + { + Type typeAsGeneric = type.IsGenericType ? type.GetGenericTypeDefinition() : type; + + if ( + type.IsArray + || type.IsInheritedBy() + || typeAsGeneric.IsInheritedBy(typeof(IList<>)) + ) + { + yield return typeof(Array); + } + + foreach (Type match in _Collections.Keys.Where(typeAsGeneric.IsInheritedBy)) + { + if (!match.Inherits() || itemType.Inherits(typeof(KeyValuePair<,>))) + { + yield return match; + } + } + } + + /// Creates basic structures for . + /// Item to be contained in the collection. + /// Handles randomizing child values. + /// Data populated with random values. + private static Array CreateInternalData(Type itemType, IRandomizerChainer randomizer) + { + Array data = Array.CreateInstance(itemType, randomizer.Options.NextCollectionSize()); + for (int i = 0; i < data.Length; i++) + { + data.SetValue(randomizer.Create(itemType), i); + } + return data; + } + + /// Constructs the new to make for the collection. + /// Matching collection with details. + /// Item to be contained in the collection. + /// to create. + private static Type MakeNewType(Type collection, Type itemType) + { + if (!collection.IsGenericType) + { + return collection; + } + else if (collection.Inherits()) + { + return collection.MakeGenericType(itemType.GetGenericArguments()); + } + else + { + return collection.MakeGenericType(itemType); + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/ComparerCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/ComparerCreateHint.cs new file mode 100644 index 00000000..6812af6c --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/ComparerCreateHint.cs @@ -0,0 +1,58 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing comparer instances for . +public sealed class ComparerCreateHint : CreateHint +{ + /// Creator for instances. + private static readonly MethodInfo _AsyncComparerMaker = typeof(IValuer).GetMethod( + nameof(IValuer.ToAsyncComparer) + )!; + + /// Creator for instances. + private static readonly MethodInfo _ComparerMaker = typeof(IValuer).GetMethod( + nameof(IValuer.ToComparer) + )!; + + /// + public override int EnginePriority => (int)CreatePriority.ComparerHint; + + /// + public override IEnumerable SupportedTypes => + [typeof(IAsyncEqualityComparer<>), typeof(IEqualityComparer<>)]; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + Type? asGeneric = GenericConverter.AsGenericBase(type); + + if (asGeneric == typeof(IAsyncEqualityComparer<>)) + { + return new( + _AsyncComparerMaker + .MakeGenericMethod(type.GetGenericArguments().Single()) + .Invoke(randomizer.Options.Valuer, []) + ); + } + else if (asGeneric == typeof(IEqualityComparer<>)) + { + return new( + _ComparerMaker + .MakeGenericMethod(type.GetGenericArguments().Single()) + .Invoke(randomizer.Options.Valuer, []) + ); + } + else + { + return CreateHintResult.None; + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/DelegateCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/DelegateCreateHint.cs new file mode 100644 index 00000000..4adf0b7c --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/DelegateCreateHint.cs @@ -0,0 +1,860 @@ +using System.Collections.Immutable; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +#pragma warning disable S1144 // Used via reflection. + +/// Handles randomizing instances for . +public sealed class DelegateCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.DelegateHint; + + /// + public override IEnumerable SupportedTypes => + [ + typeof(Delegate), + typeof(Action), + typeof(Action<>), + typeof(Action<,>), + typeof(Action<,,>), + typeof(Action<,,,>), + typeof(Action<,,,,>), + typeof(Action<,,,,,>), + typeof(Action<,,,,,,>), + typeof(Action<,,,,,,,>), + typeof(Action<,,,,,,,,>), + typeof(Action<,,,,,,,,,>), + typeof(Action<,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,,,,>), + typeof(Func<>), + typeof(Func<,>), + typeof(Func<,,>), + typeof(Func<,,,>), + typeof(Func<,,,,>), + typeof(Func<,,,,,>), + typeof(Func<,,,,,,>), + typeof(Func<,,,,,,,>), + typeof(Func<,,,,,,,,>), + typeof(Func<,,,,,,,,,>), + typeof(Func<,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,,,,>), + ]; + + /// Methods used to match delegates. + private static readonly ImmutableArray _DelegatorMethods = + [ + .. typeof(Delegator) + .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) + .Where(m => m.Name == "AutoDelegate"), + ]; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + if (type == typeof(Delegate)) + { + return new(Create(typeof(Action), randomizer)); + } + else if (type.Inherits()) + { + return new(Create(type, randomizer)); + } + else + { + return CreateHintResult.None; + } + } + + /// The randomized instance. + /// + private static object Create(Type type, IRandomizerChainer randomizer) + { + Delegator delegator = new(randomizer); + + MethodInfo info = type.GetMethod(nameof(Action.Invoke))!; + bool hasReturn = info.ReturnType != typeof(void); + + MethodInfo match = _DelegatorMethods + .Where(m => m.GetParameters().Length == info.GetParameters().Length) + .Single(m => m.ReturnType != typeof(void) == hasReturn); + + IEnumerable generics = info.GetParameters().Select(p => p.ParameterType); + if (!match.IsGenericMethod) + { + return Delegate.CreateDelegate(type, delegator, match); + } + else if (hasReturn) + { + return Delegate.CreateDelegate( + type, + delegator, + match.MakeGenericMethod([.. generics, info.ReturnType]) + ); + } + else + { + return Delegate.CreateDelegate(type, delegator, match.MakeGenericMethod([.. generics])); + } + } + + /// Provides delegate implementations. + private sealed class Delegator + { + /// Creates random results. + private readonly IRandomizerChainer _randomizer; + + /// Sets up the randomization. + /// + internal Delegator(IRandomizerChainer randomizer) + { + _randomizer = randomizer; + } + + /// Randomizes any inputs. + /// Inputs for the delegate. + private void HandleIn(params IEnumerable inputs) + { + foreach (object? outRef in inputs) + { + if (outRef != null) + { + Type inputType = outRef.GetType(); + if (inputType.Inherits()) + { + FieldInfo valueField = inputType.GetField(nameof(OutRef<>.Var))!; + valueField.SetValue(outRef, _randomizer.Create(valueField.FieldType)); + } + } + } + } + + /// Randomizes any OutRef inputs and the return. + /// Return for the delegate. + /// Inputs for the delegate. + /// Generated output for the delegate. + private T? HandleInAndOut(params IEnumerable inputs) + { + HandleIn(inputs); + return _randomizer.Create(); + } + + /// + internal void AutoDelegate() + { + HandleIn(); + } + + /// + internal void AutoDelegate(T1? in1) + { + HandleIn(in1); + } + + /// + internal void AutoDelegate(T1? in1, T2? in2) + { + HandleIn(in1, in2); + } + + /// + internal void AutoDelegate(T1? in1, T2? in2, T3? in3) + { + HandleIn(in1, in2, in3); + } + + /// + internal void AutoDelegate(T1? in1, T2? in2, T3? in3, T4? in4) + { + HandleIn(in1, in2, in3, in4); + } + + /// + internal void AutoDelegate(T1? in1, T2? in2, T3? in3, T4? in4, T5? in5) + { + HandleIn(in1, in2, in3, in4, in5); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6, in7); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6, in7, in8); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12, + T13? in13 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13); + } + + /// + internal void AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12, + T13? in13, + T14? in14 + ) + { + HandleIn(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, in12, in13, in14); + } + + /// + internal void AutoDelegate< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15 + >( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12, + T13? in13, + T14? in14, + T15? in15 + ) + { + HandleIn( + in1, + in2, + in3, + in4, + in5, + in6, + in7, + in8, + in9, + in10, + in11, + in12, + in13, + in14, + in15 + ); + } + + /// + internal void AutoDelegate< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16 + >( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12, + T13? in13, + T14? in14, + T15? in15, + T16? in16 + ) + { + HandleIn( + in1, + in2, + in3, + in4, + in5, + in6, + in7, + in8, + in9, + in10, + in11, + in12, + in13, + in14, + in15, + in16 + ); + } + + /// + internal TOut? AutoDelegate() + { + return HandleInAndOut(); + } + + /// + internal TOut? AutoDelegate(T1 in1) + { + return HandleInAndOut(in1); + } + + /// + internal TOut? AutoDelegate(T1? in1, T2? in2) + { + return HandleInAndOut(in1, in2); + } + + /// + internal TOut? AutoDelegate(T1? in1, T2? in2, T3? in3) + { + return HandleInAndOut(in1, in2, in3); + } + + /// + internal TOut? AutoDelegate(T1? in1, T2? in2, T3? in3, T4? in4) + { + return HandleInAndOut(in1, in2, in3, in4); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5 + ) + { + return HandleInAndOut(in1, in2, in3, in4, in5); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6 + ) + { + return HandleInAndOut(in1, in2, in3, in4, in5, in6); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7 + ) + { + return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8 + ) + { + return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9 + ) + { + return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10 + ) + { + return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11 + ) + { + return HandleInAndOut(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12 + ) + { + return HandleInAndOut( + in1, + in2, + in3, + in4, + in5, + in6, + in7, + in8, + in9, + in10, + in11, + in12 + ); + } + + /// + internal TOut? AutoDelegate( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12, + T13? in13 + ) + { + return HandleInAndOut( + in1, + in2, + in3, + in4, + in5, + in6, + in7, + in8, + in9, + in10, + in11, + in12, + in13 + ); + } + + /// + internal TOut? AutoDelegate< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + TOut + >( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12, + T13? in13, + T14? in14 + ) + { + return HandleInAndOut( + in1, + in2, + in3, + in4, + in5, + in6, + in7, + in8, + in9, + in10, + in11, + in12, + in13, + in14 + ); + } + + /// + internal TOut? AutoDelegate< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + TOut + >( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12, + T13? in13, + T14? in14, + T15? in15 + ) + { + return HandleInAndOut( + in1, + in2, + in3, + in4, + in5, + in6, + in7, + in8, + in9, + in10, + in11, + in12, + in13, + in14, + in15 + ); + } + + /// Matches to delegate with same number of inputs and output. + /// Type for parameter 1. + /// Type for parameter 2. + /// Type for parameter 3. + /// Type for parameter 4. + /// Type for parameter 5. + /// Type for parameter 6. + /// Type for parameter 7. + /// Type for parameter 8. + /// Type for parameter 9. + /// Type for parameter 10. + /// Type for parameter 11. + /// Type for parameter 12. + /// Type for parameter 13. + /// Type for parameter 14. + /// Type for parameter 15. + /// Type for parameter 16. + /// Type for the return value. + /// Matches input parameter 1. + /// Matches input parameter 2. + /// Matches input parameter 3. + /// Matches input parameter 4. + /// Matches input parameter 5. + /// Matches input parameter 6. + /// Matches input parameter 7. + /// Matches input parameter 8. + /// Matches input parameter 9. + /// Matches input parameter 10. + /// Matches input parameter 11. + /// Matches input parameter 12. + /// Matches input parameter 13. + /// Matches input parameter 14. + /// Matches input parameter 15. + /// Matches input parameter 16. + /// Nothing if ; otherwise random data. + internal TOut? AutoDelegate< + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + TOut + >( + T1? in1, + T2? in2, + T3? in3, + T4? in4, + T5? in5, + T6? in6, + T7? in7, + T8? in8, + T9? in9, + T10? in10, + T11? in11, + T12? in12, + T13? in13, + T14? in14, + T15? in15, + T16? in16 + ) + { + return HandleInAndOut( + in1, + in2, + in3, + in4, + in5, + in6, + in7, + in8, + in9, + in10, + in11, + in12, + in13, + in14, + in15, + in16 + ); + } + } +} + +#pragma warning restore diff --git a/src/Toolbox/RandomizerTool/Hints/EnumCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/EnumCreateHint.cs new file mode 100644 index 00000000..a2a5901d --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/EnumCreateHint.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing Enum values for . +public sealed class EnumCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.EnumHint; + + /// + public override IEnumerable SupportedTypes => []; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + if (type?.IsEnum ?? false) + { + return new(randomizer.Options.Gen.NextItem(Enum.GetValues(type).Cast())); + } + else + { + return CreateHintResult.None; + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/FakeCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/FakeCreateHint.cs new file mode 100644 index 00000000..c819148d --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/FakeCreateHint.cs @@ -0,0 +1,89 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing instances for . +public sealed class FakeCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.FakeHint; + + /// + public override IEnumerable SupportedTypes => []; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + if (type.Inherits(typeof(Fake<>))) + { + return new(Create(type, randomizer)); + } + else + { + return CreateHintResult.None; + } + } + + /// The randomized instance. + /// + private static Fake Create(Type type, IRandomizerChainer randomizer) + { + Type target = type.GetGenericArguments().Single(); + + Lock resultLock = new(); + Dictionary, Behavior> resultCache = + [ + with(randomizer.Options.Valuer.WithOptions(opt => opt with { SkipAsyncValues = true })), + ]; + DataRandom smartData = randomizer.Options.Gen.NextData(); + + Fake mock = randomizer.Options.Faker.Stub( + target, + [], + opt => + opt with + { + FakeDefaultGenerator = (method, callData) => + { + ArgumentGuard.ThrowIfNull(method); + + if (method.ReturnType == typeof(void)) + { + return Behavior.None(); + } + + Tuple key = Tuple.Create(method, callData); + lock (resultLock) + { + if (!resultCache.TryGetValue(key, out Behavior? behavior)) + { + if (method.ReturnType.IsInheritedBy()) + { + behavior = Behavior.Returns( + smartData.Find(method.Name) ?? randomizer.Create() + ); + } + else + { + behavior = Behavior.Returns( + randomizer.Create(method.ReturnType) + ); + } + resultCache.Add(key, behavior); + } + return behavior; + } + }, + } + ); + + return (Fake)type.GetConstructor([typeof(Fake)])!.Invoke([mock]); + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/GenericCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/GenericCreateHint.cs new file mode 100644 index 00000000..783328f2 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/GenericCreateHint.cs @@ -0,0 +1,56 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing generic types for . +public sealed class GenericCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.GenericHint; + + /// + public override IEnumerable SupportedTypes => []; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + if (type?.IsGenericTypeDefinition ?? false) + { + int i = 0; + foreach (Type defined in GenericResolver.CreateConcreteGenerics(type, randomizer)) + { + ArgumentGuard.ThrowUponIterationLimit( + i++, + randomizer.Options.Design.IterationLimit + ); + try + { + return new( + randomizer.CreateSpecific(defined, type, opt => + opt with + { + RequireRandomizedContents = false, + } + ) + ); + } + catch (CreateAndFakeException) + { + // Try next type. + } + } + throw new UnsupportedException( + $"Could not create generic '{GenericConverter.ExpandName(type)}'." + ); + } + else + { + return CreateHintResult.None; + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/HandlerCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/HandlerCreateHint.cs new file mode 100644 index 00000000..5af97237 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/HandlerCreateHint.cs @@ -0,0 +1,52 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing supported types for . +public sealed class HandlerCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.HandlerHint; + + /// Supported types and the methods used to generate them. + private static readonly ICreateHandler[] _Creators = + [ + new StringCreateHandler(), + new ConfigurationSectionCreateHandler(), + ]; + + internal static readonly IDictionary _CreatorsByType = + TypeSupporter.GroupByInheritance( + _Creators + .Concat(SelfCreateHandlers.Handlers) + .Concat(ValueCreateHandlers.Handlers) + .Concat(SystemCreateHandlers.Handlers) + .Concat(ExceptionCreateHandlers.Handlers) + .Concat(ReflectionCreateHandlers.Handlers), + typeof(IEnumerable), + typeof(IEnumerable<>), + typeof(IEnumerable) + ); + + /// + public override IEnumerable SupportedTypes => _CreatorsByType.Keys; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + if (type != null && _CreatorsByType.TryGetValue(type, out ICreateHandler[]? creators)) + { + return new(randomizer.Options.Gen.NextItem(creators).CreateSupported(randomizer)); + } + else + { + return CreateHintResult.None; + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/InjectedCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/InjectedCreateHint.cs new file mode 100644 index 00000000..be271131 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/InjectedCreateHint.cs @@ -0,0 +1,86 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing injected dummies for . +public sealed class InjectedCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.InjectedHint; + + /// + public override IEnumerable SupportedTypes => []; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + if (type.Inherits(typeof(Injected<>))) + { + return new(Create(type, randomizer)); + } + else + { + return CreateHintResult.None; + } + } + + /// The randomized instance. + /// + private static object Create(Type type, IRandomizerChainer randomizer) + { + Type target = type.GetGenericArguments().Single(); + + ConstructorInfo? maker = + FindConstructor(target, randomizer, BindingFlags.Public) + ?? FindConstructor(target, randomizer, BindingFlags.NonPublic); + + if (maker != null) + { + ParameterInfo[] info = maker.GetParameters(); + object?[] args = new object[info.Length]; + for (int i = 0; i < args.Length; i++) + { + args[i] = randomizer.Options.Faker.Supports(info[i].ParameterType) + ? randomizer.Create(typeof(Fake<>).MakeGenericType(info[i].ParameterType)) + : randomizer.Create(info[i].ParameterType); + } + + return type.GetConstructor([target, typeof(IEnumerable)])! + .Invoke([ + maker.Invoke([.. args.Select(v => (v is Fake fake) ? fake.Dummy : v)]), + args.OfType(), + ]); + } + else + { + throw new InvalidOperationException($"No constructors found on type '{target}'."); + } + } + + /// Finds the constructor with the most class references then by fewest parameters. + /// to find a constructor for. + /// Handles randomizing child values. + /// Scope of constructors to find. + /// Constructor if found, otherwise. + private static ConstructorInfo? FindConstructor( + Type target, + IRandomizerChainer randomizer, + BindingFlags scope + ) + { + return target + .GetConstructors(BindingFlags.Instance | scope) + .GroupBy(c => + c.GetParameters().Count(p => randomizer.Options.Faker.Supports(p.ParameterType)) + ) + .OrderByDescending(g => g.Key) + .FirstOrDefault() + ?.OrderBy(c => c.GetParameters().Length) + .FirstOrDefault(); + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/LegacyCollectionCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/LegacyCollectionCreateHint.cs new file mode 100644 index 00000000..258b9d1e --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/LegacyCollectionCreateHint.cs @@ -0,0 +1,118 @@ +using System.Collections; +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Collections.Specialized; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +#pragma warning disable IDE0058 // Return isn't present on all versions. +#pragma warning disable RCS1124 // Creates the wrong type. + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing legacy collections for . +public sealed class LegacyCollectionCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.LegacyCollectionHint; + + /// Supported types and the methods used to generate them. + private static readonly ImmutableArray<( + Type, + Func + )> _Creators = + [ + (typeof(Hashtable), CreateDict), + (typeof(SortedList), CreateDict), + (typeof(ListDictionary), CreateDict), + (typeof(HybridDictionary), CreateDict), + (typeof(StringDictionary), CreateDict), + (typeof(OrderedDictionary), CreateDict), + (typeof(NameValueCollection), CreateDict), + (typeof(Array), (data, _) => data), + (typeof(Stack), (data, _) => new Stack(data)), + (typeof(Queue), (data, _) => new Queue(data)), + (typeof(ArrayList), (data, _) => new ArrayList(data)), + ( + typeof(BitArray), + (data, gen) => new BitArray(data.Select(_ => gen.Create()).ToArray()) + ), + ( + typeof(StringCollection), + (data, _) => + { + StringCollection result = [.. data]; + return result; + } + ), + ]; + + /// Collections that the hint will create. + internal static IEnumerable PotentialCollections { get; } = + _Creators.Select(i => i.Item1).ToFrozenSet(); + + /// + public override IEnumerable SupportedTypes => PotentialCollections; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer? randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + if (type.Inherits() && FindMatches(type).Any()) + { + int size = randomizer.Options.NextCollectionSize(); + + return new( + randomizer + .Options.Gen.NextItem(FindMatches(type)) + .Item2.Invoke(CreateInternalData(size, randomizer), randomizer) + ); + } + else + { + return CreateHintResult.None; + } + } + + /// Finds potential collection matches for . + /// to find matches for. + /// All possible matches. + private static IEnumerable<(Type, Func)> FindMatches( + Type type + ) + { + return _Creators.Where(m => type.IsInheritedBy(m.Item1)); + } + + /// Creates the and populates it with data. + /// to create. + /// Keys to create in the . + /// Handles randomizing child values. + /// The created instance. + private static TDict CreateDict(string[] keys, IRandomizerChainer gen) + { + dynamic data = Activator.CreateInstance()!; + for (int i = 0; i < keys.Length; i++) + { + data.Add(keys[i], gen.Create()); + } + return data; + } + + /// Creates populated collection of data to use. + /// Number of items to generate. + /// Handles randomizing child values. + /// Data populated with random values. + private static string[] CreateInternalData(int size, IRandomizerChainer randomizer) + { + string[] data = new string[size]; + for (int i = 0; i < data.Length; i++) + { + data.SetValue(randomizer.Create(), i); + } + return data; + } +} + +#pragma warning restore diff --git a/src/Toolbox/RandomizerTool/Hints/NullableCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/NullableCreateHint.cs new file mode 100644 index 00000000..366a8894 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/NullableCreateHint.cs @@ -0,0 +1,47 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing async collection instances for . +public sealed class NullableCreateHint : CreateHint +{ + /// Method used to create a . + /// Dynamic can't be used due to creating the wrong type with subclasses. + private static readonly MethodInfo _NullableMaker = typeof(NullableCreateHint).GetMethod( + nameof(MakeNullableResult), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + /// + public override int EnginePriority => (int)CreatePriority.NullableHint; + + /// + public override IEnumerable SupportedTypes => [typeof(Nullable<>)]; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + Type? asGeneric = GenericConverter.AsGenericBase(type); + if (asGeneric == typeof(Nullable<>)) + { + Type contentType = type.GetGenericArguments().Single(); + object content = randomizer.Create(contentType); + return new(_NullableMaker.MakeGenericMethod(contentType).Invoke(null, [content])); + } + else + { + return CreateHintResult.None; + } + } + + private static T? MakeNullableResult(T item) + where T : struct + { + return new T?(item); + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/ObjectCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/ObjectCreateHint.cs new file mode 100644 index 00000000..d55c00e9 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/ObjectCreateHint.cs @@ -0,0 +1,239 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing objects in general for . +public sealed class ObjectCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.ObjectHint; + + /// + public override IEnumerable SupportedTypes => [typeof(object)]; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + object? result = + (type == null) + ? null + : randomizer.Options.CreateObjectAttemptLimit.Attempt( + $"Create object of type '{GenericConverter.ExpandName(type)}'", + () => Create(type, randomizer) + ); + + return result != null ? new(result) : CreateHintResult.None; + } + + /// The randomized instance. + /// + private static object? Create(Type type, IRandomizerChainer randomizer) + { + DataRandom smartData = randomizer.Options.Gen.NextData(); + object? data = CreateNew(type, randomizer, smartData); + if (data is null or IFaked or Exception) + { + return data; + } + + bool changed = Populate(data, smartData, randomizer); + if (changed || !randomizer.Options.RequireRandomizedContents) + { + return data; + } + else + { + Disposer.Cleanup(data); + throw new UnsupportedException( + $"Could not randomize content for '{GenericConverter.ExpandName(data)}'." + ); + } + } + + /// Sets member data for a newly created instance. + /// Instance to populate. + /// Smart data currently being utilized. + /// Handles randomizing child values. + /// if member data existed and was changed, otherwise. + private static bool Populate(object data, DataRandom smartData, IRandomizerChainer randomizer) + { + bool canChange = false; + bool changed = false; + Type dataType = data.GetType(); + + foreach (FieldInfo field in TypeDescriber.For(dataType).Fields.Writable) + { + canChange = true; + + string? smartValue = + (field.FieldType == typeof(string)) ? smartData.Find(field.Name) : null; + field.SetValue(data, smartValue ?? randomizer.CreateInternal(field.FieldType, data)); + + changed = true; + } + foreach (PropertyInfo property in TypeDescriber.For(dataType).Properties.Settable) + { + canChange = true; + + string? smartValue = + (property.PropertyType == typeof(string)) ? smartData.Find(property.Name) : null; + + object newValue = smartValue ?? randomizer.CreateInternal(property.PropertyType, data); + + try + { + property.SetValue(data, newValue); + changed = true; + } + catch (Exception) + { + // Could not set. + } + } + return canChange == changed; + } + + /// Creates a new instance of . + /// to generate. + /// Handles randomizing child values. + /// Predefined random data. + /// The created instance. + private static object? CreateNew(Type type, IRandomizerChainer randomizer, DataRandom smartData) + { + /* + * Order of preference: + * 1) Default constructor. + * 2) Visible constructors. + * 3) Visible factories. + * 4) Stub. + */ + + ConstructorInfo? defaultConstructor = type.GetConstructor(Type.EmptyTypes); + if (type == typeof(object)) + { + return randomizer.Options.Faker.Stub().Dummy; + } + else if (defaultConstructor != null) + { + return defaultConstructor.Invoke(null); + } + else if (FindConstructors(type, randomizer).Any()) + { + return CreateFrom( + randomizer, + smartData, + (c, d) => c.Invoke(d), + FindConstructors(type, randomizer) + ); + } + else if (FindFactories(type, randomizer).Any()) + { + return CreateFrom( + randomizer, + smartData, + (c, d) => c.Invoke(null, d)!, + FindFactories(type, randomizer) + ); + } + else if (randomizer.Options.Faker.Supports(type)) + { + return ((Fake)randomizer.Create(typeof(Fake<>).MakeGenericType(type))).Dummy; + } + else + { + return null; + } + } + + /// Creates a instance. + /// Creation method . + /// Handles randomizing child values. + /// Predefined random data. + /// How to create the from the creation method. + /// Possible creation methods. + /// The created instance. + private static object CreateFrom( + IRandomizerChainer randomizer, + DataRandom smartData, + Func invoker, + IEnumerable creators + ) + where T : MethodBase + { + T creator = randomizer.Options.Gen.NextItem(creators); + + if (creator is MethodInfo method && method.IsGenericMethodDefinition) + { + creator = (T)(object)GenericResolver.OfConcrete(method, randomizer); + } + + return invoker.Invoke( + creator, + [ + .. creator + .GetParameters() + .Select(p => + { + string? smartValue = + (p.ParameterType == typeof(string)) ? smartData.Find(p.Name) : null; + return smartValue ?? randomizer.Create(p.ParameterType); + }), + ] + ); + } + + /// Finds or constructors. + /// to search for. + /// Handles randomizing child values. + /// Found constructors. + private static IEnumerable FindConstructors( + Type type, + IRandomizerChainer randomizer + ) + { + return TypeDescriber + .For(type) + .Constructors.Visible.Where(c => + c.GetParameters().All(p => !randomizer.AlreadyCreated(p.ParameterType)) + ); + } + + /// Finds static methods that create . + /// to search for. + /// Handles randomizing child values. + /// Found factory methods. + private static IEnumerable FindFactories(Type type, IRandomizerChainer randomizer) + { + MethodInfo[] factories = + [ + .. TypeDescriber + .For(type) + .Factories.Visible.Where(c => + c.GetParameters().All(p => !randomizer.AlreadyCreated(p.ParameterType)) + ), + ]; + + IEnumerable nonGenericFactories = + [ + .. factories.Where(m => !m.ContainsGenericParameters), + ]; + if (nonGenericFactories.Any()) + { + return nonGenericFactories; + } + else + { + return factories; + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/SpanCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/SpanCreateHint.cs new file mode 100644 index 00000000..9039650b --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/SpanCreateHint.cs @@ -0,0 +1,34 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing Span collections for . +public sealed class SpanCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.SpanHint; + + /// + public override IEnumerable SupportedTypes => [typeof(Span<>), typeof(ReadOnlySpan<>)]; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + Type? asGeneric = GenericConverter.AsGenericBase(type); + if (asGeneric == typeof(Span<>) || asGeneric == typeof(ReadOnlySpan<>)) + { + Type content = type.GetGenericArguments().Single(); + Type arrayType = Array.CreateInstance(content, 0).GetType(); + + return new(randomizer.Create(arrayType)); + } + else + { + return CreateHintResult.None; + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/SubclassCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/SubclassCreateHint.cs new file mode 100644 index 00000000..6718fa11 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/SubclassCreateHint.cs @@ -0,0 +1,68 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing objects in general for . +public sealed class SubclassCreateHint : CreateHint +{ + /// + public override int EnginePriority => (int)CreatePriority.SubclassHint; + + /// + public override IEnumerable SupportedTypes => []; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + if (randomizer.AlreadyCreated(type)) + { + return CreateHintResult.None; + } + + TypeDescriber inheritance = TypeDescriber.For(type); + + HashSet foundAlready = []; + List subclasses = + [ + .. randomizer + .Options.Gen.NextSequence( + randomizer.Options.PreferLocalSubclasses + ? inheritance.FindLocalSubclasses() + : [] + ) + .Concat(randomizer.Options.Gen.NextSequence(inheritance.FindLoadedSubclasses())) + .Where(t => !t.IsAbstract) + .Where(foundAlready.Add) + .Where(t => !randomizer.AlreadyCreated(t)), + ]; + + if (subclasses.Count == 1 && subclasses[0] == type) + { + return CreateHintResult.None; + } + + foreach (Type subclass in subclasses) + { + try + { + return new( + randomizer.CreateSpecific(subclass, type, opt => + opt with + { + RequireRandomizedContents = false, + } + ) + ); + } + catch (Exception) + { + // Try next type. + } + } + + return CreateHintResult.None; + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/TaskCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/TaskCreateHint.cs new file mode 100644 index 00000000..f35735d4 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/TaskCreateHint.cs @@ -0,0 +1,49 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing instances for . +public sealed class TaskCreateHint : CreateHint +{ + /// Method used to create completed tasks. + /// Dynamic can't be used due to creating the wrong type with subclasses. + private static readonly MethodInfo _TaskMaker = typeof(Task).GetMethod( + nameof(Task.FromResult) + )!; + + /// + public override int EnginePriority => (int)CreatePriority.TaskHint; + + /// + public override IEnumerable SupportedTypes => + [typeof(Task), typeof(Task<>), typeof(TaskCompletionSource<>)]; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + Type? asGeneric = GenericConverter.AsGenericBase(type); + + if (asGeneric == typeof(Task<>) || asGeneric == typeof(TaskCompletionSource<>)) + { + Type contentType = type.GetGenericArguments().Single(); + return new( + _TaskMaker + .MakeGenericMethod(contentType) + .Invoke(null, [randomizer.Create(contentType)]) + ); + } + else if (type == typeof(Task)) + { + return new(Task.FromResult(randomizer.Create())); + } + else + { + return CreateHintResult.None; + } + } +} diff --git a/src/Toolbox/RandomizerTool/Hints/ValueTaskCreateHint.cs b/src/Toolbox/RandomizerTool/Hints/ValueTaskCreateHint.cs new file mode 100644 index 00000000..045dd4d4 --- /dev/null +++ b/src/Toolbox/RandomizerTool/Hints/ValueTaskCreateHint.cs @@ -0,0 +1,74 @@ +using System.Reflection; +using System.Threading.Tasks.Sources; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool.Hints; + +/// Handles randomizing instances for . +public sealed class ValueTaskCreateHint : CreateHint +{ + /// Method used to create a completed . + /// Dynamic can't be used due to creating the wrong type with subclasses. + private static readonly MethodInfo _ValueSourceMaker = typeof(ValueTaskCreateHint).GetMethod( + nameof(CreateSource), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + /// Method used to create a completed . + /// Dynamic can't be used due to creating the wrong type with subclasses. + private static readonly MethodInfo _ValueTaskMaker = typeof(ValueTaskCreateHint).GetMethod( + nameof(CreateValueTaskAsync), + BindingFlags.NonPublic | BindingFlags.Static + )!; + + /// + public override int EnginePriority => (int)CreatePriority.TaskHint; + + /// + public override IEnumerable SupportedTypes => + [typeof(ValueTask<>), typeof(IValueTaskSource<>), typeof(SingleCallValueTaskSource<>)]; + + /// + public override CreateHintResult TryToCreate(Type type, IRandomizerChainer randomizer) + { + ArgumentGuard.ThrowIfNull(randomizer); + + Type? asGeneric = GenericConverter.AsGenericBase(type); + + if ( + asGeneric == typeof(SingleCallValueTaskSource<>) + || asGeneric == typeof(IValueTaskSource<>) + ) + { + Type contentType = type.GetGenericArguments().Single(); + object content = randomizer.Create(contentType); + return new(_ValueSourceMaker.MakeGenericMethod(contentType).Invoke(null, [content])); + } + else if (asGeneric == typeof(ValueTask<>)) + { + Type contentType = type.GetGenericArguments().Single(); + return new( + _ValueTaskMaker + .MakeGenericMethod(contentType) + .Invoke(null, [randomizer.Create(contentType), randomizer]) + ); + } + else + { + return CreateHintResult.None; + } + } + + private static ValueTask CreateValueTaskAsync(T content, IRandomizerChainer randomizer) + { + return new ValueTask(CreateSource(content), randomizer.Create()); + } + + private static SingleCallValueTaskSource CreateSource(T content) + { + return new SingleCallValueTaskSource(content); + } +} diff --git a/src/Toolbox/RandomizerTool/IRandomizer.cs b/src/Toolbox/RandomizerTool/IRandomizer.cs new file mode 100644 index 00000000..d679be52 --- /dev/null +++ b/src/Toolbox/RandomizerTool/IRandomizer.cs @@ -0,0 +1,95 @@ +global using RandomizerMod = System.Func< + Werecodent.CreateAndFake.RandomizerTool.RandomizerOptions, + Werecodent.CreateAndFake.RandomizerTool.RandomizerOptions +>; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool; + +/// Tool to create s populated with random values. +/// Useful for generating data to test with. +public interface IRandomizer : IHintTool +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + IRandomizer WithOptions(RandomizerMod optionConfiguration); + + /// Creates a randomized instance. + /// to create. + /// The created instance. + /// + T Create(RandomizerMod? optionConfiguration = null); + + /// Creates a randomized instance of the . + /// to create. + /// Modifications of this tool's options to apply for this call. + /// The created instance. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + object Create(Type type, RandomizerMod? optionConfiguration = null); + + /// + /// Creates a randomized instance restricted to the given . + /// + /// + /// + T CreateSized(int size, RandomizerMod? optionConfiguration = null); + + /// + /// Creates a randomized instance of the + /// restricted to the given . + /// + /// Specific size to require of the top level collection. + /// + /// The given does not effect the size of created nested collections. + /// + /// + object CreateSized(int size, Type type, RandomizerMod? optionConfiguration = null); + + /// + /// Creates a instance using or random data as needed. + /// + /// to create. + /// The created instance. + /// + T Inject(IEnumerable? values, RandomizerMod? optionConfiguration = null); + + /// Creates an instance using or random data as needed. + /// to create. + /// Values to inject into the instance. + /// Modifications of this tool's options to apply for this call. + /// The created instance. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + object Inject( + Type type, + IEnumerable? values, + RandomizerMod? optionConfiguration = null + ); +} diff --git a/src/Toolbox/RandomizerTool/Randomizer.cs b/src/Toolbox/RandomizerTool/Randomizer.cs new file mode 100644 index 00000000..ffbedf7d --- /dev/null +++ b/src/Toolbox/RandomizerTool/Randomizer.cs @@ -0,0 +1,160 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.RandomizerTool; + +/// +/// +/// If given a parameter. +public sealed class Randomizer(RandomizerOptions options) : IRandomizer +{ + /// Handles hint based randomization. + private static readonly RandomizerEngine _Engine = new(); + + /// + public RandomizerOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public IEnumerable SupportedTypes => _Engine.SupportedTypes; + + /// + public T Create(RandomizerMod? optionConfiguration = null) + { + return (T)Create(typeof(T), optionConfiguration); + } + + /// + public object Create(Type type, RandomizerMod? optionConfiguration = null) + { + ArgumentGuard.ThrowIfNull(type); + + RandomizerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + try + { + return localOptions + .FinalConditionAttemptLimit.StallUntil( + $"Trying to create instance of '{GenericConverter.ExpandName(type)}'", + () => + { + return new RandomizerChainer(Options, _Engine).Create( + type, + (optionConfiguration != null) ? _ => localOptions : null + ); + }, + result => + { + if (localOptions.FinalCondition?.Invoke(result) ?? true) + { + return true; + } + else + { + Disposer.Cleanup(result); + return false; + } + } + ) + .Last(); + } + catch (Exception e) + { + throw WrapCreateError(type, e); + } + } + + /// + public T CreateSized(int size, RandomizerMod? optionConfiguration = null) + { + return (T)CreateSized(size, typeof(T), optionConfiguration); + } + + /// + public object CreateSized(int size, Type type, RandomizerMod? optionConfiguration = null) + { + ArgumentGuard.ThrowUponIterationLimit(size, Options.Design.IterationLimit); + + RandomizerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + return Create(type, _ => + localOptions with + { + CollectionMinSize = size, + CollectionMaxSize = size, + StringMinSize = size, + StringMaxSize = size, + NestedOptions = localOptions, + } + ); + } + + /// + public T Inject(IEnumerable? values, RandomizerMod? optionConfiguration = null) + { + try + { + return new RandomizerChainer(Options, _Engine).Inject(values, optionConfiguration); + } + catch (Exception e) + { + throw WrapCreateError(typeof(T), e); + } + } + + /// + public object Inject( + Type type, + IEnumerable? values, + RandomizerMod? optionConfiguration = null + ) + { + ArgumentGuard.ThrowIfNull(type); + try + { + return new RandomizerChainer(Options, _Engine).Inject( + type, + values, + optionConfiguration + ); + } + catch (Exception e) + { + throw WrapCreateError(type, e); + } + } + + /// + public IRandomizer WithOptions(RandomizerMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Randomizer(optionConfiguration.Invoke(Options)); + } + + /// Adds details to encountered exceptions during randomization. + /// Type attempted to be created. + /// Encountered exception. + /// Exception to throw. + private static ToolException WrapCreateError(Type type, Exception e) + { + string message; + if (e is InsufficientExecutionStackException) + { + message = + $"Ran into infinite generation trying to randomize type '{GenericConverter.ExpandName(type)}'."; + } + else if (e is TimeoutException) + { + message = + $"Could not create instance of type '{GenericConverter.ExpandName(type)}' matching condition."; + } + else + { + message = + $"Encountered issue creating instance of type '{GenericConverter.ExpandName(type)}'."; + } + return new ToolException(message, e); + } +} diff --git a/src/Toolbox/RandomizerTool/RandomizerOptions.cs b/src/Toolbox/RandomizerTool/RandomizerOptions.cs new file mode 100644 index 00000000..925ac083 --- /dev/null +++ b/src/Toolbox/RandomizerTool/RandomizerOptions.cs @@ -0,0 +1,161 @@ +using System.Collections.Frozen; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.RandomizerTool; + +/// Configuration for manipulating behavior. +public sealed record RandomizerOptions : ToolHintOptions +{ + /// Identifies the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Randomizer); + + /// + public required IValuer Valuer { get; init; } + + /// + public required IFaker Faker { get; init; } + + /// Flag to prioritize creating subclasses from the originating assembly. + /// + /// All loaded assemblies are prioritized equally if set to . Does not prevent using any + /// loaded subclass if there are no subclasses from the originating assembly that can be created successfully. + /// + /// + [ConfigurableOption] + public bool PreferLocalSubclasses { get; init; } = true; + + /// Limits attempts at creating s. + /// + /// Attempts fail upon encountering any issue creating a , such as not being + /// able to randomize an instance's contents when is set. + /// + /// Limiter.Few + [ConfigurableOption] + public Limiter CreateObjectAttemptLimit { get; init; } = Limiter.Few; + + /// Limits attempts at creating collections. + /// Attempts fail generally from failing size requirements due to hash collisions. + /// Limiter.Score + [ConfigurableOption] + public Limiter CreateCollectionAttemptLimit { get; init; } = Limiter.Score; + + /// Inclusive minimum size for randomized collections. + /// + /// Swaps with if greater than it in . + /// + /// 1 + [ConfigurableOption] + public int CollectionMinSize { get; init; } = 1; + + /// Inclusive maximum size for randomized collections. + /// + /// Swaps with if less than it in . + /// + /// 3 + [ConfigurableOption] + public int CollectionMaxSize { get; init; } = 3; + + /// Inclusive minimum size for randomized s. + /// Swaps with if greater than it in . + /// 7 + [ConfigurableOption] + public int StringMinSize { get; init; } = 7; + + /// Inclusive maximum size for randomized s. + /// Swaps with if less than it in . + /// 12 + [ConfigurableOption] + public int StringMaxSize { get; init; } = 12; + + /// Characters to use in randomized s. + /// Does not affect randomized s. + /// [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890] + [ConfigurableOption] + public FrozenSet StringCharacterSet { get; init; } = + FrozenSet.ToFrozenSet("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"); + + /// If contents must also be randomized for randomization to be successful. + /// + /// Used to ensure randomized instances have variance with other instances of the same + /// when that is mutable. Fails if not achieved within + /// the limit set by . Automatically disabled when creating + /// the specific provides randomization itself (such as picking a subclass). + /// + /// + [ConfigurableOption] + public bool RequireRandomizedContents { get; init; } = true; + + /// Limits attempts at matching . + /// Only useful when is set. + /// Limiter.Dozen + [ConfigurableOption] + public Limiter FinalConditionAttemptLimit { get; init; } = Limiter.Dozen; + + /// Optional condition that randomized instances must match before being returned. + /// Fails if not achieved within the limit set by . + /// + public Func? FinalCondition { get; init; } = null; + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal RandomizerOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + CreateCollectionAttemptLimit = Config.GetValue(section, CreateCollectionAttemptLimit), + FinalConditionAttemptLimit = Config.GetValue(section, FinalConditionAttemptLimit), + RequireRandomizedContents = Config.GetValue(section, RequireRandomizedContents), + CreateObjectAttemptLimit = Config.GetValue(section, CreateObjectAttemptLimit), + IncludeFrameworkHints = Config.GetValue(section, IncludeFrameworkHints), + PreferLocalSubclasses = Config.GetValue(section, PreferLocalSubclasses), + StringCharacterSet = Config.GetChars(section, StringCharacterSet), + CollectionMinSize = Config.GetValue(section, CollectionMinSize), + CollectionMaxSize = Config.GetValue(section, CollectionMaxSize), + IncludeFoundHints = Config.GetValue(section, IncludeFoundHints), + MaxRecursionDepth = Config.GetValue(section, MaxRecursionDepth), + StringMinSize = Config.GetValue(section, StringMinSize), + StringMaxSize = Config.GetValue(section, StringMaxSize), + }; + } + + /// + /// + /// + public int NextCollectionSize() + { + return NextSize(CollectionMinSize, CollectionMaxSize); + } + + /// + /// + /// + public int NextStringSize() + { + return NextSize(StringMinSize, StringMaxSize); + } + + /// Generates a random length within configured bounds. + /// Inclusive minimum size. + /// Inclusive maximum size. + /// The next size to use. + private int NextSize(int setMin, int setMax) + { + ArgumentGuard.ThrowIfNull(Gen); + + return Math.Max(0, (setMax < setMin) ? Gen.Next(setMax, setMin) : Gen.Next(setMin, setMax)); + } +} diff --git a/src/Toolbox/RunnerTool/Attributes/BaseCapAttribute.cs b/src/Toolbox/RunnerTool/Attributes/BaseCapAttribute.cs new file mode 100644 index 00000000..054f372e --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/BaseCapAttribute.cs @@ -0,0 +1,98 @@ +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Randomization; + +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +/// Flag to create the attached value within a range. +/// +/// 0 is the presumed minimum when not specified. +/// Value must be specifically supported by . +/// +[ExcludeFromCreateAndFake] +public abstract class BaseCapAttribute : ParameterHintAttribute, ICloneable +{ + /// If has been set with a value to use. + protected bool IsMinSet { get; } + + /// Lower boundary for the generated value. + public object Min { get; } + + /// Upper boundary for the generated value. + public object Max { get; } + + /// + /// Flag to create the attached value specifically between and . + /// + /// (Inclusive) + /// (Inclusive) + /// + protected BaseCapAttribute(object min, object max) + { + IsMinSet = true; + Min = min; + Max = max; + } + + /// Flag to create the attached value specifically below . + /// (Exclusive) + /// + protected BaseCapAttribute(object max) + { + IsMinSet = false; + Min = 0; + Max = max; + } + + /// + protected internal override object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ) + { + ArgumentGuard.ThrowIfNull(param, method, args, localOptions); + + if (localOptions.Gen.Supports(param.ParameterType)) + { + Type minType = Min.GetType(); + Type maxType = Max.GetType(); + + if (IsMinSet) + { + if (minType == maxType && maxType == param.ParameterType) + { + return localOptions.Gen.Next( + param.ParameterType, + (IComparable)Min, + (IComparable)Max + ); + } + else + { + throw new ToolException( + $"Provided min '{Min}' of type '{minType}' & max '{Max}' " + + $"of type '{maxType}' must explicitly match '{param}'." + ); + } + } + else + { + return localOptions.Gen.Next(param.ParameterType, (IComparable)Max); + } + } + else + { + throw new ToolException( + $"'{param}' is not a supported value type for the value generator." + ); + } + } + + /// + public abstract object Clone(); +} diff --git a/src/Toolbox/RunnerTool/Attributes/BaseCopyAttribute.cs b/src/Toolbox/RunnerTool/Attributes/BaseCopyAttribute.cs new file mode 100644 index 00000000..ff0a6eb0 --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/BaseCopyAttribute.cs @@ -0,0 +1,36 @@ +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +/// Flag to create the attached as a deep clone of a previous parameter.. +/// +/// +public abstract class BaseCopyAttribute : ParameterHintAttribute +{ + /// + protected internal override object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ) + { + ArgumentGuard.ThrowIfNull(param, method, args, localOptions); + + ParameterInfo[] methodParams = method.GetParameters(); + + int current = Array.FindIndex(methodParams, p => p.Name == param.Name); + for (int i = current - 1; i >= 0; i--) + { + if (param.ParameterType == methodParams[i].ParameterType) + { + return localOptions.Duplicator.Copy(args[i]); + } + } + + throw new ToolException($"No value to copy for '{param}' on '{method}'."); + } +} diff --git a/src/Toolbox/RunnerTool/Attributes/BaseFakeAttribute.cs b/src/Toolbox/RunnerTool/Attributes/BaseFakeAttribute.cs new file mode 100644 index 00000000..b1f4fcee --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/BaseFakeAttribute.cs @@ -0,0 +1,29 @@ +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +/// Flag to create the attached as a stub with injected random behavior. +/// +/// +/// +public abstract class BaseFakeAttribute : ParameterHintAttribute +{ + /// + protected internal override object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ) + { + ArgumentGuard.ThrowIfNull(param, localOptions); + + return ( + (Fake) + localOptions.Randomizer.Create(typeof(Fake<>).MakeGenericType(param.ParameterType)) + ).Dummy; + } +} diff --git a/src/Toolbox/RunnerTool/Attributes/BaseInjectAttribute.cs b/src/Toolbox/RunnerTool/Attributes/BaseInjectAttribute.cs new file mode 100644 index 00000000..a0c69aa7 --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/BaseInjectAttribute.cs @@ -0,0 +1,29 @@ +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +/// Flag to create the attached parameter using value injection of previous parameters.. +/// +/// +public abstract class BaseInjectAttribute : ParameterHintAttribute +{ + /// + protected internal override object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ) + { + ArgumentGuard.ThrowIfNull(param, args, localOptions); + + return localOptions.Randomizer.Inject( + param.ParameterType, + [.. args.Values.Cast().Where(a => a is Fake or IFaked).Reverse()] + ); + } +} diff --git a/src/Toolbox/RunnerTool/Attributes/BaseSizeAttribute.cs b/src/Toolbox/RunnerTool/Attributes/BaseSizeAttribute.cs new file mode 100644 index 00000000..4bb86392 --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/BaseSizeAttribute.cs @@ -0,0 +1,52 @@ +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +/// +/// Flag to create the attached collection with between and items. +/// +/// +/// +/// +[ExcludeFromCreateAndFake] +public abstract class BaseSizeAttribute(int min, int max) : ParameterHintAttribute +{ + /// Inclusive lower boundary for the generated collection size. + public int Min { get; } = min; + + /// Inclusive upper boundary for the generated collection size. + public int Max { get; } = max; + + /// Flag to create the attached collection with items. + /// Number of items to generate and populate the attached collection with. + /// + protected BaseSizeAttribute(int count) + : this(count, count) { } + + /// + protected internal override object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ) + { + ArgumentGuard.ThrowIfNull(param, localOptions); + + return localOptions.Randomizer.Create( + param.ParameterType, + opt => + opt with + { + CollectionMinSize = Min, + CollectionMaxSize = Max, + StringMinSize = Min, + StringMaxSize = Max, + NestedOptions = opt, + } + ); + } +} diff --git a/src/Toolbox/RunnerTool/Attributes/BaseStubAttribute.cs b/src/Toolbox/RunnerTool/Attributes/BaseStubAttribute.cs new file mode 100644 index 00000000..b664c363 --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/BaseStubAttribute.cs @@ -0,0 +1,24 @@ +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +/// Flag to create the attached as a stub. +/// +/// +public abstract class BaseStubAttribute : ParameterHintAttribute +{ + /// + protected internal override object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ) + { + ArgumentGuard.ThrowIfNull(param, localOptions); + + return localOptions.Faker.Stub(param.ParameterType).Dummy; + } +} diff --git a/src/Toolbox/RunnerTool/Attributes/BaseUniqueAttribute.cs b/src/Toolbox/RunnerTool/Attributes/BaseUniqueAttribute.cs new file mode 100644 index 00000000..b298aa78 --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/BaseUniqueAttribute.cs @@ -0,0 +1,43 @@ +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +/// Flag to create the attached as a stub with injected random behavior. +/// +/// +/// +public abstract class BaseUniqueAttribute : ParameterHintAttribute +{ + /// + protected internal override object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ) + { + ArgumentGuard.ThrowIfNull(param, args, localOptions); + + return localOptions.Mutator.UniqueOf(param.ParameterType, args.Values.Cast()); + } + + /// + protected internal override Task CreateParameterValueAsync( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(param, args, localOptions); + + return localOptions.Mutator.UniqueOfAsync( + param.ParameterType, + args.Values.Cast(), + canceler + )!; + } +} diff --git a/src/Toolbox/RunnerTool/Attributes/IRandomDataMarker.cs b/src/Toolbox/RunnerTool/Attributes/IRandomDataMarker.cs new file mode 100644 index 00000000..b563de0f --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/IRandomDataMarker.cs @@ -0,0 +1,9 @@ +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +/// Flags test methods to be populated with random values for testing. +public interface IRandomDataMarker +{ + /// Number of times to test the associated method. + /// Default:1 + int Trials { get; set; } +} diff --git a/src/Toolbox/RunnerTool/Attributes/ParameterHintAttribute.cs b/src/Toolbox/RunnerTool/Attributes/ParameterHintAttribute.cs new file mode 100644 index 00000000..4173e439 --- /dev/null +++ b/src/Toolbox/RunnerTool/Attributes/ParameterHintAttribute.cs @@ -0,0 +1,40 @@ +using System.Collections.Specialized; +using System.Reflection; + +namespace Werecodent.CreateAndFake.RunnerTool.Attributes; + +#pragma warning disable MA0042 // Using sync behavior for async versions. + +/// Flag to customize behavior for the attached parameter value during random data generation. +/// +[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] +public abstract class ParameterHintAttribute : Attribute +{ + /// Manages creating the value for the attached parameter. + /// Info for the attached parameter. + /// Originating method for the parameter. + /// Data already generated for the previous parameters of the method. + /// Potentially modified configuration to use. + /// The created parameter value. + protected internal abstract object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ); + + /// + /// Aborts execution if triggered. + protected internal virtual Task CreateParameterValueAsync( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions, + CancellationToken canceler + ) + { + return Task.FromResult(CreateParameterValue(param, method, args, localOptions)); + } +} + +#pragma warning restore diff --git a/src/Toolbox/RunnerTool/IRunner.cs b/src/Toolbox/RunnerTool/IRunner.cs new file mode 100644 index 00000000..9f09c52d --- /dev/null +++ b/src/Toolbox/RunnerTool/IRunner.cs @@ -0,0 +1,99 @@ +global using RunnerMod = System.Func< + Werecodent.CreateAndFake.RunnerTool.RunnerOptions, + Werecodent.CreateAndFake.RunnerTool.RunnerOptions +>; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.RunnerTool; + +/// Tool for generating method data and running them. +/// Useful for generating tests and invoking methods at runtime. +public interface IRunner : ITool +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + IRunner WithOptions(RunnerMod optionConfiguration); + + /// Calls all methods on the . + /// Instance whose methods to call. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// Results of the method calls. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + Task CallMethodsOnAsync( + object instance, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ); + + /// + MethodCallWrapper CreateFor( + MethodBase method, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ); + + /// + /// Constructs parameter data for the utilizing + /// attached s as instructions. + /// + /// Method to create parameters for. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// Parameter arguments for in order. + /// + /// Important relevant options: + /// + /// + /// + Task CreateForAsync( + MethodBase method, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ); + + /// + /// Constructs parameter data for the and runs it on the . + /// + /// Method to create parameter data for and run. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + Task RunAsync( + object? instance, + MethodInfo method, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ); + + /// Runs the method with constructed parameter data on the instance. + /// Instance to run on. + /// Method with parameter data to run. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// Results of the run. + /// + /// Important relevant options: + /// + /// + /// + Task RunAsync( + object? instance, + MethodCallWrapper data, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ); +} diff --git a/src/Toolbox/RunnerTool/MethodCallWrapper.cs b/src/Toolbox/RunnerTool/MethodCallWrapper.cs new file mode 100644 index 00000000..137c40d9 --- /dev/null +++ b/src/Toolbox/RunnerTool/MethodCallWrapper.cs @@ -0,0 +1,187 @@ +using System.Collections; +using System.Collections.Specialized; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.RunnerTool; + +/// Holds parameter data for a method. +/// +/// +public sealed class MethodCallWrapper(MethodBase method, OrderedDictionary args) + : IDuplicatable, + IValuerAsyncComparable +{ + /// Parameter names with associated data to pass. + private readonly OrderedDictionary _args = + args ?? throw new ArgumentNullException(nameof(args)); + + /// Associated method. + public MethodBase Method { get; } = method ?? throw new ArgumentNullException(nameof(method)); + + /// Parameter data for the method. + public IEnumerable Args => _args.Values.Cast(); + + /// Number of args. + public int ArgCount => _args.Count; + + /// Type created from calling . + public Type ResultType => Method is MethodInfo info ? info.ReturnType : Method.DeclaringType!; + + /// Sets parameter named to . + /// Name for the parameter to modify. + /// New value to use. + /// Previous value that was replaced for the parameter. + /// If is not a key. + public object? ModifyArg(string name, object? value) + { + if (_args.Contains(name)) + { + object? prev = _args[name]; + _args[name] = value; + return prev; + } + else + { + throw new KeyNotFoundException($"Parameter '{name}' not on method '{Method.Name}'."); + } + } + + /// Sets parameter at to . + /// Index of the parameter to modify. + /// New value to use. + /// Previous value that was replaced for the parameter. + public object? ModifyArg(int index, object? value) + { + object? prev = _args[index]; + _args[index] = value; + return prev; + } + + /// Invokes the method on . + /// Instance to call the method with the data on. + /// Results from the call. + public object? InvokeOn(object? instance) + { + if (instance == null && method is ConstructorInfo builder) + { + return builder.Invoke([.. Args]); + } + else + { + return Method.Invoke(instance, [.. Args]); + } + } + + /// + public async IAsyncEnumerable CompareAsync( + object? other, + IValuer valuer, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + ArgumentGuard.ThrowIfNull(valuer); + + if (other is MethodCallWrapper wrapper) + { + await foreach ( + Difference diff in valuer + .CompareAsync(Method, wrapper.Method, canceler) + .ConfigureAwait(false) + ) + { + canceler.ThrowIfCancellationRequested(); + yield return new Difference(".Method", diff); + } + + await foreach ( + Difference diff in valuer + .CompareAsync(Args, wrapper.Args, canceler) + .ConfigureAwait(false) + ) + { + canceler.ThrowIfCancellationRequested(); + yield return new Difference(".Arg", diff); + } + } + else + { + yield return new Difference(typeof(MethodCallWrapper), other?.GetType()); + } + } + + /// + public Task GetValueHashAsync(IValuer valuer, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(valuer); + + return valuer.GetHashCodeAsync(Args.Prepend(Method), canceler); + } + + /// + public MethodCallWrapper DeepClone(IDuplicator duplicator) + { + ArgumentGuard.ThrowIfNull(duplicator); + + return new MethodCallWrapper(duplicator.Copy(method), duplicator.Copy(_args)); + } + + /// + public override string ToString() + { + string nl = Environment.NewLine; + + StringBuilder argDetails = new(); + foreach (DictionaryEntry entry in _args) + { + argDetails.Append(nl).Append(" - ").Append(entry.Key).Append(": "); + + if (entry.Value is IDisposable) + { + argDetails.Append('*'); + } + if (entry.Value is IAsyncDisposable) + { + argDetails.Append("**"); + } + + if (entry.Value == null) + { + argDetails.Append("'NULL'"); + } + else if (entry.Value is Fake or IFaked) + { + argDetails.Append("'FAKE'"); + } + else if (entry.Value is ICollection series) + { + argDetails + .Append('(') + .Append(series.Count) + .Append(") ") + .Append(GenericConverter.ExpandName(entry.Value)); + } + else if (entry.Value.GetType().Inherits(typeof(ICollection<>))) + { + argDetails + .Append('(') + .Append(((dynamic)entry.Value).Count) + .Append(") ") + .Append(GenericConverter.ExpandName(entry.Value)); + } + else + { + argDetails.Append(entry.Value.ToString()); + } + } + + return $"{GenericConverter.BuildTestName(Method)}{argDetails}"; + } +} diff --git a/src/Toolbox/RunnerTool/RunResult.cs b/src/Toolbox/RunnerTool/RunResult.cs new file mode 100644 index 00000000..2cc5c976 --- /dev/null +++ b/src/Toolbox/RunnerTool/RunResult.cs @@ -0,0 +1,44 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.RunnerTool; + +/// Call and result for a call. +/// +/// +/// +/// +public sealed class RunResult( + MethodBase method, + IEnumerable args, + object? result, + bool threwException +) +{ + /// Associated method that was ran to produce the . + public MethodBase Method { get; } = method ?? throw new ArgumentNullException(nameof(method)); + + /// Parameter data used to call the . + public IEnumerable Args { get; } = [.. args]; + + /// Return data for the call. + public object? Result { get; } = result; + + /// + /// If the call completed successfully and contains the returned data. + /// + public bool HasSuccessfulResult { get; } = + !threwException && result?.GetType() != typeof(VoidType); + + /// + /// If the call threw an exception and contains the exception. + /// + public bool ThrewException { get; } = threwException; + + /// + public override string ToString() + { + return $"{GenericConverter.BuildTestName(Method)}{{{(HasSuccessfulResult ? "Success" : "Exception")}}}: {Result?.ToString()}"; + } +} diff --git a/src/Toolbox/RunnerTool/RunResults.cs b/src/Toolbox/RunnerTool/RunResults.cs new file mode 100644 index 00000000..a2b89cf4 --- /dev/null +++ b/src/Toolbox/RunnerTool/RunResults.cs @@ -0,0 +1,31 @@ +using System.Text; +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.RunnerTool; + +/// Results for a series of associated calls. +/// +/// +public sealed class RunResults(IEnumerable rawResults, RunnerOptions options) +{ + /// Associated calls with results. + public IEnumerable RawResults { get; } = [.. rawResults]; + + /// Configured options applied to the associated calls. + private RunnerOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public override string ToString() + { + StringBuilder contents = new(); + + int i = 0; + foreach (object item in RawResults) + { + ArgumentGuard.ThrowUponIterationLimit(i, Options.Design.IterationLimit); + _ = contents.Append('[').Append(i++).Append("]:").Append(item).AppendLine(); + } + return contents.ToString(); + } +} diff --git a/src/Toolbox/RunnerTool/Runner.cs b/src/Toolbox/RunnerTool/Runner.cs new file mode 100644 index 00000000..77577cad --- /dev/null +++ b/src/Toolbox/RunnerTool/Runner.cs @@ -0,0 +1,421 @@ +using System.Collections.Specialized; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.RunnerTool; + +/// +/// +/// If given a parameter. +public sealed class Runner(RunnerOptions options) : IRunner +{ + /// + public RunnerOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public async Task CallMethodsOnAsync( + object instance, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ) + { + ArgumentGuard.ThrowIfNull(instance); + + RunnerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + List results = []; + foreach ( + MethodInfo method in TypeDescriber + .For(instance.GetType()) + .Methods.OnlyPublic.Where(m => !localOptions.MethodsToIgnore.Contains(m.Name)) + .Where(m => + localOptions.IncludeBaseObjectMethods || m.DeclaringType != typeof(object) + ) + ) + { + // Sequentially executed to prevent concurrency issues; do not attempt to parallelize. + results.Add( + await RunAsync( + instance, + GenericResolver.OfConcrete(method, localOptions.Randomizer), + canceler, + (optionConfiguration != null) ? _ => localOptions : null + ) + .ConfigureAwait(false) + ); + } + return new(results, localOptions); + } + + /// + public async Task RunAsync( + object? instance, + MethodInfo method, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ) + { + return await RunAsync( + instance, + await CreateForAsync(method, canceler, optionConfiguration).ConfigureAwait(false), + canceler, + optionConfiguration + ) + .ConfigureAwait(false); + } + + /// + public async Task RunAsync( + object? instance, + MethodCallWrapper data, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ) + { + ArgumentGuard.ThrowIfNull(data); + + RunnerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + TimeSpan timeout = + (localOptions.RunTimeout.TotalMilliseconds is > -1) + ? localOptions.RunTimeout + : TimeSpan.FromMilliseconds(30000); + + Task task; + using ( + CancellationTokenSource timeoutTokenSource = + CancellationTokenSource.CreateLinkedTokenSource(canceler) + ) + { + task = Task.Run( + async () => + { + try + { + return await Unwrapper + .UnwrapResultAsync( + data.InvokeOn(instance), + data.ResultType, + localOptions, + timeoutTokenSource.Token + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new RunnerMethodErrorException(data.ToString(), e); + } + }, + timeoutTokenSource.Token + ); + + bool timedOut = + ( + await Task.WhenAny(task, Task.Delay(timeout, timeoutTokenSource.Token)) + .ConfigureAwait(false) + ) != task; + + await AsyncSeriesHelper + .TriggerCancellationAsync(timeoutTokenSource) + .ConfigureAwait(false); + + if (timedOut) + { + throw new RunnerTimeoutException(timeout, data.ToString()); + } + } + + if (task.Exception != null) + { + return new(data.Method, data.Args, UnwrapException(task.Exception), true); + } + + object? result = await task.ConfigureAwait(false); + if (data.Method is MethodInfo info && info.ReturnType == typeof(void)) + { + result = VoidType.Instance; + } + return new(data.Method, data.Args, result, false); + } + + private static Exception? UnwrapException(Exception? error) + { + Exception? result = error; + if (result is AggregateException multi) + { + result = multi.InnerException; + } + + if (result is RunnerMethodErrorException method) + { + result = method.InnerException; + } + + if (result is TargetInvocationException ex) + { + result = ex.InnerException; + } + + return result; + } + + /// + public MethodCallWrapper CreateFor( + MethodBase method, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ) + { + ArgumentGuard.ThrowIfNull(method); + + if (method.IsGenericMethodDefinition) + { + throw new UnsupportedException( + $"Method '{GenericConverter.BuildTestName(method)}' must have " + + "generics specified before data can be populated for it." + ); + } + + RunnerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + List> data = + [ + .. localOptions + .InjectionValues.Select(v => (v is Fake fake) ? fake.Dummy : v) + .Where(v => v != null) + .Select(v => Tuple.Create(v!.GetType(), v)), + ]; + + OrderedDictionary args = [with(method.GetParameters().Length)]; + + foreach (ParameterInfo param in method.GetParameters()) + { + string argName = param.Name ?? $"{args.Count}"; + + if (TryGetAttachedHint(param, out ParameterHintAttribute? hint)) + { + args.Add(argName, hint.CreateParameterValue(param, method, args, localOptions)); + } + else + { + args.Add(argName, ExtractArg(param, data, args, localOptions, canceler)); + } + } + + return new MethodCallWrapper(method, args); + } + + /// + public async Task CreateForAsync( + MethodBase method, + CancellationToken canceler, + RunnerMod? optionConfiguration = null + ) + { + ArgumentGuard.ThrowIfNull(method); + + if (method.IsGenericMethodDefinition) + { + throw new UnsupportedException( + $"Method '{GenericConverter.BuildTestName(method)}' must have " + + "generics specified before data can be populated for it." + ); + } + + RunnerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + List> data = + [ + .. localOptions + .InjectionValues.Select(v => (v is Fake fake) ? fake.Dummy : v) + .Where(v => v != null) + .Select(v => Tuple.Create(v!.GetType(), v)), + ]; + + OrderedDictionary args = [with(method.GetParameters().Length)]; + + foreach (ParameterInfo param in method.GetParameters()) + { + string argName = param.Name ?? $"{args.Count}"; + + if (TryGetAttachedHint(param, out ParameterHintAttribute? hint)) + { + args.Add( + argName, + await hint.CreateParameterValueAsync( + param, + method, + args, + localOptions, + canceler + ) + .ConfigureAwait(false) + ); + } + else + { + args.Add( + argName, + await ExtractArgAsync(param, data, args, localOptions, canceler) + .ConfigureAwait(false) + ); + } + } + + return new MethodCallWrapper(method, args); + } + + private static bool TryGetAttachedHint( + ParameterInfo param, + [NotNullWhen(true)] out ParameterHintAttribute? result + ) + { + List definedHints = + [ + .. Attribute + .GetCustomAttributes(param, typeof(ParameterHintAttribute)) + .Cast(), + ]; + if (definedHints.Count > 1) + { + throw new ToolException("Multiple hints defined."); + } + else if (definedHints.Count == 1) + { + result = definedHints[0]; + return true; + } + else + { + result = null; + return false; + } + } + + /// Randomizes an instance to fill a parameter. + /// Parameter to fill. + /// Canned data to prefer. + /// Already created parameter data. + /// Potentially modified configuration to use. + /// Aborts execution if triggered. + /// The created arg to fill the parameter with. + /// + private static object? ExtractArg( + ParameterInfo param, + List> data, + OrderedDictionary args, + RunnerOptions localOptions, + CancellationToken canceler + ) + { + Tuple match = data.Find(t => t.Item1.Inherits(param.ParameterType))!; + if (param.IsOut) + { + return null; + } + else if (param.ParameterType == typeof(CancellationToken)) + { + return canceler; + } + else if (match != default) + { + _ = data.Remove(match); + return match.Item2; + } + else if (param.ParameterType == typeof(string)) + { + string? smartData = new DataRandom(localOptions.Gen).Find(param.Name); + if (smartData != null) + { + return smartData; + } + } + + TypeDescriber info = TypeDescriber.For(param.ParameterType); + if ( + args.Count > 0 + && param.ParameterType != typeof(bool) + && ( + localOptions.Gen.Supports(param.ParameterType) + || info.IsMutable() + || info.HasInitializableOnlyState() + ) + ) + { + return localOptions.Mutator.VariantOf(param.ParameterType, args.Values.Cast()); + } + else + { + return localOptions.Randomizer.Create(param.ParameterType); + } + } + + /// + private static async Task ExtractArgAsync( + ParameterInfo param, + List> data, + OrderedDictionary args, + RunnerOptions localOptions, + CancellationToken canceler + ) + { + Tuple match = data.Find(t => t.Item1.Inherits(param.ParameterType))!; + if (param.IsOut) + { + return null; + } + else if (param.ParameterType == typeof(CancellationToken)) + { + return canceler; + } + else if (match != default) + { + _ = data.Remove(match); + return match.Item2; + } + else if (param.ParameterType == typeof(string)) + { + string? smartData = new DataRandom(localOptions.Gen).Find(param.Name); + if (smartData != null) + { + return smartData; + } + } + + TypeDescriber info = TypeDescriber.For(param.ParameterType); + if ( + args.Count > 0 + && param.ParameterType != typeof(bool) + && ( + localOptions.Gen.Supports(param.ParameterType) + || info.IsMutable() + || info.HasInitializableOnlyState() + ) + ) + { + return await localOptions + .Mutator.VariantOfAsync(param.ParameterType, args.Values.Cast(), canceler) + .ConfigureAwait(false); + } + else + { + return localOptions.Randomizer.Create(param.ParameterType); + } + } + + /// + public IRunner WithOptions(RunnerMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Runner(optionConfiguration.Invoke(Options)); + } +} diff --git a/src/Toolbox/RunnerTool/RunnerOptions.cs b/src/Toolbox/RunnerTool/RunnerOptions.cs new file mode 100644 index 00000000..1f2c2709 --- /dev/null +++ b/src/Toolbox/RunnerTool/RunnerOptions.cs @@ -0,0 +1,87 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.RandomizerTool; + +namespace Werecodent.CreateAndFake.RunnerTool; + +/// Configuration for manipulating behavior. +public sealed record RunnerOptions : ToolOptions +{ + /// Identifies the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Runner); + + /// + public required IRandomizer Randomizer { get; init; } + + /// + public required IMutator Mutator { get; init; } + + /// + public required IDuplicator Duplicator { get; init; } + + /// + public required IFaker Faker { get; init; } + + /// Names of methods to skip when running all methods on an instance. + /// + /// Useful for preventing execution of methods that leave + /// the in a bad state for other methods. + /// + /// ["Close", "Dispose", "Finalize", "DisposeAsync", "PrintMembers", "GetObjectData"] + [ConfigurableOption] + public FrozenSet MethodsToIgnore { get; init; } = + FrozenSet.ToFrozenSet([ + "Close", + "Dispose", + "Finalize", + "DisposeAsync", + "PrintMembers", + "GetObjectData", + ]); + + /// Flag to include running methods declared on the . + /// Useful in only running introduced methods when . + /// + [ConfigurableOption] + public bool IncludeBaseObjectMethods { get; init; } = false; + + /// How long to wait for methods to complete before timing out. + /// Used to gracefully end execution instead of stalling endlessly. + /// 00:00:50.0000000 + [ConfigurableOption] + public TimeSpan RunTimeout { get; init; } = new(0, 0, 50); + + /// Values to inject into called methods. + /// + /// When generating randomized parameter data, these values will be used instead of randomized instances + /// when applicable. Per method, each value will only be used once and prioritized in the order given. + /// See: + /// + /// [] + public ImmutableArray InjectionValues { get; init; } = []; + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal RunnerOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + IncludeBaseObjectMethods = Config.GetValue(section, IncludeBaseObjectMethods), + MethodsToIgnore = Config.GetSet(section, MethodsToIgnore), + RunTimeout = Config.GetValue(section, RunTimeout), + }; + } +} diff --git a/src/Toolbox/RunnerTool/Unwrapper.cs b/src/Toolbox/RunnerTool/Unwrapper.cs new file mode 100644 index 00000000..e4ce687b --- /dev/null +++ b/src/Toolbox/RunnerTool/Unwrapper.cs @@ -0,0 +1,118 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.RunnerTool; + +/// Extracts the contents from containers. +internal static class Unwrapper +{ + /// Ensures the result is completed. + /// Potentially wrapped data. + /// Data type being returned. + /// Configured options to apply to this call. + /// Aborts execution if triggered. + /// The unwrapped result. + /// + /// If does not inherit . + /// + internal static async Task UnwrapResultAsync( + object? result, + Type methodReturnType, + RunnerOptions options, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(options, methodReturnType); + + if (result == null) + { + return null; + } + + if (!methodReturnType.IsInstanceOfType(result)) + { + throw new ArgumentException( + $"Result of type '{GenericConverter.ExpandName(result.GetType())}' was not of" + + $" the provided type '{GenericConverter.ExpandName(methodReturnType)}'.", + nameof(methodReturnType) + ); + } + + TypeDescriber describer = TypeDescriber.For(result); + + if (result is Task plainTask) + { + object? content = await Invoker.AwaitAsync(plainTask).ConfigureAwait(false); + if (content == VoidType.Instance) + { + return Task.CompletedTask; + } + else + { + return result; + } + } + else if (result is ValueTask valueTask) + { + await valueTask.ConfigureAwait(false); + return Task.CompletedTask; + } + else if (describer.Inherits(typeof(ValueTask<>))) + { + dynamic? content = await ((dynamic)result).ConfigureAwait(false); + if (content == null) + { + return typeof(Task) + .GetMethod(nameof(Task.FromResult))! + .MakeGenericMethod(result.GetType().GetGenericArguments().Single()) + .Invoke(null, [null]); + } + else + { + return Task.FromResult(content); + } + } + + Type resultType = result.GetType(); + if (resultType == typeof(string) || resultType.Inherits(typeof(ICollection<>))) + { + return result; + } + + // Required to execute async yield return methods. + if (resultType.Inherits(typeof(IAsyncEnumerable<>))) + { + dynamic collection = await AsyncSeriesHelper + .ToListAsync((dynamic)result, options.Design.IterationLimit, canceler) + .ConfigureAwait(false); + + return AsyncSeriesHelper.CreateFromAsync(collection, options.Design.IterationLimit); + } + + // Required to execute yield return methods. + if (GenericConverter.AsGenericBase(methodReturnType) == typeof(IEnumerable<>)) + { + return Enumerable.AsEnumerable(CollectYieldedResults((dynamic)result, options)); + } + + return result; + } + + /// Iterates through yielded results. + /// The ' item . + /// Items to iterate. + /// Configured options to apply to this call. + /// The collected . + private static List CollectYieldedResults(IEnumerable series, RunnerOptions options) + { + int i = 0; + List results = []; + foreach (T item in series) + { + ArgumentGuard.ThrowUponIterationLimit(i++, options.Design.IterationLimit); + results.Add(item); + } + return results; + } +} diff --git a/src/Toolbox/TesterTool/BaseAssemblyTester.cs b/src/Toolbox/TesterTool/BaseAssemblyTester.cs new file mode 100644 index 00000000..6648c130 --- /dev/null +++ b/src/Toolbox/TesterTool/BaseAssemblyTester.cs @@ -0,0 +1,101 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.TesterTool; + +#pragma warning disable CA1707, VSTHRD200 // Match test format. + +/// Automatically configures and runs tests for the containing test assembly. +public abstract class BaseAssemblyTester +{ + /// Modifications of the 's options to apply for the tests. + protected virtual TesterMod? OptionConfiguration { get; } = null; + + /// Reflection tools used to run the tests. + /// Tools.Source + protected virtual IToolSet AutoTools => Tools.Source; + + /// being tested by the containing test . + protected abstract Assembly CodeAssembly { get; } + + /// + public abstract void Tester_TestClassCoverage(); + + /// + protected void TestClassCoverageImplementation() + { + AutoTools.Tester.ProvidesTestClassCoverage( + CodeAssembly, + GetType().Assembly, + OptionConfiguration + ); + } + + /// + public abstract void Tester_ValidateTestMethodNaming(); + + /// + protected void ValidateTestMethodNamingImplementation(IEnumerable testMarkers) + { + AutoTools.Tester.VerifyTestMethodNaming( + testMarkers, + CodeAssembly, + GetType().Assembly, + OptionConfiguration + ); + } + + /// + public abstract Task Tester_ValidateRandomDataParameters(); + + /// + protected Task ValidateRandomDataParametersImplementation(CancellationToken canceler) + { + return AutoTools.Tester.ValidateRandomDataParametersAsync( + GetType().Assembly, + canceler, + OptionConfiguration + ); + } + + /// + public abstract Task Tester_ValidateAutoTesterInstances(); + + /// + protected Task ValidateAutoTesterInstancesImplementation(CancellationToken canceler) + { + return AutoTools.Tester.ValidateAutoTesterInstancesAsync(canceler, OptionConfiguration); + } + + /// + public abstract Task Tester_VerifyTestSettingsConfig_Default(); + + /// + protected Task VerifyTestSettingsConfigImplementation(CancellationToken canceler) + { + return AutoTools.Tester.ValidateTestSettingsConfigAsync( + null, + canceler, + OptionConfiguration + ); + } + + /// + public abstract void Tester_VerifyAllToStrings(); + + /// + protected void VerifyAllToStringsImplementation() + { + AutoTools.Tester.VerifyAllToStrings(CodeAssembly, OptionConfiguration); + } + + /// + public abstract Task Tester_VerifyToolSetIntegrity(); + + /// + protected Task VerifyToolSetIntegrityImplementation(CancellationToken canceler) + { + return AutoTools.Tester.VerifyToolSetIntegrityAsync(canceler, OptionConfiguration); + } +} + +#pragma warning restore diff --git a/src/Toolbox/TesterTool/BaseAutoTester.cs b/src/Toolbox/TesterTool/BaseAutoTester.cs new file mode 100644 index 00000000..27705e66 --- /dev/null +++ b/src/Toolbox/TesterTool/BaseAutoTester.cs @@ -0,0 +1,189 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.TesterTool; + +#pragma warning disable CA1707, VSTHRD200 // Match test format. + +/// Automatically configures and runs common tests. +/// under test. +public abstract class BaseAutoTester(Type testType) +{ + /// Modifications of the 's options to apply for the tests. + protected virtual TesterMod? OptionConfiguration { get; } = null; + + /// Determines the behavior for . + /// + /// = + /// = + /// + /// + protected virtual bool EqualsOverrideUsesFullValueEquality { get; } = true; + + /// Reflection tools used to run the tests. + /// Tools.Source + protected virtual IToolSet AutoTools => Tools.Source; + + /// + protected TypeDescriber TestTypeDescriber { get; } = TypeDescriber.For(testType); + + /// Verifies nulls are guarded on the type. + /// Uses: + /// A that represents the asynchronous operation. + public abstract Task Tester_GuardsNulls(); + + /// Aborts execution if triggered. + /// + protected virtual async Task GuardsNullsImplementation(CancellationToken canceler) + { + try + { + await AutoTools + .Tester.PreventsNullRefExceptionAsync(testType, canceler, OptionConfiguration) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AutoTesterFailureException(GetType(), e); + } + } + + /// Verifies mutations are prevented on the type. + /// Uses: + /// A that represents the asynchronous operation. + public abstract Task Tester_NoParameterMutation(); + + /// Aborts execution if triggered. + /// + protected virtual async Task NoParameterMutationImplementation(CancellationToken canceler) + { + try + { + await AutoTools + .Tester.PreventsParameterMutationAsync(testType, canceler, OptionConfiguration) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AutoTesterFailureException(GetType(), e); + } + } + + /// Verifies proper value equality rules. + /// Control via: + public abstract Task Tester_ValueEqualityOverrideCheck(); + + /// + protected virtual async Task ValueEqualityOverrideCheckImplementation( + CancellationToken canceler + ) + { + if ( + !testType.IsEnum + && ( + testType.GetMethod(nameof(Equals), [typeof(object)])!.DeclaringType + != typeof(object) + || TestTypeDescriber.Inherits() + || TestTypeDescriber.Inherits() + || TestTypeDescriber.Inherits() + ) + ) + { + try + { + if (EqualsOverrideUsesFullValueEquality) + { + await AutoTools + .Tester.VerifyValueEqualityAsync(testType, canceler, OptionConfiguration) + .ConfigureAwait(false); + } + else + { + await AutoTools + .Tester.VerifyEqualsMatchesHashCodesAsync( + testType, + canceler, + OptionConfiguration + ) + .ConfigureAwait(false); + } + } + catch (Exception e) + { + throw new AutoTesterFailureException(GetType(), e); + } + } + } + + /// Validates the type is fully compatible with the framework as configured. + /// + /// Includes randomization, mutation, duplication, equality and faking. + /// Uses: + /// + /// A that represents the asynchronous operation. + public abstract Task Tester_ToolSupport(); + + /// Aborts execution if triggered. + /// + protected virtual async Task ToolSupportImplementation(CancellationToken canceler) + { + if (!TestTypeDescriber.IsStatic()) + { + try + { + await AutoTools + .Tester.VerifyToolSetSupportAsync(testType, canceler, OptionConfiguration) + .ConfigureAwait(false); + } + catch (Exception e) + { + throw new AutoTesterFailureException(GetType(), e); + } + } + } + + /// + /// Allows manual inspection of when + /// is set. + /// + /// Uses: + public abstract Task Tester_Debug_ToString(); + + /// + protected virtual async Task DebugToStringImplementation() + { + if (!TestTypeDescriber.IsStatic()) + { + TesterOptions localOptions = OptionConfiguration?.Invoke(AutoTools.Tester.Options) + ?? AutoTools.Tester.Options; + + object? instance = null; + try + { + if (localOptions.InjectionValues.Length > 0) + { + instance = AutoTools.Randomizer.Inject(testType, localOptions.InjectionValues); + } + else + { + instance = AutoTools.Randomizer.Create(testType); + } + AutoTools.Asserter.Debug(instance.ToString()); + } + catch (Exception e) + { + throw new AutoTesterFailureException(GetType(), e); + } + finally + { + await Disposer.CleanupAsync(instance).ConfigureAwait(false); + } + } + } +} + +#pragma warning restore diff --git a/src/Toolbox/TesterTool/BaseAutoTester{T}.cs b/src/Toolbox/TesterTool/BaseAutoTester{T}.cs new file mode 100644 index 00000000..a0ac74f7 --- /dev/null +++ b/src/Toolbox/TesterTool/BaseAutoTester{T}.cs @@ -0,0 +1,103 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.TesterTool; + +#pragma warning disable IDE0391 // Better exception handling. + +/// under test. +/// +public abstract class BaseAutoTester : BaseAutoTester +{ + /// Backing value for . + /// Used to track if has been overridden. + private readonly Lazy _defaultTestInstance; + + /// Specific instance used for automated tests. + /// AutoTools.Randomizer.Create<T>() + protected virtual T TestInstance => _defaultTestInstance.Value; + + /// + protected BaseAutoTester() + : base(typeof(T)) + { + _defaultTestInstance = new(() => AutoTools.Randomizer.Create()); + } + + /// Identifies if has been set by a subclass. + /// if overridden, otherwise. + private bool IsTestInstanceOverridden() + { + return TestInstance is not null && !_defaultTestInstance.IsValueCreated; + } + + /// + protected override async Task GuardsNullsImplementation(CancellationToken canceler) + { + try + { + if (IsTestInstanceOverridden()) + { + await AutoTools + .Tester.PreventsNullRefExceptionAsync( + TestInstance, + canceler, + OptionConfiguration + ) + .ConfigureAwait(false); + } + else + { + await AutoTools + .Tester.PreventsNullRefExceptionAsync(canceler, OptionConfiguration) + .ConfigureAwait(false); + } + } + catch (Exception e) + { + throw new AutoTesterFailureException(GetType(), e); + } + } + + /// + protected override async Task NoParameterMutationImplementation(CancellationToken canceler) + { + try + { + if (IsTestInstanceOverridden()) + { + await AutoTools + .Tester.PreventsParameterMutationAsync( + TestInstance, + canceler, + OptionConfiguration + ) + .ConfigureAwait(false); + } + else + { + await AutoTools + .Tester.PreventsParameterMutationAsync(canceler, OptionConfiguration) + .ConfigureAwait(false); + } + } + catch (Exception e) + { + throw new AutoTesterFailureException(GetType(), e); + } + } + + /// + protected override async Task DebugToStringImplementation() + { + try + { + AutoTools.Asserter.Debug(TestInstance); + } + catch (Exception e) + { + throw new AutoTesterFailureException(GetType(), e); + } + } +} + +#pragma warning restore diff --git a/src/Toolbox/TesterTool/GenericFixer.cs b/src/Toolbox/TesterTool/GenericFixer.cs new file mode 100644 index 00000000..c362c49a --- /dev/null +++ b/src/Toolbox/TesterTool/GenericFixer.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.TesterTool; + +/// Handles generic resolution. +internal static class GenericFixer +{ + /// Defines any generics in a type. + /// Type to fix. + /// Options to use. + /// Type with all generics defined. + internal static Type FixType(Type type, TesterOptions options) + { + ArgumentGuard.ThrowIfNull(options); + + return GenericResolver.OfConcrete( + type, + new RandomizerChainer(options.Randomizer.Options, new RandomizerEngine()) + ); + } + + /// Defines any generics in a method. + /// Method to fix. + /// Options to use. + /// Method with all generics defined. + internal static MethodInfo FixMethod(MethodInfo method, TesterOptions options) + { + ArgumentGuard.ThrowIfNull(options); + + return GenericResolver.OfConcrete(method, options.Randomizer); + } +} diff --git a/src/Toolbox/TesterTool/Guarders/BaseGuarder.cs b/src/Toolbox/TesterTool/Guarders/BaseGuarder.cs new file mode 100644 index 00000000..8ef087cb --- /dev/null +++ b/src/Toolbox/TesterTool/Guarders/BaseGuarder.cs @@ -0,0 +1,240 @@ +using System.Collections; +using System.Reflection; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.TesterTool.Guarders; + +/// Automates checks. +/// +internal abstract class BaseGuarder(TesterOptions options) +{ + /// Configured options for testing. + protected TesterOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// Gets all testable constructors on a type. + /// Type with the constructors to test. + /// Found constructors. + protected IEnumerable FindAllConstructors(Type type) + { + ArgumentGuard.ThrowIfNull(type); + + TypeDescriber describer = TypeDescriber.For(type); + + return ( + Options.IncludeInternals + ? describer.Constructors.Visible.Concat(describer.Factories.Visible) + : describer.Constructors.OnlyPublic.Concat( + describer.Factories.OnlyPublic + ) + ).Where(f => !f.IsGenericMethodDefinition); + } + + /// Gets all testable methods on a type. + /// Type with the methods to test. + /// Instance, static, or both. + /// Found methods. + protected IEnumerable FindAllMethods(Type type, BindingFlags kind) + { + ArgumentGuard.ThrowIfNull(type); + + TypeDescriber describer = TypeDescriber.For(type); + IEnumerable methods = []; + + if (kind.HasFlag(BindingFlags.Static)) + { + methods = methods + .Concat( + Options.IncludeInternals + ? describer.StaticMethods.Visible + : describer.StaticMethods.OnlyPublic + ) + .Where(m => !Attribute.IsDefined(m, typeof(CompilerGeneratedAttribute))); // Remove local functions. + } + + if (kind.HasFlag(BindingFlags.Instance)) + { + methods = methods.Concat( + Options.IncludeInternals ? describer.Methods.Visible : describer.Methods.OnlyPublic + ); + } + + return methods + .Where(m => !Options.MethodsToIgnore.Contains(m.Name)) + .Where(m => !Options.OnlyDeclaredMethods || m.DeclaringType == type) + .Where(m => + !Options.IgnoreObsoleteMethods || !Attribute.IsDefined(m, typeof(ObsoleteAttribute)) + ); + } + + /// Attempts to test all methods. + /// Type being tested. + /// Test to run. + /// Aborts execution if triggered. + protected async Task CreateInstanceAndTestMethodsAsync( + Type type, + Func checker, + CancellationToken canceler + ) + { + if (Options.IncludeInstanceMethods && !(type.IsAbstract && type.IsSealed)) + { + object instance = + (Options.InjectionValues.Length > 0) + ? Options.Randomizer.Inject(type, Options.InjectionValues) + : Options.Randomizer.Create(type); + try + { + await checker.Invoke(instance, canceler).ConfigureAwait(false); + } + finally + { + await Disposer.CleanupAsync(instance).ConfigureAwait(false); + } + } + } + + /// Calls all methods to test parameter being set to null. + /// Method under test. + /// Parameter being set to null. + /// Instance whose methods to test. + /// Aborts execution if triggered. + protected async Task CallAllMethodsAsync( + MethodCallWrapper? testOrigin, + ParameterInfo? testParam, + object instance, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(instance); + + foreach ( + MethodInfo method in FindAllMethods(instance.GetType(), BindingFlags.Instance) + .Select(m => GenericFixer.FixMethod(m, options)) + ) + { + MethodCallWrapper data = await options + .Runner.CreateForAsync(method, canceler, opt => + opt with + { + InjectionValues = Options.InjectionValues, + } + ) + .ConfigureAwait(false); + try + { + object? result = await RunCheckAsync( + testOrigin?.Method ?? method, + testParam, + instance, + data, + canceler + ) + .ConfigureAwait(false); + + if ( + !data.Method.IsSpecialName + && result != instance + && !(testOrigin?.Args.Contains(result) ?? false) + ) + { + await Disposer.CleanupAsync(result).ConfigureAwait(false); + } + } + finally + { + await DisposeAllButInjectedAsync(data.Args).ConfigureAwait(false); + } + } + } + + /// Runs the check. + /// Method under test. + /// Parameter being set to null. + /// Instance to run the check on. + /// Call to invoke and test. + /// Aborts execution if triggered. + /// Returned result from the call. + /// If running created an exception. + protected async Task RunCheckAsync( + MethodBase testOrigin, + ParameterInfo? testParam, + object? instance, + MethodCallWrapper data, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(testOrigin); + + RunResult result = await Options + .Runner.RunAsync(instance, data, canceler) + .ConfigureAwait(false); + + if ( + result.ThrewException + && !HandleCheckException(testOrigin, testParam, (Exception)result.Result!) + ) + { + throw new TesterFailureException( + $"Encountered exception when testing - {data}", + (Exception)result.Result! + ); + } + return result.Result; + } + + /// Checks data for disposables and disposes them. + /// Data to check and dispose. + protected async Task DisposeAllButInjectedAsync(object? data) + { + if (data is IDictionary asDict) + { + await DisposeSeriesButInjectedAsync(asDict.Keys).ConfigureAwait(false); + await DisposeSeriesButInjectedAsync(asDict.Values).ConfigureAwait(false); + } + else if (data is IEnumerable asEnum) + { + await DisposeSeriesButInjectedAsync(asEnum).ConfigureAwait(false); + } + else if (!Options.InjectionValues.Contains(data)) + { + await Disposer.CleanupAsync(data).ConfigureAwait(false); + } + } + + /// Checks data for disposables and disposes them. + /// Data to check and dispose. + private async Task DisposeSeriesButInjectedAsync(IEnumerable? data) + { + if (data is not null and not string and not IFaked) + { + int i = 0; + foreach (object item in data) + { + ArgumentGuard.ThrowUponIterationLimit(i++, Options.Design.IterationLimit); + + if (!Options.InjectionValues.Contains(item)) + { + await Disposer.CleanupAsync(item).ConfigureAwait(false); + } + } + } + } + + /// Handles exceptions encountered by the check. + /// Method under test. + /// Parameter being set to null. + /// Exception encountered. + /// If the exception is handled and should not be rethrown. + protected abstract bool HandleCheckException( + MethodBase testOrigin, + ParameterInfo? testParam, + Exception taskException + ); +} diff --git a/src/Toolbox/TesterTool/Guarders/ExceptionGuarder.cs b/src/Toolbox/TesterTool/Guarders/ExceptionGuarder.cs new file mode 100644 index 00000000..25b315a1 --- /dev/null +++ b/src/Toolbox/TesterTool/Guarders/ExceptionGuarder.cs @@ -0,0 +1,74 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.TesterTool.Guarders; + +/// Automates basic layer passthrough checks. +/// +internal sealed class ExceptionGuarder(TesterOptions options) : BaseGuarder(options) +{ + /// + public Task PassthroughWithNoExceptionsAsync(CancellationToken canceler) + { + if (Options.DisablePassthroughTests) + { + return Task.CompletedTask; + } + + object instance = Options.Randomizer.Create>().Dummy!; + return CallAllMethodsAsync(instance, canceler); + } + + /// + public Task PassthroughWithNoExceptionsAsync(object instance, CancellationToken canceler) + { + if (Options.DisablePassthroughTests) + { + return Task.CompletedTask; + } + + return CallAllMethodsAsync(instance, canceler); + } + + /// + internal async Task CallAllMethodsAsync(object instance, CancellationToken canceler) + { + using CancellationTokenSource cleanupCanceler = + CancellationTokenSource.CreateLinkedTokenSource(canceler); + + try + { + await CallAllMethodsAsync(null, null, instance, canceler).ConfigureAwait(false); + } + finally + { + await AsyncSeriesHelper.TriggerCancellationAsync(cleanupCanceler).ConfigureAwait(false); + } + } + + /// + protected override bool HandleCheckException( + MethodBase testOrigin, + ParameterInfo? testParam, + Exception taskException + ) + { + ArgumentGuard.ThrowIfNull(testOrigin); + ArgumentGuard.ThrowIfNull(taskException); + + if ( + !Options.IgnorableExceptions.Contains(taskException.GetType()) + && !Options.IgnoreAllExceptions + ) + { + Options.Asserter.Fail( + taskException, + $"Exception encountered on method '{testOrigin.Name}'." + ); + } + return true; + } +} diff --git a/src/Toolbox/TesterTool/Guarders/MutationGuarder.cs b/src/Toolbox/TesterTool/Guarders/MutationGuarder.cs new file mode 100644 index 00000000..67c7294d --- /dev/null +++ b/src/Toolbox/TesterTool/Guarders/MutationGuarder.cs @@ -0,0 +1,218 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.TesterTool.Guarders; + +/// Automates parameter mutation checks. +/// +internal sealed class MutationGuarder(TesterOptions options) : BaseGuarder(options) +{ + /// + public async Task PreventsParameterMutationAsync(Type type, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(type); + + if (Options.DisableParameterMutationTests) + { + return; + } + + MutationGuarder checker = new(Options); + + if (Options.IncludeConstructors) + { + await checker + .PreventsMutationOnConstructorsAsync(type, true, canceler) + .ConfigureAwait(false); + } + + await CreateInstanceAndTestMethodsAsync( + type, + checker.PreventsMutationOnMethodsAsync, + canceler + ) + .ConfigureAwait(false); + + if (Options.IncludeStaticMethods) + { + await checker + .PreventsMutationOnStaticsAsync(type, true, canceler) + .ConfigureAwait(false); + } + } + + /// + public async Task PreventsParameterMutationAsync(T instance, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(instance); + + if (Options.DisableParameterMutationTests) + { + return; + } + + MutationGuarder checker = new(Options); + + if (Options.IncludeConstructors) + { + await checker + .PreventsMutationOnConstructorsAsync(typeof(T), false, canceler) + .ConfigureAwait(false); + } + if (Options.IncludeInstanceMethods) + { + await checker.PreventsMutationOnMethodsAsync(instance, canceler).ConfigureAwait(false); + } + if (Options.IncludeStaticMethods) + { + await checker + .PreventsMutationOnStaticsAsync(typeof(T), false, canceler) + .ConfigureAwait(false); + } + } + + /// Verifies mutations are prevented on constructors. + /// Type to verify. + /// Run instance methods to validate constructor parameters. + /// Aborts execution if triggered. + internal async Task PreventsMutationOnConstructorsAsync( + Type type, + bool callAllMethods, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(type); + + foreach ( + MethodBase constructor in FindAllConstructors(GenericFixer.FixType(type, Options)) + .Where(c => c.GetParameters().Length > 0) + ) + { + await PreventsMutationAsync(null, constructor, callAllMethods, canceler) + .ConfigureAwait(false); + } + } + + /// Verifies mutations are prevented on methods. + /// Instance to test the methods on. + /// Aborts execution if triggered. + internal async Task PreventsMutationOnMethodsAsync(object instance, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(instance); + + foreach ( + MethodInfo method in FindAllMethods(instance.GetType(), BindingFlags.Instance) + .Where(c => c.GetParameters().Length > 0) + ) + { + await PreventsMutationAsync( + instance, + GenericFixer.FixMethod(method, Options), + false, + canceler + ) + .ConfigureAwait(false); + } + } + + /// Verifies mutations are prevented on methods. + /// Type to verify. + /// Run instance methods to validate factory parameters. + /// Aborts execution if triggered. + internal async Task PreventsMutationOnStaticsAsync( + Type type, + bool callAllMethods, + CancellationToken canceler + ) + { + Type specificType = GenericFixer.FixType(type, Options); + + foreach ( + MethodInfo method in FindAllMethods(specificType, BindingFlags.Static) + .Where(c => c.GetParameters().Length > 0) + ) + { + await PreventsMutationAsync( + null, + GenericFixer.FixMethod(method, Options), + callAllMethods && method.ReturnType.Inherits(specificType), + canceler + ) + .ConfigureAwait(false); + } + } + + /// Verifies mutations are prevented on a method. + /// Instance with the method under test. + /// Method under test. + /// If all instance methods should be called after the method. + /// Aborts execution if triggered. + private async Task PreventsMutationAsync( + object? instance, + MethodBase method, + bool callAllMethods, + CancellationToken canceler + ) + { + using CancellationTokenSource cleanupCanceler = + CancellationTokenSource.CreateLinkedTokenSource(canceler); + + MethodCallWrapper? data = null; + MethodCallWrapper? copy = null; + object? result = null; + try + { + data = await Options + .Runner.CreateForAsync(method, cleanupCanceler.Token, opt => + opt with + { + InjectionValues = Options.InjectionValues, + } + ) + .ConfigureAwait(false); + + copy = Options.Duplicator.Copy(data); + + result = await RunCheckAsync(method, null, instance, data, cleanupCanceler.Token) + .ConfigureAwait(false); + + if (result != null && callAllMethods) + { + await CallAllMethodsAsync(data, null, result, cleanupCanceler.Token) + .ConfigureAwait(false); + } + + await Options + .Asserter.ValuesEqualAsync( + copy, + data, + cleanupCanceler.Token, + $"Parameter data was mutated when testing '{GenericConverter.BuildTestName(method)}'." + ) + .ConfigureAwait(false); + } + finally + { + await AsyncSeriesHelper.TriggerCancellationAsync(cleanupCanceler).ConfigureAwait(false); + await DisposeAllButInjectedAsync(data?.Args).ConfigureAwait(false); + await DisposeAllButInjectedAsync(copy?.Args).ConfigureAwait(false); + await DisposeAllButInjectedAsync(result).ConfigureAwait(false); + } + } + + /// + protected override bool HandleCheckException( + MethodBase testOrigin, + ParameterInfo? testParam, + Exception taskException + ) + { + ArgumentGuard.ThrowIfNull(taskException); + + return Options.IgnoreAllExceptions + || Options.IgnorableExceptions.Contains(taskException.GetType()); + } +} diff --git a/src/Toolbox/TesterTool/Guarders/NullGuarder.cs b/src/Toolbox/TesterTool/Guarders/NullGuarder.cs new file mode 100644 index 00000000..5295e8e6 --- /dev/null +++ b/src/Toolbox/TesterTool/Guarders/NullGuarder.cs @@ -0,0 +1,263 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.TesterTool.Guarders; + +/// Automates null reference guard checks. +/// +internal sealed class NullGuarder(TesterOptions options) : BaseGuarder(options) +{ + /// + public async Task PreventsNullRefExceptionAsync(Type type, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(type); + + if (Options.DisableNullRefExceptionTests) + { + return; + } + + if (Options.IncludeConstructors) + { + await PreventsNullRefExceptionOnConstructorsAsync(type, true, canceler) + .ConfigureAwait(false); + } + + await CreateInstanceAndTestMethodsAsync( + type, + PreventsNullRefExceptionOnMethodsAsync, + canceler + ) + .ConfigureAwait(false); + + if (Options.IncludeStaticMethods) + { + await PreventsNullRefExceptionOnStaticsAsync(type, true, canceler) + .ConfigureAwait(false); + } + } + + /// + public async Task PreventsNullRefExceptionAsync(T instance, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(instance); + + if (Options.DisableNullRefExceptionTests) + { + return; + } + + if (Options.IncludeConstructors) + { + await PreventsNullRefExceptionOnConstructorsAsync(typeof(T), false, canceler) + .ConfigureAwait(false); + } + if (Options.IncludeInstanceMethods) + { + await PreventsNullRefExceptionOnMethodsAsync(instance, canceler).ConfigureAwait(false); + } + if (Options.IncludeStaticMethods) + { + await PreventsNullRefExceptionOnStaticsAsync(typeof(T), false, canceler) + .ConfigureAwait(false); + } + } + + /// + /// Verifies nulls are guarded on constructors. + /// Tests each nullable parameter possible with null. + /// Ignores any exception besides NullReferenceException and moves on. + /// + /// Type to verify. + /// Run instance methods to validate constructor parameters. + /// Aborts execution if triggered. + internal async Task PreventsNullRefExceptionOnConstructorsAsync( + Type type, + bool callAllMethods, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(type); + + foreach (MethodBase constructor in FindAllConstructors(type)) + { + await PreventsNullRefExceptionAsync(null, constructor, callAllMethods, canceler) + .ConfigureAwait(false); + } + } + + /// + /// Verifies nulls are guarded on methods. + /// Tests each nullable parameter possible with null. + /// Ignores any exception besides NullReferenceException and moves on. + /// + /// Instance to test the methods on. + /// Aborts execution if triggered. + internal async Task PreventsNullRefExceptionOnMethodsAsync( + object instance, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(instance); + + foreach (MethodInfo method in FindAllMethods(instance.GetType(), BindingFlags.Instance)) + { + await PreventsNullRefExceptionAsync( + instance, + GenericFixer.FixMethod(method, Options), + false, + canceler + ) + .ConfigureAwait(false); + } + } + + /// + /// Verifies nulls are guarded on methods. + /// Tests each nullable parameter possible with null. + /// Ignores any exception besides NullReferenceException and moves on. + /// + /// Type to verify. + /// Run instance methods to validate factory parameters. + /// Aborts execution if triggered. + internal async Task PreventsNullRefExceptionOnStaticsAsync( + Type type, + bool callAllMethods, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(type); + + foreach (MethodInfo method in FindAllMethods(type, BindingFlags.Static)) + { + await PreventsNullRefExceptionAsync( + null, + GenericFixer.FixMethod(method, Options), + callAllMethods && method.ReturnType.Inherits(type), + canceler + ) + .ConfigureAwait(false); + } + } + + /// Verifies nulls are guarded on a method. + /// Instance with the method under test. + /// Method under test. + /// If all instance methods should be called after the method. + /// Aborts execution if triggered. + private async Task PreventsNullRefExceptionAsync( + object? instance, + MethodBase method, + bool callAllMethods, + CancellationToken canceler + ) + { + using CancellationTokenSource cleanupCanceler = + CancellationTokenSource.CreateLinkedTokenSource(canceler); + + MethodCallWrapper? data = null; + try + { + data = await Options + .Runner.CreateForAsync(method, cleanupCanceler.Token, opt => + opt with + { + InjectionValues = Options.InjectionValues, + } + ) + .ConfigureAwait(false); + + bool called = false; + for (int i = 0; i < data.ArgCount; i++) + { + ParameterInfo param = method.GetParameters()[i]; + if ( + param.IsOut + || ( + param.ParameterType.IsValueType + && Nullable.GetUnderlyingType(param.ParameterType) == null + ) + ) + { + continue; + } + + object? original = data.ModifyArg(i, null); + object? result = null; + try + { + result = await RunCheckAsync( + method, + param, + instance, + data, + cleanupCanceler.Token + ) + .ConfigureAwait(false); + + called = true; + + if (result != null && callAllMethods) + { + await CallAllMethodsAsync(data, param, result, cleanupCanceler.Token) + .ConfigureAwait(false); + } + } + finally + { + _ = data.ModifyArg(i, original); + await DisposeAllButInjectedAsync(result).ConfigureAwait(false); + } + } + if (!called) + { + object? result = await RunCheckAsync( + method, + null, + instance, + data, + cleanupCanceler.Token + ) + .ConfigureAwait(false); + + if (!data.Method.IsSpecialName && result != instance && !data.Args.Contains(result)) + { + await Disposer.CleanupAsync(result).ConfigureAwait(false); + } + } + } + finally + { + await AsyncSeriesHelper.TriggerCancellationAsync(cleanupCanceler).ConfigureAwait(false); + await DisposeAllButInjectedAsync(data?.Args).ConfigureAwait(false); + } + } + + /// + [ExcludeFromCodeCoverage] // Assert.Fail throws and never returns. + protected override bool HandleCheckException( + MethodBase testOrigin, + ParameterInfo? testParam, + Exception taskException + ) + { + ArgumentGuard.ThrowIfNull(testOrigin, taskException); + + string details = $"on method '{testOrigin.Name}' with parameter '{testParam?.Name}'"; + + if (taskException is NullReferenceException) + { + Options.Asserter.Fail( + taskException, + $"Null reference exception encountered {details}." + ); + } + + return Options.IgnoreAllExceptions + || Options.IgnorableExceptions.Contains(taskException.GetType()) + || taskException.GetType() == typeof(ArgumentNullException); + } +} diff --git a/src/Toolbox/TesterTool/ITester.cs b/src/Toolbox/TesterTool/ITester.cs new file mode 100644 index 00000000..339e2666 --- /dev/null +++ b/src/Toolbox/TesterTool/ITester.cs @@ -0,0 +1,362 @@ +global using TesterMod = System.Func< + Werecodent.CreateAndFake.TesterTool.TesterOptions, + Werecodent.CreateAndFake.TesterTool.TesterOptions +>; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.TesterTool; + +/// Tool for testing common scenarios. +/// Useful for automating tests. +public interface ITester : ITool +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + ITester WithOptions(TesterMod optionConfiguration); + + /// Verifies can JSON serialize and deserialize. + /// + void VerifyJsonSerialization(TesterMod? optionConfiguration = null); + + /// + /// Verifies the can JSON serialize and deserialize. + /// + /// The to test. + /// The data to test. + /// Modifications of this tool's options to apply for this call. + void VerifyJsonSerialization(T instance, TesterMod? optionConfiguration = null); + + /// Verifies can XML serialize and deserialize. + /// + void VerifyXmlSerialization(TesterMod? optionConfiguration = null); + + /// + /// Verifies the can XML serialize and deserialize. + /// + /// The to test. + /// The data to test. + /// Modifications of this tool's options to apply for this call. + void VerifyXmlSerialization(T instance, TesterMod? optionConfiguration = null); + + /// Verifies has proper value equality rules for hashes. + /// to verify. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + Task VerifyEqualsMatchesHashCodesAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Verifies the has proper value equality rules for hashes. + /// to verify. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + Task VerifyEqualsMatchesHashCodesAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Verifies uses all values for value equality and equality works. + /// to verify. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + Task VerifyValueEqualityAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Verifies the uses all values for value equality and equality works. + /// to verify. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + Task VerifyValueEqualityAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Verifies cancellation behavior. + /// to verify. + /// Behavior to test. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + /// + /// Important relevant options: + /// + /// + /// + Task VerifySupportsCancellationAsync( + Func> factory, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// + Task VerifySupportsCancellationAsync( + Func> factory, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// to verify. + /// + Task PreventsNullRefExceptionAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// + /// Verifies nulls are guarded on the type. + /// Tests each parameter possible with null. + /// Constructor and factory parameters are tested by running all methods. + /// + /// to verify. + /// + Task PreventsNullRefExceptionAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// + /// Verifies nulls are guarded on the type. + /// Tests each parameter possible with null. + /// Constructor and factory parameters are not tested by running all methods. + /// + /// to verify. + /// Instance to test the methods on. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + Task PreventsNullRefExceptionAsync( + T instance, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// to verify. + /// + Task PreventsParameterMutationAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// + /// Verifies mutations are prevented on the type. + /// Constructor and factory parameters are tested by running all methods. + /// + /// to verify. + /// + Task PreventsParameterMutationAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// + /// Verifies mutations are prevented on the type. + /// Constructor and factory parameters are not tested by running all methods. + /// + /// to verify. + /// Instance to test the methods on. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + Task PreventsParameterMutationAsync( + T instance, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// to verify. + /// + Task PassthroughWithNoExceptionsAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Verifies no exceptions are thrown on any method when using injection and random data. + /// Instance to test the methods on. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + /// + /// + Task PassthroughWithNoExceptionsAsync( + object instance, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// + /// Verifies has a test + /// class for all classes in . + /// + /// Assembly being tested. + /// Assembly with the tests. + /// Modifications of this tool's options to apply for this call. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + void ProvidesTestClassCoverage( + Assembly codeAssembly, + Assembly testAssembly, + TesterMod? optionConfiguration = null + ); + + /// Verifies tests in have appropriate names. + /// All test framework s that marks methods as tests. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + void VerifyTestMethodNaming( + IEnumerable testMarkers, + Assembly codeAssembly, + Assembly testAssembly, + TesterMod? optionConfiguration = null + ); + + /// + /// Validates methods marked by + /// can be populated with random data. + /// + /// Assembly with the tests. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + Task ValidateRandomDataParametersAsync( + Assembly testAssembly, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Validates implementations have a valid TestInstance value. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + Task ValidateAutoTesterInstancesAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Validates a configuration. + /// Name of the environment to test. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + Task ValidateTestSettingsConfigAsync( + string? environmentName, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Validates the state of the CreateAndFake framework as configured. + /// + /// Important relevant options: + /// + /// + /// + /// + /// + Task VerifyToolSetIntegrityAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Validates is fully compatible with the framework as configured. + /// to verify support for. + /// + Task VerifyToolSetSupportAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Validates the is fully compatible with the framework as configured. + /// to verify support for. + /// + Task VerifyToolSetSupportAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Validates the are fully compatible with the framework as configured. + /// s to verify support for. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// A that represents the asynchronous operation. + /// + /// Important relevant options: + /// + /// + /// + Task VerifyToolSetSupportAsync( + IEnumerable types, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ); + + /// Triggers a debug assertion of all classes in the . + /// Assembly being tested. + /// Modifications of this tool's options to apply for this call. + void VerifyAllToStrings(Assembly codeAssembly, TesterMod? optionConfiguration = null); +} diff --git a/src/Toolbox/TesterTool/Tester.cs b/src/Toolbox/TesterTool/Tester.cs new file mode 100644 index 00000000..b1a64242 --- /dev/null +++ b/src/Toolbox/TesterTool/Tester.cs @@ -0,0 +1,344 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.TesterTool.Guarders; +using Werecodent.CreateAndFake.TesterTool.Validators; + +namespace Werecodent.CreateAndFake.TesterTool; + +/// Automates common tests. +/// +/// If given a parameter. +public class Tester(TesterOptions options) : ITester +{ + /// + public TesterOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// Configures options to use for a test. + /// Modifications of to apply. + /// The options to use. + private TesterOptions Configure(TesterMod? optionConfiguration = null) + { + return optionConfiguration?.Invoke(Options) ?? Options; + } + + /// + public virtual void VerifyJsonSerialization(TesterMod? optionConfiguration = null) + { + new SerializationValidator(Configure(optionConfiguration)).VerifyJsonSerialization(); + } + + /// + public virtual void VerifyJsonSerialization( + T instance, + TesterMod? optionConfiguration = null + ) + { + new SerializationValidator(Configure(optionConfiguration)).VerifyJsonSerialization( + instance + ); + } + + /// + public virtual void VerifyXmlSerialization(TesterMod? optionConfiguration = null) + { + new SerializationValidator(Configure(optionConfiguration)).VerifyXmlSerialization(); + } + + /// + public virtual void VerifyXmlSerialization(T instance, TesterMod? optionConfiguration = null) + { + new SerializationValidator(Configure(optionConfiguration)).VerifyXmlSerialization(instance); + } + + /// + public virtual Task VerifyEqualsMatchesHashCodesAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return VerifyEqualsMatchesHashCodesAsync(typeof(T), canceler, optionConfiguration); + } + + /// + public virtual Task VerifyEqualsMatchesHashCodesAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new EqualityValidator( + Configure(optionConfiguration) + ).VerifyEqualsMatchesHashCodesAsync(type, canceler); + } + + /// + public virtual Task VerifyValueEqualityAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return VerifyValueEqualityAsync(typeof(T), canceler, optionConfiguration); + } + + /// + public virtual Task VerifyValueEqualityAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new EqualityValidator(Configure(optionConfiguration)).VerifyValueEqualityAsync( + type, + canceler + ); + } + + /// + public virtual Task VerifySupportsCancellationAsync( + Func> factory, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new CancelValidator(Configure(optionConfiguration)).VerifySupportsCancellationAsync( + factory, + canceler + ); + } + + /// + public virtual Task VerifySupportsCancellationAsync( + Func> factory, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new CancelValidator(Configure(optionConfiguration)).VerifySupportsCancellationAsync( + factory, + canceler + ); + } + + /// + public virtual Task PreventsNullRefExceptionAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return PreventsNullRefExceptionAsync(typeof(T), canceler, optionConfiguration); + } + + /// + public virtual Task PreventsNullRefExceptionAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + TesterOptions localOptions = Configure(optionConfiguration); + + return new NullGuarder(localOptions).PreventsNullRefExceptionAsync( + GenericFixer.FixType(type, localOptions), + canceler + ); + } + + /// + public virtual Task PreventsNullRefExceptionAsync( + T instance, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new NullGuarder(Configure(optionConfiguration)).PreventsNullRefExceptionAsync( + instance, + canceler + ); + } + + /// + public virtual Task PreventsParameterMutationAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return PreventsParameterMutationAsync(typeof(T), canceler, optionConfiguration); + } + + /// + public virtual Task PreventsParameterMutationAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + TesterOptions localOptions = Configure(optionConfiguration); + + return new MutationGuarder(localOptions).PreventsParameterMutationAsync( + GenericFixer.FixType(type, localOptions), + canceler + ); + } + + /// + public virtual Task PreventsParameterMutationAsync( + T instance, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new MutationGuarder(Configure(optionConfiguration)).PreventsParameterMutationAsync( + instance, + canceler + ); + } + + /// + public virtual Task PassthroughWithNoExceptionsAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new ExceptionGuarder( + Configure(optionConfiguration) + ).PassthroughWithNoExceptionsAsync(canceler); + } + + /// + public virtual Task PassthroughWithNoExceptionsAsync( + object instance, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new ExceptionGuarder( + Configure(optionConfiguration) + ).PassthroughWithNoExceptionsAsync(instance, canceler); + } + + /// + public virtual void ProvidesTestClassCoverage( + Assembly codeAssembly, + Assembly testAssembly, + TesterMod? optionConfiguration = null + ) + { + new TestValidator(Configure(optionConfiguration)).ProvidesTestClassCoverage( + codeAssembly, + testAssembly + ); + } + + /// + public virtual void VerifyTestMethodNaming( + IEnumerable testMarkers, + Assembly codeAssembly, + Assembly testAssembly, + TesterMod? optionConfiguration = null + ) + { + new TestValidator(Configure(optionConfiguration)).VerifyTestMethodNaming( + testMarkers, + codeAssembly, + testAssembly + ); + } + + /// + public void VerifyAllToStrings(Assembly codeAssembly, TesterMod? optionConfiguration = null) + { + new SupportValidator(Configure(optionConfiguration)).VerifyAllToStrings(codeAssembly); + } + + /// + public virtual Task ValidateRandomDataParametersAsync( + Assembly testAssembly, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new SupportValidator( + Configure(optionConfiguration) + ).ValidateRandomDataParametersAsync(testAssembly, canceler); + } + + /// + public virtual Task ValidateAutoTesterInstancesAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new SupportValidator( + Configure(optionConfiguration) + ).ValidateAutoTesterInstancesAsync(canceler); + } + + /// + public virtual Task ValidateTestSettingsConfigAsync( + string? environmentName, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + new SupportValidator(Configure(optionConfiguration)).VerifyTestSettingsConfig( + environmentName + ); + return Task.CompletedTask; + } + + /// + public virtual Task VerifyToolSetIntegrityAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new SupportValidator(Configure(optionConfiguration)).VerifyToolSetIntegrityAsync( + canceler + ); + } + + /// + public virtual Task VerifyToolSetSupportAsync( + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return VerifyToolSetSupportAsync(typeof(T), canceler, optionConfiguration); + } + + /// + public virtual Task VerifyToolSetSupportAsync( + Type type, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + ArgumentGuard.ThrowIfNull(type); + + return new SupportValidator(Configure(optionConfiguration)).VerifyToolSetSupportAsync( + type, + canceler + ); + } + + /// + public virtual Task VerifyToolSetSupportAsync( + IEnumerable types, + CancellationToken canceler, + TesterMod? optionConfiguration = null + ) + { + return new SupportValidator(Configure(optionConfiguration)).VerifyToolSetSupportAsync( + types, + canceler + ); + } + + /// + public ITester WithOptions(TesterMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Tester(optionConfiguration.Invoke(Options)); + } +} diff --git a/src/Toolbox/TesterTool/TesterOptions.cs b/src/Toolbox/TesterTool/TesterOptions.cs new file mode 100644 index 00000000..cb2e62a0 --- /dev/null +++ b/src/Toolbox/TesterTool/TesterOptions.cs @@ -0,0 +1,225 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.TesterTool; + +/// Configuration for manipulating behavior. +public sealed record TesterOptions : ToolOptions +{ + /// Identifies the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Tester); + + /// + public required IRandomizer Randomizer { get; init; } + + /// + public required IDuplicator Duplicator { get; init; } + + /// + public required IExtractor Extractor { get; init; } + + /// + public required IFaker Faker { get; init; } + + /// + public required IMutator Mutator { get; init; } + + /// + public required IAsserter Asserter { get; init; } + + /// + public required IRunner Runner { get; init; } + + /// + public required IValuer Valuer { get; init; } + + /// Values to inject into called methods. + /// + /// When generating randomized parameter data, these values will be used instead of randomized instances + /// when applicable. Per method, each value will only be used once and prioritized in the order given. + /// See: + /// + /// [] + public ImmutableArray InjectionValues { get; init; } = []; + + /// If constructors are included when running tests on classes. + /// + [ConfigurableOption] + public bool IncludeConstructors { get; init; } = true; + + /// If methods are included when running tests on classes. + /// + [ConfigurableOption] + public bool IncludeInstanceMethods { get; init; } = true; + + /// If methods are included when running tests on classes. + /// + [ConfigurableOption] + public bool IncludeStaticMethods { get; init; } = true; + + /// If members are included when running tests on classes. + /// + [ConfigurableOption] + public bool IncludeInternals { get; init; } = true; + + /// If only methods directly declared on the (not inherited) are tested. + /// + [ConfigurableOption] + public bool OnlyDeclaredMethods { get; init; } = false; + + /// If empty series should throw when canceled before iteration. + /// A preference for how methods should be implemented. + /// + [ConfigurableOption] + public bool ThrowsUponCancelWithEmptySeries { get; init; } = true; + + /// Common suffixes attached to class names used to name the test classes. + /// Used to correlate classes with their test classes for coverage tests. + /// ["Tests", "TestBase"] + [ConfigurableOption] + public ImmutableArray TestClassNameSuffixes { get; init; } = ["Tests", "TestBase"]; + + /// Possible s replacing generics in a 's name. + /// Used to help properly correlate classes with their test classes for coverage tests. + /// ["", "_T_"] + [ConfigurableOption] + public ImmutableArray TestClassNameGenericSubstitutes { get; init; } = ["", "_T_"]; + + /// Names of the s to ignore for coverage tests. + /// [] + [ConfigurableOption] + public FrozenSet ClassCoverageExclusions { get; init; } = []; + + /// Allowed targets for test method names. + /// These targets are in addition to the normally allowed test names. + /// [] + [ConfigurableOption] + public FrozenSet AllowedTestNamePrefixes { get; init; } = []; + + /// If a target is required for a test method name. + /// The target is the text preceding the first '_' in the test name. + /// + [ConfigurableOption] + public bool RequirePrefixInTestName { get; init; } = true; + + /// Names of methods to skip when running tests on classes. + /// + /// Useful for preventing execution of methods that should be tested + /// manually or leave an instance in a bad state for other methods. + /// + /// ["Close", "Dispose", "Finalize", "DisposeAsync", "PrintMembers", "GetObjectData"] + [ConfigurableOption] + public FrozenSet MethodsToIgnore { get; init; } = + FrozenSet.ToFrozenSet([ + "Close", + "Dispose", + "Finalize", + "DisposeAsync", + "PrintMembers", + "GetObjectData", + ]); + + /// + /// If methods marked with are skipped when running tests on classes. + /// + /// Alternative to specifying them individually via . + /// + [ConfigurableOption] + public bool IgnoreObsoleteMethods { get; init; } = true; + + /// If all thrown s are ignored when running tests on classes. + /// Alternative to specifying them individually via . + /// + [ConfigurableOption] + public bool IgnoreAllExceptions { get; init; } = false; + + /// Exceptions that are safe to ignore when running tests on classes. + /// Ignored when is set to . + /// [] + [ConfigurableOption] + public FrozenSet IgnorableExceptions { get; init; } = FrozenSet.ToFrozenSet([]); + + /// Flag for disabling PreventsNullRefException tests. + /// Useful for debugging. Causes the tests to immediately pass instead of running. + /// + [ConfigurableOption] + public bool DisableNullRefExceptionTests { get; init; } = false; + + /// Flag for disabling PreventsParameterMutation tests. + /// Useful for debugging. Causes the tests to immediately pass instead of running. + /// + [ConfigurableOption] + public bool DisableParameterMutationTests { get; init; } = false; + + /// Flag for disabling PassthroughWithNoExceptions tests. + /// Useful for debugging. Causes the tests to immediately pass instead of running. + /// + [ConfigurableOption] + public bool DisablePassthroughTests { get; init; } = false; + + /// Flag for disabling ToolSetSupport tests. + /// Useful for debugging. Causes the tests to immediately pass instead of running. + /// + [ConfigurableOption] + public bool DisableToolSetSupportTests { get; init; } = false; + + /// s to be excluded for VerifyToolSetIntegrity tests. + /// Useful for ignoring known incompatible s. + /// [] + [ConfigurableOption] + public FrozenSet IntegrityIgnorableTypes { get; init; } = FrozenSet.ToFrozenSet([]); + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal TesterOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + DisableParameterMutationTests = Config.GetValue(section, DisableParameterMutationTests), + DisableNullRefExceptionTests = Config.GetValue(section, DisableNullRefExceptionTests), + DisableToolSetSupportTests = Config.GetValue(section, DisableToolSetSupportTests), + DisablePassthroughTests = Config.GetValue(section, DisablePassthroughTests), + IntegrityIgnorableTypes = Config.GetTypes(section, IntegrityIgnorableTypes), + RequirePrefixInTestName = Config.GetValue(section, RequirePrefixInTestName), + AllowedTestNamePrefixes = Config.GetSet(section, AllowedTestNamePrefixes), + ClassCoverageExclusions = Config.GetSet(section, ClassCoverageExclusions), + IncludeInstanceMethods = Config.GetValue(section, IncludeInstanceMethods), + IgnoreObsoleteMethods = Config.GetValue(section, IgnoreObsoleteMethods), + TestClassNameSuffixes = Config.GetArray(section, TestClassNameSuffixes), + IncludeStaticMethods = Config.GetValue(section, IncludeStaticMethods), + IgnoreAllExceptions = Config.GetValue(section, IgnoreAllExceptions), + IncludeConstructors = Config.GetValue(section, IncludeConstructors), + OnlyDeclaredMethods = Config.GetValue(section, OnlyDeclaredMethods), + IgnorableExceptions = Config.GetTypes(section, IgnorableExceptions), + IncludeInternals = Config.GetValue(section, IncludeInternals), + InjectionValues = Config.GetValue(section, InjectionValues), + MethodsToIgnore = Config.GetSet(section, MethodsToIgnore), + ThrowsUponCancelWithEmptySeries = Config.GetValue( + section, + ThrowsUponCancelWithEmptySeries + ), + TestClassNameGenericSubstitutes = Config.GetArray( + section, + TestClassNameGenericSubstitutes + ), + }; + } +} diff --git a/src/Toolbox/TesterTool/Validators/CancelValidator.cs b/src/Toolbox/TesterTool/Validators/CancelValidator.cs new file mode 100644 index 00000000..e56251f3 --- /dev/null +++ b/src/Toolbox/TesterTool/Validators/CancelValidator.cs @@ -0,0 +1,145 @@ +using System.Diagnostics.CodeAnalysis; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.TesterTool.Validators; + +#pragma warning disable CS8425 // Configured as given for testing. + +/// Automates common tests. +/// +/// If given a parameter. +internal sealed class CancelValidator(TesterOptions options) +{ + /// + internal TesterOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + public Task VerifySupportsCancellationAsync( + Func> factory, + CancellationToken canceler + ) + { + return VerifyUsesWithCancellationAsync((size, _) => factory(size), canceler); + } + + public async Task VerifySupportsCancellationAsync( + Func> factory, + CancellationToken canceler + ) + { + await VerifyUsesGivenCancellationTokenAsync(factory, canceler).ConfigureAwait(false); + await VerifyUsesWithCancellationAsync(factory, canceler).ConfigureAwait(false); + } + + private Task VerifyUsesWithCancellationAsync( + Func> factory, + CancellationToken canceler + ) + { + [ExcludeFromCodeCoverage] // Generated await foreach code can only be partially covered. + async IAsyncEnumerable iterateUsingForeachAsync(int size, int cancelPoint) + { + using CancellationTokenSource source = CancellationTokenSource.CreateLinkedTokenSource( + canceler + ); + + if (cancelPoint == 0) + { + await AsyncSeriesHelper.TriggerCancellationAsync(source).ConfigureAwait(false); + } + + int i = 0; + await foreach ( + T item in factory + .Invoke(size, canceler) + .WithCancellation(source.Token) + .ConfigureAwait(false) + ) + { + yield return item; + + if (++i == cancelPoint) + { + await AsyncSeriesHelper.TriggerCancellationAsync(source).ConfigureAwait(false); + } + } + } + + return RunCancelTestsAsync(iterateUsingForeachAsync, "using WithCancellation", canceler); + } + + private Task VerifyUsesGivenCancellationTokenAsync( + Func> factory, + CancellationToken canceler + ) + { + [ExcludeFromCodeCoverage] // Generated await foreach code can only be partially covered. + async IAsyncEnumerable iterateUsingForeachAsync(int size, int cancelPoint) + { + using CancellationTokenSource source = CancellationTokenSource.CreateLinkedTokenSource( + canceler + ); + + if (cancelPoint == 0) + { + await AsyncSeriesHelper.TriggerCancellationAsync(source).ConfigureAwait(false); + } + + int i = 0; + await foreach (T item in factory.Invoke(size, source.Token).ConfigureAwait(false)) + { + yield return item; + + if (++i == cancelPoint) + { + await AsyncSeriesHelper.TriggerCancellationAsync(source).ConfigureAwait(false); + } + } + } + + return RunCancelTestsAsync(iterateUsingForeachAsync, "given a token directly", canceler); + } + + private async Task RunCancelTestsAsync( + Func> modifiedTestFactory, + string testNote, + CancellationToken canceler + ) + { + Task runThrowTestAsync(int size, int cancelPoint) + { + return options.Asserter.ThrowsAsync( + modifiedTestFactory(size, cancelPoint), + canceler, + $"ThrowIfCancellationRequested() missing when {testNote}: Size={size}, Cancellation Point={cancelPoint}" + ); + } + + Task runPassTestAsync(int size, int cancelPoint) + { + return options.Asserter.HasCountAsync( + size, + modifiedTestFactory(size, cancelPoint), + canceler, + $"Results should be returned fully when {testNote}: Size={size}, Cancellation Point={cancelPoint}" + ); + } + + if (Options.ThrowsUponCancelWithEmptySeries) + { + await runThrowTestAsync(0, 0).ConfigureAwait(false); + } + else + { + await runPassTestAsync(0, 0).ConfigureAwait(false); + } + + await runThrowTestAsync(1, 0).ConfigureAwait(false); + await runThrowTestAsync(2, 1).ConfigureAwait(false); + + await runPassTestAsync(1, 1).ConfigureAwait(false); + await runPassTestAsync(2, 2).ConfigureAwait(false); + } +} + +#pragma warning restore diff --git a/src/Toolbox/TesterTool/Validators/EqualityValidator.cs b/src/Toolbox/TesterTool/Validators/EqualityValidator.cs new file mode 100644 index 00000000..74486293 --- /dev/null +++ b/src/Toolbox/TesterTool/Validators/EqualityValidator.cs @@ -0,0 +1,212 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.TesterTool.Validators; + +/// Automates common tests. +/// +/// If given a parameter. +internal sealed class EqualityValidator(TesterOptions options) +{ + /// + internal TesterOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public Task VerifyEqualsMatchesHashCodesAsync(Type type, CancellationToken canceler) + { + return VerifyValueEqualityAsync(type, false, canceler); + } + + /// + public Task VerifyValueEqualityAsync(Type type, CancellationToken canceler) + { + return VerifyValueEqualityAsync(type, true, canceler); + } + + private Task VerifyValueEqualityAsync( + Type type, + bool mustIncludeAllValues, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(type); + + TypeDescriber describer = TypeDescriber.For(type); + + if (describer.Inherits()) + { + IValuerAsyncComparable x = (IValuerAsyncComparable)Options.Randomizer.Create(type); + IValuerAsyncComparable y = Options.Duplicator.Copy(x); + return VerifyValueEqualityAsync( + describer, + x, + y, + async z => + ( + await AsyncSeriesHelper + .ToListAsync( + x.CompareAsync(z, Options.Valuer, canceler), + Options.Design.IterationLimit, + canceler + ) + .ConfigureAwait(false) + ).Count == 0, + async z => + ( + await AsyncSeriesHelper + .ToListAsync( + y.CompareAsync(z, Options.Valuer, canceler), + Options.Design.IterationLimit, + canceler + ) + .ConfigureAwait(false) + ).Count == 0, + () => x.GetValueHashAsync(Options.Valuer, canceler), + () => y.GetValueHashAsync(Options.Valuer, canceler), + mustIncludeAllValues, + canceler + ); + } + else if (describer.Inherits()) + { + IValuerEquatable x = (IValuerEquatable)Options.Randomizer.Create(type); + IValuerEquatable y = Options.Duplicator.Copy(x); + return VerifyValueEqualityAsync( + describer, + x, + y, + z => Task.FromResult(x.ValuesEqual(z, Options.Valuer)), + z => Task.FromResult(y.ValuesEqual(z, Options.Valuer)), + () => Task.FromResult(x.GetValueHash(Options.Valuer)), + () => Task.FromResult(y.GetValueHash(Options.Valuer)), + mustIncludeAllValues, + canceler + ); + } + else if (describer.Inherits()) + { + IValueEquatable x = (IValueEquatable)Options.Randomizer.Create(type); + IValueEquatable y = Options.Duplicator.Copy(x); + return VerifyValueEqualityAsync( + describer, + x, + y, + z => Task.FromResult(x.ValuesEqual(z)), + z => Task.FromResult(y.ValuesEqual(z)), + () => Task.FromResult(x.GetValueHash()), + () => Task.FromResult(y.GetValueHash()), + mustIncludeAllValues, + canceler + ); + } + else + { + object x = Options.Randomizer.Create(type); + object y = Options.Duplicator.Copy(x); + return VerifyValueEqualityAsync( + describer, + x, + y, + z => Task.FromResult(x.Equals(z)), + z => Task.FromResult(y.Equals(z)), + () => Task.FromResult(x.GetHashCode()), + () => Task.FromResult(y.GetHashCode()), + mustIncludeAllValues, + canceler + ); + } + } + + private async Task VerifyValueEqualityAsync( + TypeDescriber describer, + object x, + object y, + Func> xEquals, + Func> yEquals, + Func> xGetHash, + Func> yGetHash, + bool mustIncludeAllValues, + CancellationToken canceler + ) + { + Options.Asserter.Is( + true, + await xEquals(y).ConfigureAwait(false) && await yEquals(x).ConfigureAwait(false), + $"Equality for type '{GenericConverter.ExpandName(describer.SupportedType)}' failed with clone." + ); + Options.Asserter.Is( + await xGetHash().ConfigureAwait(false), + await yGetHash().ConfigureAwait(false), + $"Hash codes for type '{GenericConverter.ExpandName(describer.SupportedType)}' failed with clone." + ); + + async Task switchValueAsync(MemberInfo member, object? originalValue, object? newValue) + { + string originalAsText = $"{originalValue ?? "default"}"; + string newAsText = $"{newValue ?? "default"}"; + + ((dynamic)member).SetValue(x, newValue); + if (mustIncludeAllValues) + { + Options.Asserter.Is( + false, + await xEquals(y).ConfigureAwait(false) + || await yEquals(x).ConfigureAwait(false), + $"Equality for type '{GenericConverter.ExpandName(describer.SupportedType)}' failed to" + + $" differ when modifying '{member.Name}' from '{originalAsText}' -> '{newAsText}'." + ); + } + else + { + Options.Asserter.Is( + await xEquals(y).ConfigureAwait(false), + await yEquals(x).ConfigureAwait(false), + $"Equality result for type '{GenericConverter.ExpandName(describer.SupportedType)}'" + + $" mismatched when modifying '{member.Name}' from '{originalAsText}' -> '{newAsText}'." + ); + } + + ((dynamic)member).SetValue(y, newValue); + Options.Asserter.Is( + true, + await xEquals(y).ConfigureAwait(false) && await yEquals(x).ConfigureAwait(false), + $"Equality for type '{GenericConverter.ExpandName(describer.SupportedType)}' failed to" + + $" equal when modifying '{member.Name}' from '{originalAsText}' -> '{newAsText}'." + ); + + Options.Asserter.Is( + await xGetHash().ConfigureAwait(false), + await yGetHash().ConfigureAwait(false), + $"Hash codes for type '{GenericConverter.ExpandName(describer.SupportedType)}' failed to" + + $" equal when modifying '{member.Name}' from '{originalAsText}' -> '{newAsText}'." + ); + } + + foreach (PropertyInfo prop in describer.Properties.SetAndGetable) + { + object? originalValue = prop.GetValue(x); + object newValue = await Options + .Mutator.VariantAsync(prop.PropertyType, originalValue, canceler) + .ConfigureAwait(false); + + await switchValueAsync(prop, originalValue, null).ConfigureAwait(false); + await switchValueAsync(prop, null, newValue).ConfigureAwait(false); + } + + foreach (FieldInfo field in describer.Fields.Writable.Where(f => f.IsPublic)) + { + object? originalValue = field.GetValue(x); + object newValue = await Options + .Mutator.VariantAsync(field.FieldType, originalValue, canceler) + .ConfigureAwait(false); + + await switchValueAsync(field, originalValue, null).ConfigureAwait(false); + await switchValueAsync(field, null, newValue).ConfigureAwait(false); + } + } +} diff --git a/src/Toolbox/TesterTool/Validators/SerializationValidator.cs b/src/Toolbox/TesterTool/Validators/SerializationValidator.cs new file mode 100644 index 00000000..5f301ae7 --- /dev/null +++ b/src/Toolbox/TesterTool/Validators/SerializationValidator.cs @@ -0,0 +1,113 @@ +using System.Collections; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ExtractorTool; + +namespace Werecodent.CreateAndFake.TesterTool.Validators; + +/// Automates common tests. +/// +/// If given a parameter. +internal sealed class SerializationValidator(TesterOptions options) +{ + /// Internal type needed for AggregateException serialization. + private static readonly Type _ListDictionaryInternalType = typeof(IDictionary).Assembly.GetType( + "System.Collections.ListDictionaryInternal" + )!; + + /// + internal TesterOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public void VerifyJsonSerialization() + { + VerifyJsonSerialization(Options.Randomizer.Create()); + } + + /// + public void VerifyJsonSerialization(T instance) + { + VerifyJsonSerialization(typeof(T), instance); + } + + /// The for testing. + /// + private void VerifyJsonSerialization(Type type, object? instance) + { + DataContractJsonSerializer serializer = new(type, FindExtraKnownTypes(instance)); + + VerifySerialization(type, instance, serializer); + } + + /// + public void VerifyXmlSerialization() + { + VerifyXmlSerialization(Options.Randomizer.Create()); + } + + /// + public void VerifyXmlSerialization(T instance) + { + VerifyXmlSerialization(typeof(T), instance); + } + + /// The for testing. + /// + private void VerifyXmlSerialization(Type type, object? instance) + { + IContentMap contents = Options.Extractor.Extract(instance); + DataContractSerializer serializer = new( + type, + contents.Select(d => d.GetType()).Concat(FindExtraKnownTypes(instance)).Distinct() + ); + + VerifySerialization(type, instance, serializer); + } + + /// Finds known types needed for specific types. + /// Object being serialized. + /// Known types to add. + private static IEnumerable FindExtraKnownTypes(object? source) + { + if (source is Exception e) + { + yield return typeof(Exception[]); + yield return _ListDictionaryInternalType; + + if (e.InnerException != null) + { + yield return e.InnerException.GetType(); + } + } + } + + /// The for testing. + /// + private void VerifySerialization(Type type, object? instance, XmlObjectSerializer serializer) + { + using MemoryStream stream = new(); + object? result; + try + { + serializer.WriteObject(stream, instance); + stream.Position = 0; + result = serializer.ReadObject(stream); + } + catch (Exception e) + { + throw new TesterFailureException( + $"Ran into problem trying to serialize type '{GenericConverter.ExpandName(type)}'.", + e + ); + } + + Options.Asserter.Is( + result, + instance, + $"Instance of type '{GenericConverter.ExpandName(type)}' did not deserialize with the same values." + ); + } +} diff --git a/src/Toolbox/TesterTool/Validators/SupportValidator.cs b/src/Toolbox/TesterTool/Validators/SupportValidator.cs new file mode 100644 index 00000000..4c5ccf54 --- /dev/null +++ b/src/Toolbox/TesterTool/Validators/SupportValidator.cs @@ -0,0 +1,335 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.RunnerTool.Attributes; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.TesterTool.Validators; + +/// Automates common tests. +/// +/// If given a parameter. +internal sealed class SupportValidator(TesterOptions options) +{ + /// + internal TesterOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public void VerifyAllToStrings(Assembly codeAssembly) + { + ArgumentGuard.ThrowIfNull(codeAssembly); + + Options.Asserter.Debug( + ScopeChecker + .FindLoadedSpecificTypes(codeAssembly) + .Where(t => !t.IsAbstract) + .Where(t => ScopeChecker.IsVisible(t, Assembly.GetExecutingAssembly().GetName())) + .ToDictionary(GenericConverter.ExpandName, t => + { + try + { + return Options.Randomizer.Create(t); + } + catch (ToolException) + { + return null; + } + }) + ); + } + + /// + public void VerifyTestSettingsConfig(string? environmentName) + { + IConfigurationSection config = ToolSet.GetConfig(false, environmentName); + ToolSet asConfigured = ToolSet.Create(0, config); + + Dictionary configuredOptions = new() + { + { ConfiguredDesignOptions.ConfigSectionName, asConfigured.Valuer.Options.Design }, + { AsserterOptions.ConfigSectionName, asConfigured.Asserter.Options }, + { DuplicatorOptions.ConfigSectionName, asConfigured.Duplicator.Options }, + { ExtractorOptions.ConfigSectionName, asConfigured.Extractor.Options }, + { FakerOptions.ConfigSectionName, asConfigured.Faker.Options }, + { MutatorOptions.ConfigSectionName, asConfigured.Mutator.Options }, + { RandomizerOptions.ConfigSectionName, asConfigured.Randomizer.Options }, + { RunnerOptions.ConfigSectionName, asConfigured.Runner.Options }, + { ValuerOptions.ConfigSectionName, asConfigured.Valuer.Options }, + { TesterOptions.ConfigSectionName, asConfigured.Tester.Options }, + }; + + Options.Asserter.IsEmpty( + config.GetChildren().Select(c => c.Key).Except(configuredOptions.Keys), + $"Configuration '{nameof(CreateAndFake)}' had extra settings that do not match an actual setting." + ); + + foreach (KeyValuePair pair in configuredOptions) + { + VerifyNoBadConfigValues(pair.Value, pair.Key, config); + } + } + + private void VerifyNoBadConfigValues( + object options, + string configSectionName, + IConfigurationSection config + ) + { + Options.Asserter.IsEmpty( + config + .GetSection(configSectionName) + .GetChildren() + .Select(c => c.Key) + .Except( + TypeDescriber + .For(options.GetType()) + .Properties.OnlyPublic.Where(p => + Attribute.IsDefined(p, typeof(ConfigurableOptionAttribute)) + ) + .Select(p => p.Name) + ), + $"Configuration '{configSectionName}' had extra settings that do not match an actual setting." + ); + } + + /// + [ExcludeFromCodeCoverage] // Any known fail cases are to be fixed. + public async Task ValidateAutoTesterInstancesAsync(CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(canceler); + + Dictionary failures = []; + foreach ( + Type type in TypeDescriber + .For(typeof(BaseAutoTester<>)) + .FindLoadedSubclasses() + .Where(t => !t.IsAbstract) + ) + { + ConstructorInfo? constructor = type.GetConstructor([]); + if (constructor != null) + { + try + { + _ = await Options + .Runner.RunAsync( + constructor.Invoke([]), + type.GetMethod( + "get_TestInstance", + BindingFlags.NonPublic | BindingFlags.Instance + )!, + canceler + ) + .ConfigureAwait(false); + } + catch (Exception e) + { + failures.Add(type, e); + } + } + } + + Options.Asserter.IsEmpty(failures, "Randomization failed for 'TestInstance'."); + } + + /// + [ExcludeFromCodeCoverage] // Any known fail cases are to be fixed. + public async Task ValidateRandomDataParametersAsync( + Assembly testAssembly, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(testAssembly, canceler); + + IEnumerable testMethods = ScopeChecker + .FindLoadedTypes(testAssembly) + .Where(t => !t.IsGenericType) + .Select(TypeDescriber.For) + .SelectMany(d => d.Methods.PublicOrInternal.Concat(d.StaticMethods.PublicOrInternal)) + .Where(m => + !m.IsGenericMethod && m.GetCustomAttributes(true).Any(a => a is IRandomDataMarker) + ); + + List generatedData = []; + + Dictionary failures = []; + foreach (MethodInfo method in testMethods.OrderBy(m => m.Name)) + { + MethodCallWrapper? data = null; + try + { + data = await Options.Runner.CreateForAsync(method, canceler).ConfigureAwait(false); + generatedData.Add(data.ToString()); + } + catch (Exception e) + { + failures.Add(method, e); + } + finally + { + await Disposer.CleanupAsync(data?.Args).ConfigureAwait(false); + } + } + + Options.Asserter.IsEmpty(failures, "Randomization failed for test methods."); + Options.Asserter.Debug(generatedData, "All generated data for random data parameters."); + } + + /// + public Task VerifyToolSetIntegrityAsync(CancellationToken canceler) + { + return VerifyToolSetSupportAsync( + Enumerable + .Empty() + .Concat(Tools.Randomizer.SupportedTypes) + .Concat(Tools.Duplicator.SupportedTypes) + .Concat(Tools.Extractor.SupportedTypes) + .Concat(Tools.Mutator.SupportedTypes) + .Concat(Tools.Valuer.SupportedTypes) + .Concat(Tools.Faker.SupportedTypes), + canceler + ); + } + + /// + [ExcludeFromCodeCoverage] // Any known fail cases are to be fixed. + public async Task VerifyToolSetSupportAsync(IEnumerable types, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(types, canceler); + + Type[] testTypes = + [ + .. types + .Where(t => !Options.IntegrityIgnorableTypes.Contains(t)) + .Where(t => t != typeof(TypeDescriber)) + .Distinct(), + ]; + + Dictionary failures = []; + for (int i = 0; i < testTypes.Length; i++) + { + try + { + await VerifyToolSetSupportAsync(testTypes[i], canceler).ConfigureAwait(false); + } + catch (Exception e) + { + failures.Add(testTypes[i], e); + } + } + Options.Asserter.IsEmpty(failures, "Not all types were supported as expected."); + } + + /// Validates the is fully compatible with the framework as configured. + /// The to test with. + /// + public async Task VerifyToolSetSupportAsync(Type type, CancellationToken canceler) + { + ArgumentGuard.ThrowIfNull(type, canceler); + + if (Options.DisableToolSetSupportTests) + { + return; + } + + object? original = null, + variant = null, + dupe = null; + try + { + if (Options.InjectionValues.Length > 0) + { + original = Options.Randomizer.Inject(type, Options.InjectionValues); + } + else + { + original = Options.Randomizer.Create(type); + } + + if (original is IFaked) + { + return; + } + + dupe = Options.Duplicator.Copy(original); + + string failMessage = + "Behavior did not work for type '" + + GenericConverter.ExpandName(type) + + $"' randomized to '{GenericConverter.ExpandName(original)}'."; + + await Options + .Asserter.ValuesEqualAsync( + original, + dupe, + canceler, + failMessage + " Cloned data was not equal." + ) + .ConfigureAwait(false); + + Options.Asserter.Is( + original.GetType(), + dupe.GetType(), + failMessage + + $" Cloned type '{GenericConverter.ExpandName(dupe.GetType())}' mismatch." + ); + + if ( + type.IsAbstract + || TypeDescriber.For(type).IsMutable() + || TypeDescriber.For(type).HasInitializableOnlyState() + || (!type.IsSealed && TypeDescriber.For(type).FindLoadedSubclasses().Skip(1).Any()) + ) + { + variant = await Options + .Mutator.VariantAsync(type, original, canceler) + .ConfigureAwait(false); + + await Options + .Asserter.ValuesNotEqualAsync( + original, + variant, + canceler, + failMessage + " Variant data was still equal." + ) + .ConfigureAwait(false); + } + + if (Options.Mutator.Modify(original)) + { + await Options + .Asserter.ValuesNotEqualAsync( + dupe, + original, + canceler, + failMessage + " Modified data was still equal." + ) + .ConfigureAwait(false); + } + + if (Options.Faker.Supports(type) && !type.Inherits()) + { + _ = Options.Faker.Mock(type); + } + } + finally + { + await Disposer.CleanupAsync(original, variant, dupe).ConfigureAwait(false); + } + } +} diff --git a/src/Toolbox/TesterTool/Validators/TestValidator.cs b/src/Toolbox/TesterTool/Validators/TestValidator.cs new file mode 100644 index 00000000..cabef2a7 --- /dev/null +++ b/src/Toolbox/TesterTool/Validators/TestValidator.cs @@ -0,0 +1,225 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Reflection; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.TesterTool.Validators; + +/// Automates common tests. +/// +/// If given a parameter. +internal sealed class TestValidator(TesterOptions options) +{ + /// + internal TesterOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public void ProvidesTestClassCoverage(Assembly codeAssembly, Assembly testAssembly) + { + ArgumentGuard.ThrowIfNull(codeAssembly, testAssembly); + + FrozenSet testClasses = testAssembly.GetTypes().Select(t => t.Name).ToFrozenSet(); + + Options.Asserter.IsEmpty( + ScopeChecker + .FindLoadedSpecificTypes(codeAssembly) + .Where(t => !t.IsAbstract || t.IsSealed) + .Where(t => t.Namespace != null) + .Where(t => ScopeChecker.IsVisible(t, testAssembly.GetName())) + .Where(t => FindPossibleTestClassNames(t).All(name => !testClasses.Contains(name))) + .Where(t => !Options.ClassCoverageExclusions.Contains(t.Name)) + .Where(t => !t.Inherits()) + .Where(t => + !t.Namespace!.StartsWith("Microsoft.CodeCoverage", StringComparison.Ordinal) + ) + .Where(t => + !t.Namespace!.StartsWith( + "Coverlet.Core.Instrumentation.Tracker", + StringComparison.Ordinal + ) + ), + $"Missing tests for classes from {codeAssembly} in {testAssembly}." + ); + } + + private IEnumerable FindPossibleTestClassNames(Type codeClass) + { + if ( + codeClass.IsGenericTypeDefinition + && codeClass.Name.Contains("`", StringComparison.Ordinal) + ) + { + string baseName = codeClass.Name.Substring( + 0, + codeClass.Name.IndexOf("`", StringComparison.Ordinal) + ); + + return Options.TestClassNameSuffixes.SelectMany(suffix => + Options.TestClassNameGenericSubstitutes.Select(sub => baseName + sub + suffix) + ); + } + else + { + return Options.TestClassNameSuffixes.Select(suffix => codeClass.Name + suffix); + } + } + + /// + internal void VerifyTestMethodNaming( + IEnumerable testMarkers, + Assembly codeAssembly, + Assembly testAssembly + ) + { + ArgumentGuard.ThrowIfNull(testMarkers, codeAssembly, testAssembly); + + List markers = [.. testMarkers]; + + static string stripGeneric(Type codeClass) + { + if ( + codeClass.IsGenericTypeDefinition + && codeClass.Name.Contains("`", StringComparison.Ordinal) + ) + { + return codeClass.Name.Substring( + 0, + codeClass.Name.IndexOf("`", StringComparison.Ordinal) + ); + } + else + { + return codeClass.Name; + } + } + + static string getTarget(string testName) + { + string cleanedName = testName.StartsWith("Debug_", StringComparison.Ordinal) + ? testName.Substring(6) + : testName; + + if (cleanedName.Contains("_", StringComparison.Ordinal)) + { + return cleanedName.Substring(0, cleanedName.IndexOf("_", StringComparison.Ordinal)); + } + else if (testName.Contains("_", StringComparison.Ordinal)) + { + return testName.Substring(0, testName.IndexOf("_", StringComparison.Ordinal)); + } + else + { + return "?"; + } + } + + static IEnumerable getAllTypeNames(Type? codeClass) + { + if (codeClass == null || codeClass == typeof(object)) + { + yield return "Object"; + } + else + { + yield return codeClass.Name; + foreach (string name in getAllTypeNames(codeClass.BaseType)) + { + yield return name; + } + } + } + + ImmutableHashSet globalValidTargets = + [ + .. Options.AllowedTestNamePrefixes, + "New", + "Tester", + codeAssembly.GetName()!.Name!, + testAssembly.GetName()!.Name!, + ]; + + List>>> testsByTargetByClass = + [ + .. ScopeChecker + .FindLoadedSpecificTypes(testAssembly) + .Where(t => t != null) + .Select(TypeDescriber.For) + .Select(t => + Tuple.Create( + stripGeneric(t.SupportedType!), + t.Methods.PublicOrInternal.Concat(t.StaticMethods.PublicOrInternal) + .Where(m => markers.Exists(marker => Attribute.IsDefined(m, marker))) + .Select(m => m.Name) + .GroupBy(n => getTarget(n)) + .Where(g => + !( + t.SupportedType!.Name.Contains(g.Key, StringComparison.Ordinal) + || globalValidTargets.Contains(g.Key) + || (g.Key == "?" && !Options.RequirePrefixInTestName) + ) + ) + .ToDictionary(g => g.Key, g => g.ToList()) + ) + ), + ]; + + foreach ( + Type codeClass in codeAssembly + .GetTypes() + .Where(t => t != null) + .Where(t => !Attribute.IsDefined(t, typeof(CompilerGeneratedAttribute))) + ) + { + ImmutableHashSet methods = codeClass.IsEnum + ? [.. Enum.GetNames(codeClass), .. getAllTypeNames(codeClass), "Values"] + : + [ + .. getAllTypeNames(codeClass), + .. codeClass + .GetMembers( + BindingFlags.Instance + | BindingFlags.Static + | BindingFlags.Public + | BindingFlags.NonPublic + ) + .Select(m => m.Name) + .Select(n => + n.Contains("`", StringComparison.Ordinal) + ? n.Substring(0, n.IndexOf("`", StringComparison.Ordinal)) + : n + ), + ]; + + List possibleNames = + [ + .. FindPossibleTestClassNames(codeClass) + .SelectMany(name => + name.StartsWith("I", StringComparison.Ordinal) + ? new List() { name, name.Substring(1) } + : [name] + ), + ]; + + for (int i = 0; i < testsByTargetByClass.Count; i++) + { + if (possibleNames.Contains(testsByTargetByClass[i].Item1)) + { + foreach (string validTarget in methods) + { + _ = testsByTargetByClass[i].Item2.Remove(validTarget); + } + } + } + } + + Options.Asserter.IsEmpty( + testsByTargetByClass.SelectMany(t => + t.Item2.Values.SelectMany(x => x).Select(v => t.Item1 + " - " + v) + ), + $"Invalid test methods for classes from {codeAssembly} in {testAssembly}." + ); + } +} diff --git a/src/Toolbox/ToolSet.cs b/src/Toolbox/ToolSet.cs new file mode 100644 index 00000000..121aa28d --- /dev/null +++ b/src/Toolbox/ToolSet.cs @@ -0,0 +1,241 @@ +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake; + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +public sealed class ToolSet( + IRandom gen, + IValuer valuer, + IFaker faker, + IRandomizer randomizer, + IExtractor extractor, + IMutator mutator, + IAsserter asserter, + IDuplicator duplicator, + IRunner runner, + ITester tester +) : IToolSet +{ + /// For loading environment specific settings. + private static readonly string _EnvironmentName = FindEnvironmentName(); + + /// Finds the configured environment name. + /// The name if found, Production otherwise. + internal static string FindEnvironmentName() + { + IConfigurationRoot config = new ConfigurationBuilder().AddEnvironmentVariables().Build(); + + return config.GetValue("ASPNETCORE_ENVIRONMENT") + ?? config.GetValue("DOTNET_ENVIRONMENT") + ?? "Production"; + } + + /// Default tools to use. + public static ToolSet DefaultSet { get; } = CreateViaConfig(); + + /// Retrieves the configuration used in the given environment. + /// If the files are not required to be present. + /// Name for the environment to retrieve settings for. + /// The found configuration. + internal static IConfigurationSection GetConfig( + bool optional, + params IEnumerable environments + ) + { + ConfigurationBuilder builder = new(); + + foreach (string? environment in environments?.Distinct() ?? [null]) + { + if (environment == null) + { + _ = builder.AddJsonFile("testsettings.json", optional); + } + else + { + _ = builder.AddJsonFile($"testsettings.{environment}.json", optional); + } + } + + return builder.Build().GetSection(nameof(CreateAndFake)); + } + + /// Creates all the reflection tools using configuration settings. + /// The created reflection tools. + public static ToolSet CreateViaConfig() + { + return Create(null, GetConfig(true, null, _EnvironmentName)); + } + + /// Creates all the reflection tools using . + /// + /// The created reflection tools. + public static ToolSet CreateViaSeed(int seed) + { + return Create(seed, null); + } + + /// Creates all the reflection tools using the seed and configuration settings. + /// + /// Loaded configuration to use. + /// The created reflection tools. + internal static ToolSet Create(int? seed, IConfigurationSection? config) + { + ConfiguredDesignOptions commonOptions = new ConfiguredDesignOptions().WithConfig(config); + + IRandom gen = new SeededRandom( + commonOptions.IterationLimit, + !commonOptions.IncludeInfinityAndNaNGeneration, + (seed ?? commonOptions.Seed) ?? Environment.TickCount + ); + + Valuer valuer = new( + new ValuerOptions { Design = commonOptions, Gen = gen }.WithConfig(config) + ); + Faker faker = new( + new FakerOptions + { + Design = commonOptions, + Gen = gen, + Valuer = valuer, + }.WithConfig(config) + ); + Randomizer randomizer = new( + new RandomizerOptions + { + Design = commonOptions, + Gen = gen, + Valuer = valuer, + Faker = faker, + }.WithConfig(config) + ); + Extractor extractor = new( + new ExtractorOptions + { + Design = commonOptions, + Gen = gen, + Valuer = valuer, + }.WithConfig(config) + ); + Mutator mutator = new( + new MutatorOptions + { + Design = commonOptions, + Gen = gen, + Randomizer = randomizer, + Valuer = valuer, + Extractor = extractor, + }.WithConfig(config) + ); + Asserter asserter = new( + new AsserterOptions + { + Design = commonOptions, + Gen = gen, + Extractor = extractor, + Valuer = valuer, + }.WithConfig(config) + ); + Duplicator duplicator = new( + new DuplicatorOptions + { + Design = commonOptions, + Gen = gen, + Asserter = asserter, + Extractor = extractor, + }.WithConfig(config) + ); + Runner runner = new( + new RunnerOptions + { + Design = commonOptions, + Gen = gen, + Faker = faker, + Randomizer = randomizer, + Mutator = mutator, + Duplicator = duplicator, + }.WithConfig(config) + ); + Tester tester = new( + new TesterOptions + { + Design = commonOptions, + Gen = gen, + Randomizer = randomizer, + Mutator = mutator, + Faker = faker, + Duplicator = duplicator, + Extractor = extractor, + Asserter = asserter, + Runner = runner, + Valuer = valuer, + }.WithConfig(config) + ); + + return new ToolSet( + gen, + valuer, + faker, + randomizer, + extractor, + mutator, + asserter, + duplicator, + runner, + tester + ); + } + + /// + public IRandom Gen { get; } = gen ?? throw new ArgumentNullException(nameof(gen)); + + /// + public IValuer Valuer { get; } = valuer ?? throw new ArgumentNullException(nameof(valuer)); + + /// + public IFaker Faker { get; } = faker ?? throw new ArgumentNullException(nameof(faker)); + + /// + public IRandomizer Randomizer { get; } = + randomizer ?? throw new ArgumentNullException(nameof(randomizer)); + + /// + public IExtractor Extractor { get; } = + extractor ?? throw new ArgumentNullException(nameof(extractor)); + + /// + public IMutator Mutator { get; } = mutator ?? throw new ArgumentNullException(nameof(mutator)); + + /// + public IAsserter Asserter { get; } = + asserter ?? throw new ArgumentNullException(nameof(asserter)); + + /// + public IDuplicator Duplicator { get; } = + duplicator ?? throw new ArgumentNullException(nameof(duplicator)); + + /// + public IRunner Runner { get; } = runner ?? throw new ArgumentNullException(nameof(runner)); + + /// + public ITester Tester { get; } = tester ?? throw new ArgumentNullException(nameof(tester)); +} diff --git a/src/Toolbox/Tools.cs b/src/Toolbox/Tools.cs new file mode 100644 index 00000000..3fecca7f --- /dev/null +++ b/src/Toolbox/Tools.cs @@ -0,0 +1,50 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake; + +/// Manages implementations of all reflection tools. +public static class Tools +{ + /// Manages currently used tools globally. + /// Should only be modified in module initializer once. + public static IToolSet Source { get; set; } = ToolSet.DefaultSet; + + /// + public static IRandom Gen => Source.Gen; + + /// + public static IValuer Valuer => Source.Valuer; + + /// + public static IFaker Faker => Source.Faker; + + /// + public static IRandomizer Randomizer => Source.Randomizer; + + /// + public static IExtractor Extractor => Source.Extractor; + + /// + public static IMutator Mutator => Source.Mutator; + + /// + public static IAsserter Asserter => Source.Asserter; + + /// + public static IDuplicator Duplicator => Source.Duplicator; + + /// + public static IRunner Runner => Source.Runner; + + /// + public static ITester Tester => Source.Tester; +} diff --git a/src/Toolbox/ValuerTool/Difference.cs b/src/Toolbox/ValuerTool/Difference.cs new file mode 100644 index 00000000..8f2a811f --- /dev/null +++ b/src/Toolbox/ValuerTool/Difference.cs @@ -0,0 +1,107 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.ValuerTool; + +/// Expresses a value difference between two objects. +public sealed class Difference : IValueEquatable, IEquatable, IDeepCloneable +{ + /// Message stating the difference. + private readonly Lazy _message; + + /// + /// of the compared expected object. + /// of the compared actual object. + public Difference(Type expectedType, Type? actualType) + { + _message = new(() => + $"-> Expected type:<{GenericConverter.ExpandName(expectedType)}>, " + + $"Actual type:<{GenericConverter.ExpandName(actualType)}>" + ); + } + + /// + /// compared with . + /// compared against . + public Difference(object? expected, object? actual) + { + _message = new(() => $" -> Expected:<{expected}>, Actual:<{actual}>"); + } + + /// + /// Member where the compared objects differed. + /// Found difference for the compared objects. + public Difference(MemberInfo member, Difference difference) + : this("." + member?.Name, difference) + { + ArgumentGuard.ThrowIfNull(member); + } + + /// + /// Index where the compared objects differed. + /// Found difference for the compared objects. + public Difference(int index, Difference difference) + : this($"[{index}]", difference) { } + + /// + /// Access method where the compared objects differed. + /// Found difference for the compared objects. + public Difference(string access, Difference difference) + { + ArgumentGuard.ThrowIfNull(access, difference); + + _message = new(() => $"{access}{difference}"); + } + + /// + /// + public Difference(string message) + { + _message = new(() => message); + } + + /// + public Difference DeepClone() + { + return new Difference(_message.Value); + } + + /// + public bool ValuesEqual(object? other) + { + return Equals(other); + } + + /// + public override bool Equals(object? obj) + { + return Equals(obj as Difference); + } + + /// + public bool Equals(Difference? other) + { + return _message.Value == other?._message.Value; + } + + /// + public int GetValueHash() + { + return GetHashCode(); + } + + /// + public override int GetHashCode() + { + return ValueComparer.Use.GetHashCode(_message.Value); + } + + /// Converts to a . + /// representation of . + public override string ToString() + { + return _message.Value; + } +} diff --git a/src/Toolbox/ValuerTool/Engine/ByValuerAsyncComparer.cs b/src/Toolbox/ValuerTool/Engine/ByValuerAsyncComparer.cs new file mode 100644 index 00000000..80149e62 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/ByValuerAsyncComparer.cs @@ -0,0 +1,24 @@ +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// Checks if two objects are equal with async compatibility using the . +/// Supported type for comparisons. +/// +public sealed class ByValuerAsyncComparer(IValuer valuer) : IAsyncEqualityComparer +{ + /// + private readonly IValuer _valuer = valuer ?? throw new ArgumentNullException(nameof(valuer)); + + /// + public Task EqualsAsync(T? x, T? y, CancellationToken canceler) + { + return _valuer.EqualsAsync(x, y, canceler); + } + + /// + public Task GetHashCodeAsync(T? obj, CancellationToken canceler) + { + return _valuer.GetHashCodeAsync(obj, canceler); + } +} diff --git a/src/Toolbox/ValuerTool/Engine/ByValuerComparer.cs b/src/Toolbox/ValuerTool/Engine/ByValuerComparer.cs new file mode 100644 index 00000000..9f3f57b1 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/ByValuerComparer.cs @@ -0,0 +1,22 @@ +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// Checks if two objects are equal using the . +/// Supported type for comparisons. +/// +public sealed class ByValuerComparer(IValuer valuer) : IEqualityComparer +{ + /// + private readonly IValuer _valuer = valuer ?? throw new ArgumentNullException(nameof(valuer)); + + /// + public bool Equals(T? x, T? y) + { + return _valuer.Equals(x, y); + } + + /// + public int GetHashCode(T? obj) + { + return _valuer.GetHashCode(obj); + } +} diff --git a/src/Toolbox/ValuerTool/Engine/CompareHint.cs b/src/Toolbox/ValuerTool/Engine/CompareHint.cs new file mode 100644 index 00000000..b7a99546 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/CompareHint.cs @@ -0,0 +1,198 @@ +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +#pragma warning disable MA0042 // Using sync behavior for async versions. + +/// +public abstract class CompareHint : ICompareHint +{ + /// If calculated value hashes can be included in equality comparisons. + protected virtual bool EnableValueHashForComparisons => true; + + /// + public abstract int EnginePriority { get; } + + /// + public abstract IEnumerable SupportedTypes { get; } + + /// + public DifferenceHintResult TryToCompare(object expected, object actual, IValuerChainer chainer) + { + ArgumentGuard.ThrowIfNull(expected, actual, chainer); + + if (Supports(expected, actual, chainer)) + { + IEnumerable results = Compare(expected, actual, chainer); + if (EnableValueHashForComparisons && chainer.Options.IncludeValueHashInComparison) + { + int expectedHash = GetHashCode(expected, chainer); + int actualHash = GetHashCode(actual, chainer); + + if (expectedHash != actualHash) + { + results = results.Append( + new Difference("(ValueHash)", new Difference(expectedHash, actualHash)) + ); + } + } + return new(results); + } + else + { + return DifferenceHintResult.None; + } + } + + /// + public DifferenceHintAsyncResult TryToAsyncCompare( + object expected, + object actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(expected, actual, chainer); + + if (Supports(expected, actual, chainer)) + { + return new(HandleCompareAsync(expected, actual, chainer, canceler)); + } + else + { + return DifferenceHintAsyncResult.None; + } + } + + /// + /// Aborts execution if triggered. + private async IAsyncEnumerable HandleCompareAsync( + object expected, + object actual, + IValuerChainer chainer, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + await foreach ( + Difference diff in CompareAsync(expected, actual, chainer, canceler) + .ConfigureAwait(false) + ) + { + canceler.ThrowIfCancellationRequested(); + yield return diff; + } + + if (EnableValueHashForComparisons && chainer.Options.IncludeValueHashInComparison) + { + canceler.ThrowIfCancellationRequested(); + int expectedHash = await GetHashCodeAsync(expected, chainer, canceler) + .ConfigureAwait(false); + + canceler.ThrowIfCancellationRequested(); + int actualHash = await GetHashCodeAsync(actual, chainer, canceler) + .ConfigureAwait(false); + + if (expectedHash != actualHash) + { + yield return new Difference( + "(ValueHash)", + new Difference(expectedHash, actualHash) + ); + } + } + } + + /// + public HashCodeHintResult TryToGetHashCode(object item, IValuerChainer chainer) + { + ArgumentGuard.ThrowIfNull(item, chainer); + + if (Supports(item, item, chainer)) + { + return new(GetHashCode(item, chainer)); + } + else + { + return HashCodeHintResult.None; + } + } + + /// + public HashCodeHintAsyncResult TryToAsyncGetHashCode( + object item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(item, chainer); + + if (Supports(item, item, chainer)) + { + return new(GetHashCodeAsync(item, chainer, canceler)); + } + else + { + return HashCodeHintAsyncResult.None; + } + } + + /// + /// Determines if or are supported by the hint. + /// + /// if the objects can be compared, otherwise. + /// + protected abstract bool Supports(object expected, object actual, IValuerChainer chainer); + + /// Finds the differences between and . + /// The found differences between and . + /// + protected abstract IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ); + + /// + /// Aborts execution if triggered. + protected virtual IAsyncEnumerable CompareAsync( + object expected, + object actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + return AsyncSeriesHelper.CreateFromAsync( + Compare(expected, actual, chainer), + chainer.Options.Design.IterationLimit + ); + } + + /// Computes an identifying hash code for based upon value. + /// The value computed hash code for . + /// + protected abstract int GetHashCode(object item, IValuerChainer chainer); + + /// + /// Aborts execution if triggered. + protected virtual Task GetHashCodeAsync( + object item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return Task.FromResult(GetHashCode(item, chainer)); + } + + /// + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } +} + +#pragma warning restore diff --git a/src/Toolbox/ValuerTool/Engine/CompareHint{T}.cs b/src/Toolbox/ValuerTool/Engine/CompareHint{T}.cs new file mode 100644 index 00000000..9516d3f5 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/CompareHint{T}.cs @@ -0,0 +1,95 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +#pragma warning disable MA0042 // Using sync behavior for async versions. + +/// Handles comparisons. +/// Specific the hint supports. +public abstract class CompareHint : CompareHint +{ + /// + public override IEnumerable SupportedTypes { get; } = [typeof(T)]; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + return expected is T && actual is T; + } + + /// + protected sealed override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + return Compare((T)expected, (T)actual, chainer); + } + + /// + protected abstract IEnumerable Compare( + T expected, + T actual, + IValuerChainer chainer + ); + + /// + protected sealed override IAsyncEnumerable CompareAsync( + object expected, + object actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return CompareAsync((T)expected, (T)actual, chainer, canceler); + } + + /// + protected virtual IAsyncEnumerable CompareAsync( + T expected, + T actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + + return AsyncSeriesHelper.CreateFromAsync( + Compare(expected, actual, chainer), + chainer.Options.Design.IterationLimit + ); + } + + /// + protected sealed override int GetHashCode(object item, IValuerChainer chainer) + { + return GetHashCode((T)item, chainer); + } + + /// + protected abstract int GetHashCode(T item, IValuerChainer chainer); + + /// + protected sealed override Task GetHashCodeAsync( + object item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return GetHashCodeAsync((T)item, chainer, canceler); + } + + /// + protected virtual Task GetHashCodeAsync( + T item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return Task.FromResult(GetHashCode(item, chainer)); + } +} + +#pragma warning restore diff --git a/src/Toolbox/ValuerTool/Engine/ComparePriority.cs b/src/Toolbox/ValuerTool/Engine/ComparePriority.cs new file mode 100644 index 00000000..f08c7bc8 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/ComparePriority.cs @@ -0,0 +1,80 @@ +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// Priorities for s. +public enum ComparePriority +{ + /// Priority for hints that won't automatically execute. + /// Such hints only work if given to the tool via . + Disabled = int.MinValue, + + /// Priority for custom hints that'll execute last. + /// Subtract from this priority for even lower priorities. + None = 0, + + /// Priority for . + StatelessHint = 1, + + /// Priority for . + PrivateObjectHint = 2, + + /// Priority for . + PublicObjectHint = 3, + + /// Priority for . + EquatableHint = 4, + + /// Priority for . + ValuerEquatableHint = 5, + + /// Priority for . + ValuerComparableHint = 6, + + /// Priority for . + ValuerAsyncComparableHint = 7, + + /// Priority for . + ValueEquatableHint = 8, + + /// Priority for . + StructuralEquatableHint = 9, + + /// Priority for . + DefaultEqualityHint = 10, + + /// Priority for . + StreamHint = 11, + + /// Priority for . + EnumerableHint = 12, + + /// Priority for . + SetHint = 13, + + /// Priority for . + DictionaryHint = 14, + + /// Priority for . + AsyncEnumerableHint = 15, + + /// Priority for . + AsyncSetHint = 16, + + /// Priority for . + FakedHint = 17, + + /// Priority for . + ValueTaskHint = 18, + + /// Priority for . + TaskHint = 19, + + /// Priority for . + HandlerHint = 20, + + /// Starting priority for custom hints that'll execute first. + /// Add to this priority for even higher priorities. + Highest = 21, +} diff --git a/src/Toolbox/ValuerTool/Engine/DifferenceHintAsyncResult.cs b/src/Toolbox/ValuerTool/Engine/DifferenceHintAsyncResult.cs new file mode 100644 index 00000000..337c64e9 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/DifferenceHintAsyncResult.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// +public sealed class DifferenceHintAsyncResult : HintResult?> +{ + /// For when a hint doesn't support a type or fails to compare it. + public static DifferenceHintAsyncResult None { get; } = new(false, null); + + /// + private DifferenceHintAsyncResult(bool hasData, IAsyncEnumerable? data) + : base(hasData, data) { } + + /// + public DifferenceHintAsyncResult(IAsyncEnumerable data) + : this(true, data) { } +} diff --git a/src/Toolbox/ValuerTool/Engine/DifferenceHintResult.cs b/src/Toolbox/ValuerTool/Engine/DifferenceHintResult.cs new file mode 100644 index 00000000..b06c8b9c --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/DifferenceHintResult.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// +public sealed class DifferenceHintResult : HintResult?> +{ + /// For when a hint doesn't support a type or fails to compare it. + public static DifferenceHintResult None { get; } = new(false, null); + + /// + private DifferenceHintResult(bool hasData, IEnumerable? data) + : base(hasData, data) { } + + /// + public DifferenceHintResult(IEnumerable data) + : this(true, data) { } +} diff --git a/src/Toolbox/ValuerTool/Engine/HashCodeHintAsyncResult.cs b/src/Toolbox/ValuerTool/Engine/HashCodeHintAsyncResult.cs new file mode 100644 index 00000000..b7c4348c --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/HashCodeHintAsyncResult.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// +public sealed class HashCodeHintAsyncResult : HintResult?> +{ + /// For when a hint doesn't support a type or fails to compare it. + public static HashCodeHintAsyncResult None { get; } = new(false, null); + + /// + private HashCodeHintAsyncResult(bool hasData, Task? data) + : base(hasData, data) { } + + /// + public HashCodeHintAsyncResult(Task data) + : this(true, data) { } +} diff --git a/src/Toolbox/ValuerTool/Engine/HashCodeHintResult.cs b/src/Toolbox/ValuerTool/Engine/HashCodeHintResult.cs new file mode 100644 index 00000000..fec7b86c --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/HashCodeHintResult.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// +public sealed class HashCodeHintResult : HintResult +{ + /// For when a hint doesn't support a type or fails to compare it. + public static HashCodeHintResult None { get; } = new(false, default); + + /// + private HashCodeHintResult(bool hasData, int data) + : base(hasData, data) { } + + /// + public HashCodeHintResult(int data) + : this(true, data) { } +} diff --git a/src/Toolbox/ValuerTool/Engine/ICompareHandler.cs b/src/Toolbox/ValuerTool/Engine/ICompareHandler.cs new file mode 100644 index 00000000..f959f913 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/ICompareHandler.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// Handles comparison and hashing of a specific type. +internal interface ICompareHandler : ITypeSupporter +{ + /// + /// Compares instances of the . + /// + /// + IEnumerable CompareSupported( + object expected, + object actual, + IValuerChainer chainer + ); + + /// + /// Computes the identifying hash code for the . + /// + /// + int HashSupported(object item, IValuerChainer chainer); +} diff --git a/src/Toolbox/ValuerTool/Engine/ICompareHint.cs b/src/Toolbox/ValuerTool/Engine/ICompareHint.cs new file mode 100644 index 00000000..f15f7e5f --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/ICompareHint.cs @@ -0,0 +1,38 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// Handles comparisons of the . +public interface ICompareHint : IToolHint +{ + /// + /// Tries to find the differences between and . + /// + /// Instance to compare with . + /// Potentially different object to compare against . + /// Handles comparing child values. + /// If the hint supported the operation with the attempt result if so. + DifferenceHintResult TryToCompare(object expected, object actual, IValuerChainer chainer); + + /// + DifferenceHintAsyncResult TryToAsyncCompare( + object expected, + object actual, + IValuerChainer chainer, + CancellationToken canceler + ); + + /// Tries to compute an identifying hash code for based upon value. + /// Instance to generate a hash code for. + /// Handles hashing behavior for child values. + /// If the hint supported the operation with the attempt result if so. + HashCodeHintResult TryToGetHashCode(object item, IValuerChainer chainer); + + /// + /// Aborts execution if triggered. + HashCodeHintAsyncResult TryToAsyncGetHashCode( + object item, + IValuerChainer chainer, + CancellationToken canceler + ); +} diff --git a/src/Toolbox/ValuerTool/Engine/IValuerChainer.cs b/src/Toolbox/ValuerTool/Engine/IValuerChainer.cs new file mode 100644 index 00000000..d408cd8b --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/IValuerChainer.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// +public interface IValuerChainer : IValuer, IToolChainer; diff --git a/src/Toolbox/ValuerTool/Engine/IValuerEngine.cs b/src/Toolbox/ValuerTool/Engine/IValuerEngine.cs new file mode 100644 index 00000000..23427f80 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/IValuerEngine.cs @@ -0,0 +1,28 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// +public interface IValuerEngine : IToolEngine +{ + /// Handles callback behavior for child values. + /// + IEnumerable Compare(object? expected, object? actual, IValuerChainer chainer); + + /// Handles callback behavior for child values. + /// + IAsyncEnumerable CompareAsync( + object? expected, + object? actual, + IValuerChainer chainer, + CancellationToken canceler + ); + + /// Handles callback behavior for child values. + /// + int GetHashCode(object? item, IValuerChainer chainer); + + /// Handles callback behavior for child values. + /// + Task GetHashCodeAsync(object? item, IValuerChainer chainer, CancellationToken canceler); +} diff --git a/src/Toolbox/ValuerTool/Engine/ValuerChainer.cs b/src/Toolbox/ValuerTool/Engine/ValuerChainer.cs new file mode 100644 index 00000000..c915af2d --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/ValuerChainer.cs @@ -0,0 +1,262 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// Provides a callback into to create child values. +public sealed class ValuerChainer + : ToolChainer, + IValuerChainer +{ + /// History of hashes to match up references. + private readonly ISet _hashHistory; + + /// History of comparisons to match up references. + private readonly HashSet<(int, int)> _compareHistory; + + /// + public ValuerChainer(ValuerOptions options, IValuerEngine engine) + : base(options, engine) + { + _hashHistory = new HashSet(ReferenceComparer.Use); + _compareHistory = []; + } + + /// + private ValuerChainer(ValuerOptions options, ValuerChainer prevChainer) + : base(options, prevChainer) + { + _hashHistory = prevChainer._hashHistory; + _compareHistory = prevChainer._compareHistory; + } + + /// + protected override ValuerChainer CreateSubChainer(ValuerOptions subOptions) + { + return new ValuerChainer(subOptions, this); + } + + /// If can be tracked in history. + /// Item to check. + /// if tracking is possible, otherwise. + private static bool CanTrack([NotNullWhen(true)] object? item) + { + return item?.GetType().IsValueType == false; + } + + /// + public IEnumerable Compare( + object? expected, + object? actual, + ValuerMod? optionConfiguration = null + ) + { + (int, int)? refHash = + (CanTrack(expected) && CanTrack(actual)) + ? (RuntimeHelpers.GetHashCode(expected), RuntimeHelpers.GetHashCode(actual)) + : null; + + if (refHash == null || _compareHistory.Add(refHash.Value)) + { + try + { + // Yield return is required here to prevent infinite loops. + foreach ( + Difference diff in Engine.Compare( + expected, + actual, + GetSubChainer(optionConfiguration) + ) + ) + { + yield return diff; + } + } + finally + { + if (refHash != null) + { + _ = _compareHistory.Remove(refHash.Value); + } + } + } + } + + /// + public IAsyncEnumerable CompareAsync( + object? expected, + object? actual, + CancellationToken canceler, + ValuerMod? optionConfiguration = null + ) + { + return HandleCompareAsync(expected, actual, optionConfiguration, canceler); + } + + /// + private async IAsyncEnumerable HandleCompareAsync( + object? expected, + object? actual, + ValuerMod? optionConfiguration, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + (int, int)? refHash = + (CanTrack(expected) && CanTrack(actual)) + ? (RuntimeHelpers.GetHashCode(expected), RuntimeHelpers.GetHashCode(actual)) + : null; + + if (refHash == null || _compareHistory.Add(refHash.Value)) + { + try + { + // Await & yield return is required here to prevent infinite loops. + await foreach ( + Difference diff in Engine + .CompareAsync( + expected, + actual, + GetSubChainer(optionConfiguration), + canceler + ) + .ConfigureAwait(false) + ) + { + yield return diff; + } + } + finally + { + if (refHash != null) + { + _ = _compareHistory.Remove(refHash.Value); + } + } + } + } + + /// + public int GetHashCode(object? item) + { + return GetHashCode(item, null); + } + + /// + public int GetHashCode(object? item, ValuerMod? optionConfiguration) + { + if (!CanTrack(item)) + { + return Engine.GetHashCode(item, GetSubChainer(optionConfiguration)); + } + + if (_hashHistory.Add(item)) + { + try + { + return Engine.GetHashCode(item, GetSubChainer(optionConfiguration)); + } + finally + { + _ = _hashHistory.Remove(item); + } + } + else + { + return 0; + } + } + + /// + public Task GetHashCodeAsync(object? item, CancellationToken canceler) + { + return GetHashCodeAsync(item, canceler, null); + } + + /// + public async Task GetHashCodeAsync( + object? item, + CancellationToken canceler, + ValuerMod? optionConfiguration + ) + { + if (!CanTrack(item)) + { + return await Engine + .GetHashCodeAsync(item, GetSubChainer(optionConfiguration), canceler) + .ConfigureAwait(false); + } + + if (_hashHistory.Add(item)) + { + try + { + // Await is required here to prevent infinite loops. + return await Engine + .GetHashCodeAsync(item, GetSubChainer(optionConfiguration), canceler) + .ConfigureAwait(false); + } + finally + { + _ = _hashHistory.Remove(item); + } + } + else + { + return 0; + } + } + + /// + public new bool Equals(object? x, object? y) + { + return !Compare(x, y).Any(); + } + + /// + public bool Equals(object? x, object? y, ValuerMod? optionConfiguration) + { + return !Compare(x, y, optionConfiguration).Any(); + } + + /// + public Task EqualsAsync(object? x, object? y, CancellationToken canceler) + { + return EqualsAsync(x, y, canceler, null); + } + + /// + public async Task EqualsAsync( + object? x, + object? y, + CancellationToken canceler, + ValuerMod? optionConfiguration + ) + { + return !await AsyncSeriesHelper + .HasAnyAsync(CompareAsync(x, y, canceler, optionConfiguration), canceler) + .ConfigureAwait(false); + } + + /// + public IEqualityComparer ToComparer() + { + return new ByValuerComparer(this); + } + + /// + public IAsyncEqualityComparer ToAsyncComparer() + { + return new ByValuerAsyncComparer(this); + } + + /// + public IValuer WithOptions(ValuerMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new ValuerChainer(optionConfiguration.Invoke(Options), this); + } +} diff --git a/src/Toolbox/ValuerTool/Engine/ValuerEngine.cs b/src/Toolbox/ValuerTool/Engine/ValuerEngine.cs new file mode 100644 index 00000000..5ab55e27 --- /dev/null +++ b/src/Toolbox/ValuerTool/Engine/ValuerEngine.cs @@ -0,0 +1,295 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.ValuerTool.Engine; + +/// +public sealed class ValuerEngine : ToolEngine, IValuerEngine +{ + /// + public IEnumerable Compare(object? expected, object? actual, IValuerChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + if (ReferenceEquals(expected, actual)) + { + return []; + } + else if (expected is null || actual is null) + { + return [new Difference(expected, actual)]; + } + + DifferenceHintResult? result; + try + { + result = SelectHints(chainer) + .Select(h => h.TryToCompare(expected, actual, chainer)) + .FirstOrDefault(r => r?.HasData ?? false); + } + catch (Exception e) + { + throw new ToolException( + $"Error comparing instance of type '{GenericConverter.ExpandName(expected)}' " + + $"with an instance of type '{GenericConverter.ExpandName(actual)}'.", + e + ); + } + + if (result != null) + { + return WithErrorHandling(result.Data!, expected, actual, chainer); + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(expected)}' & '{GenericConverter.ExpandName(actual)}' not " + + "supported by the valuer. Create a hint to generate the type and pass it to the valuer." + ); + } + } + + /// + public IAsyncEnumerable CompareAsync( + object? expected, + object? actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + if (ReferenceEquals(expected, actual)) + { + return AsyncSeriesHelper.Empty; + } + else if (expected is null || actual is null) + { + return AsyncSeriesHelper.CreateFromAsync( + [new Difference(expected, actual)], + chainer.Options.Design.IterationLimit + ); + } + + DifferenceHintAsyncResult? result; + try + { + result = SelectHints(chainer) + .Select(h => h.TryToAsyncCompare(expected, actual, chainer, canceler)) + .FirstOrDefault(r => r?.HasData ?? false); + } + catch (Exception e) + { + throw new ToolException( + $"Error comparing instance of type '{GenericConverter.ExpandName(expected)}' " + + $"with an instance of type '{GenericConverter.ExpandName(actual)}'.", + e + ); + } + + if (result != null) + { + return WithErrorHandlingAsync(result.Data!, expected, actual, chainer, canceler); + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(expected)}' & '{GenericConverter.ExpandName(actual)}' not " + + "supported by the valuer. Create a hint to generate the type and pass it to the valuer." + ); + } + } + + /// + public int GetHashCode(object? item, IValuerChainer chainer) + { + ArgumentGuard.ThrowIfNull(chainer); + if (item is null) + { + return ValueComparer.NullHash; + } + + HashCodeHintResult? result; + try + { + result = SelectHints(chainer) + .Select(h => h.TryToGetHashCode(item, chainer)) + .FirstOrDefault(r => r?.HasData ?? false); + } + catch (Exception e) + { + throw new ToolException( + $"Error hashing instance of type '{GenericConverter.ExpandName(item)}'.", + e + ); + } + + if (result != null) + { + return result.Data; + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(item)}' not supported by the valuer. " + + "Create a hint to generate the type and pass it to the valuer." + ); + } + } + + /// + public Task GetHashCodeAsync( + object? item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + ArgumentGuard.ThrowIfNull(chainer); + if (item is null) + { + return Task.FromResult(ValueComparer.NullHash); + } + + HashCodeHintAsyncResult? result; + try + { + result = SelectHints(chainer) + .Select(h => h.TryToAsyncGetHashCode(item, chainer, canceler)) + .FirstOrDefault(r => r?.HasData ?? false); + } + catch (Exception e) + { + throw new ToolException( + $"Error hashing instance of type '{GenericConverter.ExpandName(item)}'.", + e + ); + } + + if (result != null) + { + return WithErrorHandlingAsync(result.Data!, item); + } + else + { + throw new UnsupportedException( + $"Type '{GenericConverter.ExpandName(item)}' not supported by the valuer. " + + "Create a hint to generate the type and pass it to the valuer." + ); + } + } + + /// Iterates the result and wraps any exception encountered with details. + /// Result of the tool hint being returned. + /// + private static IEnumerable WithErrorHandling( + IEnumerable result, + object? expected, + object? actual, + IValuerChainer chainer + ) + { + IEnumerator enumerator = result.GetEnumerator(); + try + { + bool hasNext; + int i = 0; + do + { + try + { + ArgumentGuard.ThrowUponIterationLimit( + i++, + chainer.Options.Design.IterationLimit + ); + hasNext = enumerator.MoveNext(); + } + catch (Exception e) + { + throw new ToolException( + $"Error comparing instance of type '{GenericConverter.ExpandName(expected)}'" + + $" with an instance of type '{GenericConverter.ExpandName(actual)}'.", + e + ); + } + + if (hasNext) + { + yield return enumerator.Current; + } + } while (hasNext); + } + finally + { + Disposer.Cleanup(enumerator); + } + } + + /// Iterates the result and wraps any exception encountered with details. + /// Result of the tool hint being returned. + /// + [ExcludeFromCodeCoverage] // Generated AsyncEnumerator code can only be partially covered. + private static async IAsyncEnumerable WithErrorHandlingAsync( + IAsyncEnumerable result, + object? expected, + object? actual, + IValuerChainer chainer, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + // Cannot use await foreach because yield return cannot be inside try/catch. + IAsyncEnumerator enumerator = result.GetAsyncEnumerator(canceler); + await using (enumerator.ConfigureAwait(false)) + { + bool hasNext; + int i = 0; + do + { + try + { + ArgumentGuard.ThrowUponIterationLimit( + i++, + chainer.Options.Design.IterationLimit + ); + canceler.ThrowIfCancellationRequested(); + hasNext = await enumerator.MoveNextAsync().ConfigureAwait(false); + } + catch (Exception e) + { + throw new ToolException( + "Error comparing instance of type " + + $"'{GenericConverter.ExpandName(expected)}' with an " + + $"instance of type '{GenericConverter.ExpandName(actual)}'.", + e + ); + } + + if (hasNext) + { + yield return enumerator.Current; + } + } while (hasNext); + } + } + + /// Awaits the result and wraps any exception encountered with details. + /// Result of the tool hint being returned. + /// + private static async Task WithErrorHandlingAsync(Task result, object? item) + { + try + { + return await result.ConfigureAwait(false); + } + catch (Exception e) + { + throw new ToolException( + $"Error hashing instance of type '{GenericConverter.ExpandName(item)}'.", + e + ); + } + } +} diff --git a/src/Toolbox/ValuerTool/Handlers/ConvertCompareHandler.cs b/src/Toolbox/ValuerTool/Handlers/ConvertCompareHandler.cs new file mode 100644 index 00000000..6a83dbd9 --- /dev/null +++ b/src/Toolbox/ValuerTool/Handlers/ConvertCompareHandler.cs @@ -0,0 +1,33 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Handlers; + +/// +/// Behavior handling comparisons of the supported type. +internal sealed class ConvertCompareHandler(Func converter) + : ICompareHandler +{ + /// + public Type SupportedType { get; } = typeof(T); + + /// + public IEnumerable CompareSupported( + object expected, + object actual, + IValuerChainer chainer + ) + { + ArgumentGuard.ThrowIfNull(converter, expected, actual, chainer); + + return chainer.Compare(converter((T)expected, chainer), converter((T)actual, chainer)); + } + + /// + public int HashSupported(object item, IValuerChainer chainer) + { + ArgumentGuard.ThrowIfNull(converter, item, chainer); + + return chainer.GetHashCode(converter((T)item, chainer)); + } +} diff --git a/src/Toolbox/ValuerTool/Handlers/DefaultEqualityCompareHandler.cs b/src/Toolbox/ValuerTool/Handlers/DefaultEqualityCompareHandler.cs new file mode 100644 index 00000000..b5ac3091 --- /dev/null +++ b/src/Toolbox/ValuerTool/Handlers/DefaultEqualityCompareHandler.cs @@ -0,0 +1,34 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Handlers; + +/// +internal sealed class DefaultEqualityCompareHandler(Type supportedType) : ICompareHandler +{ + /// + public Type SupportedType { get; } = supportedType; + + /// + public IEnumerable CompareSupported( + object expected, + object actual, + IValuerChainer chainer + ) + { + ArgumentGuard.ThrowIfNull(expected); + + if (!expected.Equals(actual)) + { + yield return new Difference(".equals", new Difference(expected, actual)); + } + } + + /// + public int HashSupported(object item, IValuerChainer chainer) + { + ArgumentGuard.ThrowIfNull(item); + + return item.GetHashCode(); + } +} diff --git a/src/Toolbox/ValuerTool/Handlers/ReflectionCompareHandlers.cs b/src/Toolbox/ValuerTool/Handlers/ReflectionCompareHandlers.cs new file mode 100644 index 00000000..4c269974 --- /dev/null +++ b/src/Toolbox/ValuerTool/Handlers/ReflectionCompareHandlers.cs @@ -0,0 +1,14 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Handlers; + +internal static class ReflectionCompareHandlers +{ + /// Supported types and the methods used to generate them. + internal static IEnumerable Handlers { get; } = + RuntimeDetails + .RuntimeTypes.Select(t => new DefaultEqualityCompareHandler(t)) + .Concat([new DefaultEqualityCompareHandler(typeof(AssemblyName))]); +} diff --git a/src/Toolbox/ValuerTool/Handlers/SystemCompareHandlers.cs b/src/Toolbox/ValuerTool/Handlers/SystemCompareHandlers.cs new file mode 100644 index 00000000..006592be --- /dev/null +++ b/src/Toolbox/ValuerTool/Handlers/SystemCompareHandlers.cs @@ -0,0 +1,67 @@ +using System.Collections; +using System.Collections.Specialized; +using System.Numerics; +using System.Text; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Handlers; + +/// Holds a collection of related handlers. +internal static class SystemCompareHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + [ + new DefaultEqualityCompareHandler(typeof(string)), + new DefaultEqualityCompareHandler(typeof(RuntimeMethodHandle)), + new ConvertCompareHandler((s, _) => s.ToString()), + new ConvertCompareHandler((s, _) => s.Uri), + new ConvertCompareHandler((reader, _) => reader.BaseStream), + new ConvertCompareHandler((v, _) => new { v.X, v.Y }), + new ConvertCompareHandler( + (v, _) => + new + { + v.X, + v.Y, + v.Z, + } + ), + new ConvertCompareHandler( + (v, _) => + new + { + v.X, + v.Y, + v.Z, + v.W, + } + ), + new ConvertCompareHandler( + (writer, _) => + { + writer.Flush(); + return writer.BaseStream; + } + ), + new ConvertCompareHandler( + (token, _) => new { token.CanBeCanceled, token.IsCancellationRequested } + ), + new ConvertCompareHandler( + (dict, _) => + dict.Cast().ToDictionary(e => (string)e.Key, e => (string?)e.Value) + ), + new ConvertCompareHandler( + (task, _) => + new + { + SingleCallSource = SingleCallValueTaskSource.ExtractFrom(task), + Token = SingleCallValueTaskSource.ExtractTokenFrom(task), + } + ), +#if NET9_0_OR_GREATER + new DefaultEqualityCompareHandler(typeof(Lock)), +#endif + ]; +} diff --git a/src/Toolbox/ValuerTool/Handlers/ValueCompareHandlers.cs b/src/Toolbox/ValuerTool/Handlers/ValueCompareHandlers.cs new file mode 100644 index 00000000..1e3e0e7e --- /dev/null +++ b/src/Toolbox/ValuerTool/Handlers/ValueCompareHandlers.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Handlers; + +/// Holds a collection of related handlers. +internal static class ValueCompareHandlers +{ + /// The collection of related handlers. + internal static IEnumerable Handlers { get; } = + ValueRandom.SupportedTypes.Select(t => new DefaultEqualityCompareHandler(t)); +} diff --git a/src/Toolbox/ValuerTool/Hints/AsyncEnumerableCompareHint.cs b/src/Toolbox/ValuerTool/Hints/AsyncEnumerableCompareHint.cs new file mode 100644 index 00000000..5f52e6c7 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/AsyncEnumerableCompareHint.cs @@ -0,0 +1,235 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles the comparing of s. +public sealed class AsyncEnumerableCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.AsyncEnumerableHint; + + /// + public override IEnumerable SupportedTypes { get; } = [typeof(IAsyncEnumerable<>)]; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + Type expectedType = expected.GetType(); + Type actualType = actual.GetType(); + + if (expectedType.Inherits(typeof(IAsyncEnumerable<>))) + { + return actualType.Inherits(typeof(IAsyncEnumerable<>)) + || actualType.Inherits(typeof(IEnumerable<>)); + } + else + { + return actualType.Inherits(typeof(IAsyncEnumerable<>)) + && expectedType.Inherits(typeof(IEnumerable<>)); + } + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + if (chainer.Options.SkipAsyncValues) + { + return []; + } + else + { + throw new EngineException( + $"Cannot compare {nameof(Type)}s of '{nameof(IAsyncEnumerable<>)}' in " + + $"synchronous context when {nameof(ValuerOptions.SkipAsyncValues)} " + + $"is {false}. Use an asynchronous method or override the setting." + ); + } + } + + /// + protected override IAsyncEnumerable CompareAsync( + object expected, + object actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + dynamic convertedExpected = ConvertFromSync(expected, chainer); + dynamic convertedActual = ConvertFromSync(actual, chainer); + + Type expectedType = GenericConverter.FindConcreteType( + convertedExpected.GetType(), + typeof(IAsyncEnumerable<>) + ); + Type actualType = GenericConverter.FindConcreteType( + convertedActual.GetType(), + typeof(IAsyncEnumerable<>) + ); + + if (expectedType != actualType) + { + return AsyncSeriesHelper.CreateFromAsync( + [new Difference(expected.GetType(), actual.GetType())], + chainer.Options.Design.IterationLimit + ); + } + + return ContentsCompareAsync(convertedExpected, convertedActual, chainer, canceler); + } + + /// Converts to asynchronous if not already. + /// Series to potentially convert. + /// Handles comparing child values. + /// The asynchronous result. + private static dynamic ConvertFromSync(object collection, IValuerChainer chainer) + { + if (collection.GetType().Inherits(typeof(IAsyncEnumerable<>))) + { + return collection; + } + else + { + return AsyncSeriesHelper.CreateFromAsync( + (dynamic)collection, + chainer.Options.Design.IterationLimit + ); + } + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + if (chainer.Options.SkipAsyncValues) + { + return 0; + } + else + { + throw new EngineException( + $"Cannot hash {nameof(Type)}s of '{nameof(IAsyncEnumerable<>)}' in " + + $"synchronous context when {nameof(ValuerOptions.SkipAsyncValues)} " + + $"is {false}. Use an asynchronous method or override the setting." + ); + } + } + + /// + protected override Task GetHashCodeAsync( + object item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return ContentsGetHashCodeAsync(ConvertFromSync(item, chainer), chainer, canceler); + } + + /// + /// The enumerable's item . + [ExcludeFromCodeCoverage] // Generated AsyncEnumerator code can only be partially covered. + private static async IAsyncEnumerable ContentsCompareAsync( + IAsyncEnumerable expected, + IAsyncEnumerable actual, + IValuerChainer chainer, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + canceler.ThrowIfCancellationRequested(); + if (chainer.Options.CheckCollectionType && expected.GetType() != actual.GetType()) + { + yield return new Difference(expected.GetType(), actual.GetType()); + } + + IAsyncEnumerator expectedEnumerator = expected.GetAsyncEnumerator(canceler); + IAsyncEnumerator actualEnumerator = actual.GetAsyncEnumerator(canceler); + await using (expectedEnumerator.ConfigureAwait(false)) + await using (actualEnumerator.ConfigureAwait(false)) + { + int index = 0; + while ( + await expectedEnumerator.MoveNextAsync().ConfigureAwait(false) + && index < chainer.Options.Design.IterationLimit + ) + { + ArgumentGuard.ThrowUponIterationLimit(index, chainer.Options.Design.IterationLimit); + canceler.ThrowIfCancellationRequested(); + + if (await actualEnumerator.MoveNextAsync().ConfigureAwait(false)) + { + canceler.ThrowIfCancellationRequested(); + + await foreach ( + Difference diff in chainer + .CompareAsync( + expectedEnumerator.Current, + actualEnumerator.Current, + canceler + ) + .ConfigureAwait(false) + ) + { + yield return new Difference(index, diff); + canceler.ThrowIfCancellationRequested(); + } + } + else + { + yield return new Difference( + index, + new Difference(expectedEnumerator.Current, "'out of range'") + ); + canceler.ThrowIfCancellationRequested(); + } + index++; + } + + canceler.ThrowIfCancellationRequested(); + + while ( + await actualEnumerator.MoveNextAsync().ConfigureAwait(false) + && index < chainer.Options.Design.IterationLimit + ) + { + ArgumentGuard.ThrowUponIterationLimit(index, chainer.Options.Design.IterationLimit); + + yield return new Difference( + index++, + new Difference("'out of range'", actualEnumerator.Current) + ); + canceler.ThrowIfCancellationRequested(); + } + + canceler.ThrowIfCancellationRequested(); + } + } + + /// + /// The enumerable's item . + private static async Task ContentsGetHashCodeAsync( + IAsyncEnumerable item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + int hash = ValueComparer.BaseHash; + await AsyncSeriesHelper + .ForEachAsync(item, chainer.Options.Design.IterationLimit, canceler, async current => + { + hash *= ValueComparer.HashMultiplier; + hash += await chainer.GetHashCodeAsync(current, canceler).ConfigureAwait(false); + }) + .ConfigureAwait(false); + + return hash; + } +} diff --git a/src/Toolbox/ValuerTool/Hints/AsyncSetCompareHint.cs b/src/Toolbox/ValuerTool/Hints/AsyncSetCompareHint.cs new file mode 100644 index 00000000..36a3e5c4 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/AsyncSetCompareHint.cs @@ -0,0 +1,206 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles the comparing of s. +public sealed class AsyncSetCompareHint : CompareHint +{ + /// Creator for instances. + private static readonly MethodInfo _ComparerMaker = typeof(IValuer).GetMethod( + nameof(IValuer.ToAsyncComparer) + )!; + + /// + public override int EnginePriority => (int)ComparePriority.AsyncSetHint; + + /// + public override IEnumerable SupportedTypes { get; } = [typeof(IAsyncSet<>)]; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + Type expectedType = expected.GetType(); + Type actualType = actual.GetType(); + + if (expectedType.Inherits(typeof(IAsyncSet<>))) + { + return actualType.Inherits(typeof(IAsyncSet<>)) || actualType.Inherits(typeof(ISet<>)); + } + else + { + return actualType.Inherits(typeof(IAsyncSet<>)) + && expectedType.Inherits(typeof(ISet<>)); + } + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + if (chainer.Options.SkipAsyncValues) + { + return []; + } + else + { + throw new EngineException( + $"Cannot compare {nameof(Type)}s of '{nameof(IAsyncSet<>)}' in " + + $"synchronous context when {nameof(ValuerOptions.SkipAsyncValues)} " + + $"is {false}. Use an asynchronous method or override the setting." + ); + } + } + + /// + protected override IAsyncEnumerable CompareAsync( + object expected, + object actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + dynamic convertedExpected = ConvertFromSync(expected, chainer, canceler); + dynamic convertedActual = ConvertFromSync(actual, chainer, canceler); + + Type expectedType = GenericConverter.FindConcreteType( + convertedExpected.GetType(), + typeof(IAsyncSet<>) + ); + Type actualType = GenericConverter.FindConcreteType( + convertedActual.GetType(), + typeof(IAsyncSet<>) + ); + + if (expectedType != actualType) + { + return AsyncSeriesHelper.CreateFromAsync( + [new Difference(expected.GetType(), actual.GetType())], + chainer.Options.Design.IterationLimit + ); + } + + return ContentsCompareAsync(convertedExpected, convertedActual, canceler); + } + + /// Converts to asynchronous if not already. + /// Series to potentially convert. + /// Handles comparing child values. + /// Aborts execution if triggered + /// The asynchronous result. + private static dynamic ConvertFromSync( + object collection, + IValuerChainer chainer, + CancellationToken canceler + ) + { + Type type = collection.GetType(); + + if (type.Inherits(typeof(IAsyncSet<>))) + { + return collection; + } + else + { + return AsyncHashSet.CreateFromAsync( + (dynamic)collection, + (dynamic?) + _ComparerMaker + .MakeGenericMethod(type.GetGenericArguments().Single()) + .Invoke(chainer, []), + chainer.Options.Design.IterationLimit, + canceler + ); + } + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + if (chainer.Options.SkipAsyncValues) + { + return 0; + } + else + { + throw new EngineException( + $"Cannot hash {nameof(Type)}s of '{nameof(IAsyncSet<>)}' in " + + $"synchronous context when {nameof(ValuerOptions.SkipAsyncValues)} " + + $"is {false}. Use an asynchronous method or override the setting." + ); + } + } + + /// + protected override Task GetHashCodeAsync( + object item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return ContentsGetHashCodeAsync( + ConvertFromSync(item, chainer, canceler), + chainer, + canceler + ); + } + + /// + /// The enumerable's item . + [ExcludeFromCodeCoverage] // Generated await foreach code can only be partially covered. + private static async IAsyncEnumerable ContentsCompareAsync( + IAsyncSet expected, + IAsyncSet actual, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + canceler.ThrowIfCancellationRequested(); + await foreach ( + T item in expected.FindMissingFromAsync(actual, canceler).ConfigureAwait(false) + ) + { + yield return new Difference(item, "'missing'"); + } + + await foreach ( + T item in actual.FindMissingFromAsync(expected, canceler).ConfigureAwait(false) + ) + { + yield return new Difference("'missing'", item); + } + } + + /// + /// The enumerable's item . + private static async Task ContentsGetHashCodeAsync( + IAsyncSet item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + int hash = ValueComparer.BaseHash; + await AsyncSeriesHelper + .ForEachAsync( + item, + chainer.Options.Design.IterationLimit, + canceler, + async current => + { + hash *= ValueComparer.HashMultiplier; + hash += await chainer.GetHashCodeAsync(current, canceler).ConfigureAwait(false); + } + ) + .ConfigureAwait(false); + + return hash; + } +} diff --git a/src/Toolbox/ValuerTool/Hints/DefaultEqualityCompareHint.cs b/src/Toolbox/ValuerTool/Hints/DefaultEqualityCompareHint.cs new file mode 100644 index 00000000..f520c6ae --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/DefaultEqualityCompareHint.cs @@ -0,0 +1,51 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles basic compare issues for . +public sealed class DefaultEqualityCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.DefaultEqualityHint; + + /// + public override IEnumerable SupportedTypes { get; } = [.. ValueRandom.SupportedTypes]; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + Type expectedType = expected.GetType(); + Type actualType = actual.GetType(); + return expectedType != actualType + || expectedType.IsPrimitive + || expectedType.IsEnum + || chainer.Options.DefaultEqualityTypes.Contains(expectedType) + || expected is Delegate + || expectedType == typeof(object); + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + if (expected.GetType() != actual.GetType()) + { + yield return new Difference(expected.GetType(), actual.GetType()); + } + else if (!expected.Equals(actual)) + { + yield return new Difference(expected, actual); + } + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + return ValueComparer.Use.GetHashCode(item); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/DictionaryCompareHint.cs b/src/Toolbox/ValuerTool/Hints/DictionaryCompareHint.cs new file mode 100644 index 00000000..085a4a7a --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/DictionaryCompareHint.cs @@ -0,0 +1,168 @@ +using System.Collections; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// +public sealed class DictionaryCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.DictionaryHint; + + /// + protected override IEnumerable Compare( + IDictionary expected, + IDictionary actual, + IValuerChainer chainer + ) + { + if (chainer.Options.CheckCollectionType && expected.GetType() != actual.GetType()) + { + yield return new Difference(expected.GetType(), actual.GetType()); + } + + HashSet expectedKeys = new(expected.Keys.Cast(), chainer); + Dictionary actualKeys = actual + .Keys.Cast() + .ToDictionary(e => e, e => e, chainer); + + foreach (object key in expectedKeys) + { + if (actualKeys.TryGetValue(key, out object? match)) + { + foreach (Difference diff in chainer.Compare(expected[key], actual[match])) + { + yield return new Difference($"[{TryDescribe(key)}]", diff); + } + } + else + { + yield return new Difference( + $"[{TryDescribe(key)}]", + new Difference(expected[key], "'missing'") + ); + } + } + + foreach (object key in actualKeys.Keys) + { + if (!expectedKeys.Contains(key)) + { + yield return new Difference( + $"[{TryDescribe(key)}]", + new Difference("'missing'", actual[key]) + ); + } + } + } + + /// + protected override IAsyncEnumerable CompareAsync( + IDictionary expected, + IDictionary actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return HandleCompareAsync(expected, actual, chainer, canceler); + } + + /// + private static async IAsyncEnumerable HandleCompareAsync( + IDictionary expected, + IDictionary actual, + IValuerChainer chainer, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + canceler.ThrowIfCancellationRequested(); + if (chainer.Options.CheckCollectionType && expected.GetType() != actual.GetType()) + { + yield return new Difference(expected.GetType(), actual.GetType()); + } + + HashSet expectedKeys = new(expected.Keys.Cast(), chainer); + Dictionary actualKeys = actual + .Keys.Cast() + .ToDictionary(e => e, e => e, chainer); + + foreach (object key in expectedKeys) + { + if (actualKeys.TryGetValue(key, out object? match)) + { + await foreach ( + Difference diff in chainer + .CompareAsync(expected[key], actual[match], canceler) + .ConfigureAwait(false) + ) + { + yield return new Difference($"[{TryDescribe(key)}]", diff); + canceler.ThrowIfCancellationRequested(); + } + } + else + { + yield return new Difference( + $"[{TryDescribe(key)}]", + new Difference(expected[key], "'missing'") + ); + } + } + + foreach (object key in actualKeys.Keys) + { + if (!expectedKeys.Contains(key)) + { + yield return new Difference( + $"[{TryDescribe(key)}]", + new Difference("'missing'", actual[key]) + ); + } + } + } + + /// Expands the 's name if it's a . + /// Potential to describe. + /// + /// Description of the if it's a , + /// the otherwise. + /// + private static object TryDescribe(object item) + { + return (item is Type type) ? GenericConverter.ExpandName(type) : item; + } + + /// + protected override int GetHashCode(IDictionary item, IValuerChainer chainer) + { + int hash = ValueComparer.BaseHash; + foreach (DictionaryEntry entry in item) + { + hash += chainer.GetHashCode(entry.Key); + hash += chainer.GetHashCode(entry.Value); + } + return hash; + } + + /// + protected override async Task GetHashCodeAsync( + IDictionary item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + int hash = ValueComparer.BaseHash; + foreach (DictionaryEntry entry in item) + { + canceler.ThrowIfCancellationRequested(); + hash += await chainer.GetHashCodeAsync(entry.Key, canceler).ConfigureAwait(false); + hash += await chainer.GetHashCodeAsync(entry.Value, canceler).ConfigureAwait(false); + } + + canceler.ThrowIfCancellationRequested(); + return hash; + } +} diff --git a/src/Toolbox/ValuerTool/Hints/EnumerableCompareHint.cs b/src/Toolbox/ValuerTool/Hints/EnumerableCompareHint.cs new file mode 100644 index 00000000..e3cf0840 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/EnumerableCompareHint.cs @@ -0,0 +1,183 @@ +using System.Collections; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing collections for . +public sealed class EnumerableCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.EnumerableHint; + + /// + protected override IEnumerable Compare( + IEnumerable expected, + IEnumerable actual, + IValuerChainer chainer + ) + { + return LazyCompare(expected, actual, chainer); + } + + /// + private static IEnumerable LazyCompare( + IEnumerable expected, + IEnumerable actual, + IValuerChainer chainer + ) + { + if (chainer.Options.CheckCollectionType && expected.GetType() != actual.GetType()) + { + yield return new Difference(expected.GetType(), actual.GetType()); + } + + IEnumerator? expectedEnumerator = null; + IEnumerator? actualEnumerator = null; + try + { + expectedEnumerator = expected.GetEnumerator(); + actualEnumerator = actual.GetEnumerator(); + int index = 0; + + while (expectedEnumerator.MoveNext() && index < chainer.Options.Design.IterationLimit) + { + ArgumentGuard.ThrowUponIterationLimit(index, chainer.Options.Design.IterationLimit); + + if (actualEnumerator.MoveNext()) + { + foreach ( + Difference diff in chainer.Compare( + expectedEnumerator.Current, + actualEnumerator.Current + ) + ) + { + yield return new Difference(index, diff); + } + } + else + { + yield return new Difference( + index, + new Difference(expectedEnumerator.Current, "'out of range'") + ); + } + index++; + } + while (actualEnumerator.MoveNext() && index < chainer.Options.Design.IterationLimit) + { + ArgumentGuard.ThrowUponIterationLimit(index, chainer.Options.Design.IterationLimit); + + yield return new Difference( + index++, + new Difference("'out of range'", actualEnumerator.Current) + ); + } + } + finally + { + Disposer.Cleanup(expectedEnumerator, actualEnumerator); + } + } + + /// + protected override async IAsyncEnumerable CompareAsync( + IEnumerable expected, + IEnumerable actual, + IValuerChainer chainer, + [EnumeratorCancellation] CancellationToken canceler + ) + { + if (chainer.Options.CheckCollectionType && expected.GetType() != actual.GetType()) + { + yield return new Difference(expected.GetType(), actual.GetType()); + } + + IEnumerator? expectedEnumerator = null; + IEnumerator? actualEnumerator = null; + try + { + expectedEnumerator = expected.GetEnumerator(); + actualEnumerator = actual.GetEnumerator(); + int index = 0; + + while (expectedEnumerator.MoveNext() && index < chainer.Options.Design.IterationLimit) + { + ArgumentGuard.ThrowUponIterationLimit(index, chainer.Options.Design.IterationLimit); + + if (actualEnumerator.MoveNext()) + { + await foreach ( + Difference diff in chainer + .CompareAsync( + expectedEnumerator.Current, + actualEnumerator.Current, + canceler + ) + .ConfigureAwait(false) + ) + { + yield return new Difference(index, diff); + } + } + else + { + yield return new Difference( + index, + new Difference(expectedEnumerator.Current, "'out of range'") + ); + } + index++; + } + while (actualEnumerator.MoveNext() && index < chainer.Options.Design.IterationLimit) + { + ArgumentGuard.ThrowUponIterationLimit(index, chainer.Options.Design.IterationLimit); + + yield return new Difference( + index++, + new Difference("'out of range'", actualEnumerator.Current) + ); + } + } + finally + { + await Disposer.CleanupAsync(expectedEnumerator, actualEnumerator).ConfigureAwait(false); + } + } + + /// + protected override int GetHashCode(IEnumerable item, IValuerChainer chainer) + { + int index = 0; + int hash = ValueComparer.BaseHash; + foreach (object value in item) + { + ArgumentGuard.ThrowUponIterationLimit(index++, chainer.Options.Design.IterationLimit); + hash = hash * ValueComparer.HashMultiplier + chainer.GetHashCode(value); + } + return hash; + } + + /// + protected override async Task GetHashCodeAsync( + IEnumerable item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + int index = 0; + int hash = ValueComparer.BaseHash; + foreach (object value in item) + { + ArgumentGuard.ThrowUponIterationLimit(index++, chainer.Options.Design.IterationLimit); + hash = + hash * ValueComparer.HashMultiplier + + await chainer.GetHashCodeAsync(value, canceler).ConfigureAwait(false); + } + return hash; + } +} diff --git a/src/Toolbox/ValuerTool/Hints/EquatableCompareHint.cs b/src/Toolbox/ValuerTool/Hints/EquatableCompareHint.cs new file mode 100644 index 00000000..b6885b37 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/EquatableCompareHint.cs @@ -0,0 +1,45 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing instances for . +public sealed class EquatableCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.EquatableHint; + + /// + public override IEnumerable SupportedTypes { get; } = []; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + return chainer.Options.UseEquatableComparisons + && expected + .GetType() + .Inherits(typeof(IEquatable<>).MakeGenericType(expected.GetType())); + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + if (!expected.Equals(actual)) + { + return [new Difference(expected, actual)]; + } + else + { + return []; + } + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + return item.GetHashCode(); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/FakedCompareHint.cs b/src/Toolbox/ValuerTool/Hints/FakedCompareHint.cs new file mode 100644 index 00000000..2b91def2 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/FakedCompareHint.cs @@ -0,0 +1,34 @@ +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// +public sealed class FakedCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.FakedHint; + + /// + protected override IEnumerable Compare( + IFaked expected, + IFaked actual, + IValuerChainer chainer + ) + { + if (expected.GetType() != actual.GetType()) + { + return chainer.Compare(expected.GetType(), actual.GetType()); + } + else + { + return chainer.Compare(expected.FakeMeta, actual.FakeMeta); + } + } + + /// + protected override int GetHashCode(IFaked item, IValuerChainer chainer) + { + return chainer.GetHashCode((item.GetType(), item.FakeMeta)); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/HandlerCompareHint.cs b/src/Toolbox/ValuerTool/Hints/HandlerCompareHint.cs new file mode 100644 index 00000000..ca86ea50 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/HandlerCompareHint.cs @@ -0,0 +1,59 @@ +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Handlers; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing instances utilizing s for . +public sealed class HandlerCompareHint : CompareHint +{ + /// Supported types and the methods used to compare them. + /// WARNING: Not async compatible. Internals must have no async content. + private static readonly ICompareHandler[] _Handlers = + [ + new ConvertCompareHandler( + (rand, c) => + c.Options.IgnoreCurrentRandomSeed + ? rand.InitialSeed + : new[] { rand.InitialSeed, rand.Seed } + ), + ]; + + private static readonly IDictionary _HandlersByType = + TypeSupporter.GroupBySupportedType( + _Handlers + .Concat(ValueCompareHandlers.Handlers) + .Concat(SystemCompareHandlers.Handlers) + .Concat(ReflectionCompareHandlers.Handlers) + ); + + /// + public override int EnginePriority => (int)ComparePriority.HandlerHint; + + /// + public override IEnumerable SupportedTypes => _HandlersByType.Keys; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + Type type = expected.GetType(); + return _HandlersByType.ContainsKey(type) && type == actual.GetType(); + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + return _HandlersByType[expected.GetType()].CompareSupported(expected, actual, chainer); + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + return _HandlersByType[item.GetType()].HashSupported(item, chainer); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/ObjectCompareHint.cs b/src/Toolbox/ValuerTool/Hints/ObjectCompareHint.cs new file mode 100644 index 00000000..bb159280 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/ObjectCompareHint.cs @@ -0,0 +1,173 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +#pragma warning disable CA1062 // Temporary + +/// Handles comparing objects for . +/// If private members are excluded. +public abstract class ObjectCompareHint(bool onlyPublic) : CompareHint +{ + /// + public override IEnumerable SupportedTypes { get; } = [typeof(object)]; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + Type type = expected.GetType(); + return GetAccessibleProperties(type).Any() || GetAccessibleFields(type).Any(); + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + return LazyCompare(expected, actual, chainer); + } + + /// + private IEnumerable LazyCompare( + object expected, + object actual, + IValuerChainer chainer + ) + { + Type type = expected.GetType(); + + foreach (PropertyInfo property in GetAccessibleProperties(type)) + { + foreach ( + Difference diff in chainer.Compare( + property.GetValue(expected), + property.GetValue(actual) + ) + ) + { + yield return new Difference(property, diff); + } + } + + foreach (FieldInfo field in GetAccessibleFields(type)) + { + foreach ( + Difference diff in chainer.Compare(field.GetValue(expected), field.GetValue(actual)) + ) + { + yield return new Difference(field, diff); + } + } + } + + /// + protected override async IAsyncEnumerable CompareAsync( + object expected, + object actual, + IValuerChainer chainer, + [EnumeratorCancellation] CancellationToken canceler + ) + { + Type type = expected.GetType(); + + foreach (PropertyInfo property in GetAccessibleProperties(type)) + { + await foreach ( + Difference diff in chainer + .CompareAsync(property.GetValue(expected), property.GetValue(actual), canceler) + .WithCancellation(canceler) + .ConfigureAwait(false) + ) + { + yield return new Difference(property, diff); + } + } + + foreach (FieldInfo field in GetAccessibleFields(type)) + { + await foreach ( + Difference diff in chainer + .CompareAsync(field.GetValue(expected), field.GetValue(actual), canceler) + .WithCancellation(canceler) + .ConfigureAwait(false) + ) + { + yield return new Difference(field, diff); + } + } + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + Type type = item.GetType(); + int hash = ValueComparer.BaseHash + type.GetHashCode(); + + foreach (PropertyInfo property in GetAccessibleProperties(type)) + { + hash = + hash * ValueComparer.HashMultiplier + chainer.GetHashCode(property.GetValue(item)); + } + + foreach (FieldInfo field in GetAccessibleFields(type)) + { + hash = hash * ValueComparer.HashMultiplier + chainer.GetHashCode(field.GetValue(item)); + } + + return hash; + } + + /// + protected override async Task GetHashCodeAsync( + object item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + Type type = item.GetType(); + int hash = ValueComparer.BaseHash + type.GetHashCode(); + + foreach (PropertyInfo property in GetAccessibleProperties(type)) + { + hash = + hash * ValueComparer.HashMultiplier + + await chainer + .GetHashCodeAsync(property.GetValue(item), canceler) + .ConfigureAwait(false); + } + + foreach (FieldInfo field in GetAccessibleFields(type)) + { + hash = + hash * ValueComparer.HashMultiplier + + await chainer + .GetHashCodeAsync(field.GetValue(item), canceler) + .ConfigureAwait(false); + } + + return hash; + } + + private IEnumerable GetAccessibleProperties(Type? type) + { + return ( + onlyPublic + ? TypeDescriber.For(type).Properties.OnlyPublic + : TypeDescriber.For(type).Properties.All + ).Where(p => p.CanRead); + } + + private IEnumerable GetAccessibleFields(Type? type) + { + return onlyPublic + ? TypeDescriber.For(type).Fields.OnlyPublic + : TypeDescriber.For(type).Fields.All; + } +} + +#pragma warning restore diff --git a/src/Toolbox/ValuerTool/Hints/PrivateObjectCompareHint.cs b/src/Toolbox/ValuerTool/Hints/PrivateObjectCompareHint.cs new file mode 100644 index 00000000..fabf5c3a --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/PrivateObjectCompareHint.cs @@ -0,0 +1,10 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing objects for . +public sealed class PrivateObjectCompareHint() : ObjectCompareHint(false) +{ + /// + public override int EnginePriority => (int)ComparePriority.PrivateObjectHint; +} diff --git a/src/Toolbox/ValuerTool/Hints/PublicObjectCompareHint.cs b/src/Toolbox/ValuerTool/Hints/PublicObjectCompareHint.cs new file mode 100644 index 00000000..5f1388b9 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/PublicObjectCompareHint.cs @@ -0,0 +1,10 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing objects for . +public sealed class PublicObjectCompareHint() : ObjectCompareHint(true) +{ + /// + public override int EnginePriority => (int)ComparePriority.PublicObjectHint; +} diff --git a/src/Toolbox/ValuerTool/Hints/SetCompareHint.cs b/src/Toolbox/ValuerTool/Hints/SetCompareHint.cs new file mode 100644 index 00000000..e256a54c --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/SetCompareHint.cs @@ -0,0 +1,170 @@ +using System.Collections; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// +public sealed class SetCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.SetHint; + + /// + public override IEnumerable SupportedTypes { get; } = [typeof(ISet<>)]; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + return expected.GetType().Inherits(typeof(ISet<>)) + && actual.GetType().Inherits(typeof(ISet<>)); + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + return HandleCompare((IEnumerable)expected, (IEnumerable)actual, chainer); + } + + /// + private static IEnumerable HandleCompare( + IEnumerable expected, + IEnumerable actual, + IValuerChainer chainer + ) + { + if (chainer.Options.CheckCollectionType && expected.GetType() != actual.GetType()) + { + yield return new Difference(expected.GetType(), actual.GetType()); + } + + HashSet expectedByValues = new(expected.Cast(), chainer); + HashSet actualByValues = new(actual.Cast(), chainer); + + foreach (object item in expectedByValues) + { + if (!actualByValues.Contains(item)) + { + yield return new Difference( + $"[{TryDescribe(item)}]", + new Difference(item, "'missing'") + ); + } + } + + foreach (object item in actualByValues) + { + if (!expectedByValues.Contains(item)) + { + yield return new Difference( + $"[{TryDescribe(item)}]", + new Difference("'missing'", item) + ); + } + } + } + + /// + protected override IAsyncEnumerable CompareAsync( + object expected, + object actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return HandleCompareAsync((dynamic)expected, (dynamic)actual, chainer, canceler); + } + + /// + private static async IAsyncEnumerable HandleCompareAsync( + IEnumerable expected, + IEnumerable actual, + IValuerChainer chainer, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + canceler.ThrowIfCancellationRequested(); + if (chainer.Options.CheckCollectionType && expected.GetType() != actual.GetType()) + { + yield return new Difference(expected.GetType(), actual.GetType()); + } + + AsyncHashSet expectedByHash = AsyncHashSet.CreateFromAsync( + expected.Cast(), + chainer, + chainer.Options.Design.IterationLimit, + canceler + ); + AsyncHashSet actualByHash = AsyncHashSet.CreateFromAsync( + actual.Cast(), + chainer, + chainer.Options.Design.IterationLimit, + canceler + ); + + await foreach ( + object item in expectedByHash + .FindMissingFromAsync(actualByHash, canceler) + .ConfigureAwait(false) + ) + { + yield return new Difference(item, "'missing'"); + } + + await foreach ( + object item in actualByHash + .FindMissingFromAsync(expectedByHash, canceler) + .ConfigureAwait(false) + ) + { + yield return new Difference("'missing'", item); + } + } + + /// Expands the 's name if it's a . + /// Potential to describe. + /// + /// Description of the if it's a , + /// the otherwise. + /// + private static object? TryDescribe(object? item) + { + return (item is Type type) ? GenericConverter.ExpandName(type) : item; + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + int hash = ValueComparer.BaseHash; + foreach (object entry in ((IEnumerable)item).Cast()) + { + hash += chainer.GetHashCode(entry); + } + return hash; + } + + /// + protected override async Task GetHashCodeAsync( + object item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + int hash = ValueComparer.BaseHash; + foreach (object entry in ((IEnumerable)item).Cast()) + { + canceler.ThrowIfCancellationRequested(); + hash += await chainer.GetHashCodeAsync(entry, canceler).ConfigureAwait(false); + } + + canceler.ThrowIfCancellationRequested(); + return hash; + } +} diff --git a/src/Toolbox/ValuerTool/Hints/StatelessCompareHint.cs b/src/Toolbox/ValuerTool/Hints/StatelessCompareHint.cs new file mode 100644 index 00000000..db5262b4 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/StatelessCompareHint.cs @@ -0,0 +1,38 @@ +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing stateless objects for . +public sealed class StatelessCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.StatelessHint; + + /// + public override IEnumerable SupportedTypes { get; } = []; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + Type type = expected.GetType(); + return !TypeDescriber.For(type).Properties.All.Any(p => p.CanRead) + && !TypeDescriber.For(type).Fields.All.Any(); + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + return []; + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + return item.GetType().GetHashCode(); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/StreamCompareHint.cs b/src/Toolbox/ValuerTool/Hints/StreamCompareHint.cs new file mode 100644 index 00000000..9cced1e7 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/StreamCompareHint.cs @@ -0,0 +1,46 @@ +using System.Text; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// +public sealed class StreamCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.StreamHint; + + /// + protected override IEnumerable Compare( + Stream expected, + Stream actual, + IValuerChainer chainer + ) + { + return chainer.Compare(ReadContents(expected, chainer), ReadContents(actual, chainer)); + } + + /// + protected override int GetHashCode(Stream item, IValuerChainer chainer) + { + return chainer.GetHashCode(ReadContents(item, chainer)); + } + + private static IEnumerable ReadContents(Stream stream, IValuerChainer chainer) + { + stream.Flush(); + + long startingPosition = stream.Position; + stream.Position = 0; + + using StreamReader reader = new(stream, Encoding.UTF8, true, 1024, true); + for (int i = 0; !reader.EndOfStream; i++) + { + ArgumentGuard.ThrowUponIterationLimit(i, chainer.Options.Design.IterationLimit); + + yield return reader.ReadLine(); + } + + stream.Position = startingPosition; + } +} diff --git a/src/Toolbox/ValuerTool/Hints/StructuralEquatableCompareHint.cs b/src/Toolbox/ValuerTool/Hints/StructuralEquatableCompareHint.cs new file mode 100644 index 00000000..f36aa4ce --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/StructuralEquatableCompareHint.cs @@ -0,0 +1,40 @@ +using System.Collections; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// +public sealed class StructuralEquatableCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.StructuralEquatableHint; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + return chainer.Options.UseEquatableComparisons && expected is IStructuralEquatable; + } + + /// + protected override IEnumerable Compare( + IStructuralEquatable expected, + IStructuralEquatable actual, + IValuerChainer chainer + ) + { + if (!expected.Equals(actual, chainer)) + { + return [new Difference(expected, actual)]; + } + else + { + return []; + } + } + + /// + protected override int GetHashCode(IStructuralEquatable item, IValuerChainer chainer) + { + return item.GetHashCode(chainer); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/TaskCompareHint.cs b/src/Toolbox/ValuerTool/Hints/TaskCompareHint.cs new file mode 100644 index 00000000..2bcf8129 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/TaskCompareHint.cs @@ -0,0 +1,160 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// +public sealed class TaskCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.TaskHint; + + /// + protected override IEnumerable Compare( + Task expected, + Task actual, + IValuerChainer chainer + ) + { + return chainer.Compare(ExtractData(expected), ExtractData(actual)); + } + + /// + protected override IAsyncEnumerable CompareAsync( + Task expected, + Task actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return HandleCompareAsync(expected, actual, chainer, canceler); + } + + /// + private static async IAsyncEnumerable HandleCompareAsync( + Task expected, + Task actual, + IValuerChainer chainer, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + await foreach ( + Difference diff in chainer + .CompareAsync( + await ExtractDataAsync(expected, chainer, canceler).ConfigureAwait(false), + await ExtractDataAsync(actual, chainer, canceler).ConfigureAwait(false), + canceler + ) + .ConfigureAwait(false) + ) + { + yield return diff; + } + } + + /// + protected override int GetHashCode(Task item, IValuerChainer chainer) + { + return chainer.GetHashCode(ExtractData(item)); + } + + /// + protected override async Task GetHashCodeAsync( + Task item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return await chainer + .GetHashCodeAsync( + await ExtractDataAsync(item, chainer, canceler).ConfigureAwait(false), + canceler + ) + .ConfigureAwait(false); + } + + /// Converts the to comparable data. + /// Instance intended to be compared. + /// The found data to use for comparisons. + private static object? ExtractData(Task item) + { + if (item.IsCompleted && !item.IsCanceled && !item.IsFaulted && IsGenericTask(item)) + { + return GrabResult(item); + } + else + { + return (item.Status, item.Exception); + } + } + + /// + /// + private static async Task ExtractDataAsync( + Task item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + using CancellationTokenSource timeoutTokenSource = + CancellationTokenSource.CreateLinkedTokenSource(canceler); + + if ( + !item.IsCompleted + && await Task.WhenAny( + item, + Task.Delay(chainer.Options.AsyncTimeout, timeoutTokenSource.Token) + ) + .ConfigureAwait(false) != item + ) + { + canceler.ThrowIfCancellationRequested(); + throw new EngineException( + $"Attempting to await the {GenericConverter.ExpandName(item)} exceeded the timeout " + + $"({nameof(ValuerOptions.AsyncTimeout)}) of '{chainer.Options.AsyncTimeout}'." + ); + } + + await AsyncSeriesHelper.TriggerCancellationAsync(timeoutTokenSource).ConfigureAwait(false); + + if (!item.IsCanceled && !item.IsFaulted && IsGenericTask(item)) + { + return GrabResult(item); + } + else + { + return (item.Status, item.Exception); + } + } + + /// Retrieves data from a completed task. + /// Wrapped data. + /// The unwrapped result. + private static object? GrabResult(Task task) + { + PropertyInfo resultProp = TypeDescriber + .For(task.GetType()) + .Properties.OnlyPublic.First(p => p.Name == "Result"); + + // await ((dynamic)result) crashes legacy .NET. + return resultProp.GetValue(task); + } + + /// Determines if the is a . + /// Instance to check. + /// + /// if the is generic, false otherwise. + /// + private static bool IsGenericTask(Task item) + { + return GenericConverter + .AsConcreteType(item.GetType(), typeof(Task<>)) + ?.GetGenericArguments() + .Single() + .Name.Contains("VoidTaskResult", StringComparison.Ordinal) == false; + } +} diff --git a/src/Toolbox/ValuerTool/Hints/ValueEquatableCompareHint.cs b/src/Toolbox/ValuerTool/Hints/ValueEquatableCompareHint.cs new file mode 100644 index 00000000..00aa6e45 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/ValueEquatableCompareHint.cs @@ -0,0 +1,55 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing instances for . +public sealed class ValueEquatableCompareHint : CompareHint +{ + /// Compares equatables by value as well. + private static readonly PrivateObjectCompareHint _NestedHint = new(); + + /// + public override int EnginePriority => (int)ComparePriority.ValueEquatableHint; + + /// + protected override IEnumerable Compare( + IValueEquatable expected, + IValueEquatable actual, + IValuerChainer chainer + ) + { + return LazyCompare(expected, actual, chainer); + } + + /// + private static IEnumerable LazyCompare( + IValueEquatable expected, + IValueEquatable actual, + IValuerChainer chainer + ) + { + if (!expected.ValuesEqual(actual)) + { + yield return new Difference( + $".{nameof(IValuerEquatable.ValuesEqual)}", + new Difference(true, false) + ); + + DifferenceHintResult byValues = _NestedHint.TryToCompare(expected, actual, chainer); + if (byValues.HasData) + { + foreach (Difference difference in byValues.Data!) + { + yield return difference; + } + } + } + } + + /// + protected override int GetHashCode(IValueEquatable item, IValuerChainer chainer) + { + return ValueComparer.Use.GetHashCode(item); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/ValueTaskCompareHint.cs b/src/Toolbox/ValuerTool/Hints/ValueTaskCompareHint.cs new file mode 100644 index 00000000..5d8df7a8 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/ValueTaskCompareHint.cs @@ -0,0 +1,92 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// +public sealed class ValueTaskCompareHint : CompareHint +{ + /// + protected override bool EnableValueHashForComparisons => false; + + /// + public override int EnginePriority => (int)ComparePriority.ValueTaskHint; + + /// + public override IEnumerable SupportedTypes => [typeof(ValueTask<>)]; + + /// + protected override bool Supports(object expected, object actual, IValuerChainer chainer) + { + return TypeDescriber.For(expected.GetType()).Inherits(typeof(ValueTask<>)); + } + + /// + protected override IEnumerable Compare( + object expected, + object actual, + IValuerChainer chainer + ) + { + if (expected.GetType() != actual.GetType()) + { + return [new Difference(expected.GetType(), actual.GetType())]; + } + else + { + return CompareTasks((dynamic)expected, (dynamic)actual, chainer); + } + } + + /// + protected override int GetHashCode(object item, IValuerChainer chainer) + { + return GetTaskHashCode((dynamic)item, chainer); + } + + /// + private static IEnumerable CompareTasks( + ValueTask expected, + ValueTask actual, + IValuerChainer chainer + ) + { + SingleCallValueTaskSource? expectedSource = SingleCallValueTaskSource.ExtractFrom( + expected + ); + SingleCallValueTaskSource? actualSource = SingleCallValueTaskSource.ExtractFrom( + actual + ); + + foreach (Difference diff in chainer.Compare(expectedSource, actualSource)) + { + yield return new Difference("(Source)", diff); + } + + foreach ( + Difference diff in chainer.Compare( + SingleCallValueTaskSource.ExtractTokenFrom(expected), + SingleCallValueTaskSource.ExtractTokenFrom(actual) + ) + ) + { + yield return new Difference("(Token)", diff); + } + } + + /// + private static int GetTaskHashCode(ValueTask item, IValuerChainer chainer) + { + int hash = chainer.GetHashCode(SingleCallValueTaskSource.ExtractTokenFrom(item)); + + SingleCallValueTaskSource? source = SingleCallValueTaskSource.ExtractFrom(item); + if (source != null) + { + hash = hash * ValueComparer.HashMultiplier + chainer.GetHashCode(source); + } + + return hash; + } +} diff --git a/src/Toolbox/ValuerTool/Hints/ValuerAsyncComparableCompareHint.cs b/src/Toolbox/ValuerTool/Hints/ValuerAsyncComparableCompareHint.cs new file mode 100644 index 00000000..61c55ec8 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/ValuerAsyncComparableCompareHint.cs @@ -0,0 +1,71 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing instances for . +public sealed class ValuerAsyncComparableCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.ValuerAsyncComparableHint; + + /// + protected override IEnumerable Compare( + IValuerAsyncComparable expected, + IValuerAsyncComparable actual, + IValuerChainer chainer + ) + { + if (chainer.Options.SkipAsyncValues) + { + return []; + } + else + { + throw new EngineException( + "Cannot compare IValuerAsyncComparables in synchronous context " + + $"using {nameof(IValuer)}. Use {nameof(IAsserter)} to " + + "compare IAsyncEnumerables in asynchronous context." + ); + } + } + + /// + protected override IAsyncEnumerable CompareAsync( + IValuerAsyncComparable expected, + IValuerAsyncComparable actual, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return expected.CompareAsync(actual, chainer, canceler); + } + + /// + protected override int GetHashCode(IValuerAsyncComparable item, IValuerChainer chainer) + { + if (chainer.Options.SkipAsyncValues) + { + return 0; + } + else + { + throw new EngineException( + "Cannot hash IValuerAsyncComparable in synchronous " + + $"context using {nameof(IValuer)}. Collect into a " + + "synchronous collection before attempting to hash." + ); + } + } + + /// + protected override Task GetHashCodeAsync( + IValuerAsyncComparable item, + IValuerChainer chainer, + CancellationToken canceler + ) + { + return item.GetValueHashAsync(chainer, canceler); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/ValuerComparableCompareHint.cs b/src/Toolbox/ValuerTool/Hints/ValuerComparableCompareHint.cs new file mode 100644 index 00000000..57b8a608 --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/ValuerComparableCompareHint.cs @@ -0,0 +1,26 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing instances for . +public sealed class ValuerComparableCompareHint : CompareHint +{ + /// + public override int EnginePriority => (int)ComparePriority.ValuerComparableHint; + + /// + protected override IEnumerable Compare( + IValuerComparable expected, + IValuerComparable actual, + IValuerChainer chainer + ) + { + return expected.Compare(actual, chainer); + } + + /// + protected override int GetHashCode(IValuerComparable item, IValuerChainer chainer) + { + return item.GetValueHash(chainer); + } +} diff --git a/src/Toolbox/ValuerTool/Hints/ValuerEquatableCompareHint.cs b/src/Toolbox/ValuerTool/Hints/ValuerEquatableCompareHint.cs new file mode 100644 index 00000000..3018acda --- /dev/null +++ b/src/Toolbox/ValuerTool/Hints/ValuerEquatableCompareHint.cs @@ -0,0 +1,54 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool.Hints; + +/// Handles comparing instances for . +public sealed class ValuerEquatableCompareHint : CompareHint +{ + /// Compares equatables by value as well. + private static readonly PrivateObjectCompareHint _NestedHint = new(); + + /// + public override int EnginePriority => (int)ComparePriority.ValuerEquatableHint; + + /// + protected override IEnumerable Compare( + IValuerEquatable expected, + IValuerEquatable actual, + IValuerChainer chainer + ) + { + return LazyCompare(expected, actual, chainer); + } + + /// + private static IEnumerable LazyCompare( + IValuerEquatable expected, + IValuerEquatable actual, + IValuerChainer chainer + ) + { + if (!expected.ValuesEqual(actual, chainer)) + { + yield return new Difference( + $".{nameof(IValuerEquatable.ValuesEqual)}", + new Difference(true, false) + ); + + DifferenceHintResult byValues = _NestedHint.TryToCompare(expected, actual, chainer); + if (byValues.HasData) + { + foreach (Difference difference in byValues.Data!) + { + yield return difference; + } + } + } + } + + /// + protected override int GetHashCode(IValuerEquatable item, IValuerChainer chainer) + { + return item.GetValueHash(chainer); + } +} diff --git a/src/Toolbox/ValuerTool/IValuer.cs b/src/Toolbox/ValuerTool/IValuer.cs new file mode 100644 index 00000000..1fbf43ac --- /dev/null +++ b/src/Toolbox/ValuerTool/IValuer.cs @@ -0,0 +1,142 @@ +global using ValuerMod = System.Func< + Werecodent.CreateAndFake.ValuerTool.ValuerOptions, + Werecodent.CreateAndFake.ValuerTool.ValuerOptions +>; +using System.Collections; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool; + +#pragma warning disable CA1068 // Overloaded parameter last. + +/// Tool to compare s by value via reflection if needed. +/// +/// Useful for checking equality between s without having to override +/// and manually. +/// +public interface IValuer + : IHintTool, + IAsyncEqualityComparer, + IEqualityComparer, + IEqualityComparer +{ + /// Creates a new tool with the changes applied. + /// Modifications of this tool's options for the new tool. + /// The created tool. + IValuer WithOptions(ValuerMod optionConfiguration); + + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + /// + /// + IEnumerable Compare( + object? expected, + object? actual, + ValuerMod? optionConfiguration = null + ); + + /// Finds the differences between and . + /// Instance to compare with . + /// Potentially different object to compare against . + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// Found differences between and . + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + /// + /// + /// + IAsyncEnumerable CompareAsync( + object? expected, + object? actual, + CancellationToken canceler, + ValuerMod? optionConfiguration = null + ); + + /// + new bool Equals(object? x, object? y); + + /// + bool Equals(object? x, object? y, ValuerMod? optionConfiguration); + + /// + new Task EqualsAsync(object? x, object? y, CancellationToken canceler); + + /// Determines if equals by value. + /// Instance to compare with . + /// Instance to compare with . + /// + /// if equals by value, + /// otherwise. + /// + /// + Task EqualsAsync( + object? x, + object? y, + CancellationToken canceler, + ValuerMod? optionConfiguration + ); + + /// + new int GetHashCode(object? item); + + /// + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + int GetHashCode(object? item, ValuerMod? optionConfiguration); + + /// + new Task GetHashCodeAsync(object? item, CancellationToken canceler); + + /// Computes an identifying hash code for based upon value. + /// Instance to generate a hash code for. + /// Aborts execution if triggered. + /// Modifications of this tool's options to apply for this call. + /// The value computed hash code for . + /// + /// Important relevant options: + /// + /// + /// + /// + /// + /// + Task GetHashCodeAsync( + object? item, + CancellationToken canceler, + ValuerMod? optionConfiguration + ); + + /// Provides a comparer that uses this tool as the source for the comparisons. + /// to compare. + /// The comparer to use. + IEqualityComparer ToComparer(); + + /// Provides a comparer that uses this tool as the source for the comparisons. + /// to compare. + /// The comparer to use. + IAsyncEqualityComparer ToAsyncComparer(); +} + +#pragma warning restore diff --git a/src/Toolbox/ValuerTool/IValuerAsyncComparable.cs b/src/Toolbox/ValuerTool/IValuerAsyncComparable.cs new file mode 100644 index 00000000..cfb4fd0e --- /dev/null +++ b/src/Toolbox/ValuerTool/IValuerAsyncComparable.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.ValuerTool; + +/// Provides value equality with the aid of an . +public interface IValuerAsyncComparable +{ + /// Handles comparison behavior for child values. + /// + IAsyncEnumerable CompareAsync( + object? other, + IValuer valuer, + CancellationToken canceler = default + ); + + /// Handles hashing behavior for child values. + /// + Task GetValueHashAsync(IValuer valuer, CancellationToken canceler); +} diff --git a/src/Toolbox/ValuerTool/IValuerComparable.cs b/src/Toolbox/ValuerTool/IValuerComparable.cs new file mode 100644 index 00000000..c37ec323 --- /dev/null +++ b/src/Toolbox/ValuerTool/IValuerComparable.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.ValuerTool; + +/// Provides value equality with the aid of an . +public interface IValuerComparable : IValuerEquatable +{ + /// Handles comparison behavior for child values. + /// + IEnumerable Compare(object? other, IValuer valuer); +} diff --git a/src/CreateAndFake/Toolbox/ValuerTool/IValuerEquatable.cs b/src/Toolbox/ValuerTool/IValuerEquatable.cs similarity index 83% rename from src/CreateAndFake/Toolbox/ValuerTool/IValuerEquatable.cs rename to src/Toolbox/ValuerTool/IValuerEquatable.cs index e0bbdf59..297b7956 100644 --- a/src/CreateAndFake/Toolbox/ValuerTool/IValuerEquatable.cs +++ b/src/Toolbox/ValuerTool/IValuerEquatable.cs @@ -1,15 +1,15 @@ -using CreateAndFake.Design.Content; - -namespace CreateAndFake.Toolbox.ValuerTool; - -/// Provides value equality with the aid of an . -public interface IValuerEquatable -{ - /// Handles comparison behavior for child values. - /// - bool ValuesEqual(object? other, IValuer valuer); - - /// Handles hashing behavior for child values. - /// - int GetValueHash(IValuer valuer); -} +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.ValuerTool; + +/// Provides value equality with the aid of an . +public interface IValuerEquatable +{ + /// Handles comparison behavior for child values. + /// + bool ValuesEqual(object? other, IValuer valuer); + + /// Handles hashing behavior for child values. + /// + int GetValueHash(IValuer valuer); +} diff --git a/src/Toolbox/ValuerTool/Valuer.cs b/src/Toolbox/ValuerTool/Valuer.cs new file mode 100644 index 00000000..939b8bd4 --- /dev/null +++ b/src/Toolbox/ValuerTool/Valuer.cs @@ -0,0 +1,176 @@ +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool; + +/// +/// +/// If given a parameter. +public sealed class Valuer(ValuerOptions options) : IValuer +{ + /// Handles hint based comparisons. + private static readonly ValuerEngine _Engine = new(); + + /// + public ValuerOptions Options { get; } = + options ?? throw new ArgumentNullException(nameof(options)); + + /// + public IEnumerable SupportedTypes => _Engine.SupportedTypes; + + /// + public IEnumerable Compare( + object? expected, + object? actual, + ValuerMod? optionConfiguration = null + ) + { + return new ValuerChainer(Options, _Engine).Compare(expected, actual, optionConfiguration); + } + + /// + public IAsyncEnumerable CompareAsync( + object? expected, + object? actual, + CancellationToken canceler, + ValuerMod? optionConfiguration = null + ) + { + return HandleCompareAsync(expected, actual, optionConfiguration, canceler); + } + + /// + private async IAsyncEnumerable HandleCompareAsync( + object? expected, + object? actual, + ValuerMod? optionConfiguration, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + ValuerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + using CancellationTokenSource timeoutSource = + CancellationTokenSource.CreateLinkedTokenSource(canceler); + + timeoutSource.CancelAfter(localOptions.AsyncTimeout); + + await foreach ( + Difference diff in new ValuerChainer(Options, _Engine) + .CompareAsync( + expected, + actual, + timeoutSource.Token, + (optionConfiguration != null) ? _ => localOptions : null + ) + .ConfigureAwait(false) + ) + { + yield return diff; + } + } + + /// + public int GetHashCode(object? item) + { + return new ValuerChainer(Options, _Engine).GetHashCode(item); + } + + /// + public int GetHashCode(object? item, ValuerMod? optionConfiguration) + { + return new ValuerChainer(Options, _Engine).GetHashCode(item, optionConfiguration); + } + + /// + public Task GetHashCodeAsync(object? item, CancellationToken canceler) + { + return GetHashCodeAsync(item, canceler, null); + } + + /// + public async Task GetHashCodeAsync( + object? item, + CancellationToken canceler, + ValuerMod? optionConfiguration + ) + { + ValuerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + using CancellationTokenSource timeoutSource = + CancellationTokenSource.CreateLinkedTokenSource(canceler); + + timeoutSource.CancelAfter(localOptions.AsyncTimeout); + + return await new ValuerChainer(Options, _Engine) + .GetHashCodeAsync( + item, + timeoutSource.Token, + (optionConfiguration != null) ? _ => localOptions : null + ) + .ConfigureAwait(false); + } + + /// + public new bool Equals(object? x, object? y) + { + return new ValuerChainer(Options, _Engine).Equals(x, y); + } + + /// + public bool Equals(object? x, object? y, ValuerMod? optionConfiguration) + { + return new ValuerChainer(Options, _Engine).Equals(x, y, optionConfiguration); + } + + /// + public Task EqualsAsync(object? x, object? y, CancellationToken canceler) + { + return EqualsAsync(x, y, canceler, null); + } + + /// + public async Task EqualsAsync( + object? x, + object? y, + CancellationToken canceler, + ValuerMod? optionConfiguration + ) + { + ValuerOptions localOptions = optionConfiguration?.Invoke(Options) ?? Options; + + using CancellationTokenSource timeoutSource = + CancellationTokenSource.CreateLinkedTokenSource(canceler); + + timeoutSource.CancelAfter(localOptions.AsyncTimeout); + + return await new ValuerChainer(Options, _Engine) + .EqualsAsync( + x, + y, + timeoutSource.Token, + (optionConfiguration != null) ? _ => localOptions : null + ) + .ConfigureAwait(false); + } + + /// + public IEqualityComparer ToComparer() + { + return new ByValuerComparer(this); + } + + /// + public IAsyncEqualityComparer ToAsyncComparer() + { + return new ByValuerAsyncComparer(this); + } + + /// + public IValuer WithOptions(ValuerMod optionConfiguration) + { + ArgumentGuard.ThrowIfNull(optionConfiguration); + return new Valuer(optionConfiguration.Invoke(Options)); + } +} diff --git a/src/Toolbox/ValuerTool/ValuerOptions.cs b/src/Toolbox/ValuerTool/ValuerOptions.cs new file mode 100644 index 00000000..5b0faaf2 --- /dev/null +++ b/src/Toolbox/ValuerTool/ValuerOptions.cs @@ -0,0 +1,86 @@ +using System.Collections.Frozen; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Properties; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.ValuerTool; + +/// Configuration for controlling comparison behavior. +public sealed record ValuerOptions : ToolHintOptions +{ + /// Identifies the configuration section containing these settings. + internal static string ConfigSectionName { get; } = nameof(Valuer); + + /// Allows implementations to handle comparisons if applicable. + /// Useful for s with value based overrides that are otherwise not supported. + /// + [ConfigurableOption] + public bool UseEquatableComparisons { get; init; } = false; + + /// Triggers strict checking for collections. + /// + /// Collections are compared by their contents and not the + /// container unless set to . + /// + /// + [ConfigurableOption] + public bool CheckCollectionType { get; init; } = false; + + /// Excludes from comparison checks. + /// Prevents issues from the changing during comparison. + /// + [ConfigurableOption] + public bool IgnoreCurrentRandomSeed { get; init; } = true; + + /// s to use default equality/hashing. + /// Useful for s with value based overrides that are otherwise not supported. + /// [typeof(ValueTuple)] + [ConfigurableOption] + public FrozenSet DefaultEqualityTypes { get; init; } = [typeof(ValueTuple)]; + + /// How long to wait for comparisons to complete. + /// Used to gracefully fail tests instead of stalling endlessly. + /// 00:01:00.0000000 + [ConfigurableOption] + public TimeSpan AsyncTimeout { get; init; } = new(0, 1, 0); + + /// If asynchronous values should be skipped in synchronous contexts instead of throwing. + /// Useful for contexts that must be synchronous even at the potential cost of a false positive. + /// + [ConfigurableOption] + public bool SkipAsyncValues { get; init; } = false; + + /// If calculated value hashes should be included in equality comparisons. + /// Useful for validating hashing with the caveat that hash collisions can be false negatives. + /// + [ConfigurableOption] + public bool IncludeValueHashInComparison { get; init; } = false; + + /// Derives options from overridden by 's values. + /// Configuration with the potential overrides to use. + /// The created options. + internal ValuerOptions WithConfig(IConfigurationSection? config) + { + IConfigurationSection? section = config?.GetSection(ConfigSectionName); + if (section == null) + { + return this; + } + + return this with + { + IncludeValueHashInComparison = Config.GetValue(section, IncludeValueHashInComparison), + IgnoreCurrentRandomSeed = Config.GetValue(section, IgnoreCurrentRandomSeed), + UseEquatableComparisons = Config.GetValue(section, UseEquatableComparisons), + IncludeFrameworkHints = Config.GetValue(section, IncludeFrameworkHints), + DefaultEqualityTypes = Config.GetTypes(section, DefaultEqualityTypes), + CheckCollectionType = Config.GetValue(section, CheckCollectionType), + IncludeFoundHints = Config.GetValue(section, IncludeFoundHints), + MaxRecursionDepth = Config.GetValue(section, MaxRecursionDepth), + SkipAsyncValues = Config.GetValue(section, SkipAsyncValues), + AsyncTimeout = Config.GetValue(section, AsyncTimeout), + }; + } +} diff --git a/src/xUnit.v2/AssemblyTester.cs b/src/xUnit.v2/AssemblyTester.cs new file mode 100644 index 00000000..bf92851f --- /dev/null +++ b/src/xUnit.v2/AssemblyTester.cs @@ -0,0 +1,57 @@ +using Werecodent.CreateAndFake.TesterTool; +using Xunit; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public abstract class AssemblyTester : BaseAssemblyTester +{ + /// + [Fact] + public override void Tester_TestClassCoverage() + { + TestClassCoverageImplementation(); + } + + /// + [Fact] + public override Task Tester_ValidateAutoTesterInstances() + { + return ValidateAutoTesterInstancesImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_ValidateRandomDataParameters() + { + return ValidateRandomDataParametersImplementation(CancellationToken.None); + } + + /// + [Fact] + public override void Tester_ValidateTestMethodNaming() + { + ValidateTestMethodNamingImplementation([typeof(FactAttribute), typeof(TheoryAttribute)]); + } + + /// + [Fact] + public override void Tester_VerifyAllToStrings() + { + VerifyAllToStringsImplementation(); + } + + /// + [Fact] + public override Task Tester_VerifyTestSettingsConfig_Default() + { + return VerifyTestSettingsConfigImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_VerifyToolSetIntegrity() + { + return VerifyToolSetIntegrityImplementation(CancellationToken.None); + } +} diff --git a/src/xUnit.v2/AutoTester.cs b/src/xUnit.v2/AutoTester.cs new file mode 100644 index 00000000..2b10ead9 --- /dev/null +++ b/src/xUnit.v2/AutoTester.cs @@ -0,0 +1,43 @@ +using Werecodent.CreateAndFake.TesterTool; +using Xunit; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public abstract class AutoTester(Type testType) : BaseAutoTester(testType) +{ + /// + [Fact] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/xUnit.v2/AutoTester{T}.cs b/src/xUnit.v2/AutoTester{T}.cs new file mode 100644 index 00000000..27aa87fb --- /dev/null +++ b/src/xUnit.v2/AutoTester{T}.cs @@ -0,0 +1,43 @@ +using Werecodent.CreateAndFake.TesterTool; +using Xunit; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public abstract class AutoTester : BaseAutoTester +{ + /// + [Fact] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(CancellationToken.None); + } + + /// + [Fact] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/xUnit.v2/CapAttribute.cs b/src/xUnit.v2/CapAttribute.cs new file mode 100644 index 00000000..cbbb0326 --- /dev/null +++ b/src/xUnit.v2/CapAttribute.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public sealed class CapAttribute : BaseCapAttribute +{ + /// + public CapAttribute(object min, object max) + : base(min, max) { } + + /// + public CapAttribute(object max) + : base(max) { } + + /// + public override object Clone() + { + return IsMinSet ? new CapAttribute(Min, Max) : new CapAttribute(Max); + } +} diff --git a/src/xUnit.v2/CopyAttribute.cs b/src/xUnit.v2/CopyAttribute.cs new file mode 100644 index 00000000..50595853 --- /dev/null +++ b/src/xUnit.v2/CopyAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public sealed class CopyAttribute : BaseCopyAttribute; diff --git a/src/xUnit.v2/CreateAndFake.xUnit.v2.csproj b/src/xUnit.v2/CreateAndFake.xUnit.v2.csproj new file mode 100644 index 00000000..8b0126ce --- /dev/null +++ b/src/xUnit.v2/CreateAndFake.xUnit.v2.csproj @@ -0,0 +1,16 @@ + + + + net11.0;net10.0;netstandard2.0 + + + + A C# class library that handles mocking, test data generation, and validation. + + + + + + + + diff --git a/src/xUnit.v2/FakeAttribute.cs b/src/xUnit.v2/FakeAttribute.cs new file mode 100644 index 00000000..bd7d2e12 --- /dev/null +++ b/src/xUnit.v2/FakeAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public sealed class FakeAttribute : BaseFakeAttribute; diff --git a/src/xUnit.v2/InjectAttribute.cs b/src/xUnit.v2/InjectAttribute.cs new file mode 100644 index 00000000..c4c40b49 --- /dev/null +++ b/src/xUnit.v2/InjectAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public sealed class InjectAttribute : BaseInjectAttribute; diff --git a/src/xUnit.v2/RandomDataAttribute.cs b/src/xUnit.v2/RandomDataAttribute.cs new file mode 100644 index 00000000..c31b0f1f --- /dev/null +++ b/src/xUnit.v2/RandomDataAttribute.cs @@ -0,0 +1,91 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.RunnerTool.Attributes; +using Xunit.Sdk; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +/// Flags methods +/// to be populated with random values for testing. +/// +/// +/// Earlier Parameters will be used to construct later Parameters if possible.
+/// Use with Parameter attributes to control randomization behavior: +/// +/// , +/// & +/// +/// +/// +/// Example test: +/// [Theory, RandomData] +/// internal static void Test([Size(2)] string data) +/// { +/// data.Length.Assert().Is(2); +/// } +/// +///
+[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class RandomDataAttribute : DataAttribute, IRandomDataMarker +{ + /// Number of times to run the attached test. + public int Trials { get; set; } = 1; + + /// + public override IEnumerable GetData(MethodInfo testMethod) + { + if (testMethod == null) + { + return []; + } + + List results = []; + for (int i = 0; i < Trials; i++) + { + try + { + ArgumentGuard.ThrowUponIterationLimit( + i, + Tools.Runner.Options.Design.IterationLimit + ); + MethodCallWrapper data = Tools.Runner.CreateFor(testMethod, default); + results.Add([.. data.Args.Select(FixArg)]); + } + catch (Exception e) + { + Console.Error.WriteLine($"Test generation failure on {testMethod}= {e.Message}"); + break; + } + } + return results; + } + + /// Fixes to be compatible with xUnit. + /// Generated Parameter argument to fix. + /// , modified if necessary. + /// Prevents crashes due to displaying in results/windows. + private static object? FixArg(object? arg) + { + if (arg is IFaked faked) + { + if (arg is IReflectableType reflectable) + { + reflectable.GetTypeInfo().SetupReturn(typeof(Type), Times.Any); + } + if (arg is Type type) + { + type.UnderlyingSystemType.SetupReturn(typeof(Type).UnderlyingSystemType, Times.Any); + type.FullName.SetupReturn(typeof(Type).FullName, Times.Any); + type.IsArray.SetupReturn(typeof(Type).IsArray, Times.Any); + } + faked.ToString().SetupReturn(GenericConverter.ExpandName(faked), Times.Any); + } + return arg; + } +} diff --git a/src/xUnit.v2/SizeAttribute.cs b/src/xUnit.v2/SizeAttribute.cs new file mode 100644 index 00000000..67f66265 --- /dev/null +++ b/src/xUnit.v2/SizeAttribute.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public sealed class SizeAttribute : BaseSizeAttribute +{ + /// + public SizeAttribute(int min, int max) + : base(min, max) { } + + /// + public SizeAttribute(int count) + : base(count) { } +} diff --git a/src/xUnit.v2/StubAttribute.cs b/src/xUnit.v2/StubAttribute.cs new file mode 100644 index 00000000..86ac1fd8 --- /dev/null +++ b/src/xUnit.v2/StubAttribute.cs @@ -0,0 +1,32 @@ +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Extensions; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public sealed class StubAttribute : BaseStubAttribute +{ + /// + protected override object? CreateParameterValue( + ParameterInfo param, + MethodBase method, + OrderedDictionary args, + RunnerOptions localOptions + ) + { + ArgumentGuard.ThrowIfNull(param, localOptions); + + if (param.ParameterType.Inherits()) + { + return localOptions.Faker.Stub(param.ParameterType, typeof(IReflectableType)).Dummy; + } + else + { + return base.CreateParameterValue(param, method, args, localOptions); + } + } +} diff --git a/src/xUnit.v2/UniqueAttribute.cs b/src/xUnit.v2/UniqueAttribute.cs new file mode 100644 index 00000000..7e87dc6c --- /dev/null +++ b/src/xUnit.v2/UniqueAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v2; + +/// +public sealed class UniqueAttribute : BaseUniqueAttribute; diff --git a/src/xUnit.v3/AssemblyTester.cs b/src/xUnit.v3/AssemblyTester.cs new file mode 100644 index 00000000..770346e1 --- /dev/null +++ b/src/xUnit.v3/AssemblyTester.cs @@ -0,0 +1,57 @@ +using Werecodent.CreateAndFake.TesterTool; +using Xunit; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public abstract class AssemblyTester : BaseAssemblyTester +{ + /// + [Fact] + public override void Tester_TestClassCoverage() + { + TestClassCoverageImplementation(); + } + + /// + [Fact] + public override Task Tester_ValidateAutoTesterInstances() + { + return ValidateAutoTesterInstancesImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_ValidateRandomDataParameters() + { + return ValidateRandomDataParametersImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override void Tester_ValidateTestMethodNaming() + { + ValidateTestMethodNamingImplementation([typeof(FactAttribute), typeof(TheoryAttribute)]); + } + + /// + [Fact] + public override void Tester_VerifyAllToStrings() + { + VerifyAllToStringsImplementation(); + } + + /// + [Fact] + public override Task Tester_VerifyTestSettingsConfig_Default() + { + return VerifyTestSettingsConfigImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_VerifyToolSetIntegrity() + { + return VerifyToolSetIntegrityImplementation(TestContext.Current.CancellationToken); + } +} diff --git a/src/xUnit.v3/AutoTester.cs b/src/xUnit.v3/AutoTester.cs new file mode 100644 index 00000000..ceb0c821 --- /dev/null +++ b/src/xUnit.v3/AutoTester.cs @@ -0,0 +1,43 @@ +using Werecodent.CreateAndFake.TesterTool; +using Xunit; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public abstract class AutoTester(Type testType) : BaseAutoTester(testType) +{ + /// + [Fact] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/xUnit.v3/AutoTester{T}.cs b/src/xUnit.v3/AutoTester{T}.cs new file mode 100644 index 00000000..f8e90559 --- /dev/null +++ b/src/xUnit.v3/AutoTester{T}.cs @@ -0,0 +1,43 @@ +using Werecodent.CreateAndFake.TesterTool; +using Xunit; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public abstract class AutoTester : BaseAutoTester +{ + /// + [Fact] + public override Task Tester_GuardsNulls() + { + return GuardsNullsImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_NoParameterMutation() + { + return NoParameterMutationImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_ValueEqualityOverrideCheck() + { + return ValueEqualityOverrideCheckImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_ToolSupport() + { + return ToolSupportImplementation(TestContext.Current.CancellationToken); + } + + /// + [Fact] + public override Task Tester_Debug_ToString() + { + return DebugToStringImplementation(); + } +} diff --git a/src/xUnit.v3/CapAttribute.cs b/src/xUnit.v3/CapAttribute.cs new file mode 100644 index 00000000..027dc457 --- /dev/null +++ b/src/xUnit.v3/CapAttribute.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public sealed class CapAttribute : BaseCapAttribute +{ + /// + public CapAttribute(object min, object max) + : base(min, max) { } + + /// + public CapAttribute(object max) + : base(max) { } + + /// + public override object Clone() + { + return IsMinSet ? new CapAttribute(Min, Max) : new CapAttribute(Max); + } +} diff --git a/src/xUnit.v3/CopyAttribute.cs b/src/xUnit.v3/CopyAttribute.cs new file mode 100644 index 00000000..e5d03524 --- /dev/null +++ b/src/xUnit.v3/CopyAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public sealed class CopyAttribute : BaseCopyAttribute; diff --git a/src/xUnit.v3/CreateAndFake.xUnit.v3.csproj b/src/xUnit.v3/CreateAndFake.xUnit.v3.csproj new file mode 100644 index 00000000..9b2fb8eb --- /dev/null +++ b/src/xUnit.v3/CreateAndFake.xUnit.v3.csproj @@ -0,0 +1,16 @@ + + + + net11.0;net10.0;netstandard2.0 + + + + A C# class library that handles mocking, test data generation, and validation. + + + + + + + + diff --git a/src/xUnit.v3/FakeAttribute.cs b/src/xUnit.v3/FakeAttribute.cs new file mode 100644 index 00000000..e88ce6e7 --- /dev/null +++ b/src/xUnit.v3/FakeAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public sealed class FakeAttribute : BaseFakeAttribute; diff --git a/src/xUnit.v3/InjectAttribute.cs b/src/xUnit.v3/InjectAttribute.cs new file mode 100644 index 00000000..42c7037f --- /dev/null +++ b/src/xUnit.v3/InjectAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public sealed class InjectAttribute : BaseInjectAttribute; diff --git a/src/xUnit.v3/Properties/AssemblyInfo.cs b/src/xUnit.v3/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..57d42974 --- /dev/null +++ b/src/xUnit.v3/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("CreateAndFake.xUnit.v3.Tests")] diff --git a/src/xUnit.v3/RandomDataAttribute.cs b/src/xUnit.v3/RandomDataAttribute.cs new file mode 100644 index 00000000..d485cad7 --- /dev/null +++ b/src/xUnit.v3/RandomDataAttribute.cs @@ -0,0 +1,116 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.RunnerTool.Attributes; +using Xunit; +using Xunit.Sdk; +using Xunit.v3; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +/// Flags methods to be populated with random values for testing. +/// +/// +/// Earlier Parameters will be used to construct later Parameters if possible.
+/// Use with Parameter attributes to control randomization behavior: +/// +/// , +/// & +/// +/// +/// +/// Example test: +/// [Theory, RandomData] +/// internal static void Test([Size(2)] string data) +/// { +/// data.Length.Assert().Is(2); +/// } +/// +///
+[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class RandomDataAttribute : DataAttribute, IRandomDataMarker +{ + /// + public int Trials { get; set; } = 1; + + /// + public override async ValueTask> GetData( + MethodInfo testMethod, + DisposalTracker disposalTracker + ) + { + if (testMethod == null) + { + return []; + } + + List data = []; + for (int i = 0; i < Trials; i++) + { + try + { + ArgumentGuard.ThrowUponIterationLimit( + i, + Tools.Runner.Options.Design.IterationLimit + ); + + MethodCallWrapper test = await Tools + .Runner.CreateForAsync(testMethod, default) + .ConfigureAwait(false); + + data.Add( + new TheoryDataRow([.. test.Args.Select(FixArg)]) + { + Label = GenericConverter.BuildTestParametersName(test.Method), + } + ); + } + catch (Exception e) + { +#pragma warning disable MA0040 // Not available for all .NET versions. + await Console + .Error.WriteLineAsync( + $"Test generation failure on {testMethod.Name}= {e.Message}" + ) + .ConfigureAwait(false); +#pragma warning restore MA0040 + break; + } + } + + disposalTracker?.AddRange( + data.Select(row => SafeDisposer.TryTracking(testMethod.Name, row.GetData())) + .Where(d => d != null) + ); + + return data; + } + + /// + public override bool SupportsDiscoveryEnumeration() + { + return false; + } + + /// Fixes to be compatible with xUnit. + /// Generated Parameter argument to fix. + /// , modified if necessary. + /// Prevents crashes due to displaying in results/windows. + private static object? FixArg(object? arg) + { + if (arg is IFaked faked) + { + if (arg is IReflectableType reflectable) + { + reflectable.GetTypeInfo().SetupReturn(typeof(Type), Times.Any); + } + faked.ToString().SetupReturn(GenericConverter.ExpandName(faked), Times.Any); + } + return arg; + } +} diff --git a/src/xUnit.v3/SafeDisposer.cs b/src/xUnit.v3/SafeDisposer.cs new file mode 100644 index 00000000..f76a7816 --- /dev/null +++ b/src/xUnit.v3/SafeDisposer.cs @@ -0,0 +1,97 @@ +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +#pragma warning disable CA1816 // To prevent crashing the entire program. +#pragma warning disable MA0040 // Not available for all .NET versions. + +/// Handles disposing randomly generated data with logging for failures. +internal sealed class SafeDisposer : IAsyncDisposable +{ + /// Name of the method the data was generated for. + private readonly string _methodName; + + /// Generated synchronous disposables to handle. + private readonly IEnumerable _disposables; + + /// Generated asynchronous disposables to handle. + private readonly IEnumerable _asyncDisposables; + + /// + public async ValueTask DisposeAsync() + { + foreach (IDisposable current in _disposables) + { + try + { + current.Dispose(); + } + catch (Exception e) + { + // Prevent test harness crashes. + GC.SuppressFinalize(current); + + await Console + .Error.WriteLineAsync($"Disposal failure from {_methodName}= {e.Message}") + .ConfigureAwait(false); + } + } + foreach (IAsyncDisposable current in _asyncDisposables) + { + try + { + await current.DisposeAsync().ConfigureAwait(false); + } + catch (Exception e) + { + // Prevent test harness crashes. + GC.SuppressFinalize(current); + + await Console + .Error.WriteLineAsync($"Disposal failure from {_methodName}= {e.Message}") + .ConfigureAwait(false); + } + } + } + + /// + /// + /// + /// + private SafeDisposer( + string methodName, + IEnumerable disposables, + IEnumerable asyncDisposables + ) + { + _methodName = methodName; + _disposables = disposables; + _asyncDisposables = asyncDisposables; + } + + /// Wraps all disposables from the if any. + /// + /// Generated data for the method with potential disposables. + /// Instance if there are any disposables, if none. + public static SafeDisposer? TryTracking(string methodName, IEnumerable items) + { + ArgumentGuard.ThrowIfNull(items); + + object?[] disposables = [.. items.Where(item => item is IDisposable or IAsyncDisposable)]; + + if (disposables.Length != 0) + { + return new( + methodName, + disposables.OfType(), + disposables.OfType() + ); + } + else + { + return null; + } + } +} + +#pragma warning restore diff --git a/src/xUnit.v3/SizeAttribute.cs b/src/xUnit.v3/SizeAttribute.cs new file mode 100644 index 00000000..18558d68 --- /dev/null +++ b/src/xUnit.v3/SizeAttribute.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public sealed class SizeAttribute : BaseSizeAttribute +{ + /// + public SizeAttribute(int min, int max) + : base(min, max) { } + + /// + public SizeAttribute(int count) + : base(count) { } +} diff --git a/src/xUnit.v3/StubAttribute.cs b/src/xUnit.v3/StubAttribute.cs new file mode 100644 index 00000000..57dc68c3 --- /dev/null +++ b/src/xUnit.v3/StubAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public sealed class StubAttribute : BaseStubAttribute; diff --git a/src/xUnit.v3/UniqueAttribute.cs b/src/xUnit.v3/UniqueAttribute.cs new file mode 100644 index 00000000..e1500bf0 --- /dev/null +++ b/src/xUnit.v3/UniqueAttribute.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.xUnit.v3; + +/// +public sealed class UniqueAttribute : BaseUniqueAttribute; diff --git a/tests/.csharpierignore b/tests/.csharpierignore new file mode 100644 index 00000000..50005146 --- /dev/null +++ b/tests/.csharpierignore @@ -0,0 +1,2 @@ +**/*.csproj +**/Directory.Build.props diff --git a/tests/.editorconfig b/tests/.editorconfig index 93ef8e07..bcabdb87 100644 --- a/tests/.editorconfig +++ b/tests/.editorconfig @@ -1,58 +1,28 @@ [*.cs] -# Default severity for all analyzer diagnostics -dotnet_analyzer_diagnostic.severity = warning - -# CA1034: Nested types should not be visible # Needed for testing and cleaner tests. -dotnet_diagnostic.CA1034.severity = none - -# CA1044:PropertiesShouldNotBeWriteOnly -# Necessary to test write only properties. -dotnet_diagnostic.CA1044.severity = none - -# CA1051:DoNotDeclareVisibleInstanceFields -# Necessary to test publically visible instance fields. -dotnet_diagnostic.CA1051.severity = none +dotnet_diagnostic.CA1002.severity = None +dotnet_diagnostic.CA1034.severity = None +dotnet_diagnostic.CA1044.severity = None +dotnet_diagnostic.CA1051.severity = None +dotnet_diagnostic.CA1515.severity = None +dotnet_diagnostic.CA1812.severity = None +dotnet_diagnostic.CA2263.severity = None +dotnet_diagnostic.MA0016.severity = None -# CA1062: Validate parameter is non-null -# Not necessary for tests to early fail for nulls. -dotnet_diagnostic.CA1062.severity = none - -# CA1307: Specify StringComparison for clarity # Unnecessary for tests. -dotnet_diagnostic.CA1307.severity = none - -# CA1707: Identifiers should not contain underscores -# Good for test names. -dotnet_diagnostic.CA1707.severity = none - -# CA1805: Do not initialize unnecessarily -# Important for clarity and understanding intention. -dotnet_diagnostic.CA1805.severity = none +dotnet_diagnostic.CA1062.severity = None +dotnet_diagnostic.CS1591.severity = None +dotnet_diagnostic.VSTHRD200.severity = None -# CA1812: Avoid uninstantiated internal classes -# Needed for testing and cleaner tests. -dotnet_diagnostic.CA1812.severity = none - -# CS1591: Missing XML comment for publicaly visible -# Tests do not need comments. -dotnet_diagnostic.CS1591.severity = none - -# IDE0045: 'if' statement can be simplified -# IDE0046: Convert to conditional expression -# Choice should be left to developer to maximize readability. -dotnet_diagnostic.IDE0045.severity = none -dotnet_diagnostic.IDE0046.severity = none - -# IDE0048: Add parentheses for clarity -# Unneeded parentheses can hurt readability. -dotnet_diagnostic.IDE0048.severity = none +# Noise when using fluent APIs. +dotnet_diagnostic.IDE0058.severity = None -# IDE0057 Substring can be simplified -# No support in legacy frameworks. -dotnet_diagnostic.IDE0057.severity = none +# Default of .ConfigureAwait(true) for tests is proper. +dotnet_diagnostic.CA2007.severity = None +dotnet_diagnostic.MA0004.severity = None +dotnet_diagnostic.VSTHRD111.severity = None -# IDE0058: Expression value is never used -# Noise when using fluent APIs. -dotnet_diagnostic.IDE0058.severity = none +# Conflict for test name matching. +dotnet_diagnostic.CA1707.severity = None +dotnet_diagnostic.MA0048.severity = None diff --git a/tests/Configuration.Tests/CreateAndFake.Configuration.Tests.csproj b/tests/Configuration.Tests/CreateAndFake.Configuration.Tests.csproj new file mode 100644 index 00000000..1f624618 --- /dev/null +++ b/tests/Configuration.Tests/CreateAndFake.Configuration.Tests.csproj @@ -0,0 +1,36 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + exe + + + + + Always + + + + + + + + + + + + + + + + + + + diff --git a/tests/Configuration.Tests/TestSettingsTests.cs b/tests/Configuration.Tests/TestSettingsTests.cs new file mode 100644 index 00000000..0a040751 --- /dev/null +++ b/tests/Configuration.Tests/TestSettingsTests.cs @@ -0,0 +1,155 @@ +using System.Collections; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Configuration.Tests; + +public static class TestSettingsTests +{ + private static readonly ToolSet _PlainTools = ToolSet.CreateViaSeed(Tools.Gen.Next()); + + [Fact] + internal static Task VerifyTestSettingsConfig_Default() + { + return _PlainTools.Tester.ValidateTestSettingsConfigAsync( + null, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task VerifyTestSettingsConfig_Production() + { + return _PlainTools.Tester.ValidateTestSettingsConfigAsync( + "Production", + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void CreateViaConfig_SetsSeed() + { + _PlainTools.Asserter.Is(2, Tools.Gen.InitialSeed); + } + + [Fact] + internal static void CreateViaConfig_SetsDesignOptions() + { + TestConfigurableOptions(Tools.Asserter.Options.Design, _PlainTools.Asserter.Options.Design); + } + + [Fact] + internal static void CreateViaConfig_SetsAsserterOptions() + { + TestConfigurableOptions(Tools.Asserter.Options, _PlainTools.Asserter.Options); + } + + [Fact] + internal static void CreateViaConfig_SetsDuplicatorOptions() + { + TestConfigurableOptions(Tools.Duplicator.Options, _PlainTools.Duplicator.Options); + } + + [Fact] + internal static void CreateViaConfig_SetsExtractorOptions() + { + TestConfigurableOptions(Tools.Extractor.Options, _PlainTools.Extractor.Options); + } + + [Fact] + internal static void CreateViaConfig_SetsFakerOptions() + { + TestConfigurableOptions(Tools.Faker.Options, _PlainTools.Faker.Options); + } + + [Fact] + internal static void CreateViaConfig_SetsMutatorOptions() + { + TestConfigurableOptions(Tools.Mutator.Options, _PlainTools.Mutator.Options); + } + + [Fact] + internal static void CreateViaConfig_SetsRandomizerOptions() + { + TestConfigurableOptions(Tools.Randomizer.Options, _PlainTools.Randomizer.Options); + } + + [Fact] + internal static void CreateViaConfig_SetsRunnerOptions() + { + TestConfigurableOptions(Tools.Runner.Options, _PlainTools.Runner.Options); + } + + [Fact] + internal static void CreateViaConfig_SetsTesterOptions() + { + TestConfigurableOptions(Tools.Tester.Options, _PlainTools.Tester.Options); + } + + [Fact] + internal static void CreateViaConfig_SetsValuerOptions() + { + TestConfigurableOptions(Tools.Valuer.Options, _PlainTools.Valuer.Options); + } + + private static void TestConfigurableOptions(T configOptions, T plainOptions) + { + Dictionary invalids = []; + foreach ( + PropertyInfo prop in TypeDescriber + .For() + .Properties.OnlyPublic.Where(p => + Attribute.IsDefined(p, typeof(ConfigurableOptionAttribute)) + ) + ) + { + object currentValue = prop.GetValue(configOptions); + if (_PlainTools.Valuer.Equals(currentValue, prop.GetValue(plainOptions))) + { + invalids.Add(prop, currentValue); + } + else if (currentValue is IEnumerable collection) + { + bool hasData = false; + foreach (object item in collection) + { + hasData = true; + } + + if (!hasData) + { + invalids.Add(prop, "[]"); + } + } + } + _PlainTools.Asserter.IsEmpty(invalids, "Options were not set for properties."); + } + + [Fact] + internal static void FindEnvironmentName_PrioritizesSetValue() + { + string value1 = _PlainTools.Randomizer.Create(); + string value2 = _PlainTools.Randomizer.Create(); + + _PlainTools.Asserter.Is(ToolSet.FindEnvironmentName(), "Production"); + TestEnvironmentName("DOTNET_ENVIRONMENT", value1); + TestEnvironmentName("ASPNETCORE_ENVIRONMENT", value2); + _PlainTools.Asserter.Is(ToolSet.FindEnvironmentName(), "Production"); + } + + private static void TestEnvironmentName(string name, string value) + { + string originalValue = Environment.GetEnvironmentVariable(name); + + Environment.SetEnvironmentVariable(name, value); + try + { + _PlainTools.Asserter.Is(ToolSet.FindEnvironmentName(), value); + } + finally + { + Environment.SetEnvironmentVariable(name, originalValue); + } + } +} diff --git a/tests/Configuration.Tests/testsettings.Production.json b/tests/Configuration.Tests/testsettings.Production.json new file mode 100644 index 00000000..32ad1417 --- /dev/null +++ b/tests/Configuration.Tests/testsettings.Production.json @@ -0,0 +1,126 @@ +{ + "CreateAndFake": { + "Design": { + "Seed": 2, + "IterationLimit": 876, + "IncludeInfinityAndNaNGeneration": true + }, + "Asserter": { + "TriggerFailureForDebugAsserts": true, + "DisableCatchingForThrowAsserts": true, + "IncludeInternalExceptionForThrowAsserts": false, + "ComparisonModeForStringAsserts": "CurrentCulture" + }, + "Duplicator": { + "MaxRecursionDepth": 9, + "IncludeFoundHints": false, + "IncludeFrameworkHints": false, + "VerifyEqualityForClones": false + }, + "Extractor": { + "MaxRecursionDepth": 9, + "IncludeFoundHints": false, + "ExtractPrivateMembers": true, + "IncludeFrameworkHints": false, + "IgnoredTypesForUniques": [ + "Werecodent.CreateAndFake.Design.Randomization.FastRandom, CreateAndFake.Design", + "System.Int32" + ], + "NonExtractableTypes": [ + "System.String" + ] + }, + "Faker": { + "MaxRecursionDepth": 9, + "IncludeFoundHints": false, + "IncludeFrameworkHints": false + }, + "Mutator": { + "MaxRecursionDepth": 8, + "MaxAttemptsForModify": 7, + "IncludeFoundHints": false, + "AttemptLimitForUniques": 18, + "AttemptLimitForVariants": 16, + "IncludeFrameworkHints": false, + "MaxAttemptsForMutatingSets": 10, + "VerifyModifyViaValueHashes": false + }, + "Randomizer": { + "StringMinSize": 2, + "StringMaxSize": 4, + "CollectionMinSize": 2, + "CollectionMaxSize": 4, + "MaxRecursionDepth": 9, + "IncludeFoundHints": false, + "StringCharacterSet": "ABC1", + "IncludeFrameworkHints": false, + "PreferLocalSubclasses": false, + "CreateCollectionAttemptLimit": 5, + "RequireRandomizedContents": false, + "FinalConditionAttemptLimit": "Few", + "CreateObjectAttemptLimit": "00:01:00" + }, + "Runner": { + "RunTimeout": "00:00:10", + "IncludeBaseObjectMethods": true, + "MethodsToIgnore": [ + "A", + "B" + ] + }, + "Tester": { + "IncludeInternals": false, + "OnlyDeclaredMethods": true, + "IgnoreAllExceptions": true, + "IncludeConstructors": false, + "IncludeStaticMethods": false, + "IgnoreObsoleteMethods": false, + "IncludeInstanceMethods": false, + "DisablePassthroughTests": true, + "RequirePrefixInTestName": false, + "DisableToolSetSupportTests": true, + "DisableNullRefExceptionTests": true, + "DisableParameterMutationTests": true, + "ThrowsUponCancelWithEmptySeries": false, + "TestClassNameGenericSubstitutes": [ + "", + "_T_", + "_" + ], + "AllowedTestNamePrefixes": [ + "Start" + ], + "ClassCoverageExclusions": [ + "A", + "C" + ], + "IntegrityIgnorableTypes": [ + "System.ValueTuple" + ], + "TestClassNameSuffixes": [ + "Test" + ], + "IgnorableExceptions": [ + "System.Exception" + ], + "MethodsToIgnore": [ + "A", + "B" + ] + }, + "Valuer": { + "MaxRecursionDepth": 9, + "SkipAsyncValues": true, + "AsyncTimeout": "00:00:33", + "IncludeFoundHints": false, + "CheckCollectionType": true, + "IncludeFrameworkHints": false, + "UseEquatableComparisons": true, + "IgnoreCurrentRandomSeed": false, + "IncludeValueHashInComparison": true, + "DefaultEqualityTypes": [ + "System.Type" + ] + } + } +} \ No newline at end of file diff --git a/tests/Configuration.Tests/testsettings.json b/tests/Configuration.Tests/testsettings.json new file mode 100644 index 00000000..c14be724 --- /dev/null +++ b/tests/Configuration.Tests/testsettings.json @@ -0,0 +1,7 @@ +{ + "CreateAndFake": { + "Design": { + "Seed": 1 + } + } +} diff --git a/tests/CreateAndFakeTests/Attributes/RandomDataAttributeTests.cs b/tests/CreateAndFakeTests/Attributes/RandomDataAttributeTests.cs deleted file mode 100644 index 12723beb..00000000 --- a/tests/CreateAndFakeTests/Attributes/RandomDataAttributeTests.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Reflection; - -namespace CreateAndFakeTests.Attributes; - -/// Verifies behavior. -public static class RandomDataAttributeTests -{ - [Fact] - internal static void TypeExtensions_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void GetData_UsesTrials() - { - MethodInfo method = Tools.Randomizer.Create(m => !m.IsGenericMethod && !m.IsGenericMethodDefinition); - - Tools.Asserter.HasCount(0, new RandomDataAttribute() { Trials = 0 }.GetData(method)); - Tools.Asserter.HasCount(1, new RandomDataAttribute() { Trials = 1 }.GetData(method)); - Tools.Asserter.HasCount(2, new RandomDataAttribute() { Trials = 2 }.GetData(method)); - } -} diff --git a/tests/CreateAndFakeTests/CreateAndFakeTests.csproj b/tests/CreateAndFakeTests/CreateAndFakeTests.csproj deleted file mode 100644 index 143d896e..00000000 --- a/tests/CreateAndFakeTests/CreateAndFakeTests.csproj +++ /dev/null @@ -1,38 +0,0 @@ - - - - net8.0;net7.0;net48 - enable - false - - - - net8.0;net7.0 - enable - false - - - - LEGACY - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/CreateAndFakeTests/Design/ArgumentGuardTests.cs b/tests/CreateAndFakeTests/Design/ArgumentGuardTests.cs deleted file mode 100644 index c8cec8a7..00000000 --- a/tests/CreateAndFakeTests/Design/ArgumentGuardTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFakeTests.Design; - -public static class ArgumentGuardTests -{ - [Theory, RandomData] - internal static void ThrowIfNull_NoExceptionWithNonNull(object value, string name) - { - ArgumentGuard.ThrowIfNull(value, name); - } - - [Theory, RandomData] - internal static void ThrowIfNull_ExceptionWithNull(string name) - { - name.Assert(n => ArgumentGuard.ThrowIfNull(null, n)).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Design/Content/ValueComparerTests.cs b/tests/CreateAndFakeTests/Design/Content/ValueComparerTests.cs deleted file mode 100644 index a1e35377..00000000 --- a/tests/CreateAndFakeTests/Design/Content/ValueComparerTests.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System.Collections; -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Design.Content; - -#pragma warning disable CA1859 // Change to concrete types: Needed for generic resolution. - -public static class ValueComparerTests -{ - private static readonly int[] _OneValue = [0]; - - private static readonly int[] _TwoValues = [0, 0]; - - [Fact] - internal static void ValueComparer_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void ValueComparer_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Fact] - internal static void Equals_MismatchSizeFalse() - { - ValueComparer.Use.Equals(_OneValue, _TwoValues).Assert().Is(false); - ValueComparer.Use.Equals(_TwoValues, _OneValue).Assert().Is(false); - } - - [Theory, RandomData] - internal static void GetHashCode_SupportsParams(int item1, int item2, int item3) - { - Tools.Asserter.Is( - ValueComparer.Use.GetHashCode(new List { item1, item2, item3 }), - ValueComparer.Use.GetHashCode(item1, item2, item3)); - } - - [Theory, RandomData] - internal static void Equals_SupportsValueEquatable( - [Fake] IValueEquatable stub1, [Fake] IValueEquatable stub2, bool result) - { - stub1.ValuesEqual(stub2).SetupReturn(result); - stub2.ValuesEqual(stub1).SetupReturn(result); - - ValueComparer.Use.Equals(stub1, stub2).Assert().Is(result); - ValueComparer.Use.Equals((object)stub1, stub2).Assert().Is(result); - } - - [Theory, RandomData] - internal static void Equals_SupportsValueEquatableNulls([Fake] IValueEquatable stub, bool result) - { - stub.ValuesEqual(null).SetupReturn(result, 2); - ValueComparer.Use.Equals(stub, null).Assert().Is(result); - ValueComparer.Use.Equals(null, stub).Assert().Is(result); - ValueComparer.Use.Equals((IValueEquatable)null, null).Assert().Is(true); - stub.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void GetHashCode_SupportsValueEquatable([Fake] IValueEquatable stub, int hash) - { - stub.GetValueHash().SetupReturn(hash, 2); - ValueComparer.Use.GetHashCode(stub).Assert().Is(hash); - ValueComparer.Use.GetHashCode((object)stub).Assert().Is(hash); - stub.VerifyAllCalls(); - } - - [Fact] - internal static void ValueComparer_SupportsObject() - { - TestBehavior(ValueComparer.Use, ValueComparer.Use); - TestBehavior(ValueComparer.Use, ValueComparer.Use); - } - - [Fact] - internal static void ValueComparer_SupportsIEnumerable() - { - TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); - - TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); - } - - [Fact] - internal static void ValueComparer_SupportsIDictionary() - { - TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IDictionary>(ValueComparer.Use, ValueComparer.Use); - - TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IDictionary>(ValueComparer.Use, ValueComparer.Use); - - TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IDictionary>(ValueComparer.Use, ValueComparer.Use); - - TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); - TestBehavior, IDictionary>(ValueComparer.Use, ValueComparer.Use); - } - - private static void TestBehavior( - IComparer comparer, IEqualityComparer equalityComparer) where TActual : TComparer - { - TActual baseObject = Tools.Randomizer.Create(); - TActual equalObject = Tools.Duplicator.Copy(baseObject); - TActual unequalObject = Tools.Mutator.Variant(baseObject); - - Tools.Asserter.Is(true, equalityComparer.Equals(default, default)); - Tools.Asserter.Is(true, equalityComparer.Equals(baseObject, baseObject)); - Tools.Asserter.Is(true, equalityComparer.Equals(baseObject, equalObject)); - Tools.Asserter.Is(false, equalityComparer.Equals(baseObject, unequalObject)); - Tools.Asserter.Is(false, equalityComparer.Equals(baseObject, default)); - Tools.Asserter.Is(false, equalityComparer.Equals(default, baseObject)); - - Tools.Asserter.Is(0, comparer.Compare(default, default)); - Tools.Asserter.Is(0, comparer.Compare(baseObject, baseObject)); - Tools.Asserter.Is(0, comparer.Compare(baseObject, equalObject)); - Tools.Asserter.IsNot(0, comparer.Compare(baseObject, unequalObject)); - Tools.Asserter.IsNot(0, comparer.Compare(baseObject, default)); - Tools.Asserter.IsNot(0, comparer.Compare(default, baseObject)); - } -} - -#pragma warning restore CA1859 // Change to concrete types diff --git a/tests/CreateAndFakeTests/Design/Content/ValueComparer[T]Tests.cs b/tests/CreateAndFakeTests/Design/Content/ValueComparer[T]Tests.cs deleted file mode 100644 index 8d734c5e..00000000 --- a/tests/CreateAndFakeTests/Design/Content/ValueComparer[T]Tests.cs +++ /dev/null @@ -1,66 +0,0 @@ -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Design.Content; - -public static class ValueComparer_T_Tests -{ - [Fact] - internal static void ValueComparer_GuardsNulls() - { - Tools.Tester.PreventsNullRefException>(); - } - - [Fact] - internal static void ValueComparer_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation>(); - } - - [Theory, RandomData] - internal static void GetHashCode_UsesGetValueHash([Fake] IValueEquatable stub, int hash) - { - stub.GetValueHash().SetupReturn(hash, 3); - ValueComparer.Use.GetHashCode(stub).Assert().Is(hash); - ValueComparer.Use.GetHashCode([stub]).Assert().IsNot(0); - ValueComparer.Use.GetHashCode(MapByIndex([stub])).Assert().IsNot(0); - stub.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Equals_UsesValuesEqual( - [Fake] IValueEquatable stub1, [Fake] IValueEquatable stub2, bool result) - { - stub1.ValuesEqual(stub2).SetupReturn(result); - stub2.ValuesEqual(stub1).SetupReturn(result); - - ValueComparer.Use.Equals(stub1, stub2).Assert().Is(result); - ValueComparer.Use.Equals([stub1], [stub2]).Assert().Is(result); - ValueComparer.Use.Equals(MapByIndex([stub1]), MapByIndex([stub2])).Assert().Is(result); - } - - [Theory, RandomData] - internal static void Equals_UsesGetValueHash( - [Fake] IValueEquatable stub, [Fake] IValueEquatable equalStub, [Fake] IValueEquatable unequalStub, int hash) - { - stub.GetValueHash().SetupReturn(hash); - equalStub.GetValueHash().SetupReturn(hash); - unequalStub.GetValueHash().SetupReturn(hash.CreateVariant()); - - ValueComparer comparer = ValueComparer.Use; - - comparer.Compare(stub, stub).Assert().Is(0); - comparer.Compare(stub, equalStub).Assert().Is(0); - comparer.Compare(stub, unequalStub).Assert().IsNot(0); - comparer.Compare(stub, null).Assert().IsNot(0); - comparer.Compare(null, stub).Assert().IsNot(0); - comparer.Compare((IValueEquatable)null, null).Assert().Is(0); - } - - private static Dictionary MapByIndex(IEnumerable collection) - { - return collection - .Select((item, index) => new { index, item }) - .ToDictionary(pair => pair.index, pair => pair.item); - } -} diff --git a/tests/CreateAndFakeTests/Design/Context/PersonContextTests.cs b/tests/CreateAndFakeTests/Design/Context/PersonContextTests.cs deleted file mode 100644 index ad58de95..00000000 --- a/tests/CreateAndFakeTests/Design/Context/PersonContextTests.cs +++ /dev/null @@ -1,6 +0,0 @@ -using CreateAndFake.Design.Context; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Design.Context; - -public sealed class PersonContextTests : DataContextTestBase { } diff --git a/tests/CreateAndFakeTests/Design/Data/NameDataTests.cs b/tests/CreateAndFakeTests/Design/Data/NameDataTests.cs deleted file mode 100644 index d17a76eb..00000000 --- a/tests/CreateAndFakeTests/Design/Data/NameDataTests.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CreateAndFake.Design.Data; - -namespace CreateAndFakeTests.Design.Data; - -public static class NameDataTests -{ - [Fact] - internal static void Values_Populated() - { - NameData.Values.Assert().IsNotEmpty(); - } -} diff --git a/tests/CreateAndFakeTests/Design/LimiterTests.cs b/tests/CreateAndFakeTests/Design/LimiterTests.cs deleted file mode 100644 index dd1545ef..00000000 --- a/tests/CreateAndFakeTests/Design/LimiterTests.cs +++ /dev/null @@ -1,552 +0,0 @@ -using System.Diagnostics; -using System.Reflection; -using CreateAndFake.Design; - -namespace CreateAndFakeTests.Design; - -#pragma warning disable xUnit1031 // Test methods should not use blocking code: Ensures blocking code works for library. - -public static class LimiterTests -{ - private const int _WaitAccuracy = 5; - - private static readonly TimeSpan _SmallDelay = new(0, 0, 0, 0, 20); - - [Fact] - internal static void Limiter_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(Limiter.Few); - } - - [Fact] - internal static async Task Repeat_AtLeastOnce() - { - int attempts = 0; - - await new Limiter(0).Repeat(null, () => attempts++); - attempts.Assert().Is(1); - - await new Limiter(TimeSpan.MinValue).Repeat("Message", () => attempts++); - attempts.Assert().Is(2); - } - - [Fact] - internal static void StallUntil_AtLeastOnce() - { - int attempts = 0; - - new Limiter(0) - .Assert(l => l.StallUntil("", () => attempts++, () => false).Wait()) - .Throws(); - attempts.Assert().Is(1); - - new Limiter(TimeSpan.MinValue) - .Assert(l => l.StallUntil("", () => attempts++, () => false).Wait()) - .Throws(); - attempts.Assert().Is(2); - } - - [Theory, RandomData] - internal static void Retry_AtLeastOnce(Exception exception) - { - int attempts = 0; - - new Limiter(0) - .Assert(l => l.Retry("", () => { attempts++; throw exception; }).Wait()) - .Throws().InnerException.Assert().Is(exception) - .Also(attempts).Is(1); - - new Limiter(TimeSpan.MinValue).Assert(l => l.Retry("", () => { attempts++; throw exception; }).Wait()) - .Throws().InnerException.Assert().Is(exception) - .Also(attempts).Is(2); - } - - [Theory, RandomData] - internal static async Task Attempt_AtLeastOnce(Exception exception) - { - int attempts = 0; - - await new Limiter(0).Attempt("", () => { attempts++; throw exception; }); - attempts.Assert().Is(1); - - await new Limiter(TimeSpan.MinValue).Attempt("", () => { attempts++; throw exception; }); - attempts.Assert().Is(2); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static async Task Repeat_TryLimited(int tries) - { - int attempts = 0; - await new Limiter(tries).Repeat("", () => attempts++); - attempts.Assert().Is(tries); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static void StallUntil_TryLimited(int tries) - { - int attempts = 0; - - new Limiter(tries) - .Assert(l => l.StallUntil("", () => attempts++, () => false).Wait()) - .Throws(); - attempts.Assert().Is(tries); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static void Retry_TryLimited(int tries) - { - Exception exception = Tools.Randomizer.Create(); - int attempts = 0; - - new Limiter(tries) - .Assert(l => l.Retry("", () => { attempts++; throw exception; }).Wait()) - .Throws().InnerException.Assert().Is(exception) - .Also(attempts).Is(tries); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static void Attempt_TryLimited(int tries) - { - Exception exception = Tools.Randomizer.Create(); - int attempts = 0; - - new Limiter(tries).Attempt("", () => { attempts++; throw exception; }).Wait(); - attempts.Assert().Is(tries); - } - - [Fact] - internal static async Task Repeat_TimeoutLimited() - { - Stopwatch watch = Stopwatch.StartNew(); - await new Limiter(_SmallDelay).Repeat("", () => { }); - watch.Elapsed.TotalMilliseconds.Assert().GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); - } - - [Fact] - internal static void StallUntil_TimeoutLimited() - { - Stopwatch watch = Stopwatch.StartNew(); - - new Limiter(_SmallDelay) - .Assert(l => l.StallUntil("", () => { }, () => false).Wait()) - .Throws(); - - watch.Elapsed.TotalMilliseconds.Assert().GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); - } - - [Theory, RandomData] - internal static void Retry_TimeoutLimited(Exception exception) - { - Stopwatch watch = Stopwatch.StartNew(); - - new Limiter(_SmallDelay) - .Assert(l => l.Retry("", () => { throw exception; }).Wait()) - .Throws().InnerException - .Assert() - .Is(exception) - .Also(watch.Elapsed.TotalMilliseconds) - .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); - } - - [Theory, RandomData] - internal static void Attempt_TimeoutLimited(Exception exception) - { - Stopwatch watch = Stopwatch.StartNew(); - - new Limiter(_SmallDelay) - .Attempt("", () => watch.IsRunning ? throw exception : new object()).Result - .Assert() - .Is(null) - .Also(watch.Elapsed.TotalMilliseconds) - .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); - } - - [Theory, - InlineData(1), - InlineData(2), - InlineData(3)] - internal static async Task Repeat_DelayOccurs(int tries) - { - Stopwatch watch = Stopwatch.StartNew(); - await new Limiter(tries, _SmallDelay).Repeat("", () => { }); - - watch.Elapsed.TotalMilliseconds.Assert().GreaterThanOrEqualTo( - (_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); - } - - [Theory, - InlineData(1), - InlineData(2), - InlineData(3)] - internal static async Task StallUntil_DelayOccurs(int tries) - { - int attempts = 0; - - Stopwatch watch = Stopwatch.StartNew(); - await new Limiter(tries, _SmallDelay).StallUntil("", () => ++attempts == tries); - - watch.Elapsed.TotalMilliseconds.Assert().GreaterThanOrEqualTo( - (_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); - } - - [Theory, - InlineData(1), - InlineData(2), - InlineData(3)] - internal static async Task Retry_DelayOccurs(int tries) - { - Exception exception = Tools.Randomizer.Create(); - int attempts = 0; - - Stopwatch watch = Stopwatch.StartNew(); - await new Limiter(tries, _SmallDelay) - .Retry("", () => - { - if (++attempts != tries) { throw exception; } - }); - - watch.Elapsed.TotalMilliseconds.Assert().GreaterThanOrEqualTo( - (_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); - } - - [Theory, - InlineData(1), - InlineData(2), - InlineData(3)] - internal static async Task Attempt_DelayOccurs(int tries) - { - Exception exception = Tools.Randomizer.Create(); - int attempts = 0; - - Stopwatch watch = Stopwatch.StartNew(); - await new Limiter(tries, _SmallDelay) - .Attempt("", () => - { - if (++attempts != tries) { throw exception; } - }); - - watch.Elapsed.TotalMilliseconds.Assert().GreaterThanOrEqualTo( - (_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); - } - - [Fact] - internal static void Repeat_Cancelable() - { - using (CancellationTokenSource tokenSource = new()) - { - Limiter.Few - .Assert(l => l.Repeat("", () => tokenSource.Cancel(), tokenSource.Token).Wait()) - .Throws(); - } - Limiter.Few - .Assert(l => l.Repeat("Test", () => { }, new CancellationToken(true)).Wait()) - .Throws(); - - Limiter.Quick - .Assert(l => l.Repeat("", () => { }, new CancellationToken(true)).Wait()) - .Throws(); - } - - [Fact] - internal static void StallUntil_Cancelable() - { - using (CancellationTokenSource tokenSource = new()) - { - Limiter.Few - .Assert(l => l.StallUntil("", () => tokenSource.Cancel(), () => false, tokenSource.Token).Wait()) - .Throws(); - } - Limiter.Few - .Assert(l => l.StallUntil("Test", () => false, new CancellationToken(true)).Wait()) - .Throws(); - - Limiter.Quick - .Assert(l => l.StallUntil("", () => false, new CancellationToken(true)).Wait()) - .Throws(); - } - - [Theory, RandomData] - internal static void Retry_Cancelable(Exception exception) - { - using (CancellationTokenSource tokenSource = new()) - { - Limiter.Few - .Assert(l => l.Retry("", () => throw exception, () => tokenSource.Cancel(), tokenSource.Token).Wait()) - .Throws(); - } - Limiter.Few - .Assert(l => l.Retry("Test", () => throw exception, new CancellationToken(true)).Wait()) - .Throws(); - - Limiter.Quick - .Assert(l => l.Retry("", () => throw exception, new CancellationToken(true)).Wait()) - .Throws(); - } - - [Theory, RandomData] - internal static void Attempt_Cancelable(Exception exception) - { - using (CancellationTokenSource tokenSource = new()) - { - Limiter.Few - .Assert(l => l.Attempt("", () => throw exception, () => tokenSource.Cancel(), tokenSource.Token).Wait()) - .Throws(); - } - Limiter.Few - .Assert(l => l.Attempt(null, () => throw exception, new CancellationToken(true)).Wait()) - .Throws(); - - Limiter.Quick - .Assert(l => l.Attempt("", () => throw exception, new CancellationToken(true)).Wait()) - .Throws(); - } - - [Theory, RandomData] - internal static async Task Repeat_ResultsValid(List data) - { - int attempt = 0; - (await new Limiter(data.Count).Repeat("", () => data[attempt++])).Assert().Is(data.AsReadOnly()); - } - - [Theory, RandomData] - internal static async Task StallUntil_ResultsValid(List data) - { - int attempt = 0; - (await new Limiter(data.Count) - .StallUntil("", () => data[attempt++], () => attempt == data.Count)) - .Assert() - .Is(data.AsReadOnly()); - } - - [Theory, RandomData] - internal static async Task Retry_ResultsValid(int data) - { - (await new Limiter(1).Retry("", () => data)).Assert().Is(data); - (await new Limiter(1).Retry("", () => data)).Assert().Is(data); - } - - [Fact] - internal static async Task Retry_Continues() - { - int calls = 0; - - await new Limiter(2).Retry("", () => - { - calls++; - if (calls == 1) - { - throw new ArithmeticException(); - } - }); - calls.Assert().Is(2); - - await new Limiter(2).Retry("", () => - { - calls++; - if (calls == 3) - { - throw new ArithmeticException(); - } - }); - calls.Assert().Is(4); - } - - [Theory, RandomData] - internal static async Task Attempt_ResultsValid(int data) - { - (await new Limiter(1).Attempt("", () => data)).Assert().Is(data); - (await new Limiter(1).Attempt("", () => data)).Assert().Is(data); - } - - [Fact] - internal static async Task Attempt_Continues() - { - int calls = 0; - - await new Limiter(2).Attempt("", () => - { - calls++; - if (calls == 1) - { - throw new ArithmeticException(); - } - }); - calls.Assert().Is(2); - - await new Limiter(2).Attempt("", () => - { - calls++; - if (calls == 3) - { - throw new ArithmeticException(); - } - }); - calls.Assert().Is(4); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static async Task StallUntil_CheckStateBehavior(int tries) - { - int attempt = 0; - int checkAttempt = 0; - - await new Limiter(tries).StallUntil("", () => attempt++, () => ++checkAttempt == tries); - tries.Assert().Is(attempt).And.Is(checkAttempt); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static async Task Retry_ResetStateBehavior(int tries) - { - Exception exception = Tools.Randomizer.Create(); - int attempt = 0; - int resetAttempt = 0; - - await new Limiter(tries) - .Retry("", () => - { - if (++attempt != tries) { throw exception; } - }, () => resetAttempt++); - - attempt.Assert().Is(tries).Also(resetAttempt).Is(tries - 1); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static async Task Retry_ReturnResetStateBehavior(int tries) - { - Exception exception = Tools.Randomizer.Create(); - int attempt = 0; - int resetAttempt = 0; - - int result = Tools.Randomizer.Create(); - int ResetBehavior() - { - return (++attempt == tries) ? result : throw exception; - } - - (await new Limiter(tries).Retry("", ResetBehavior, () => resetAttempt++)) - .Assert().Is(result) - .Also(attempt).Is(tries) - .Also(resetAttempt).Is(tries - 1); - } - - [Theory, RandomData] - internal static void Retry_WrongExceptionThrows(NotSupportedException exception) - { - new Limiter(3) - .Assert(l => l.Retry("", (Action)(() => throw exception)).Wait()) - .Throws() - .Assert().Is(exception); - - IOException exception2 = new(); - - new Limiter(3) - .Assert(l => l.Retry("", () => throw exception2).Wait()) - .Throws().InnerExceptions.Single().Assert().Is(exception2); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static async Task Attempt_ResetStateBehavior(int tries) - { - Exception exception = Tools.Randomizer.Create(); - int attempt = 0; - int resetAttempt = 0; - - await new Limiter(tries) - .Attempt("", () => - { - if (++attempt != tries) { throw exception; } - }, () => resetAttempt++); - - attempt.Assert().Is(tries).Also(resetAttempt).Is(tries - 1); - } - - [Theory, - InlineData(1), - InlineData(3)] - internal static async Task Attempt_ReturnResetStateBehavior(int tries) - { - Exception exception = Tools.Randomizer.Create(); - int attempt = 0; - int resetAttempt = 0; - - int result = Tools.Randomizer.Create(); - int ResetBehavior() - { - return (++attempt == tries) ? result : throw exception; - } - - (await new Limiter(tries).Attempt("", ResetBehavior, () => resetAttempt++)) - .Assert().Is(result) - .Also(attempt).Is(tries) - .Also(resetAttempt).Is(tries - 1); - } - - [Theory, RandomData] - internal static void Attempt_WrongExceptionThrows(NotSupportedException exception) - { - new Limiter(3) - .Assert(l => l.Attempt(null, (Action)(() => throw exception)).Wait()) - .Throws().Assert().Is(exception); - - IOException exception2 = new(); - - new Limiter(3) - .Assert(l => l.Attempt("", () => throw exception2).Wait()) - .Throws().InnerExceptions.Single().Assert().Is(exception2); - } - - [Fact] - internal static void Limiter_DefaultsSet() - { - foreach (PropertyInfo info in typeof(Limiter) - .GetProperties(BindingFlags.Static | BindingFlags.Public) - .Where(p => p.PropertyType == typeof(Limiter))) - { - info.GetValue(null).Assert().IsNot(null); - } - } - - [Theory, RandomData] - internal static void Equality_MatchesValue(int tries, TimeSpan elapsed) - { - Limiter original = new(tries, elapsed); - Limiter dupe = new(tries, elapsed); - Limiter variant1 = new(tries.CreateVariant(), elapsed); - Limiter variant2 = new(tries, elapsed.CreateVariant()); - - true.Assert() - .Is(original.Equals(original)) - .And.Is(original.Equals(dupe)) - .And.IsNot(original.Equals(variant1)) - .And.IsNot(original.Equals(variant2)) - .Also(original.GetHashCode()) - .Is(original.GetHashCode()) - .And.Is(dupe.GetHashCode()) - .And.IsNot(variant1.GetHashCode()) - .And.IsNot(variant2.GetHashCode()); - } - - [Theory, RandomData] - internal static void ToString_Readable(int tries, TimeSpan timeout, TimeSpan delay) - { - new Limiter(timeout, tries, delay).ToString().Assert().Is($"{tries}-{timeout}-{delay}"); - } -} - -#pragma warning restore xUnit1031 // Test methods should not use blocking code diff --git a/tests/CreateAndFakeTests/Design/Randomization/DataRandomTests.cs b/tests/CreateAndFakeTests/Design/Randomization/DataRandomTests.cs deleted file mode 100644 index 5b6a8080..00000000 --- a/tests/CreateAndFakeTests/Design/Randomization/DataRandomTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design.Randomization; - -namespace CreateAndFakeTests.Design.Randomization; - -public static class DataRandomTests -{ - [Fact] - internal static void DataRandom_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void DataRandom_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void DataRandom_MaintainsValues(DataRandom testInstance) - { - foreach (PropertyInfo prop in typeof(DataRandom).GetProperties()) - { - prop.GetValue(testInstance).Assert().Is(prop.GetValue(testInstance)); - } - } - - [Theory, RandomData] - internal static void DataRandom_DataVaries(DataRandom testInstance) - { - testInstance.CreateVariant().Assert().IsNot(testInstance); - } - - [Theory, RandomData] - internal static void Find_AllSearchable(DataRandom testInstance) - { - foreach (string item in DataRandom.SupportedProperties) - { - testInstance.Find(item).Assert().IsNot(null); - } - } - - [Theory, RandomData] - internal static void Find_IgnoresSpecialChars(DataRandom testInstance) - { - testInstance.Find("_" + Tools.Gen.NextItem(DataRandom.SupportedProperties)).Assert().IsNot(null); - } - - [Theory, RandomData] - internal static void Find_MissingName(DataRandom testInstance, string name) - { - testInstance.Find(name).Assert().Is(null); - } -} diff --git a/tests/CreateAndFakeTests/Design/Randomization/FastRandomTests.cs b/tests/CreateAndFakeTests/Design/Randomization/FastRandomTests.cs deleted file mode 100644 index b3c147d7..00000000 --- a/tests/CreateAndFakeTests/Design/Randomization/FastRandomTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Design.Randomization; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Design.Randomization; - -public sealed class FastRandomTests : ValueRandomTestBase -{ - private static readonly double[] _BadDoubles = [ - double.NaN, - double.NegativeInfinity, - double.PositiveInfinity]; - - private static readonly float[] _BadFloats = [ - float.NaN, - float.NegativeInfinity, - float.PositiveInfinity]; - - [Fact] - internal static async Task Create_InvalidValuesPossible() - { - FastRandom random = new(false); - - Limiter limiter = new(15000); - await limiter.StallUntil("Trying to create bad double.", - () => _BadDoubles.Contains(random.Next())); - await limiter.StallUntil("Trying to create bad float.", - () => _BadFloats.Contains(random.Next())); - } - - [Fact] - internal static async Task Create_OnlyValidValuesPreventsInvalids() - { - FastRandom random = new(true); - - await Limiter.Myriad.Repeat("Trying to avoid bad doubles.", - () => _BadDoubles.Assert().ContainsNot(random.Next())); - await Limiter.Myriad.Repeat("Trying to avoid bad floats.", - () => _BadFloats.Assert().ContainsNot(random.Next())); - } -} diff --git a/tests/CreateAndFakeTests/Design/Randomization/SecureRandomTests.cs b/tests/CreateAndFakeTests/Design/Randomization/SecureRandomTests.cs deleted file mode 100644 index c6e85cb5..00000000 --- a/tests/CreateAndFakeTests/Design/Randomization/SecureRandomTests.cs +++ /dev/null @@ -1,6 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Design.Randomization; - -public sealed class SecureRandomTests : ValueRandomTestBase { } diff --git a/tests/CreateAndFakeTests/Design/Randomization/SeededRandomTests.cs b/tests/CreateAndFakeTests/Design/Randomization/SeededRandomTests.cs deleted file mode 100644 index 26a7cf12..00000000 --- a/tests/CreateAndFakeTests/Design/Randomization/SeededRandomTests.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Design.Randomization; - -public sealed class SeededRandomTests : ValueRandomTestBase -{ - [Fact] - internal static void Seed_Deterministic() - { - SeededRandom random1 = new(); - SeededRandom random2 = new(random1.Seed); - - random1.Next().Assert().Is(random2.Next()); - random1.Next().Assert().Is(random2.Next()); - - random2 = new SeededRandom(random1.Seed); - - random1.Next().Assert().Is(random2.Next()); - random1.Seed.Assert().Is(random2.Seed); - } -} diff --git a/tests/CreateAndFakeTests/Extensions/AssertExtensionsTests.cs b/tests/CreateAndFakeTests/Extensions/AssertExtensionsTests.cs deleted file mode 100644 index ee65566c..00000000 --- a/tests/CreateAndFakeTests/Extensions/AssertExtensionsTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace CreateAndFakeTests.Extensions; - -public static class AssertExtensionsTests -{ - [Fact] - internal static void AssertExtensions_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(typeof(AssertExtensions)); - } - - [Fact] - internal static void AssertExtensions_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(typeof(AssertExtensions)); - } - - [Theory, RandomData] - internal static void Assert_ObjectIsFluent(int data) - { - data.Assert().Is(data).And.IsNot(null); - } - - [Theory, RandomData] - internal static void Assert_StringIsFluent(string data) - { - data.Assert().Is(data).And.Contains(data).And.HasCount(data.Length); - } - - [Theory, RandomData] - internal static void Assert_CollectionIsFluent(ICollection data) - { - data.Assert().IsNotEmpty().And.Contains(data.First()); - } - - [Theory, RandomData] - public static void Assert_ComparableIsFluent(int data) - { - data.Assert().GreaterThanOrEqualTo(int.MinValue).And.LessThanOrEqualTo(int.MaxValue); - } - - [Theory, RandomData] - public static void Assert_TypeIsFluent(Exception data) - { - data.GetType().Assert().Inherits().And.Inherits(); - } -} diff --git a/tests/CreateAndFakeTests/Extensions/CreateExtensionsTests.cs b/tests/CreateAndFakeTests/Extensions/CreateExtensionsTests.cs deleted file mode 100644 index 6d6a3d2c..00000000 --- a/tests/CreateAndFakeTests/Extensions/CreateExtensionsTests.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace CreateAndFakeTests.Extensions; - -public static class CreateExtensionsTests -{ - [Fact] - internal static void CreateExtensions_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(typeof(CreateExtensions)); - } - - [Fact] - internal static void CreateExtensions_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(typeof(CreateExtensions)); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/Extensions/FakeExtensionsTests.cs b/tests/CreateAndFakeTests/Extensions/FakeExtensionsTests.cs deleted file mode 100644 index 7ee16018..00000000 --- a/tests/CreateAndFakeTests/Extensions/FakeExtensionsTests.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace CreateAndFakeTests.Extensions; - -public static class FakeExtensionsTests -{ - [Fact] - internal static void FakeExtensions_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(typeof(FakeExtensions)); - } - - [Theory, RandomData] - internal static void Called_PassesAsserters(int[] group, int comparable, - string text, Action behavior, object item, [Fake] object data) - { - item.Assert().Called(data).And.Is(item); - group.Assert().Called(data).And.Is(group); - comparable.Assert().Called(data).And.Is(comparable); - text.Assert().Called(data).And.Is(text); - behavior.Assert().Called(data).And.Is(behavior); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/Extensions/TypeExtensionsTests.cs b/tests/CreateAndFakeTests/Extensions/TypeExtensionsTests.cs deleted file mode 100644 index 22232709..00000000 --- a/tests/CreateAndFakeTests/Extensions/TypeExtensionsTests.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox; -using CreateAndFake.Toolbox.FakerTool; -using TypeExtensions = CreateAndFake.Toolbox.TypeExtensions; - -namespace CreateAndFakeTests.Extensions; - -public static class TypeExtensionsTests -{ - [Fact] - internal static void TypeExtensions_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(typeof(TypeExtensions)); - } - - [Fact] - internal static void Inherits_RaceConditionPrevented() - { - Type testType = Tools.Faker.Stub(Assembly.GetExecutingAssembly() - .GetTypes().Where(t => t.IsInterface).Where(t => t.IsVisible).ToArray()).GetType(); - - Parallel.For(0, 10, i => testType.Inherits()).IsCompleted.Assert().Is(true); - } - - [Theory, RandomData] - internal static void FindLoadedTypes_IgnoresMissingAssembly(Fake assembly, FileNotFoundException error) - { - assembly.Setup(d => d.GetTypes(), Behavior.Throw(error)); - - TypeExtensions.FindLoadedTypes(assembly.Dummy).Assert().IsEmpty(); - } - - [Theory, RandomData] - internal static void FindLoadedTypes_IgnoresReflectError(Fake assembly, ReflectionTypeLoadException error) - { - assembly.Setup(d => d.GetTypes(), Behavior.Throw(error)); - - TypeExtensions.FindLoadedTypes(assembly.Dummy).Assert().IsEmpty(); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue001Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue001Tests.cs deleted file mode 100644 index 809c53f5..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue001Tests.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication._000_050; - -public static class Issue001Tests -{ - internal sealed class Sample - { - public int Value { get; set; } - - public string Name { get; set; } - } - - [Theory, RandomData] - internal static void Issue001_CanCreateUniques(Sample original) - { - Sample unique = original.CreateUnique(); - unique.Name.Assert().IsNot(original.Name); - unique.Value.Assert().IsNot(original.Value); - unique.Assert().UniqueFrom(original); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue002Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue002Tests.cs deleted file mode 100644 index 74e1f94d..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue002Tests.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue002Tests -{ - [Fact] - internal static void Issue002_CallDataEncapsulated() - { - typeof(CallData).IsPublic.Assert().Is(false); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue003Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue003Tests.cs deleted file mode 100644 index 1320b668..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue003Tests.cs +++ /dev/null @@ -1,46 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue003Tests -{ - public abstract class RefHolder - { - public abstract int TestMethodA(out int value); - - public abstract int TestMethodB(ref int value); - } - - [Theory, RandomData] - internal static void Issue003_FakeHandlesOut(Fake sample, int testValue, int result) - { - sample.Setup( - d => d.TestMethodA(out Arg.AnyRef().Var), - Behavior.Set((OutRef v) => - { - v.Var = testValue; - return result; - })); - - sample.Dummy.TestMethodA(out int newValue).Assert().Is(result); - sample.VerifyAll(); - newValue.Assert().Is(testValue); - } - - [Theory, RandomData] - internal static void Issue003_FakeHandlesRef(Fake sample, int result) - { - int testValue = 0; - sample.Setup( - d => d.TestMethodB(ref Arg.AnyRef().Var), - Behavior.Set((OutRef v) => - { - v.Var -= 5; - return result; - })); - - sample.Dummy.TestMethodB(ref testValue).Assert().Is(result); - sample.VerifyAll(); - testValue.Assert().Is(-5); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue004Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue004Tests.cs deleted file mode 100644 index d5844ddb..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue004Tests.cs +++ /dev/null @@ -1,101 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue004Tests -{ - public interface IBaseHolder - { - void GetValueUnset(); - } - - public abstract class BaseHolder - { - internal static readonly int _TestValue = Tools.Randomizer.Create(); - - public int ValueHolder { get; set; } - - public virtual int GetValueA() - { - return _TestValue; - } - - public virtual int GetValueB(int input) - { - return input; - } - - public virtual void GetValueC() - { - ValueHolder = _TestValue; - } - - public virtual void GetValueD(int input) - { - ValueHolder = input; - } - - public virtual void ThrowError(Exception e) - { - throw e; - } - - public abstract void GetValueUnset(); - } - - [Theory, RandomData] - internal static void Issue004_MockCanCallBaseA(Fake sample) - { - sample.Setup(d => d.GetValueA(), Behavior.Base()); - sample.Dummy.GetValueA().Assert().Is(BaseHolder._TestValue); - sample.VerifyAll(); - } - - [Theory, RandomData] - internal static void Issue004_MockCanCallBaseB(Fake sample, int value) - { - sample.Setup(d => d.GetValueB(value), Behavior.Base()); - sample.Dummy.GetValueB(value).Assert().Is(value); - sample.VerifyAll(); - } - - [Theory, RandomData] - internal static void Issue004_MockCanCallBaseC(Fake sample) - { - sample.Setup(d => d.GetValueC(), Behavior.Base()); - sample.Dummy.GetValueC(); - sample.Dummy.ValueHolder.Assert().Is(BaseHolder._TestValue); - sample.VerifyAll(); - } - - [Theory, RandomData] - internal static void Issue004_MockCanCallBaseD(Fake sample, int value) - { - sample.Setup(d => d.GetValueD(value), Behavior.Base()); - sample.Dummy.GetValueD(value); - sample.Dummy.ValueHolder.Assert().Is(value); - sample.VerifyAll(); - } - - [Theory, RandomData] - internal static void Issue004_MockCanCallBaseThrow(Fake sample, Exception e) - { - sample.Setup(d => d.ThrowError(e), Behavior.Base()); - sample.Dummy.Assert(d => d.ThrowError(e)).Throws().Assert().Is(e); - sample.VerifyAll(); - } - - [Theory, RandomData] - internal static void Issue004_MockCallBaseAbstractInvalid(Fake sample) - { - sample.Setup(d => d.GetValueUnset(), Behavior.Base()); - sample.Dummy.Assert(d => d.GetValueUnset()).Throws(); - } - - [Theory, RandomData] - internal static void Issue004_MockCallBaseWrongTypeInvalid(Fake sample) - { - sample.Setup(d => d.GetValueUnset(), Behavior.Base()); - sample.Dummy.Assert(d => d.GetValueUnset()).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue009Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue009Tests.cs deleted file mode 100644 index df0c6a64..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue009Tests.cs +++ /dev/null @@ -1,23 +0,0 @@ -using CreateAndFake.Design.Data; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue009Tests -{ - internal sealed class Sample(string lastName) - { - public string FirstName { get; set; } - - public string _middleName = null; - - public string LastName { get; } = lastName; - } - - [Theory, RandomData] - internal static void Issue009_SmartDataIsUsed(Sample sample) - { - NameData.Values.Assert().Contains(sample.FirstName); - NameData.Values.Assert().Contains(sample._middleName); - NameData.Values.Assert().Contains(sample.LastName); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue012Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue012Tests.cs deleted file mode 100644 index c3ab78c7..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue012Tests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue012Tests -{ - public abstract class Sample - { - public abstract double Value(); - } - - [Theory, RandomData] - internal static void Issue012_RandomizedFake(Fake sample) - { - sample.Dummy.Value().Assert().IsNot(sample.Dummy.Value()); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue015Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue015Tests.cs deleted file mode 100644 index 90e3409e..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue015Tests.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CreateAndFake.Design; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue015Tests -{ - internal static class Sample - { - public static void Bad(int[] value) - { - ArgumentGuard.ThrowIfNull(value, nameof(value)); - - value[0] = value[0].CreateVariant(); - } - } - - [Fact] - internal static void Issue015_GuardsParameterMutation() - { - typeof(Sample).Assert(t => Tools.Tester.PreventsParameterMutation(t)).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue016Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue016Tests.cs deleted file mode 100644 index 1e77209d..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue016Tests.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue016Tests -{ - internal sealed class Sample - { - public static int ValueA = 0; - - public int ValueB = 0; - } - - [Theory, RandomData] - internal static void Issue016_StaticsNotRandomized(Sample sample) - { - sample.ValueB.Assert().IsNot(0).Also(Sample.ValueA).Is(0); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue021Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue021Tests.cs deleted file mode 100644 index e4c5a7b8..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue021Tests.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue021Tests -{ - internal sealed class Sample - { - public string Value { get; set; } - } - - [Theory, RandomData] - internal static void Issue021_MutatorMutates(Sample sample) - { - string original = sample.Value; - Tools.Mutator.Modify(sample); - sample.Value.Assert().IsNot(original); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue028Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue028Tests.cs deleted file mode 100644 index 20a42d1c..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue028Tests.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue028Tests -{ - internal sealed class Sample - { - public int Value { get; set; } - } - - [Fact] - internal static void Issue028_ConditionalCreation() - { - Tools.Randomizer.Create(s => s.Value > 0).Value.Assert().GreaterThan(0); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue038Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue038Tests.cs deleted file mode 100644 index 0db93cc1..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue038Tests.cs +++ /dev/null @@ -1,78 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue038Tests -{ - public interface ISample - { - string Value { get; set; } - - int Check(InnerSample value); - - int Check(string item1, string item2); - } - - public class InnerSample - { - public string Value { get; set; } - } - - [Theory, RandomData] - internal static void Issue038_FluentStubSetup([Stub] ISample sample, string value) - { - sample.Value.Assert().Is(null); - sample.Value.SetupReturn(value); - sample.Value.Assert().Is(value); - sample.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Issue038_FluentFakeSetup([Fake] ISample sample, string value) - { - sample.Value.Assert().IsNot(null); - sample.Value.SetupReturn(value); - sample.Value.Assert().Is(value); - sample.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Issue038_FluentArgsByValue([Stub] ISample sample, InnerSample item, int result) - { - sample.Check(item).SetupReturn(result); - sample.Check(Tools.Duplicator.Copy(item)).Assert().Is(result); - sample.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Issue038_FluentArgWorks([Stub] ISample sample, string item1, string item2, int result) - { - sample.Check(Arg.Any(), Arg.Where(s => s == item2)).SetupReturn(result); - sample.Check(item2, item1).Assert().Is(0); - sample.Check(item1, item2).Assert().Is(result); - sample.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Issue038_FluentTimesCorrect([Stub] ISample sample, string value) - { - sample.Value.SetupReturn(value, Times.Exactly(2)); - sample.Value.Assert().Is(value); - sample.Assert(s => s.VerifyAllCalls()).Throws(); - sample.Value.Assert().Is(value); - sample.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Issue038_FluentFakeCastWorks([Stub] ISample sample, string value, string identity) - { - sample.ToFake().Setup(d => d.Value, Behavior.Returns(value)); - sample.ToFake().Setup(d => d.ToString(), Behavior.Returns(identity)); - - sample.Value.Assert().Is(value); - sample.ToString().Assert().Is(identity); - - sample.ToFake().ToFake().VerifyAll(); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue043Tests.cs b/tests/CreateAndFakeTests/IssueReplication/000-050/Issue043Tests.cs deleted file mode 100644 index 67be746e..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue043Tests.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue043Tests -{ - [Fact] - internal static void Issue043_SupportsTask() - { - TestSample(); - } - - [Fact] - internal static void Issue043_SupportsGenericTask() - { - TestSample>(); - } - - private static void TestSample() - { - for (int i = 0; i < 50; i++) - { - T sample = Tools.Randomizer.Create(); - Tools.Asserter.IsNot(null, sample); - Tools.Asserter.IsNot(sample, Tools.Mutator.Variant(sample)); - - T dupe = Tools.Duplicator.Copy(sample); - - Tools.Asserter.Is(sample, dupe); - Tools.Asserter.Is(Tools.Valuer.GetHashCode(sample), Tools.Valuer.GetHashCode(dupe)); - } - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue052Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue052Tests.cs deleted file mode 100644 index d23b2e97..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue052Tests.cs +++ /dev/null @@ -1,61 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue052Tests -{ - internal sealed class Data - { - public string Item { get; set; } - } - - [Theory, RandomData] - internal static void Issue052_RandomizerPostCustomizable(Fake hint) - { - Randomizer randomizer = new(Tools.Faker, Tools.Gen, Limiter.Dozen, false); - Data testItem = new() { Item = "Sample" }; - - hint.Setup( - d => d.TryCreate(typeof(Data), Arg.Any()), - Behavior.Returns((true, (object)testItem), Times.Once)); - - randomizer.AddHint(hint.Dummy); - randomizer.Create().Assert().ReferenceEqual(testItem); - hint.VerifyAll(); - } - - [Theory, RandomData] - internal static void Issue052_DuplicatorPostCustomizable(Fake hint, Data item) - { - Duplicator duplicator = new(Tools.Asserter, false); - - hint.Setup( - d => d.TryCopy(item, Arg.Any()), - Behavior.Returns((true, (object)item), Times.Once)); - - duplicator.AddHint(hint.Dummy); - duplicator.Copy(item).Assert().ReferenceEqual(item); - hint.VerifyAll(); - } - - [Theory, RandomData] - internal static void Issue052_ValuerPostCustomizable(Fake hint, Data item1, Data item2) - { - Valuer valuer = new(false); - - hint.Setup("Supports", - [item1, item2, Arg.LambdaAny()], - Behavior.Returns(true, Times.Once)); - hint.Setup("Compare", - [item1, item2, Arg.LambdaAny()], - Behavior.Returns(Enumerable.Empty(), Times.Once)); - - valuer.AddHint(hint.Dummy); - valuer.Equals(item1, item2).Assert().Is(true); - hint.VerifyAll(); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue065Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue065Tests.cs deleted file mode 100644 index e21c903f..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue065Tests.cs +++ /dev/null @@ -1,50 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue065Tests -{ - internal sealed class InfiniteA - { - public ICollection Start { get; set; } - } - - internal sealed class InfiniteB - { - public InfiniteC Nested { get; set; } - } - - internal sealed class InfiniteC - { - public InfiniteA Back { get; set; } - } - - [Theory, RandomData] - internal static void Issue065_HandlesInfiniteChainsA(InfiniteA sample) - { - TestInfiniteSample(sample); - } - - [Theory, RandomData] - internal static void Issue065_HandlesInfiniteChainsB(InfiniteB sample) - { - TestInfiniteSample(sample); - } - - [Theory, RandomData] - internal static void Issue065_HandlesInfiniteChainsC(InfiniteC sample) - { - TestInfiniteSample(sample); - } - - private static void TestInfiniteSample(T sample) where T : new() - { - sample.Assert() - .IsNot(null).And - .IsNot(new T()).And - .IsNot(sample.CreateVariant()); - - T dupe = sample.CreateDeepClone(); - - dupe.Assert().Is(sample); - Tools.Valuer.GetHashCode(dupe).Assert().Is(Tools.Valuer.GetHashCode(sample)); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue078Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue078Tests.cs deleted file mode 100644 index 6ee7f25a..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue078Tests.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue078Tests -{ - [Theory, RandomData] - internal static void Issue078_CanChainObjects(int[] valueA, bool valueB) - { - valueA.Assert().IsNotEmpty().Also(valueB).IsNot(null); - } - - [Theory, RandomData] - internal static void Issue078_CanChainCollections(bool valueA, int[] valueB) - { - valueA.Assert().IsNot(null).Also(valueB).IsNotEmpty(); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue081Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue081Tests.cs deleted file mode 100644 index 4a859591..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue081Tests.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue081Tests -{ - [Fact] - internal static void Issue081_RandomizationIsSeeded() - { - Tools.Gen.InitialSeed.Assert().IsNot(null); - } - - [Fact] - internal static void Issue081_AssertionsContainSeed() - { - Tools.Asserter - .Assert(a => a.Fail()) - .Throws().Message - .Assert() - .Contains($"{Tools.Gen.InitialSeed}"); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue089Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue089Tests.cs deleted file mode 100644 index 6d1cafe5..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue089Tests.cs +++ /dev/null @@ -1,94 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue089Tests -{ - [Theory, RandomData] - internal static void Issue089_StringAssertions(string text) - { - text.Assert().Is(Tools.Duplicator.Copy(text)); - text.Assert().HasCount(text.Length); - - string startSample = text.Substring(0, 2); - string endSample = text.Substring(text.Length - 2, 2); - - text.Assert().Contains(text.Substring(2, 2)); - text.Assert().ContainsNot(Tools.Mutator.Variant(text)); - text.Assert().StartsWith(startSample); - text.Assert().StartsNotWith(Tools.Mutator.Variant(startSample)); - text.Assert().EndsWith(endSample); - text.Assert().EndsNotWith(Tools.Mutator.Variant(endSample)); - } - - [Theory, RandomData] - internal static void Issue089_InvalidStringAssertions(string text) - { - text.Assert(t => t.Assert().IsNot(Tools.Duplicator.Copy(text))).Throws(); - text.Assert(t => t.Assert().HasCount(text.Length + 1)).Throws(); - - string startSample = text.Substring(0, 2); - string endSample = text.Substring(text.Length - 2, 2); - - text.Assert(t => t.Assert().Contains(Tools.Mutator.Variant(text))).Throws(); - text.Assert(t => t.Assert().ContainsNot(text.Substring(2, 2))).Throws(); - text.Assert(t => t.Assert().StartsWith(Tools.Mutator.Variant(startSample))).Throws(); - text.Assert(t => t.Assert().StartsNotWith(startSample)).Throws(); - text.Assert(t => t.Assert().EndsWith(Tools.Mutator.Variant(endSample))).Throws(); - text.Assert(t => t.Assert().EndsNotWith(endSample)).Throws(); - } - - [Theory, RandomData] - internal static void Issue089_DelegateAssertions(InvalidOperationException error, object item) - { - Action action = () => throw error; - action.Assert().Throws().Assert().Is(error); - - Func func = () => throw error; - func.Assert().Throws().Assert().Is(error); - - item.Assert(o => throw error).Throws().Assert().Is(error); - - item.Assert(o => o.Assert().Fail()).Throws().Assert().IsNot(error); - } - - [Theory, RandomData] - internal static void Issue089_ComparableAssertions(int value) - { - value.Assert().GreaterThan(value - 1); - value.Assert().GreaterThanOrEqualTo(value - 1); - value.Assert().GreaterThanOrEqualTo(value); - value.Assert().LessThanOrEqualTo(value); - value.Assert().LessThanOrEqualTo(value + 1); - value.Assert().LessThan(value + 1); - - value.Assert().InRange(value - 1, value + 1); - value.Assert().InRange(value, value); - - value.Assert().GreaterThanOrIs(value - 1); - value.Assert().GreaterThanOrIs(value); - value.Assert().LessThanOrIs(value); - value.Assert().LessThanOrIs(value + 1); - - ((int?)null).Assert().GreaterThanOrIs(null); - ((int?)null).Assert().LessThanOrIs(null); - } - - [Theory, RandomData] - internal static void Issue089_InvalidComparableAssertions(int value) - { - value.Assert(v => v.Assert().GreaterThan(value + 1)).Throws(); - value.Assert(v => v.Assert().GreaterThanOrEqualTo(value + 1)).Throws(); - value.Assert(v => v.Assert().LessThanOrEqualTo(value - 1)).Throws(); - value.Assert(v => v.Assert().LessThan(value - 1)).Throws(); - - value.Assert(v => v.Assert().InRange(value + 1, value)).Throws(); - value.Assert(v => v.Assert().InRange(value, value - 1)).Throws(); - - value.Assert(v => v.Assert().GreaterThan(null)).Throws(); - value.Assert(v => v.Assert().InRange(null, value)).Throws(); - value.Assert(v => v.Assert().InRange(value, null)).Throws(); - ((int?)null).Assert(v => v.Assert().InRange(value, value)).Throws(); - ((int?)null).Assert(v => v.Assert().GreaterThan(value)).Throws(); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue091Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue091Tests.cs deleted file mode 100644 index 39597d05..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue091Tests.cs +++ /dev/null @@ -1,78 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue091Tests -{ - internal sealed class Api(ILayer layer) - { - public Item FindItem(int key) - { - return layer.GetItem(key); - } - - public Item FindItem(Guid id) - { - return layer.GetItem(id); - } - - public Item FindItem(object key) - { - return layer.GetItem(key); - } - } - - public interface ILayer - { - Item GetItem(int key); - - Item GetItem(Guid id); - - Item GetItem(object key); - } - - public class Item - { - public Guid Id { get; set; } - } - - [Theory, RandomData] - internal static void Issue091_FluentArgMatchesInt([Fake] ILayer layer, Api api, Item sample, int key) - { - layer.GetItem(Arg.Any()).SetupReturn(sample, Times.Once); - - api.FindItem(key).Assert().Is(sample); - - layer.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Issue091_FluentArgMatchesGuid([Fake] ILayer layer, Api api, Item sample) - { - layer.GetItem(Arg.Any()).SetupReturn(sample, Times.Once); - - api.FindItem(sample.Id).Assert().Is(sample); - - layer.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Issue091_FluentArgMatchesObject([Fake] ILayer layer, Api api, Item sample, object key) - { - layer.GetItem(Arg.Any()).SetupReturn(sample, Times.Once); - - api.FindItem(key).Assert().Is(sample); - - layer.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Issue091_FluentArgMatchesNull([Fake] ILayer layer, Api api, Item sample) - { - layer.GetItem(null).SetupReturn(sample, Times.Once); - - api.FindItem(null).Assert().Is(sample); - - layer.VerifyAllCalls(); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue093Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue093Tests.cs deleted file mode 100644 index d3da0461..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue093Tests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue093Tests -{ - public abstract class Provider - { - public abstract string Value { get; set; } - } - - internal sealed class Api - { - private readonly Provider _provider; - - internal Api(Provider provider) - { - _provider = provider; - } - - public string Value => _provider.Value; - } - - [Theory, RandomData] - internal static void Issue093_AssertFakeCallIntegration([Fake] Provider faked, Api sample, string value) - { - faked.Value.SetupReturn(value); - - Tools.Asserter.Throws(() => "".Assert().Called(faked).And.Is("")); - - sample.Value.Assert().Called(faked).And.Is(value); - - Tools.Asserter.Throws(() => sample.Value.Assert().Called(faked).And.Is("")); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue096Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue096Tests.cs deleted file mode 100644 index 321efa91..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue096Tests.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue096Tests -{ - [Fact] - internal static void Issue096_SupportsIAsyncEnumerable() - { - TestSample>(); - TestSample>(); - TestSample>(); - } - - [Theory, RandomData] - internal static async Task Issue096_SupportsSizedAsyncEnumerable([Size(5)] IAsyncEnumerable items) - { - int count = 0; - await foreach (int item in items) - { - count++; - } - count.Assert().Is(5); - } - - private static void TestSample() - { - for (int i = 0; i < 50; i++) - { - T sample = Tools.Randomizer.Create(); - Tools.Asserter.IsNot(null, sample); - Tools.Asserter.IsNot(sample, Tools.Mutator.Variant(sample)); - - T dupe = Tools.Duplicator.Copy(sample); - - Tools.Asserter.Is(sample, dupe); - Tools.Asserter.Is(Tools.Valuer.GetHashCode(sample), Tools.Valuer.GetHashCode(dupe)); - } - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue099Tests.cs b/tests/CreateAndFakeTests/IssueReplication/050-100/Issue099Tests.cs deleted file mode 100644 index 0d4c3b27..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue099Tests.cs +++ /dev/null @@ -1,30 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue099Tests -{ - public static int ExtendedCall(this ITester sample, object item) - { - return sample?.GetValue(item) ?? 0; - } - - public interface ITester - { - int GetValue(object item); - } - - [Theory, RandomData] - internal static void Issue099_FakingThrowsWithExtensionMethod(Fake sample, object item, int result) - { - Tools.Asserter.Throws( - () => sample.Setup(f => f.ExtendedCall(item), Behavior.Returns(result))); - } - - [Theory, RandomData] - internal static void Issue099_FluentPassthroughWithExtensionMethod([Stub] ITester sample, object item, int result) - { - sample.ExtendedCall(item).SetupReturn(result); - sample.ExtendedCall(item).Assert().Is(result); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue101Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue101Tests.cs deleted file mode 100644 index 7ebf8d3d..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue101Tests.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue101Tests -{ - [Theory, RandomData] - internal static void Issue101_EasyCloneValues(int value) - { - value.CreateDeepClone().Assert().Is(value); - } - - [Theory, RandomData] - internal static void Issue101_EasyCloneObjects(string value) - { - value.CreateDeepClone().Assert().Is(value); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue103Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue103Tests.cs deleted file mode 100644 index 8ee419ae..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue103Tests.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue103Tests -{ - [Theory, RandomData] - internal static void Issue103_AssertFailIncludesTestValue(string text) - { - string alt = Tools.Mutator.Variant(text); - Tools.Asserter.Throws(() => text.Assert().Contains(alt)).Message.Assert().Contains(alt); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue104Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue104Tests.cs deleted file mode 100644 index 0570a6ce..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue104Tests.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue104Tests -{ - [Theory, RandomData] - internal static void Issue104_EasyVariantValues(int value) - { - value.CreateVariant().Assert().IsNot(value); - } - - [Theory, RandomData] - internal static void Issue104_EasyVariantObjects(string value) - { - value.CreateVariant().Assert().IsNot(value); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue106Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue106Tests.cs deleted file mode 100644 index 8f0ffada..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue106Tests.cs +++ /dev/null @@ -1,38 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue106Tests -{ - internal sealed class RandomNameContainer - { - public T Content { get; set; } - } - - public sealed class RandomNameItem - { - public string Message { get; set; } - } - - [Theory, RandomData] - internal static void Issue106_AssertIncludesGenericName(RandomNameContainer generic) - { - generic - .Assert(l => l.Assert().Is(generic.CreateVariant())) - .Throws() - .Message - .Assert() - .Contains(nameof(RandomNameItem)); - } - - [Theory, RandomData] - internal static void Issue106_AssertIncludesGenericNameCollections(List> generic) - { - generic - .Assert(l => l.Assert().Is(generic.CreateVariant())) - .Throws() - .Message - .Assert() - .Contains(nameof(RandomNameItem)); - } -} diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue107Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue107Tests.cs deleted file mode 100644 index be381300..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue107Tests.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue107Tests -{ - internal abstract class SelfReferenceContainer where T : SelfReferenceContainer { } - - [Fact] - internal static void Issue107_SelfReferenceGenericMustHaveSubclass() - { - typeof(SelfReferenceContainer<>).Assert(c => c.CreateRandomInstance()).Throws(); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue108Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue108Tests.cs deleted file mode 100644 index 812b0f23..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue108Tests.cs +++ /dev/null @@ -1,51 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue108Tests -{ - public abstract class InnerStuff where T : InnerStuff - { - public string Message { get; set; } - } - - public sealed class Wrapper : InnerStuff - { - public int Value { get; set; } - } - - public class Container where T : InnerStuff - { - public T Content { get; set; } - } - - public sealed class WrapperContainer : Container { } - - [Fact] - internal static void Issue108_SupportsSelfReference() - { - typeof(InnerStuff<>).CreateRandomInstance().Assert().IsNot(null); - } - - [Theory, RandomData] - internal static void Issue108_SupportsWrappingSelfReference(Wrapper instance) - { - instance.Assert().IsNot(null); - } - - [Fact] - internal static void Issue108_SupportsContainerWithSelfReferenceContent() - { - typeof(Container<>).CreateRandomInstance().Assert().IsNot(null); - } - - [Theory, RandomData] - internal static void Issue108_SupportsContainerWithWrappedSelfReference(Container instance) - { - instance.Assert().IsNot(null); - } - - [Theory, RandomData] - internal static void Issue108_SupportsWrappedContainer(WrapperContainer instance) - { - instance.Assert().IsNot(null); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue109Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue109Tests.cs deleted file mode 100644 index 7ad072fb..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue109Tests.cs +++ /dev/null @@ -1,60 +0,0 @@ -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; - -#pragma warning disable CA2227 // Change collection to read-only property setter: For testing. - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue109Tests -{ - public interface IDetails - { - string Name { get; set; } - } - - [Serializable] - public sealed class Details : IDetails - { - public string Name { get; set; } - public int Year { get; set; } - - public Details() { } - } - - public interface IContainer - { - IDetails Item { get; set; } - } - - [Serializable] - public sealed class Container : IContainer - { - public IDetails Item { get; set; } - - private List Values { get; set; } - - public Dictionary> Map { get; set; } - - public Container() { } - - public override string ToString() - { - return Values?.ToString() + Map?.ToString(); - } - } - - [Theory, RandomData] - internal static void Issue109_BinarySerializationRemovedDateTime(DateTime date) - { - date.CreateDeepClone().Assert().Is(date); - } - - [Theory, RandomData] - internal static void Issue109_BinarySerializationRemovedSample(IContainer sample) - { - sample.CreateDeepClone().Assert().Is(sample); - new Duplicator(Tools.Asserter, true, new SerializableCopyHint()).Copy(sample).Assert().Is(sample); - } -} - -#pragma warning restore CA2227 diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue114Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue114Tests.cs deleted file mode 100644 index d304e02f..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue114Tests.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue114Tests -{ - [Theory, RandomData] - internal static void Issue114_IntArraySequencesEqualRegardlessOfType(int[] sample) - { - sample.Assert().Is(sample.CreateDeepClone().ToList()); - } - - [Theory, RandomData] - internal static void Issue114_ObjectArraySequencesEqualRegardlessOfType(object[] sample) - { - sample.Assert().Is(sample.CreateDeepClone().ToList()); - } - - [Theory, RandomData] - internal static void Issue114_StringListSequencesEqualRegardlessOfType(IEnumerable sample) - { - sample.Assert().Is(sample.CreateDeepClone().ToList()); - } - - [Theory, RandomData] - internal static void Issue114_ObjectListSequencesEqualRegardlessOfType(IEnumerable sample) - { - sample.Assert().Is(sample.CreateDeepClone().ToList()); - } - - [Theory, RandomData] - internal static void Issue114_StringSequencesEqualRegardlessOfType(IDictionary sample) - { - sample.Assert().Is(sample.CreateDeepClone().ToDictionary(e => e.Key, e => e.Value)); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue118Tests.cs b/tests/CreateAndFakeTests/IssueReplication/100-150/Issue118Tests.cs deleted file mode 100644 index 86aa55ac..00000000 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue118Tests.cs +++ /dev/null @@ -1,26 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue118Tests -{ - [Fact] - internal static void Issue118_AddsPass() - { - typeof(object).Assert().Pass(); - } - - [Theory, RandomData] - internal static void Issue118_FixesFakeTypeRandomData(Fake type) - { - type.Assert().IsNot(null); - } - -#if !LEGACY // Xunit needs Type parameters to inherit IReflectableType, which cannot be faked in legacy .NET. - [Theory, RandomData] - internal static void Issue118_FixesStubTypeRandomData([Stub] Type type) - { - type.Assert().IsNot(null); - } -#endif -} diff --git a/tests/CreateAndFakeTests/Properties/AssemblyInfo.cs b/tests/CreateAndFakeTests/Properties/AssemblyInfo.cs deleted file mode 100644 index 5dbf9982..00000000 --- a/tests/CreateAndFakeTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1 +0,0 @@ -[assembly: CLSCompliant(false)] diff --git a/tests/CreateAndFakeTests/TestBases/CompareHintTestBase.cs b/tests/CreateAndFakeTests/TestBases/CompareHintTestBase.cs deleted file mode 100644 index dde06c6c..00000000 --- a/tests/CreateAndFakeTests/TestBases/CompareHintTestBase.cs +++ /dev/null @@ -1,181 +0,0 @@ -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFakeTests.TestBases; - -/// Handles testing compare hints. -/// Compare hint to test. -/// Instance to test with. -/// Types that can be compared by the hint. -/// Types that can't be compared by the hint. -public abstract class CompareHintTestBase( - T testInstance, - IEnumerable validTypes, - IEnumerable invalidTypes) where T : CompareHint -{ - /// Instance to test with. - protected T TestInstance { get; } = testInstance; - - /// Types that can be compared by the hint. - private readonly IEnumerable _validTypes = validTypes; - - /// Types that can't be compared by the hint. - private readonly IEnumerable _invalidTypes = invalidTypes; - - /// Verifies null reference exceptions are prevented. - [Fact] - public void CompareHint_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(TestInstance); - } - - /// Verifies the hint supports the correct types. - [Fact] - public void TryCompare_SupportsSameValidTypes() - { - foreach (Type type in _validTypes) - { - object data = Tools.Randomizer.Create(type); - try - { - (bool, IEnumerable) result = TestInstance.TryCompare(data, data, CreateChainer()); - - result.Item1.Assert().Is(true, - $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); - result.Item2.Assert().IsEmpty( - $"Hint '{typeof(T).Name}' found differences with same '{type.Name}' of '{data.GetType()}'."); - } - finally - { - Disposer.Cleanup(data); - } - } - } - - /// Verifies the hint supports the correct types. - [Fact] - public virtual void TryCompare_SupportsDifferentValidTypes() - { - foreach (Type type in _validTypes) - { - object one = null, two = null; - try - { - one = Tools.Randomizer.Create(type); - two = Tools.Mutator.Variant(one.GetType(), one); - - (bool, IEnumerable) result = TestInstance.TryCompare(one, two, CreateChainer()); - - result.Item1.Assert().Is(true, - $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); - result.Item2.ToArray().Assert().IsNotEmpty( - $"Hint '{typeof(T).Name}' didn't find differences with two random '{type.Name}'."); - } - finally - { - Disposer.Cleanup(one, two); - } - } - } - - /// Verifies the hint doesn't support the wrong types. - [Fact] - public void TryCompare_InvalidTypesFail() - { - foreach (Type type in _invalidTypes) - { - object one = null, two = null; - try - { - one = Tools.Randomizer.Create(type); - two = Tools.Randomizer.Create(one.GetType()); - - TestInstance.TryCompare(one, two, CreateChainer()).Assert().Is((false, (IEnumerable)null), - $"Hint '{typeof(T).Name}' should not support type '{type.Name}'."); - } - finally - { - Disposer.Cleanup(one, two); - } - } - } - - /// Verifies the hint supports the correct types. - [Fact] - public void TryGetHashCode_SupportsSameValidTypes() - { - foreach (Type type in _validTypes) - { - object data = null, dataCopy = null; - try - { - data = Tools.Randomizer.Create(type); - dataCopy = Tools.Duplicator.Copy(data); - - (bool, int) dataHash = TestInstance.TryGetHashCode(data, CreateChainer()); - dataHash.Item1.Assert().Is(true, - $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); - TestInstance.TryGetHashCode(data, CreateChainer()).Assert().Is(dataHash, - $"Hint '{typeof(T).Name}' generated different hash for same '{type.Name}'."); - TestInstance.TryGetHashCode(dataCopy, CreateChainer()).Assert().Is(dataHash, - $"Hint '{typeof(T).Name}' generated different hash for dupe '{type.Name}'."); - } - finally - { - Disposer.Cleanup(data, dataCopy); - } - } - } - - /// Verifies the hint supports the correct types. - [Fact] - public void TryGetHashCode_SupportsDifferentValidTypes() - { - foreach (Type type in _validTypes) - { - object data = null, dataDiffer = null; - try - { - data = Tools.Randomizer.Create(type); - dataDiffer = Tools.Mutator.Variant(data); - - (bool, int) dataHash = TestInstance.TryGetHashCode(data, CreateChainer()); - dataHash.Item1.Assert().Is(true, - $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); - TestInstance.TryGetHashCode(dataDiffer, CreateChainer()).Assert().IsNot(dataHash, - $"Hint '{typeof(T).Name}' generated same hash for different '{type.Name}'."); - } - finally - { - Disposer.Cleanup(data, dataDiffer); - } - } - } - - /// Verifies the hint doesn't support the wrong types. - [Fact] - public void TryGetHashCode_InvalidTypesFail() - { - foreach (Type type in _invalidTypes) - { - object data = Tools.Randomizer.Create(type); - try - { - TestInstance.TryGetHashCode(data, CreateChainer()).Assert().Is((false, default(int)), - $"Hint '{typeof(T).Name}' should not support type '{type.Name}'."); - } - finally - { - Disposer.Cleanup(data); - } - } - } - - /// Chainer to use for testing. - protected static ValuerChainer CreateChainer() - { - return new ValuerChainer(Tools.Valuer, - (o, c) => Tools.Valuer.GetHashCode(o), - (e, a, c) => Tools.Valuer.Compare(e, a)); - } -} diff --git a/tests/CreateAndFakeTests/TestBases/CopyHintTestBase.cs b/tests/CreateAndFakeTests/TestBases/CopyHintTestBase.cs deleted file mode 100644 index 699e46ea..00000000 --- a/tests/CreateAndFakeTests/TestBases/CopyHintTestBase.cs +++ /dev/null @@ -1,93 +0,0 @@ -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.DuplicatorTool; - -namespace CreateAndFakeTests.TestBases; - -/// Handles testing copy hints. -/// Copy hint to test. -/// Types that can be copied by the hint. -/// Types that can't be copied by the hint. -/// If the hint copies by reference instead for value types. -public abstract class CopyHintTestBase( - IEnumerable validTypes, - IEnumerable invalidTypes, - bool copiesByRef = false) where T : CopyHint, new() -{ - /// Instance to test with. - protected T TestInstance { get; } = new T(); - - /// Types that can be copied by the hint. - private readonly IEnumerable _validTypes = validTypes ?? Type.EmptyTypes; - - /// Types that can't be copied by the hint. - private readonly IEnumerable _invalidTypes = invalidTypes ?? Type.EmptyTypes; - - /// If the hint copies by reference instead for value types. - private readonly bool _copiesByRef = copiesByRef; - - /// Verifies null reference exceptions are prevented. - [Fact] - public void CopyHint_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(TestInstance); - } - - /// Verifies the hint supports the correct types. - [Fact] - public void TryCopy_SupportsValidTypes() - { - foreach (Type type in _validTypes) - { - object data = null; - (bool, object) result = (false, null); - try - { - data = Tools.Randomizer.Create(type); - result = TestInstance.TryCopy(data, CreateChainer()); - - result.Assert().Is((true, data), - "Hint '" + typeof(T).Name + "' failed to clone type '" + type.Name + "'."); - - if (_copiesByRef || data is string) - { - result.Item2.Assert().ReferenceEqual(data, - "Hint '" + typeof(T).Name + "' expected to copy value types by ref of type '" + type.Name + "'."); - } - else - { - result.Item2.Assert().ReferenceNotEqual(data, - "Hint '" + typeof(T).Name + "' copied by ref instead of a deep clone of type '" + type.Name + "'."); - } - } - finally - { - Disposer.Cleanup(data, result.Item2); - } - } - } - - /// Verifies the hint doesn't support the wrong types. - [Fact] - public void TryCopy_InvalidTypesFail() - { - foreach (Type type in _invalidTypes) - { - object data = Tools.Randomizer.Create(type); - try - { - TestInstance.TryCopy(data, CreateChainer()).Assert().Is((false, (object)null), - "Hint '" + typeof(T).Name + "' should not support type '" + type.Name + "'."); - } - finally - { - Disposer.Cleanup(data); - } - } - } - - /// Chainer to use for testing. - protected static DuplicatorChainer CreateChainer() - { - return new DuplicatorChainer(Tools.Duplicator, (o, c) => Tools.Duplicator.Copy(o)); - } -} diff --git a/tests/CreateAndFakeTests/TestBases/CreateHintTestBase.cs b/tests/CreateAndFakeTests/TestBases/CreateHintTestBase.cs deleted file mode 100644 index 0c200c55..00000000 --- a/tests/CreateAndFakeTests/TestBases/CreateHintTestBase.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Collections; -using CreateAndFake.Design.Content; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.RandomizerTool; - -namespace CreateAndFakeTests.TestBases; - -/// Handles testing create hints. -/// Create hint to test. -/// Instance to test with. -/// Types that can be created by the hint. -/// Types that can't be created by the hint. -public abstract class CreateHintTestBase( - T testInstance, - IEnumerable validTypes, - IEnumerable invalidTypes) where T : CreateHint -{ - /// Instance to test with. - protected T TestInstance { get; } = testInstance; - - /// Types that can be created by the hint. - private readonly IEnumerable _validTypes = validTypes ?? Type.EmptyTypes; - - /// Types that can't be created by the hint. - private readonly IEnumerable _invalidTypes = invalidTypes ?? Type.EmptyTypes; - - /// Verifies null reference exceptions are prevented. - [Fact] - public void CreateHint_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(TestInstance); - } - - /// Verifies the hint supports the correct types. - [Fact] - public void TryCreate_SupportsValidTypes() - { - foreach (Type type in _validTypes) - { - (bool, object) result = TestInstance.TryCreate(type, CreateChainer()); - try - { - result.Item1.Assert().Is(true, - "Hint '" + typeof(T).Name + "' did not support type '" + type.Name + "'."); - result.Item2.Assert().IsNot(null, - "Hint '" + typeof(T).Name + "' did not create valid '" + type.Name + "'."); - - if (result.Item2 is IEnumerable collection) - { - collection.GetEnumerator().MoveNext().Assert().Is(true, - "Hint '" + typeof(T).Name + "' failed to create populated '" + type + "'."); - } - } - finally - { - Disposer.Cleanup(result.Item2); - } - } - } - - /// Verifies the hint doesn't support the wrong types. - [Fact] - public void TryCreate_InvalidTypesFail() - { - foreach (Type type in _invalidTypes) - { - TestInstance.TryCreate(type, CreateChainer()).Assert().Is((false, (object)null), - "Hint '" + typeof(T).Name + "' should not support type '" + type.Name + "'."); - } - } - - /// Chainer to use for testing. - protected static RandomizerChainer CreateChainer() - { - return new RandomizerChainer(Tools.Faker, new FastRandom(), (t, c) => Tools.Randomizer.Create(t)); - } -} \ No newline at end of file diff --git a/tests/CreateAndFakeTests/TestBases/DataContextTestBase.cs b/tests/CreateAndFakeTests/TestBases/DataContextTestBase.cs deleted file mode 100644 index a96cf8eb..00000000 --- a/tests/CreateAndFakeTests/TestBases/DataContextTestBase.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design.Context; - -namespace CreateAndFakeTests.TestBases; - -/// Handles testing data context classes. -/// Type to test. -public abstract class DataContextTestBase where T : BaseDataContext -{ - /// Verifies null reference exceptions are prevented. - [Fact] - public void DataContext_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - /// Verifies data remains consistent on instance. - [Theory, RandomData] - public void DataContext_MaintainsValues(T testInstance) - { - foreach (PropertyInfo prop in typeof(T).GetProperties()) - { - prop.GetValue(testInstance).Assert().Is(prop.GetValue(testInstance)); - } - } - - /// Verifies instances are not equal. - [Theory, RandomData] - public void DataContext_DataVaries(T testInstance) - { - testInstance.CreateVariant().Assert().IsNot(testInstance); - } -} diff --git a/tests/CreateAndFakeTests/TestBases/ExceptionTestBase.cs b/tests/CreateAndFakeTests/TestBases/ExceptionTestBase.cs deleted file mode 100644 index cdb6cec8..00000000 --- a/tests/CreateAndFakeTests/TestBases/ExceptionTestBase.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Runtime.Serialization; -using System.Runtime.Serialization.Json; - -namespace CreateAndFakeTests.TestBases; - -/// Handles testing exceptions. -/// Exception type to test. -public abstract class ExceptionTestBase where T : Exception -{ - /// Verifies the default constructor is present for serialization but private. - [Fact] - public void Exception_DefaultConstructorPrivate() - { - typeof(T).GetConstructor(Type.EmptyTypes).Assert().Is(null); - Activator.CreateInstance(typeof(T), true).Assert().IsNot(null); - } - - /// Verifies that the exception can make an xml roundtrip. - [Theory, RandomData] - public void Exception_XmlSerializes(T original) - { - DataContractSerializer formatter = new(typeof(T), - new[] { original.InnerException }.Where(t => t != null).Select(t => t.GetType())); - - using MemoryStream stream = new(); - - formatter.WriteObject(stream, original); - _ = stream.Seek(0, SeekOrigin.Begin); - - formatter.ReadObject(stream).Assert().Is(original); - } - - /// Verifies that the exception can make a json roundtrip. - [Fact] - public void Exception_JsonSerializes() - { - T original; - do - { - original = Tools.Randomizer.Create(); - } while (original.InnerException != null); - - DataContractJsonSerializer formatter = new(typeof(T)); - - using MemoryStream stream = new(); - formatter.WriteObject(stream, original); - _ = stream.Seek(0, SeekOrigin.Begin); - - formatter.ReadObject(stream).Assert().Is(original); - } -} diff --git a/tests/CreateAndFakeTests/TestBases/ValueRandomTestBase.cs b/tests/CreateAndFakeTests/TestBases/ValueRandomTestBase.cs deleted file mode 100644 index 9b04cd13..00000000 --- a/tests/CreateAndFakeTests/TestBases/ValueRandomTestBase.cs +++ /dev/null @@ -1,230 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Design.Randomization; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.TestBases; - -/// Handles testing value random classes. -/// Value random type to test. -public abstract class ValueRandomTestBase where T : ValueRandom -{ - /// Instance to test with. - private static readonly ValueRandom _TestInstance = Tools.Randomizer.Create(); - - /// Verifies null reference exceptions are prevented. - [Fact] - public void ValueRandom_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - /// Verifies parameters are not mutated. - [Fact] - public void ValueRandom_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - /// Verifies intended value types work. - [Fact] - public void Supports_TypeCoverage() - { - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - _TestInstance.Supports().Assert().Is(true); - } - - /// Verifies an invalid type is not supported. - [Fact] - public void Supports_InvalidTypeFalse() - { - _TestInstance.Supports(typeof(object)).Assert().Is(false); - } - - /// Verifies intended value types work. - [Fact] - public void Next_TypeCoverage() - { - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - _TestInstance.Next(); - } - - /// Verifies intended value types work. - [Fact] - public void Next_MaxTypeCoverage() - { - _TestInstance.Next(true); - _TestInstance.Next(int.MaxValue); - _TestInstance.Next(byte.MaxValue); - _TestInstance.Next(uint.MaxValue); - _TestInstance.Next(long.MaxValue); - _TestInstance.Next(char.MaxValue); - _TestInstance.Next(ulong.MaxValue); - _TestInstance.Next(float.MaxValue); - _TestInstance.Next(short.MaxValue); - _TestInstance.Next(sbyte.MaxValue); - _TestInstance.Next(double.MaxValue); - _TestInstance.Next(ushort.MaxValue); - _TestInstance.Next(decimal.MaxValue); - } - - /// Verifies intended value types work. - [Fact] - public void Next_MinTypeCoverage() - { - _TestInstance.Next(false, true); - _TestInstance.Next(int.MinValue, int.MaxValue); - _TestInstance.Next(byte.MinValue, byte.MaxValue); - _TestInstance.Next(uint.MinValue, uint.MaxValue); - _TestInstance.Next(long.MinValue, long.MaxValue); - _TestInstance.Next(char.MinValue, char.MaxValue); - _TestInstance.Next(ulong.MinValue, ulong.MaxValue); - _TestInstance.Next(float.MinValue, float.MaxValue); - _TestInstance.Next(short.MinValue, short.MaxValue); - _TestInstance.Next(sbyte.MinValue, sbyte.MaxValue); - _TestInstance.Next(double.MinValue, double.MaxValue); - _TestInstance.Next(ushort.MinValue, ushort.MaxValue); - _TestInstance.Next(decimal.MinValue, decimal.MaxValue); - } - - /// Verifies backup stumble behavior works. - [Fact] - public async Task Next_StumbleWorks() - { - int min = int.MinValue / 2 - 1; - int max = int.MaxValue / 2 + 1; - - await Limiter.Myriad.Repeat("Testing stumble behavior.", () => - { - _TestInstance.Next(min, max).Assert().GreaterThanOrEqualTo(min).And.LessThan(max); - }); - } - - /// Verifies that an invalid type throws. - [Fact] - public void Next_InvalidTypeThrows() - { - _TestInstance.Assert(t => t.Next(typeof(object))).Throws(); - } - - /// Verifies the same min and max can be used. - [Fact] - public void Next_SameMinMaxWorks() - { - _TestInstance.Next(0, 0).Assert().Is(0); - } - - /// Verifies different values are generated. - [Fact] - public void Next_Variation() - { - _TestInstance.Next().Assert().IsNot(_TestInstance.Next()); - } - - /// Verifies unsupported types don't work. - [Theory, RandomData] - public void Next_UnsupportedTypeThrows(StructSample sample) - { - _TestInstance.Assert(t => t.Next()).Throws(); - _TestInstance.Assert(t => t.Next(sample)).Throws(); - } - - /// Verifies max is excluded as a possible result. - [Fact] - public void Next_MaxDoubleExcluded() - { - double min = 9.9999999; - double max = 10; - - for (int i = 0; i < 25000; i++) - { - _TestInstance.Next(min, max).Assert().GreaterThanOrEqualTo(min).And.LessThan(max); - } - } - - /// Verifies max is excluded as a possible result. - [Fact] - public void Next_MaxDecimalExcluded() - { - decimal min = 9.9999999M; - decimal max = 10; - - for (int i = 0; i < 25000; i++) - { - _TestInstance.Next(min, max).Assert().GreaterThanOrEqualTo(min).And.LessThan(max); - } - } - - /// Verifies max values greater than min can't be used. - [Fact] - public void Next_MinGreaterMaxThrows() - { - _TestInstance.Assert(t => t.Next(0, -1)).Throws(); - } - - /// Verifies collections work. - [Theory, RandomData] - public void NextItem_CollectionsWork(ICollection data) - { - data.Assert().Contains(_TestInstance.NextItem(data)); - } - - /// Verifies linq enumerables work. - [Fact] - public void NextItem_YieldWorks() - { - _TestInstance.NextItem(CreateEnum(1)).Assert().IsNot(null); - _TestInstance.NextItem(CreateEnum(2)).Assert().IsNot(null); - _TestInstance.NextItem(CreateEnum(3)).Assert().IsNot(null); - } - - /// Verifies empty enumerables throw. - [Fact] - public void NextItem_EmptyThrows() - { - _TestInstance.Assert(t => t.NextItem(CreateEnum(0))).Throws(); - _TestInstance.Assert(t => t.NextItem(Array.Empty())).Throws(); - } - - /// Verifies empty enumerables give default values. - [Fact] - public void NextItemOrDefault_EmptyGivesDefault() - { - _TestInstance.NextItemOrDefault((int[])null).Assert().Is(0); - _TestInstance.NextItemOrDefault(CreateEnum(0)).Assert().Is(null); - _TestInstance.NextItemOrDefault((object[])null).Assert().Is(null); - _TestInstance.NextItemOrDefault(Array.Empty()).Assert().Is(null); - } - - /// Helper for creating linq enumerables. - /// Size of the enumerable to create. - /// Enumerable to test with. - private static IEnumerable CreateEnum(int size) - { - for (int i = 0; i < size; i++) - { - yield return new object(); - } - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/ChildWithParentSample.cs b/tests/CreateAndFakeTests/TestSamples/ChildWithParentSample.cs deleted file mode 100644 index 7cbe34ef..00000000 --- a/tests/CreateAndFakeTests/TestSamples/ChildWithParentSample.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public sealed class ChildWithParentSample -{ - public ParentLoopSample Parent { get; set; } -} diff --git a/tests/CreateAndFakeTests/TestSamples/ConstraintSample.cs b/tests/CreateAndFakeTests/TestSamples/ConstraintSample.cs deleted file mode 100644 index 7a755e20..00000000 --- a/tests/CreateAndFakeTests/TestSamples/ConstraintSample.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public abstract class ConstraintSample - where TStruct : struct - where TClass : DataSample, new() -{ - public TStruct StructValue { get; set; } - - public TClass ClassValue { get; set; } -} diff --git a/tests/CreateAndFakeTests/TestSamples/DataHolderSample.cs b/tests/CreateAndFakeTests/TestSamples/DataHolderSample.cs deleted file mode 100644 index 94702684..00000000 --- a/tests/CreateAndFakeTests/TestSamples/DataHolderSample.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests.TestSamples; - -public class DataHolderSample : DataSample -{ - public DataSample NestedValue { get; set; } - - [ExcludeFromCodeCoverage] - public virtual bool HasNested(DataSample value) - { - return false; - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/DataSample.cs b/tests/CreateAndFakeTests/TestSamples/DataSample.cs deleted file mode 100644 index 9395cf57..00000000 --- a/tests/CreateAndFakeTests/TestSamples/DataSample.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public class DataSample -{ - public string StringValue { get; set; } - - public int NumberValue { get; set; } - - public IEnumerable CollectionValue { get; set; } -} diff --git a/tests/CreateAndFakeTests/TestSamples/FactorySample.cs b/tests/CreateAndFakeTests/TestSamples/FactorySample.cs deleted file mode 100644 index 8b641b02..00000000 --- a/tests/CreateAndFakeTests/TestSamples/FactorySample.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests.TestSamples; - -public sealed class FactorySample -{ - [ExcludeFromCodeCoverage] - public string Data { get; } - - private FactorySample(string data) - { - Data = data; - } - - internal static FactorySample Create(int data) - { - return new FactorySample("Value:" + data); - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/FieldSample.cs b/tests/CreateAndFakeTests/TestSamples/FieldSample.cs deleted file mode 100644 index c54eb4ce..00000000 --- a/tests/CreateAndFakeTests/TestSamples/FieldSample.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public class FieldSample(string stringValue, string stringValue2) -{ - public const int Perm = 1; - - public readonly string PermText = stringValue2; - - public string StringValue = stringValue; - - public int NumberValue; - - public IEnumerable CollectionValue; -} diff --git a/tests/CreateAndFakeTests/TestSamples/GenericSample.cs b/tests/CreateAndFakeTests/TestSamples/GenericSample.cs deleted file mode 100644 index 66a04a58..00000000 --- a/tests/CreateAndFakeTests/TestSamples/GenericSample.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public abstract class GenericSample -{ - public abstract string Run(TMethod input); - - public abstract TReturn Run(TClass in1, TMethod in2) - where TMethod : DataSample - where TReturn : new(); -} diff --git a/tests/CreateAndFakeTests/TestSamples/IIsGoodOrBadSample.cs b/tests/CreateAndFakeTests/TestSamples/IIsGoodOrBadSample.cs deleted file mode 100644 index 5b60dd88..00000000 --- a/tests/CreateAndFakeTests/TestSamples/IIsGoodOrBadSample.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public interface IIsGoodOrBadSample -{ - int GoodOrBadProp { get; set; } -} diff --git a/tests/CreateAndFakeTests/TestSamples/IOnlyMockSample.cs b/tests/CreateAndFakeTests/TestSamples/IOnlyMockSample.cs deleted file mode 100644 index 7b714b1d..00000000 --- a/tests/CreateAndFakeTests/TestSamples/IOnlyMockSample.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public interface IOnlyMockSample -{ - bool FailIfNotMocked(); -} diff --git a/tests/CreateAndFakeTests/TestSamples/IUnimplementedSample.cs b/tests/CreateAndFakeTests/TestSamples/IUnimplementedSample.cs deleted file mode 100644 index e56b6ced..00000000 --- a/tests/CreateAndFakeTests/TestSamples/IUnimplementedSample.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public interface IUnimplementedSample -{ - int Flag { get; } - - bool Funny { set; } - - string GetData(); -} diff --git a/tests/CreateAndFakeTests/TestSamples/InfiniteSample.cs b/tests/CreateAndFakeTests/TestSamples/InfiniteSample.cs deleted file mode 100644 index 065952b8..00000000 --- a/tests/CreateAndFakeTests/TestSamples/InfiniteSample.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public sealed class InfiniteSample -{ - public InfiniteSample Hole { get; set; } -} diff --git a/tests/CreateAndFakeTests/TestSamples/InjectMockSample.cs b/tests/CreateAndFakeTests/TestSamples/InjectMockSample.cs deleted file mode 100644 index 544b7bd0..00000000 --- a/tests/CreateAndFakeTests/TestSamples/InjectMockSample.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public sealed class InjectMockSample(IOnlyMockSample sample1, IOnlyMockSample sample2) -{ - private readonly IOnlyMockSample - _sample1 = sample1 ?? throw new ArgumentNullException(nameof(sample1)), - _sample2 = sample2 ?? throw new ArgumentNullException(nameof(sample2)); - - public void TestIfMockedSeparately() - { - _sample1.FailIfNotMocked(); - _sample2.FailIfNotMocked(); - Tools.Asserter.IsNot(_sample1, _sample2); - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/InjectSample.cs b/tests/CreateAndFakeTests/TestSamples/InjectSample.cs deleted file mode 100644 index 2f4d7d64..00000000 --- a/tests/CreateAndFakeTests/TestSamples/InjectSample.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public class InjectSample(DataSample data, DataSample data2) -{ - public DataSample Data { get; } = data; - - public DataSample Data2 { get; } = data2; -} diff --git a/tests/CreateAndFakeTests/TestSamples/InternalSample.cs b/tests/CreateAndFakeTests/TestSamples/InternalSample.cs deleted file mode 100644 index a3957928..00000000 --- a/tests/CreateAndFakeTests/TestSamples/InternalSample.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests.TestSamples; - -[ExcludeFromCodeCoverage] -internal sealed class InternalSample -{ - public string Data { get; set; } -} diff --git a/tests/CreateAndFakeTests/TestSamples/InvalidCreateSample.cs b/tests/CreateAndFakeTests/TestSamples/InvalidCreateSample.cs deleted file mode 100644 index 066f867b..00000000 --- a/tests/CreateAndFakeTests/TestSamples/InvalidCreateSample.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests.TestSamples; - -[ExcludeFromCodeCoverage] -public sealed class InvalidCreateSample : IOnlyMockSample -{ - public InvalidCreateSample() - { - throw new InvalidOperationException("Tried to create invalid sample."); - } - - public bool FailIfNotMocked() - { - throw new InvalidOperationException("Mock was not created."); - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/IsBadSample.cs b/tests/CreateAndFakeTests/TestSamples/IsBadSample.cs deleted file mode 100644 index 28949f37..00000000 --- a/tests/CreateAndFakeTests/TestSamples/IsBadSample.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests.TestSamples; - -public class IsBadSample : IIsGoodOrBadSample -{ - [ExcludeFromCodeCoverage] - public int GoodOrBadProp - { - get => 0; - set => throw new NotImplementedException(); - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/IsGoodSample.cs b/tests/CreateAndFakeTests/TestSamples/IsGoodSample.cs deleted file mode 100644 index f201c9b0..00000000 --- a/tests/CreateAndFakeTests/TestSamples/IsGoodSample.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public class IsGoodSample : IIsGoodOrBadSample -{ - public int GoodOrBadProp { get; set; } -} diff --git a/tests/CreateAndFakeTests/TestSamples/MismatchDataSample.cs b/tests/CreateAndFakeTests/TestSamples/MismatchDataSample.cs deleted file mode 100644 index ecd7919f..00000000 --- a/tests/CreateAndFakeTests/TestSamples/MismatchDataSample.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public class MismatchDataSample(int value) -{ - public string Data { get; set; } = "Value:" + value; -} diff --git a/tests/CreateAndFakeTests/TestSamples/OutSample.cs b/tests/CreateAndFakeTests/TestSamples/OutSample.cs deleted file mode 100644 index 25ca1980..00000000 --- a/tests/CreateAndFakeTests/TestSamples/OutSample.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public abstract class OutSample -{ - public abstract void ReturnVoid(out string input); - - public abstract int ReturnValue(out int input); -} diff --git a/tests/CreateAndFakeTests/TestSamples/ParentLoopSample.cs b/tests/CreateAndFakeTests/TestSamples/ParentLoopSample.cs deleted file mode 100644 index e1fbcc87..00000000 --- a/tests/CreateAndFakeTests/TestSamples/ParentLoopSample.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public sealed class ParentLoopSample -{ - public ChildWithParentSample Child { get; set; } -} diff --git a/tests/CreateAndFakeTests/TestSamples/PrivateValuerEquatableSample.cs b/tests/CreateAndFakeTests/TestSamples/PrivateValuerEquatableSample.cs deleted file mode 100644 index 04fd7101..00000000 --- a/tests/CreateAndFakeTests/TestSamples/PrivateValuerEquatableSample.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFakeTests.TestSamples; - -public class PrivateValuerEquatableSample(string stringValue) : IValuerEquatable -{ - private string StringValue { get; } = stringValue; - - public virtual bool ValuesEqual(object other, IValuer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return (other is PrivateValuerEquatableSample sample) - && valuer.Equals(StringValue, sample.StringValue); - } - - public virtual int GetValueHash(IValuer valuer) - { - return valuer?.GetHashCode(StringValue) ?? throw new ArgumentNullException(nameof(valuer)); - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/ProtectedSample.cs b/tests/CreateAndFakeTests/TestSamples/ProtectedSample.cs deleted file mode 100644 index 92a16770..00000000 --- a/tests/CreateAndFakeTests/TestSamples/ProtectedSample.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public abstract class ProtectedSample -{ - protected abstract void ChildMethod(); -} diff --git a/tests/CreateAndFakeTests/TestSamples/RefSample.cs b/tests/CreateAndFakeTests/TestSamples/RefSample.cs deleted file mode 100644 index a82be95f..00000000 --- a/tests/CreateAndFakeTests/TestSamples/RefSample.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public abstract class RefSample -{ - public abstract void ReturnVoid(ref string input); - - public abstract int ReturnValue(ref int input); -} diff --git a/tests/CreateAndFakeTests/TestSamples/ScopeSample.cs b/tests/CreateAndFakeTests/TestSamples/ScopeSample.cs deleted file mode 100644 index 0bb92077..00000000 --- a/tests/CreateAndFakeTests/TestSamples/ScopeSample.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests.TestSamples; - -[ExcludeFromCodeCoverage] -public class ScopeSample -{ - public virtual string PublicProp { get; set; } - - internal virtual string InternalProp { get; set; } - - protected internal virtual string ProIntProp { get; set; } - - protected virtual string ProtectProp { get; set; } - - public virtual string InternalGet { internal get; set; } - - public virtual string ProIntGet { protected internal get; set; } - - public virtual string ProtectGet { protected get; set; } - - public virtual string PrivateGet { private get; set; } - - public virtual string InternalSet { get; internal set; } - - public virtual string ProIntSet { get; protected internal set; } - - public virtual string ProtectSet { get; protected set; } - - public virtual string PrivateSet { get; private set; } - - public virtual string PublicMethod() { return "Value"; } - - internal virtual string InternalMethod() { return "Value"; } - - protected internal virtual string ProIntMethod() { return "Value"; } - - protected virtual string ProtectMethod() { return "Value"; } - - public string CallProtectProp() - { - return ProtectProp; - } - - public void SetProtectProp(string data) - { - ProtectProp = data; - } - - public string CallProtectGet() - { - return ProtectGet; - } - - public void SetProtectSet(string data) - { - ProtectSet = data; - } - - public string CallProtectMethod() - { - return ProtectMethod(); - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/StatelessSample.cs b/tests/CreateAndFakeTests/TestSamples/StatelessSample.cs deleted file mode 100644 index dbb2b1c4..00000000 --- a/tests/CreateAndFakeTests/TestSamples/StatelessSample.cs +++ /dev/null @@ -1,3 +0,0 @@ -namespace CreateAndFakeTests.TestSamples; - -public sealed class StatelessSample { } diff --git a/tests/CreateAndFakeTests/TestSamples/StructSample.cs b/tests/CreateAndFakeTests/TestSamples/StructSample.cs deleted file mode 100644 index 9fb14b16..00000000 --- a/tests/CreateAndFakeTests/TestSamples/StructSample.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using CreateAndFake.Design.Content; - -#pragma warning disable IDE0250 // Struct can be made 'readonly': For testing. -#pragma warning disable IDE0251 // Member can be made 'readonly': For testing. - -namespace CreateAndFakeTests.TestSamples; - -[ExcludeFromCodeCoverage] -public struct StructSample(string stringValue) : IEquatable, IComparable, IComparable -{ - public string StringValue { get; } = stringValue; - - public int CompareTo(StructSample other) - { - return ValueComparer.Use.Compare(this, other); - } - - public int CompareTo(object obj) - { - return ValueComparer.Use.Compare(this, obj); - } - - public override bool Equals(object obj) - { - return (obj is StructSample sample) && Equals(sample); - } - - public bool Equals(StructSample other) - { - return ValueComparer.Use.Equals(StringValue, other.StringValue); - } - - public override int GetHashCode() - { - return ValueComparer.Use.GetHashCode(StringValue); - } - - public static bool operator ==(StructSample left, StructSample right) - { - return left.Equals(right); - } - - public static bool operator !=(StructSample left, StructSample right) - { - return !(left == right); - } - - public static bool operator <(StructSample left, StructSample right) - { - return left.CompareTo(right) < 0; - } - - public static bool operator <=(StructSample left, StructSample right) - { - return left.CompareTo(right) <= 0; - } - - public static bool operator >(StructSample left, StructSample right) - { - return left.CompareTo(right) > 0; - } - - public static bool operator >=(StructSample left, StructSample right) - { - return left.CompareTo(right) >= 0; - } -} - -#pragma warning restore IDE0250 // Struct can be made 'readonly' -#pragma warning restore IDE0251 // Member can be made 'readonly' diff --git a/tests/CreateAndFakeTests/TestSamples/ValueEquatableSample.cs b/tests/CreateAndFakeTests/TestSamples/ValueEquatableSample.cs deleted file mode 100644 index 80a22cce..00000000 --- a/tests/CreateAndFakeTests/TestSamples/ValueEquatableSample.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CreateAndFake.Design.Content; - -namespace CreateAndFakeTests.TestSamples; - -public class ValueEquatableSample : IValueEquatable -{ - public string StringValue { get; set; } - - public int NumberValue; - - public virtual bool ValuesEqual(object other) - { - return (other is ValueEquatableSample sample) - && StringValue == sample.StringValue - && NumberValue == sample.NumberValue; - } - - public virtual int GetValueHash() - { - return ValueComparer.Use.GetHashCode(StringValue, NumberValue); - } -} diff --git a/tests/CreateAndFakeTests/TestSamples/ValuerEquatableSample.cs b/tests/CreateAndFakeTests/TestSamples/ValuerEquatableSample.cs deleted file mode 100644 index c725e172..00000000 --- a/tests/CreateAndFakeTests/TestSamples/ValuerEquatableSample.cs +++ /dev/null @@ -1,25 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFakeTests.TestSamples; - -public class ValuerEquatableSample : IValuerEquatable -{ - public string StringValue { get; set; } - - public int NumberValue; - - public virtual bool ValuesEqual(object other, IValuer valuer) - { - ArgumentGuard.ThrowIfNull(valuer, nameof(valuer)); - - return (other is ValuerEquatableSample sample) - && valuer.Equals(StringValue, sample.StringValue) - && valuer.Equals(NumberValue, sample.NumberValue); - } - - public virtual int GetValueHash(IValuer valuer) - { - return valuer?.GetHashCode(StringValue, NumberValue) ?? throw new ArgumentNullException(nameof(valuer)); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/AsserterTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/AsserterTests.cs deleted file mode 100644 index edd23b5f..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/AsserterTests.cs +++ /dev/null @@ -1,293 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Toolbox.AsserterTool; - -public sealed class AsserterTests -{ - private readonly Asserter _testInstance; - - public AsserterTests() - { - _testInstance = new Asserter(Tools.Gen, Tools.Valuer); - } - - [Fact] - internal static void Asserter_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void Asserter_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Fact] - internal static void Asserter_AllMethodsVirtual() - { - Tools.Asserter.IsEmpty(typeof(Asserter) - .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) - .Where(m => !m.IsVirtual) - .Select(m => m.Name) - .Where(n => n is not "Is" and not "IsNot")); - } - - [Fact] - internal void CheckAll_RunsEachValidCase() - { - bool ran1 = false; - bool ran2 = false; - - _testInstance.CheckAll(() => ran1 = true, () => ran2 = true); - - ran1.Assert().Is(true).Also(ran2).Is(true); - } - - [Theory, RandomData] - internal void CheckAll_SingleErrorThrows(Exception error) - { - bool ran2 = false; - - _testInstance - .Assert(t => t.CheckAll( - () => throw error, - () => ran2 = true)) - .Throws().InnerExceptions - .Assert().Is(new[] { error }) - .Also(ran2).Is(true); - } - - [Theory, RandomData] - internal void CheckAll_RunsEachErrorCase(Exception error1, Exception error2) - { - _testInstance - .Assert(t => t.CheckAll( - () => throw error1, - () => throw error2)) - .Throws().InnerExceptions - .Assert().Is(new[] { error1, error2 }); - } - - [Fact] - internal void Fail_Throws() - { - _testInstance.Assert(t => t.Fail()).Throws(); - } - - [Theory, RandomData] - internal void Fail_ThrowsWithException(Exception error) - { - _testInstance - .Assert(t => t.Fail(error)) - .Throws().InnerException.Assert() - .Is(error); - } - - [Fact] - internal void Throws_ActionThrows() - { - _testInstance.Throws((Action)(() => throw new InvalidOperationException())); - } - - [Fact] - internal void Throws_ActionTypeMismatch() - { - _testInstance - .Assert(t => t.Throws((Action)(() => throw new NotImplementedException()))) - .Throws(); - } - - [Fact] - internal void Throws_ActionNoThrow() - { - _testInstance - .Assert(t => t.Throws(() => { })) - .Throws(); - } - - [Fact] - internal void Throws_ActionNullCase() - { - _testInstance - .Assert(t => t.Throws((Action)null)) - .Throws(); - } - - [Fact] - internal void Throws_FuncThrows() - { - _testInstance.Throws(() => throw new InvalidOperationException()); - } - - [Fact] - internal void Throws_FuncTypeMismatch() - { - _testInstance - .Assert(t => t.Throws(() => throw new NotImplementedException())) - .Throws(); - } - - [Fact] - internal void Throws_FuncNoThrow() - { - _testInstance - .Assert(t => t.Throws(() => true)) - .Throws(); - } - - [Fact] - internal void Throws_FuncNullCase() - { - _testInstance - .Assert(t => t.Throws(null)) - .Throws(); - } - - [Theory, RandomData] - internal void Throws_Disposes([Stub] IDisposable disposable) - { - disposable.ToFake().Setup(m => m.Dispose(), Behavior.None(Times.Once)); - - _testInstance - .Assert(t => t.Throws(() => disposable)) - .Throws(); - - disposable.VerifyAllCalls(); - } - - [Theory, RandomData] - internal void Throws_AggregateUnwraps(InvalidOperationException ex) - { - _testInstance - .Throws(() => throw new AggregateException(ex)) - .Assert() - .Is(ex); - } - - [Theory, RandomData] - internal void Throws_AggregateExtraInternal(InvalidOperationException error1, Exception error2) - { - AggregateException ex = new(error1, error2); - - _testInstance - .Assert(t => t.Throws(() => throw ex)) - .Throws().InnerException - .Assert().Is(ex); - } - - [Theory, RandomData] - internal void Throws_AggregateWrongInternals(InvalidOperationException error) - { - AggregateException ex = new(error); - - _testInstance - .Assert(t => t.Throws(() => throw ex)) - .Throws().InnerException - .Assert().Is(ex); - } - - [Theory, RandomData] - internal void IsEmpty_Works(IEnumerable data) - { - _testInstance.IsEmpty(Array.Empty()); - - _testInstance.Assert(t => t.IsEmpty(null)).Throws(); - _testInstance.Assert(t => t.IsEmpty(data)).Throws(); - } - - [Theory, RandomData] - internal void IsNotEmpty_Works(IEnumerable data) - { - _testInstance.IsNotEmpty(data); - - _testInstance.Assert(t => t.IsNotEmpty(null)).Throws(); - _testInstance.Assert(t => t.IsNotEmpty(Array.Empty())).Throws(); - } - - [Theory, RandomData] - internal void HasCount_Works(IEnumerable data) - { - _testInstance.HasCount(data.Count(), data); - - _testInstance.Assert(t => t.HasCount(data.Count(), null)).Throws(); - _testInstance.Assert(t => t.HasCount(data.Count() - 1, data)).Throws(); - _testInstance.Assert(t => t.HasCount(data.Count() + 1, data)).Throws(); - } - - [Theory, RandomData] - internal void ReferenceEqual_NotByValue([Stub] object fake) - { - fake.Equals(Arg.Any()).SetupReturn(true, Times.Never); - - _testInstance.ReferenceEqual(fake, fake); - _testInstance.Assert(t => t.ReferenceEqual(fake, fake.CreateDeepClone())); - - fake.VerifyAllCalls(Times.Never); - } - - [Theory, RandomData] - internal void ReferenceNotEqual_NotByValue([Stub] object fake) - { - fake.Equals(Arg.Any()).SetupReturn(false, Times.Never); - - _testInstance.ReferenceNotEqual(fake, fake.CreateDeepClone()); - _testInstance.Assert(t => t.ReferenceNotEqual(fake, fake)).Throws(); - - fake.VerifyAllCalls(Times.Never); - } - - [Theory, RandomData] - internal void ValuesEqual_EqualValid(object value) - { - _testInstance.ValuesEqual(value, value.CreateDeepClone()); - } - - [Theory, RandomData] - internal void ValuesEqual_UnequalInvalid(string value) - { - _testInstance.Assert(t => t.ValuesEqual(value, value.CreateVariant())).Throws(); - _testInstance.Assert(t => t.ValuesEqual(null, value)).Throws(); - } - - [Theory, RandomData] - internal void ValuesEqual_CanHandleNullsNotEqual(object value) - { - _testInstance.Assert(t => t.ValuesEqual(value, null)).Throws(); - _testInstance.Assert(t => t.ValuesEqual(null, value)).Throws(); - } - - [Theory, RandomData] - internal void ValuesNotEqual_UnequalValid(string value) - { - _testInstance.ValuesNotEqual(value, value.CreateVariant()); - _testInstance.ValuesNotEqual(null, value); - _testInstance.ValuesNotEqual(value, null); - } - - [Theory, RandomData] - internal void ValuesNotEqual_EqualInvalid(string value) - { - _testInstance.Assert(t => t.ValuesNotEqual(value, value.CreateDeepClone())).Throws(); - _testInstance.Assert(t => t.ValuesNotEqual(value, value)).Throws(); - _testInstance.Assert(t => t.ValuesNotEqual(null, null)).Throws(); - } - - [Theory, RandomData] - internal void AreUnique_UnequalValid(string value) - { - _testInstance.AreUnique(value, value.CreateVariant()); - _testInstance.AreUnique(null, value); - _testInstance.AreUnique(value, null); - } - - [Theory, RandomData] - internal void AreUnique_EqualInvalid(string value) - { - _testInstance.Assert(t => t.AreUnique(value, value.CreateDeepClone())).Throws(); - _testInstance.Assert(t => t.AreUnique(value, value)).Throws(); - _testInstance.Assert(t => t.AreUnique(null, null)).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertBehaviorTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertBehaviorTests.cs deleted file mode 100644 index 90c553e3..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertBehaviorTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.AsserterTool.Fluent; - -namespace CreateAndFakeTests.Toolbox.AsserterTool.Fluent; - -public static class AssertBehaviorTests -{ - [Fact] - internal static void AssertBehavior_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void AssertBehavior_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void Throws_ReturnsException(Exception error) - { - error.Assert(e => throw e).Throws().Assert().Is(error); - } - - [Theory, RandomData] - internal static void Throws_CatchesExpected(ArgumentNullException error) - { - error.Assert(e => throw e).Throws().Assert().Is(error); - } - - [Theory, RandomData] - internal static void Throws_UnwrapsAggregate(InvalidOperationException error) - { - error.Assert(e => throw new AggregateException(e)).Throws().Assert().Is(error); - } - - [Theory, RandomData] - internal static void Throws_ActionNoException(Action behavior) - { - behavior.Assert(d => d.Assert().Throws()).Throws(); - } - - [Theory, RandomData] - internal static void Throws_FuncNoException(Func behavior) - { - behavior.Assert(d => d.Assert().Throws()).Throws(); - } - - [Theory, RandomData] - internal static void Throws_WrongException(ArgumentNullException error) - { - error.Assert(e => e.Assert(ex => throw ex).Throws()).Throws(); - } - - [Theory, RandomData] - internal static void Throws_WrongAggregate(InvalidOperationException error) - { - error - .Assert(e => e.Assert(ex => throw new AggregateException(ex)).Throws()) - .Throws(); - } - - [Theory, RandomData] - internal static void Throws_TooManyAggregate(ArgumentNullException error, InvalidOperationException error2) - { - error - .Assert(e => error2.Assert(ex => throw new AggregateException(e, ex)).Throws()) - .Throws(); - } - - [Theory, RandomData] - internal static void ThrowsNoException_NoopAction(Action behavior) - { - behavior.Assert().ThrowsNoException(); - } - - [Theory, RandomData] - internal static void ThrowsNoException_NoopFunc(Func behavior) - { - behavior.Assert().ThrowsNoException(); - } - - [Theory, RandomData] - internal static void ThrowsNoException_Error(Exception error) - { - error.Assert(e => e.Assert(ex => throw ex).ThrowsNoException()).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertChainerTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertChainerTests.cs deleted file mode 100644 index 5f0cac04..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertChainerTests.cs +++ /dev/null @@ -1,84 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool.Fluent; - -namespace CreateAndFakeTests.Toolbox.AsserterTool.Fluent; - -public static class AssertChainerTests -{ - [Fact] - internal static void AssertChainer_GuardsNulls() - { - Tools.Tester.PreventsNullRefException>(); - } - - [Fact] - internal static void AssertChainer_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation>(); - } - - [Theory, RandomData] - internal static void And_ReturnsInput(object data) - { - new AssertChainer(data, Tools.Gen, Tools.Valuer).And.Assert().Is(data); - } - - [Theory, RandomData] - internal static void Also_HandlesObject(AssertChainer chainer, object data) - { - chainer.Also(data).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesCollection(AssertChainer chainer, IEnumerable data) - { - chainer.Also(data).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesString(AssertChainer chainer, string data) - { - chainer.Also(data).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesComparables(AssertChainer chainer, IComparable data) - { - chainer.Also(data).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesType(AssertChainer chainer, Type data) - { - chainer.Also(data).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesException(AssertChainer chainer, Exception data) - { - chainer.Also(data).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesAction(AssertChainer chainer, Action behavior) - { - chainer.Also(behavior).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesFunc(AssertChainer chainer, Func behavior) - { - chainer.Also(behavior).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesCompiledAction(AssertChainer chainer, string data) - { - chainer.Also(data, d => d.VerifyAllCalls()).GetType().Assert().Inherits(); - } - - [Theory, RandomData] - internal static void Also_HandlesCompiledFunc(AssertChainer chainer, string data) - { - chainer.Also(data, d => d.Length).GetType().Assert().Inherits(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertComparableTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertComparableTests.cs deleted file mode 100644 index 7eaca815..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertComparableTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool.Fluent; - -namespace CreateAndFakeTests.Toolbox.AsserterTool.Fluent; - -public static class AssertComparableTests -{ - [Fact] - internal static void AssertComparable_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void AssertComparable_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } -} - diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertErrorTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertErrorTests.cs deleted file mode 100644 index 47ddd69e..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertErrorTests.cs +++ /dev/null @@ -1,25 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.AsserterTool.Fluent; - -namespace CreateAndFakeTests.Toolbox.AsserterTool.Fluent; - -public static class AssertErrorTests -{ - [Fact] - internal static void AssertError_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void AssertError_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void Fail_Throws(Exception error) - { - error.Assert(d => d.Assert().Fail()).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertGroupTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertGroupTests.cs deleted file mode 100644 index cc09872d..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertGroupTests.cs +++ /dev/null @@ -1,90 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.AsserterTool.Fluent; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.AsserterTool.Fluent; - -public static class AssertCollectionTests -{ - [Fact] - internal static void AssertGroup_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void AssertGroup_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void IsEmpty_NoItems([Size(0)] IEnumerable items) - { - items.Assert().IsEmpty(); - } - - [Theory, RandomData] - internal static void IsEmpty_WithItems(IEnumerable items) - { - items.Assert(d => d.Assert().IsEmpty()).Throws(); - } - - [Theory, RandomData] - internal static void IsNotEmpty_WithItems(IEnumerable items) - { - items.Assert().IsNotEmpty(); - } - - [Theory, RandomData] - internal static void IsNotEmpty_NoItems([Size(0)] IEnumerable items) - { - items.Assert(d => d.Assert().IsNotEmpty()).Throws(); - } - - [Theory, RandomData] - internal static void HasCount_SameSize(ICollection items) - { - items.Assert().HasCount(items.Count); - } - - [Theory, RandomData] - internal static void HasCount_MismatchedSize(ICollection items) - { - items.Assert(d => d.Assert().HasCount(items.Count.CreateVariant())).Throws(); - } - - [Theory, RandomData] - internal static void Contains_UsingSubitem(ICollection items) - { - items.Assert().Contains(Tools.Gen.NextItem(items)); - } - - [Theory, RandomData] - internal static void Contains_RandomOther(ICollection items) - { - items - .Assert(d => d.Assert().Contains(Tools.Mutator.Variant(items.First(), items.Skip(1).ToArray()))) - .Throws(); - } - - [Theory, RandomData] - internal static void ContainsNot_RandomOther(ICollection items) - { - items.Assert().ContainsNot(Tools.Mutator.Variant(items.First(), items.Skip(1).ToArray())); - } - - [Theory, RandomData] - internal static void ContainsNot_UsingSubitem(ICollection items) - { - items - .Assert(d => d.Assert().ContainsNot(Tools.Gen.NextItem(items))) - .Throws(); - } - - [Theory, RandomData] - internal static void Fail_Throws(IEnumerable items) - { - items.Assert(d => d.Assert().Fail()).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertObjectTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertObjectTests.cs deleted file mode 100644 index 76d79379..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertObjectTests.cs +++ /dev/null @@ -1,116 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.AsserterTool.Fluent; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.AsserterTool.Fluent; - -public static class AssertObjectTests -{ - [Fact] - internal static void AssertObject_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void AssertObject_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void Is_UsesValueQualityPass(DataSample sample) - { - sample.Assert().Is(sample.CreateDeepClone()); - } - - [Theory, RandomData] - internal static void Is_UsesValueQualityFail(DataSample sample) - { - sample.Assert(s => s.Assert().Is(sample.CreateVariant())).Throws(); - } - - [Theory, RandomData] - internal static void IsNot_UsesValueQualityPass(DataSample sample) - { - sample.Assert().IsNot(sample.CreateVariant()); - } - - [Theory, RandomData] - internal static void IsNot_UsesValueQualityFail(DataSample sample) - { - sample.Assert(s => s.Assert().IsNot(sample.CreateDeepClone())).Throws(); - } - - [Theory, RandomData] - internal static void ReferenceEqual_SameObject(DataSample sample) - { - sample.Assert().ReferenceEqual(sample); - } - - [Theory, RandomData] - internal static void ReferenceEqual_DifferentObject(DataSample sample) - { - sample.Assert(s => s.Assert().ReferenceEqual(sample.CreateDeepClone())).Throws(); - } - - [Theory, RandomData] - internal static void ReferenceNotEqual_DifferentObject(DataSample sample) - { - sample.Assert().ReferenceNotEqual(sample.CreateVariant()); - } - - [Theory, RandomData] - internal static void ReferenceNotEqual_SameObject(DataSample sample) - { - sample.Assert(s => s.Assert().ReferenceNotEqual(sample)).Throws(); - } - - [Theory, RandomData] - internal static void ValuesEqual_UsesValueQualityPass(DataSample sample) - { - sample.Assert().ValuesEqual(sample.CreateDeepClone()); - } - - [Theory, RandomData] - internal static void ValuesEqual_UsesValueQualityFail(DataSample sample) - { - sample.Assert(s => s.Assert().ValuesEqual(sample.CreateVariant())).Throws(); - } - - [Theory, RandomData] - internal static void ValuesNotEqual_UsesValueQualityPass(DataSample sample) - { - sample.Assert().ValuesNotEqual(sample.CreateVariant()); - } - - [Theory, RandomData] - internal static void ValuesNotEqual_UsesValueQualityFail(DataSample sample) - { - sample.Assert(s => s.Assert().ValuesNotEqual(sample.CreateDeepClone())).Throws(); - } - - [Theory, RandomData] - internal static void UniqueFrom_NoSharedPass(string sample) - { - sample.Assert().UniqueFrom(sample.CreateVariant()); - } - - [Theory, RandomData] - internal static void UniqueFrom_SharedFail(string sample) - { - sample.Assert(s => s.Assert().UniqueFrom(sample.CreateDeepClone())).Throws(); - } - - [Theory, RandomData] - internal static void Fail_Throws(IEnumerable items) - { - items.Assert(d => d.Assert().Fail()).Throws(); - } - - [Theory, RandomData] - internal static void Pass_Works(object item) - { - item.Assert().Pass(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertTextTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertTextTests.cs deleted file mode 100644 index 6d0c0471..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertTextTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.AsserterTool.Fluent; - -namespace CreateAndFakeTests.Toolbox.AsserterTool.Fluent; - -public static class AssertTextTests -{ - [Fact] - internal static void AssertText_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void AssertText_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void Contains_UsingSubstring(ICollection sample) - { - string.Join("", sample).Assert().Contains(Tools.Gen.NextItem(sample)); - } - - [Theory, RandomData] - internal static void Contains_RandomOther(string sample) - { - sample.Assert(d => d.Assert().Contains(Tools.Mutator.Variant(sample))).Throws(); - } - - [Theory, RandomData] - internal static void ContainsNot_RandomOther(string sample) - { - sample.Assert().ContainsNot(Tools.Mutator.Variant(sample)); - } - - [Theory, RandomData] - internal static void ContainsNot_UsingSubstring(ICollection sample) - { - string.Join("", sample) - .Assert(d => d.Assert().ContainsNot(Tools.Gen.NextItem(sample))) - .Throws(); - } - - [Theory, RandomData] - internal static void StartsWith_UsingFirstString(ICollection sample) - { - string.Join("", sample).Assert().StartsWith(sample.First()); - } - - [Theory, RandomData] - internal static void StartsWith_UsingNonFirstString([Size(3)] ICollection sample) - { - string.Join("", sample) - .Assert(d => d.Assert().StartsWith(Tools.Gen.NextItem(sample.Skip(1)))) - .Throws(); - } - - [Theory, RandomData] - internal static void StartsNotWith_UsingNonFirstString([Size(3)] ICollection sample) - { - string.Join("", sample).Assert().StartsNotWith(Tools.Gen.NextItem(sample.Skip(1))); - } - - [Theory, RandomData] - internal static void StartsNotWith_UsingFirstString(ICollection sample) - { - string.Join("", sample) - .Assert(d => d.Assert().StartsNotWith(sample.First())) - .Throws(); - } - - [Theory, RandomData] - internal static void EndsWith_UsingLastString(ICollection sample) - { - string.Join("", sample).Assert().EndsWith(sample.Last()); - } - - [Theory, RandomData] - internal static void EndsWith_UsingNonLstString([Size(3)] ICollection sample) - { - string.Join("", sample) - .Assert(d => d.Assert().EndsWith(Tools.Gen.NextItem(sample.Reverse().Skip(1)))) - .Throws(); - } - - [Theory, RandomData] - internal static void EndsNotWith_UsingNonLastString([Size(3)] ICollection sample) - { - string.Join("", sample).Assert().EndsNotWith(Tools.Gen.NextItem(sample.Reverse().Skip(1))); - } - - [Theory, RandomData] - internal static void EndsNotWith_UsingLstString(ICollection sample) - { - string.Join("", sample) - .Assert(d => d.Assert().EndsNotWith(sample.Last())) - .Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertTypeTests.cs b/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertTypeTests.cs deleted file mode 100644 index 2d82a976..00000000 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/Fluent/AssertTypeTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.AsserterTool.Fluent; - -namespace CreateAndFakeTests.Toolbox.AsserterTool.Fluent; - -public static class AssertTypeTests -{ - private interface IParentType : IChildType { } - - private interface IChildType { } - - [Fact] - internal static void AssertType_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void AssertType_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Fact] - internal static void Inherits_ParentToChild() - { - typeof(IParentType).Assert().Inherits().And.Inherits(typeof(IChildType)); - } - - [Fact] - internal static void Inherits_ChildToParent() - { - typeof(IChildType).Assert(t => t.Assert().Inherits()).Throws(); - typeof(IChildType).Assert(t => t.Assert().Inherits(typeof(IParentType))).Throws(); - } - - [Fact] - internal static void InheritedBy_ChildToParent() - { - typeof(IChildType).Assert().InheritedBy().And.InheritedBy(typeof(IParentType)); - } - - [Fact] - internal static void InheritedBy_ParentToChild() - { - typeof(IParentType).Assert(t => t.Assert().InheritedBy()).Throws(); - typeof(IParentType).Assert(t => t.Assert().InheritedBy(typeof(IChildType))).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/AsyncCollectionCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/AsyncCollectionCopyHintTests.cs deleted file mode 100644 index c0064365..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/AsyncCollectionCopyHintTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class AsyncCollectionCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = - [ - typeof(IAsyncEnumerable), - typeof(IAsyncEnumerable), - typeof(IAsyncEnumerable) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(object), - typeof(IEnumerable) - ]; - - public AsyncCollectionCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal static void TryCopy_Empty([Size(0)] IAsyncEnumerable items) - { - items.CreateDeepClone().Assert().Is(items); - } - - [Theory, RandomData] - internal static async Task CopyAsync_Interrupt([Size(5)] IAsyncEnumerable original) - { - IAsyncEnumerable items = original.CreateDeepClone(); - - await items.GetAsyncEnumerator().DisposeAsync().ConfigureAwait(true); - - int count = 0; - await foreach (int item in items) - { - count++; - if (count == 3) - { - break; - } - } - - count = 0; - await foreach (int item in items) - { - count++; - } - count.Assert().Is(5); - - items.Assert().Is(original); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/BasicCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/BasicCopyHintTests.cs deleted file mode 100644 index 5e035951..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/BasicCopyHintTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class BasicCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = - [ - typeof(BindingFlags), - typeof(string), - typeof(int), - typeof(decimal) - ]; - - private static readonly Type[] _InvalidTypes = [typeof(DataHolderSample)]; - - public BasicCopyHintTests() : base(_ValidTypes, _InvalidTypes, true) { } - - [Fact] - internal static void TryCopy_HandlesBaseObject() - { - object data = new(); - (bool, object) result = new BasicCopyHint().TryCopy(data, CreateChainer()); - - result.Assert().Is((true, data)); - result.Item2.Assert().ReferenceEqual(data); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CloneableCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CloneableCopyHintTests.cs deleted file mode 100644 index e6930dc3..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CloneableCopyHintTests.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class CloneableCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = Enumerable.Repeat(typeof(ICloneable), 10).ToArray(); - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public CloneableCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CollectionCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CollectionCopyHintTests.cs deleted file mode 100644 index f8201703..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CollectionCopyHintTests.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class CollectionCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = CollectionCreateHint.PotentialCollections - .Concat([ - typeof(int[]), - typeof(string[]), - typeof(ArrayList), - typeof(Queue), - typeof(Stack), - typeof(Array)]) - .ToArray(); - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public CollectionCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CommonSystemCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CommonSystemCopyHintTests.cs deleted file mode 100644 index 2780c36f..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/CommonSystemCopyHintTests.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class CommonSystemCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = [typeof(TimeSpan), typeof(WeakReference), typeof(Uri)]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public CommonSystemCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal static void TryCopy_HandlesMemberInfo(MemberInfo data) - { - (bool, object) result = new CommonSystemCopyHint().TryCopy(data, CreateChainer()); - - result.Item1.Assert().Is(true); - result.Item2.Assert().ReferenceEqual(data); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/DeepCloneableCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/DeepCloneableCopyHintTests.cs deleted file mode 100644 index 12acfbb4..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/DeepCloneableCopyHintTests.cs +++ /dev/null @@ -1,14 +0,0 @@ -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class DeepCloneableCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = Enumerable.Repeat(typeof(IDeepCloneable), 10).ToArray(); - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public DeepCloneableCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/DuplicatableCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/DuplicatableCopyHintTests.cs deleted file mode 100644 index b6001c95..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/DuplicatableCopyHintTests.cs +++ /dev/null @@ -1,14 +0,0 @@ -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class DuplicatableCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = [typeof(IDuplicatable)]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public DuplicatableCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/LegacyCollectionCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/LegacyCollectionCopyHintTests.cs deleted file mode 100644 index 0cc527da..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/LegacyCollectionCopyHintTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class LegacyCollectionCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = LegacyCollectionCreateHint.PotentialCollections - .Except([typeof(ArrayList), typeof(Queue), typeof(Stack), typeof(Array)]) - .ToArray(); - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public LegacyCollectionCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/ObjectCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/ObjectCopyHintTests.cs deleted file mode 100644 index 5531dd90..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/ObjectCopyHintTests.cs +++ /dev/null @@ -1,21 +0,0 @@ -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class ObjectCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = - [ - typeof(PrivateValuerEquatableSample), - typeof(IUnimplementedSample), - typeof(DataHolderSample), - typeof(FieldSample), - typeof(object) - ]; - - private static readonly Type[] _InvalidTypes = [typeof(MismatchDataSample)]; - - public ObjectCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/SerializableCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/SerializableCopyHintTests.cs deleted file mode 100644 index 93cb320e..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/SerializableCopyHintTests.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class SerializableCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = [typeof(Exception)]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public SerializableCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/TaskCopyHintTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/TaskCopyHintTests.cs deleted file mode 100644 index 9405c566..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/CopyHints/TaskCopyHintTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -using CreateAndFake.Toolbox.DuplicatorTool.CopyHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool.CopyHints; - -public sealed class TaskCopyHintTests : CopyHintTestBase -{ - private static readonly Type[] _ValidTypes = - [ - typeof(Task), - typeof(Task), - typeof(Task), - typeof(Task), - typeof(Task) - ]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public TaskCopyHintTests() : base(_ValidTypes, _InvalidTypes) { } - - [Fact] - internal void TryCopy_NonGenericTaskFalse() - { - TestInstance.TryCopy(new Task(() => { }), CreateChainer()).Assert().Is((false, (object)null)); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/DuplicatorChainerTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/DuplicatorChainerTests.cs deleted file mode 100644 index f6d155fc..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/DuplicatorChainerTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using CreateAndFake.Toolbox.DuplicatorTool; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool; - -public static class DuplicatorChainerTests -{ - [Fact] - internal static void DuplicatorChainer_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void DuplicatorChainer_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/DuplicatorTests.cs b/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/DuplicatorTests.cs deleted file mode 100644 index f9022d66..00000000 --- a/tests/CreateAndFakeTests/Toolbox/DuplicatorTool/DuplicatorTests.cs +++ /dev/null @@ -1,57 +0,0 @@ -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Toolbox.DuplicatorTool; - -public static class DuplicatorTests -{ - [Fact] - internal static void Duplicator_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void New_NullHintsValid() - { - new Duplicator(Tools.Asserter, true, null).Assert().IsNot(null); - new Duplicator(Tools.Asserter, false, null).Assert().IsNot(null); - } - - [Fact] - internal static void Copy_MissingMatchThrows() - { - new Duplicator(Tools.Asserter, false) - .Assert(d => d.Copy(new object())) - .Throws(); - } - - [Fact] - internal static void Copy_NullWorks() - { - new Duplicator(Tools.Asserter, false).Copy(null).Assert().Is(null); - } - - [Theory, RandomData] - internal static void Copy_ValidHintWorks(object data, [Stub] CopyHint hint) - { - hint.TryCopy(data, Arg.Any()).SetupReturn((true, data), Times.Once); - - new Duplicator(Tools.Asserter, false, hint).Copy(data).Assert().Is(data); - - hint.VerifyAllCalls(Times.Once); - } - - [Theory, RandomData] - internal static void Copy_InfiniteLoopDetails(object instance, [Stub] CopyHint hint) - { - hint.ToFake().Setup( - m => m.TryCopy(instance, Arg.Any()), - Behavior.Throw(Times.Once)); - - new Duplicator(Tools.Asserter, false, hint) - .Assert(d => d.Copy(instance)) - .Throws().Message - .Assert().Contains(instance.GetType().Name); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/AnyGenericTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/AnyGenericTests.cs deleted file mode 100644 index 99a44596..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/AnyGenericTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class AnyGenericTests -{ - [Fact] - internal static void VoidType_PrivateConstructor() - { - ConstructorInfo constructor = typeof(AnyGeneric) - .GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) - .Single(); - - constructor.IsPrivate.Assert().Is(true); - constructor.Invoke([]).Assert().IsNot(null); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/BehaviorTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/BehaviorTests.cs deleted file mode 100644 index 24c4c826..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/BehaviorTests.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class BehaviorTests -{ - [Fact] - internal static void Set_BehaviorWorks() - { - foreach (MethodInfo info in typeof(Behavior) - .GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(m => m.Name == nameof(Behavior.Set))) - { - Type type = info.GetParameters().First().ParameterType; - - Type[] generics = type - .AsGenericType() - ?.GetGenericArguments() - .Select(a => typeof(string)) - .ToArray() ?? Type.EmptyTypes; - - MethodInfo caller = (generics.Length != 0) - ? info.MakeGenericMethod(generics) - : info; - - Type setupType = caller.GetParameters().First().ParameterType; - - Type[] args = type.Name.StartsWith("Func", StringComparison.InvariantCulture) - ? generics.Skip(1).ToArray() - : generics; - - Behavior noTimes = (Behavior)caller.Invoke(null, [Tools.Randomizer.Create(setupType), null]); - - noTimes.HasExpectedCalls().Assert().Is(false); - noTimes.Invoke(args.Select(g => Tools.Randomizer.Create(g)).ToArray()); - noTimes.HasExpectedCalls().Assert().Is(true); - - Behavior withTimes = (Behavior)caller.Invoke(null, [Tools.Randomizer.Create(setupType), Times.Never]); - - withTimes.HasExpectedCalls().Assert().Is(true); - withTimes.Invoke(args.Select(g => Tools.Randomizer.Create(g)).ToArray()); - withTimes.HasExpectedCalls().Assert().Is(false); - } - } - - [Fact] - internal static void None_BehaviorWorks() - { - Behavior.None().Invoke([]).Assert().Is(default); - } - - [Fact] - internal static void Error_BehaviorWorks() - { - Behavior.Error().Assert(b => b.Invoke([])).Throws(); - } - - [Fact] - internal static void Null_BehaviorWorks() - { - Behavior.Null().Invoke([]).Assert().Is(null); - } - - [Fact] - internal static void Default_BehaviorWorks() - { - Behavior.Default().Invoke([]).Assert().Is(default(int)); - } - - [Fact] - internal static void Throw_BehaviorWorks() - { - Behavior.Throw().Assert(b => b.Invoke([])).Throws(); - } - - [Theory, RandomData] - internal static void Returns_BehaviorWorks(int value) - { - Behavior.Returns(value).Invoke([]).Assert().Is(value); - } - - [Fact] - internal static void Series_BehaviorWorks() - { - Behavior behavior = Behavior.Series(true, false, true); - behavior.Invoke([]).Assert().Is(true); - behavior.Invoke([]).Assert().Is(false); - behavior.Invoke([]).Assert().Is(true); - behavior.Invoke([]).Assert().Is(false); - behavior.Invoke([]).Assert().Is(false); - } - - [Theory, RandomData] - internal static void Series_NullCountsAsNone(string value) - { - Behavior behavior = Behavior.Series(value, null); - behavior.Invoke([]).Assert().Is(value); - behavior.Invoke([]).Assert().Is(null); - behavior.Invoke([]).Assert().Is(null); - } - - [Theory, RandomData] - internal static void ToExpectedCalls_MatchesTimes(Times times) - { - Behavior.None().ToExpectedCalls().Assert().Is(Times.Min(1).ToString()); - Behavior.None(times).ToExpectedCalls().Assert().Is(times.ToString()); - } - - [Fact] - internal static void Invoke_ThrowsWithWrongArgs() - { - Behavior.Set((int _) => { }).Assert(b => b.Invoke([])).Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/Behavior[T]Tests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/Behavior[T]Tests.cs deleted file mode 100644 index 5e454a9f..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/Behavior[T]Tests.cs +++ /dev/null @@ -1,21 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class Behavior_T_Tests -{ - [Fact] - internal static void Error_BehaviorWorks() - { - Behavior.Error().Assert(b => b.Invoke([])).Throws(); - } - - [Fact] - internal static void Throw_BehaviorWorks() - { - Behavior - .Throw() - .Assert(b => b.Invoke([])) - .Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/FakeTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/FakeTests.cs deleted file mode 100644 index 0f6b6401..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/FakeTests.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class FakeTests -{ - [Fact] - internal static void Verify_NoTotalValid() - { - Tools.Faker.Mock().VerifyAll(); - } - - [Fact] - internal static void SetupVerify_WorksProtectedMethods() - { - MethodInfo method = typeof(ProtectedSample) - .GetMethod("ChildMethod", BindingFlags.Instance | BindingFlags.NonPublic); - object[] args = []; - - Fake fake = Tools.Faker.Mock(); - fake.Setup(method.Name, args, Behavior.None()); - fake.Verify(Times.Never, method.Name, args); - - method.Invoke(fake.Dummy, []); - fake.Verify(Times.Once, method.Name, args); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/Fake[T]Tests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/Fake[T]Tests.cs deleted file mode 100644 index ec72bbc1..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/Fake[T]Tests.cs +++ /dev/null @@ -1,229 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.ValuerTool; -using CreateAndFakeTests.TestSamples; -using CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class Fake_T_Tests -{ - [Fact] - internal static void Fake_GuardsNulls() - { - ((IFaked)null).Assert(v => new Fake(v)).Throws(); - ((Fake)null).Assert(v => new Fake(v)).Throws(); - } - - [Fact] - internal static void Setup_GuardsNulls() - { - Tools.Faker.Stub() - .Assert(s => s.Setup(null, Behavior.None())) - .Throws(); - } - - [Fact] - internal static void Fake_InterfacesWork() - { - FakeTester(); - } - - [Fact] - internal static void Fake_ClassesWork() - { - FakeTester(); - FakeTester(); - } - - [Theory, RandomData] - internal static void Fake_ScopeBehavior(string name) - { - Fake fake = Tools.Faker.Mock(); - fake.Dummy.Assert(d => d.PublicProp).Throws(); - fake.Dummy.Assert(d => d.PublicProp = name).Throws(); - fake.Dummy.Assert(d => d.PublicMethod()).Throws(); - - fake.Dummy.Assert(d => d.CallProtectProp()).Throws(); - fake.Dummy.Assert(d => d.SetProtectProp(name)).Throws(); - fake.Dummy.Assert(d => d.CallProtectGet()).Throws(); - fake.Dummy.Assert(d => d.SetProtectSet(name)).Throws(); - fake.Dummy.Assert(d => d.CallProtectMethod()).Throws(); - - fake.Dummy.Assert(d => d.ProIntProp).Throws(); - fake.Dummy.Assert(d => d.ProIntProp = name).Throws(); - fake.Dummy.Assert(d => d.ProIntGet).Throws(); - fake.Dummy.Assert(d => d.ProIntSet = name).Throws(); - fake.Dummy.Assert(d => d.ProIntMethod()).Throws(); - - fake.Dummy.InternalProp = name; - fake.Dummy.InternalProp.Assert().Is(name); - fake.Dummy.InternalMethod().Assert().IsNot(null); - - fake.Dummy.Assert(d => d.InternalGet = name).Throws(); - fake.Dummy.InternalGet.Assert().Is(null); - fake.Dummy.InternalSet = name; - fake.Dummy.Assert(d => d.InternalSet).Throws(); - } - - [Theory, RandomData] - internal static void Fake_HandlesOut(string data) - { - Fake fake = Tools.Faker.Mock(); - fake.Setup( - d => d.ReturnVoid(out Arg.AnyRef().Var), - Behavior.Set((OutRef d) => { d.Var = data; }, Times.Once)); - - fake.Dummy.ReturnVoid(out string value); - - value.Assert().Is(data); - fake.VerifyAll(Times.Once); - } - - [Theory, RandomData] - internal static void Fake_HandlesOutValue(int plain, int data) - { - Fake fake = Tools.Faker.Mock(); - fake.Setup( - d => d.ReturnValue(out Arg.AnyRef().Var), - Behavior.Set((OutRef d) => - { - d.Var = data; - return plain; - }, Times.Once)); - - fake.Dummy.ReturnValue(out int value).Assert().Is(plain); - - value.Assert().Is(data); - fake.VerifyAll(Times.Once); - } - - [Theory, RandomData] - internal static void Fake_HandlesRef(string data, string start) - { - Fake fake = Tools.Faker.Mock(); - fake.Setup( - d => d.ReturnVoid(ref Arg.WhereRef(v => v == start).Var), - Behavior.Set((OutRef d) => { d.Var = data; }, Times.Once)); - - string value = start; - fake.Dummy.ReturnVoid(ref value); - - value.Assert().Is(data); - fake.VerifyAll(Times.Once); - } - - [Theory, RandomData] - internal static void Fake_GenericsWork(string text, DataSample sample) - { - Fake> fake = Tools.Faker.Mock>(); - - fake.Setup( - m => m.Run(text, sample), - Behavior.Returns(true, Times.Once)); - fake.Setup( - m => m.Run(text, sample), - Behavior.Returns(5, Times.Once)); - - fake.Dummy.Run(text, sample).Assert().Is(true); - fake.Dummy.Run(text, sample).Assert().Is(5); - - fake.VerifyAll(Times.Exactly(2)); - fake.Dummy.Assert(d => d.Run(text, sample)).Throws(); - } - - [Fact] - internal static void Setup_InvalidExpressionThrows() - { - Tools.Faker.Mock() - .Assert(f => f.Setup(d => new object(), Behavior.Returns(new object()))) - .Throws(); - } - - [Theory, RandomData] - internal static void ConvertArg_ConvertExpression([Stub] IValuer valuer, string[] data) - { - valuer.ToFake().Setup( - m => m.Equals(true, true), - Behavior.Returns(true)); - valuer.ToFake().Setup( - m => m.Compare(true, Arg.Any()), - Behavior.Set((object o1, object o2) => - { - return (!o1.Equals(o2)) - ? Tools.Randomizer.Create>() - : []; - })); - - Asserter tester = new(Tools.Gen, valuer); - tester.IsNotEmpty(data); - tester.Assert(t => t.IsNotEmpty(null)).Throws(); - tester.Assert(t => t.IsNotEmpty(Array.Empty())).Throws(); - } - - private static void FakeTester() where T : IFakeSample - { - Fake fake = Tools.Faker.Mock(typeof(IClashingFakeSample)); - - Behavior hintBehavior = Behavior.Returns("Hint"); - fake.Setup(m => m.Hint, hintBehavior); - fake.Verify(Times.Never, m => m.Hint); - fake.Dummy.Hint.Assert().Is("Hint"); - fake.Verify(Times.Once, m => m.Hint); - fake.Dummy.Hint.Assert().Is("Hint"); - fake.Verify(Times.Exactly(2), m => m.Hint); - - Fake fake2 = fake.ToFake(); - fake2.SetupSet(m => m.Text, Arg.LambdaAny(), Behavior.None()); - fake2.VerifySet(Times.Never, m => m.Text, Arg.LambdaAny()); - fake2.Dummy.Text = "What"; - fake2.VerifySet(Times.Once, m => m.Text, Arg.LambdaAny()); - - fake2.SetupSet(m => m.Text, "Hinter", Behavior.Set((string input) => { })); - fake2.VerifySet(Times.Never, m => m.Text, "Hinter"); - fake2.Dummy.Text = "Hinter"; - fake2.VerifySet(Times.Once, m => m.Text, "Hinter"); - fake2.VerifySet(Times.Exactly(2), m => m.Text, Arg.LambdaAny()); - - fake.Setup(m => m.Read(), Behavior.Set(() => "Test")); - fake.Verify(Times.Never, m => m.Read()); - fake.Dummy.Read().Assert().Is("Test"); - fake.Verify(Times.Once, m => m.Read()); - - fake.Setup(m => m.Calc(), Behavior.Returns(5)); - fake.Verify(Times.Never, m => m.Calc()); - fake.Dummy.Calc().Assert().Is(5); - fake.Verify(Times.Once, m => m.Calc()); - - fake.Setup(m => m.Read("Hey"), Behavior.Returns("Test2")); - fake.Verify(Times.Never, m => m.Read("Hey")); - fake.Dummy.Read("Hey").Assert().Is("Test2"); - fake.Verify(Times.Once, m => m.Read("Hey")); - - fake.Setup(m => m.Calc(3), Behavior.Returns(4)); - fake.Dummy.Calc(3).Assert().Is(4); - - fake.Dummy.Read().Assert().Is("Test"); - fake.Dummy.Calc().Assert().Is(5); - fake.Dummy.Read("Hey").Assert().Is("Test2"); - - fake.Setup(m => m.Calc(Arg.Where(i => i > 8)), Behavior.Returns(1)); - fake.Verify(Times.Never, m => m.Calc(Arg.Where(i => i > 8))); - fake.Dummy.Calc(9); - fake.Verify(Times.Once, m => m.Calc(Arg.Where(i => i > 8))); - - fake.Setup(m => m.Calc(Arg.Any()), Behavior.Returns(7)); - fake.Dummy.Calc(0).Assert().Is(7); - - fake.Setup(m => m.Read(Arg.Any()), Behavior.Returns("Wow!")); - fake.Dummy.Read("Okay?").Assert().Is("Wow!"); - - fake.Setup(m => m.Combo(2, "Finally"), Behavior.Set((int num, string text) => { })); - fake.Verify(Times.Never, m => m.Combo(2, "Finally")); - fake.Dummy.Combo(2, "Finally"); - fake.Verify(Times.Once, m => m.Combo(2, "Finally")); - - hintBehavior.Calls.Assert().Is(2); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/FakerTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/FakerTests.cs deleted file mode 100644 index 88a745f1..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/FakerTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFakeTests.TestSamples; -using CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class FakerTests -{ - [Fact] - internal static void Faker_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void Faker_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Fact] - internal static void New_NullValuerValid() - { - new Faker(null).Assert().Pass(); - } - - [Fact] - internal static void Mock_SampleWorks() - { - Fake sample = Tools.Faker.Mock(); - sample.ThrowByDefault.Assert().Is(true); - sample.Dummy.Assert(d => d.HasNested(sample.Dummy.NestedValue)).Throws(); - } - - [Fact] - internal static void Stub_SampleWorks() - { - Fake sample = Tools.Faker.Stub(); - sample.ThrowByDefault.Assert().Is(false); - sample.Dummy.HasNested(null).Assert().Is(false); - } - - [Fact] - internal static void Supports_InvalidTypesFalse() - { - Tools.Faker.Supports().Assert().Is(false); - Tools.Faker.Supports().Assert().Is(false); - Tools.Faker.Supports().Assert().Is(false); - Tools.Faker.Supports(typeof(void*)).Assert().Is(false); - Tools.Faker.Supports(typeof(ConstraintSample<,>)).Assert().Is(false); - } - - [Fact] - internal static void Inject_HandlesValues() - { - Injected sample = Tools.Faker.InjectMocks(); - sample.Dummy.Value1.Assert().Is(0); - sample.Dummy.Value2.Assert().Is(null); - } - - [Fact] - internal static void Inject_ConstructorRequired() - { - Tools.Faker.Assert(f => f.InjectStubs()).Throws(); - } - - [Theory, RandomData] - internal static void Inject_UsesValues(int num, string text) - { - Injected sample = Tools.Faker.InjectMocks( - null, Tools.Faker.Stub(), num, text); - - sample.Dummy.Sample1.Text.Assert().Is(null); - sample.Dummy.Sample2.Assert(s => s.Calc()).Throws(); - sample.Dummy.Value1.Assert().Is(num); - sample.Dummy.Value2.Assert().Is(text); - } - - [Fact] - internal static void InjectMocks_AreMocks() - { - Injected sample = Tools.Faker.InjectMocks(); - - sample.Dummy.Sample1.Assert(s => s.Calc()).Throws(); - sample.Dummy.Sample2.Assert(s => s.Text).Throws(); - } - - [Fact] - internal static void InjectStubs_AreStubs() - { - Injected sample = Tools.Faker.InjectStubs(); - - sample.Dummy.Sample1.Calc().Assert().Is(0); - sample.Dummy.Sample2.Text.Assert().Is(null); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/InjectedTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/InjectedTests.cs deleted file mode 100644 index d5eb61c5..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/InjectedTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFakeTests.TestSamples; -using CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class InjectedTests -{ - [Theory, RandomData] - internal static void Injected_GuardsNulls(Injected sample) - { - Tools.Tester.PreventsNullRefException(sample, sample.Fakes); - } - - [Theory, RandomData] - internal static void Injected_NoParameterMutation(Injected sample) - { - Tools.Tester.PreventsParameterMutation(sample, sample.Fakes); - } - - [Theory, RandomData] - internal static void Fake_CanFindByDummy(Injected sample) - { - sample.Fake(sample.Dummy.Sample1).Assert().Is(sample.Fake()); - sample.Fake(sample.Dummy.Sample2).Assert().Is(sample.Fake()); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/CallDataTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/CallDataTests.cs deleted file mode 100644 index db620de7..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/CallDataTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.FakerTool.Proxy; - -public static class CallDataTests -{ - [Fact] - internal static void CallData_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void CallData_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void MatchesCall_MethodNameMismatch(DataHolderSample[] data, Type[] generics, string name) - { - new CallData(name, generics, data, Tools.Valuer) - .MatchesCall(new CallData(name.CreateVariant(), generics, data, null)) - .Assert().Is(false); - } - - [Theory, RandomData] - internal static void MatchesCall_GenericsMismatch(DataHolderSample[] data, string name) - { - Type[] generics1 = Tools.Randomizer.Create().Except([typeof(AnyGeneric)]).ToArray(); - Type[] generics2 = Tools.Mutator.Variant(generics1); - - new CallData(name, generics1, data, Tools.Valuer) - .MatchesCall(new CallData(name, generics2, data, null)) - .Assert().Is(false); - } - - [Theory, RandomData] - internal static void MatchesCall_AnyGenericMatchesAll(DataHolderSample[] data, string name, Type[] generics1) - { - Type[] generics2 = generics1.Select(t => typeof(AnyGeneric)).ToArray(); - - new CallData(name, generics2, data, Tools.Valuer) - .MatchesCall(new CallData(name, generics1, data, null)) - .Assert().Is(true); - } - - [Theory, RandomData] - internal static void MatchesCall_DataMatchBehavior(string name, Type[] generics, DataHolderSample[] data1) - { - DataHolderSample[] data2 = data1.Select(d => d.CreateDeepClone()).ToArray(); - - new CallData(name, generics, data1, Tools.Valuer) - .MatchesCall(new CallData(name, generics, data2, null)) - .Assert().Is(true); - - new CallData(name, generics, data1, null) - .MatchesCall(new CallData(name, generics, data2, null)) - .Assert().Is(false); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeCallExceptionTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeCallExceptionTests.cs deleted file mode 100644 index 4b0ef044..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeCallExceptionTests.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.FakerTool.Proxy; - -public sealed class FakeCallExceptionTests : ExceptionTestBase -{ - [Fact] - internal static void FakeCallException_MultiNullsOkay() - { - new FakeCallException(null, null).Assert().IsNot(null); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeMetaProviderTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeMetaProviderTests.cs deleted file mode 100644 index 2a54aa06..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeMetaProviderTests.cs +++ /dev/null @@ -1,111 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; - -namespace CreateAndFakeTests.Toolbox.FakerTool.Proxy; - -public static class FakeMetaProviderTests -{ - [Fact] - internal static void FakeMetaProvider_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void FakeMetaProvider_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void Verify_PresetOutOfRangeThrows(string name) - { - FakeMetaProvider provider = new() - { - ThrowByDefault = false - }; - - CallData data = new(name, Type.EmptyTypes, [], Tools.Valuer); - - provider.SetCallBehavior(data, Behavior.None(Times.Once)); - provider.Assert(p => p.Verify()).Throws(); - - provider.CallVoid(null, Tools.Mutator.Variant(name), Type.EmptyTypes, []); - provider.Assert(p => p.Verify()).Throws(); - - provider.CallVoid(null, name, Type.EmptyTypes, []); - provider.Verify(); - - provider.CallVoid(null, name, Type.EmptyTypes, []); - provider.Assert(p => p.Verify()).Throws(); - } - - [Theory, RandomData] - internal static void Verify_CustomOutOfRangeThrows(string name) - { - FakeMetaProvider provider = new() - { - ThrowByDefault = false - }; - - CallData data = new(name, Type.EmptyTypes, [], Tools.Valuer); - - provider.Verify(0, data); - provider.Assert(p => p.Verify(1, data)).Throws(); - - provider.CallVoid(null, name.CreateVariant(), Type.EmptyTypes, []); - provider.Verify(0, data); - provider.Assert(p => p.Verify(1, data)).Throws(); - - provider.CallVoid(null, name, Type.EmptyTypes, []); - provider.Assert(p => p.Verify(0, data)).Throws(); - provider.Verify(1, data); - - provider.CallVoid(null, name, Type.EmptyTypes, []); - provider.Assert(p => p.Verify(1, data)).Throws(); - provider.Verify(2, data); - } - - [Theory, RandomData] - internal static void VerifyTotalCalls_OutOfRangeThrows(string name) - { - FakeMetaProvider provider = new() - { - ThrowByDefault = false - }; - - provider.VerifyTotalCalls(0); - provider.Assert(p => p.VerifyTotalCalls(1)).Throws(); - - provider.CallVoid(null, name, Type.EmptyTypes, []); - provider.Assert(p => p.VerifyTotalCalls(0)).Throws(); - provider.VerifyTotalCalls(1); - - provider.CallVoid(null, name.CreateVariant(), Type.EmptyTypes, []); - provider.Assert(p => p.VerifyTotalCalls(1)).Throws(); - provider.VerifyTotalCalls(2); - } - - [Theory, RandomData] - internal static void CallVoid_ReturnValueThrows(string name) - { - FakeMetaProvider provider = new(); - - CallData data = new(name, Type.EmptyTypes, [], Tools.Valuer); - provider.SetCallBehavior(data, Behavior.Returns("")); - - provider.Assert(p => p.CallVoid(null, name, Type.EmptyTypes, [])).Throws(); - } - - [Theory, RandomData] - internal static void SetLastCallBehavior_RequiresPreviousCall(Behavior behavior) - { - behavior - .Assert(b => - { - FakeMetaProvider.SetLastCallBehavior(b); - FakeMetaProvider.SetLastCallBehavior(b); - }) - .Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeVerifyExceptionTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeVerifyExceptionTests.cs deleted file mode 100644 index 71b22cf5..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/FakeVerifyExceptionTests.cs +++ /dev/null @@ -1,6 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.FakerTool.Proxy; - -public sealed class FakeVerifyExceptionTests : ExceptionTestBase { } diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/SubclasserTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/SubclasserTests.cs deleted file mode 100644 index cc91fc49..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/Proxy/SubclasserTests.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFakeTests.TestSamples; -using CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.FakerTool.Proxy; - -public static class SubclasserTests -{ - [Fact] - internal static void Subclasser_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(typeof(Subclasser)); - } - - [Fact] - internal static void Subclasser_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(typeof(Subclasser)); - } - - [Fact] - internal static void Create_InterfacesWork() - { - Subclasser.Create().Assert().IsNot(null); - Subclasser.Create(typeof(IClashingFakeSample)).Assert().IsNot(null); - } - - [Fact] - internal static void Create_ClassesWork() - { - Subclasser.Create().Assert().IsNot(null); - Subclasser.Create().Assert().IsNot(null); - } - - [Fact] - internal static void Create_BothWork() - { - Subclasser.Create(typeof(IFakeSample)).Assert().IsNot(null); - Subclasser.Create(typeof(IFakeSample), typeof(IClashingFakeSample)).Assert().IsNot(null); - } - - [Fact] - internal static void Create_IFakedDefault() - { - Subclasser.Create().GetType().Assert().Inherits(); - Subclasser.Create(null, null).Assert().IsNot(null); - } - - [Fact] - internal static void Create_IFakedFunctional() - { - Subclasser.Create().FakeMeta.Assert().IsNot(null); - } - - [Fact] - internal static void Create_OnlyMultipleInterfaces() - { - typeof(object).Assert(t => Subclasser.Create(t)).Throws(); - } - - [Fact] - internal static void Create_SealedTypesThrow() - { - typeof(string).Assert(t => Subclasser.Create(t)).Throws(); - } - - [Fact] - internal static void CreateInfo_NoDuplicatesCreated() - { - Subclasser.CreateInfo(typeof(IFakeSample), typeof(IClashingFakeSample)).Assert().ReferenceEqual( - Subclasser.CreateInfo(typeof(IClashingFakeSample), typeof(IFakeSample))); - } - - [Fact] - internal static void CreateInfo_IgnoreDupeInterfaces() - { - Subclasser.CreateInfo(typeof(IFakeSample)).Assert().ReferenceEqual( - Subclasser.CreateInfo(typeof(IFakeSample), typeof(IFakeSample))); - } - - [Fact] - internal static void Create_DefinedGenericsWork() - { - Subclasser.Create>().Assert().IsNot(null); - Subclasser.Create>().Assert().IsNot(null); - } - - [Fact] - internal static void Create_UndefinedGenericsThrow() - { - typeof(ConstraintSample<,>).Assert(t => Subclasser.Create(t)).Throws(); - } - - [Fact] - internal static void Create_PointersThrow() - { - typeof(void*).Assert(t => Subclasser.Create(t)).Throws(); - } - - [Fact] - internal static void Create_InternalTypesThrow() - { - typeof(InternalSample).Assert(t => Subclasser.Create(t)).Throws(); - } - - [Fact] - internal static void Supports_FalseWithWithNonVisibleTypes() - { - TypeAttributes invisibleAttributes - = TypeAttributes.NotPublic - | TypeAttributes.Class; - - Type type = Tools.Faker.Stub().Dummy; - - type.ToFake().Setup("GetAttributeFlagsImpl", [], Behavior.Returns(invisibleAttributes)); - type.ToFake().Setup("HasElementTypeImpl", [], Behavior.Returns(false)); - type.ToFake().Setup("IsPointerImpl", [], Behavior.Returns(false)); - type.Assembly.SetupReturn(typeof(object).Assembly); - type.Name.SetupReturn("TestInvisibleType"); - - type.Assert(t => Subclasser.Create(t)) - .Throws().Message - .Assert().Contains("InternalsVisibleTo"); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/FakeHolderSample.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/FakeHolderSample.cs deleted file mode 100644 index 7a2f7701..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/FakeHolderSample.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -public sealed class FakeHolderSample(IFakeSample sample1, AbstractFakeSample sample2, int value1, string value2) -{ - public IFakeSample Sample1 { get; } = sample1; - - public AbstractFakeSample Sample2 { get; } = sample2; - - public int Value1 { get; } = value1; - - public string Value2 { get; } = value2; -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/TimesTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/TimesTests.cs deleted file mode 100644 index 8c7ac05a..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/TimesTests.cs +++ /dev/null @@ -1,116 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class TimesTests -{ - [Fact] - internal static void Times_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void Times_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Fact] - internal static void Never_Works() - { - Times.Never.IsInRange(0).Assert().Is(true); - Times.Never.IsInRange(1).Assert().Is(false); - Times.Never.IsInRange(2).Assert().Is(false); - } - - [Fact] - internal static void Once_Works() - { - Times.Once.IsInRange(0).Assert().Is(false); - Times.Once.IsInRange(1).Assert().Is(true); - Times.Once.IsInRange(2).Assert().Is(false); - } - - [Theory, RandomData] - internal static void Exactly_Works(int value) - { - Times.Exactly(value).IsInRange(value - 1).Assert().Is(false); - Times.Exactly(value).IsInRange(value).Assert().Is(true); - Times.Exactly(value).IsInRange(value + 1).Assert().Is(false); - } - - [Fact] - internal static void Between_Works() - { - int min, max; - do - { - min = Tools.Randomizer.Create(); - max = Tools.Randomizer.Create(); - } while (min >= max); - - Times.Between(min, max).IsInRange(min - 1).Assert().Is(false); - Times.Between(min, max).IsInRange(min).Assert().Is(true); - Times.Between(min, max).IsInRange(min + 1).Assert().Is(true); - - Times.Between(min, max).IsInRange(max - 1).Assert().Is(true); - Times.Between(min, max).IsInRange(max).Assert().Is(true); - Times.Between(min, max).IsInRange(max + 1).Assert().Is(false); - } - - [Theory, RandomData] - internal static void Min_Works(int value) - { - Times.Min(value).IsInRange(value - 1).Assert().Is(false); - Times.Min(value).IsInRange(value).Assert().Is(true); - Times.Min(value).IsInRange(value + 1).Assert().Is(true); - } - - [Fact] - internal static void Max_Works() - { - int value; - do - { - value = Tools.Randomizer.Create(); - } while (value <= 0); - - Times.Max(value).IsInRange(value - 1).Assert().Is(true); - Times.Max(value).IsInRange(value).Assert().Is(true); - Times.Max(value).IsInRange(value + 1).Assert().Is(false); - } - - [Fact] - internal static void ToString_Terse() - { - Times.Never.ToString().Assert().Is("0"); - Times.Once.ToString().Assert().Is("1"); - Times.Exactly(2).ToString().Assert().Is("2"); - Times.Max(1).ToString().Assert().Is("[0-1]"); - Times.Min(1).ToString().Assert().Is("[1-*]"); - Times.Between(1, 2).ToString().Assert().Is("[1-2]"); - } - - [Fact] - internal static void Equality_MatchesValue() - { - int min, max; - do - { - min = Tools.Randomizer.Create(); - max = Tools.Randomizer.Create(); - } while (min >= max); - - Times.Once.Equals(null).Assert().Is(false); - Times.Exactly(min).Equals(Times.Between(min, min)).Assert().Is(true); - Times.Exactly(max).Equals((object)Times.Between(max, max)).Assert().Is(true); - Times.Exactly(min).Equals(Times.Between(min, max)).Assert().Is(false); - Times.Exactly(max).Equals((object)Times.Between(min, max)).Assert().Is(false); - - Times.Between(min, min).GetHashCode().Assert().Is(Times.Exactly(min).GetHashCode()); - Times.Between(max, max).GetHashCode().Assert().Is(Times.Exactly(max).GetHashCode()); - Times.Between(min, max).GetHashCode().Assert().IsNot(Times.Exactly(min).GetHashCode()); - Times.Between(min, max).GetHashCode().Assert().IsNot(Times.Exactly(max).GetHashCode()); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/VoidTypeTests.cs b/tests/CreateAndFakeTests/Toolbox/FakerTool/VoidTypeTests.cs deleted file mode 100644 index be0ecc5f..00000000 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/VoidTypeTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class VoidTypeTests -{ - [Fact] - internal static void VoidType_PrivateConstructor() - { - ConstructorInfo constructor = typeof(VoidType).GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Single(); - - constructor.IsPrivate.Assert().Is(true); - constructor.Invoke([]).Assert().Pass(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/MutatorTool/ContentMapTests.cs b/tests/CreateAndFakeTests/Toolbox/MutatorTool/ContentMapTests.cs deleted file mode 100644 index 05a64e81..00000000 --- a/tests/CreateAndFakeTests/Toolbox/MutatorTool/ContentMapTests.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.MutatorTool; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.MutatorTool; - -public static class ContentMapTests -{ - [Fact] - internal static void ContentMap_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void ContentMap_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Theory, RandomData] - internal static void HasContent_UsesObjectByValue(DataHolderSample sample) - { - ContentMap map = ContentMap.Extract(sample); - map.HasContent(Tools.Valuer, sample.NestedValue.CreateVariant()).Assert().Is(false); - map.HasContent(Tools.Valuer, sample.NestedValue.CreateDeepClone()).Assert().Is(true); - } - - [Theory, RandomData] - internal static void HasContent_UsesValueByValue(DataHolderSample sample) - { - ContentMap map = ContentMap.Extract(sample); - map.HasContent(Tools.Valuer, sample.NestedValue.NumberValue.CreateVariant()).Assert().Is(false); - map.HasContent(Tools.Valuer, sample.NestedValue.NumberValue.CreateDeepClone()).Assert().Is(true); - } - - [Theory, RandomData] - internal static void HasContent_UsesStringByValue(DataHolderSample sample) - { - ContentMap map = ContentMap.Extract(sample); - map.HasContent(Tools.Valuer, sample.NestedValue.StringValue.CreateVariant()).Assert().Is(false); - map.HasContent(Tools.Valuer, sample.NestedValue.StringValue.CreateDeepClone()).Assert().Is(true); - } - - [Theory, RandomData] - internal static void FindAll_ContainsNestedObjects(DataHolderSample sample) - { - ContentMap map = ContentMap.Extract(sample); - map.FindAll().Assert().Contains(sample.NestedValue); - map.FindAll(typeof(DataSample)).Assert().Contains(sample.NestedValue); - } - - [Theory, RandomData] - internal static void FindAll_ContainsNestedValues(DataHolderSample sample) - { - ContentMap map = ContentMap.Extract(sample); - map.FindAll().Assert().Contains(sample.NestedValue.NumberValue); - map.FindAll(typeof(int)).Assert().Contains(sample.NestedValue.NumberValue); - } - - [Theory, RandomData] - internal static void AllContent_ContainsEverything(DataHolderSample sample) - { - ContentMap map = ContentMap.Extract(sample); - map.AllContent().Assert().Contains(sample.NestedValue); - map.AllContent().Assert().Contains(sample.NestedValue.NumberValue); - } - - [Theory, RandomData] - internal static void FindSharedContent_ObjectValuesFound(DataHolderSample sample) - { - ContentMap map = ContentMap.Extract(sample); - ContentMap test = ContentMap.Extract(sample.NestedValue); - map.FindSharedContent(Tools.Valuer, test).Assert().Contains(sample.NestedValue); - map.HasSharedContent(Tools.Valuer, test).Assert().Is(true); - } - - [Theory, RandomData] - internal static void FindSharedContent_ValueValuesFound(DataHolderSample sample) - { - ContentMap map = ContentMap.Extract(sample); - ContentMap test = ContentMap.Extract(sample.NestedValue.NumberValue); - map.FindSharedContent(Tools.Valuer, test).Assert().Contains(sample.NestedValue.NumberValue); - map.HasSharedContent(Tools.Valuer, test).Assert().Is(true); - } - - [Theory, RandomData] - internal static void HasSharedContent_FalseWithNothingShared(string sample) - { - ContentMap map = ContentMap.Extract(sample); - ContentMap test = ContentMap.Extract(sample.CreateVariant()); - map.HasSharedContent(Tools.Valuer, test).Assert().Is(false); - } - - [Fact] - internal static void ExtractData_CollectionsWork() - { - foreach (Type type in CollectionCreateHint.PotentialCollections) - { - ContentMap.Extract(Tools.Randomizer.Create(type)).AllContent().Assert().IsNotEmpty(); - } - } - - [Fact] - internal static void ExtractData_LegacyCollectionsWork() - { - foreach (Type type in LegacyCollectionCreateHint.PotentialCollections) - { - ContentMap.Extract(Tools.Randomizer.Create(type)).AllContent().Assert().IsNotEmpty(); - } - } - - [Theory, RandomData] - internal static void HasSharedContent_IgnoresSimpleTypes(char sample1, bool sample2, BindingFlags sample3) - { - ContentMap - .Extract(sample1) - .HasSharedContent(Tools.Valuer, ContentMap.Extract(sample1.CreateDeepClone())) - .Assert() - .Is(false); - - ContentMap - .Extract(sample2) - .HasSharedContent(Tools.Valuer, ContentMap.Extract(sample2.CreateDeepClone())) - .Assert() - .Is(false); - - ContentMap - .Extract(sample3) - .HasSharedContent(Tools.Valuer, ContentMap.Extract(sample3.CreateDeepClone())) - .Assert() - .Is(false); - } - - [Theory, RandomData] - internal static void FindSharedContent_EmptyCollectionsIgnored([Size(0)] object[] sample) - { - ContentMap - .Extract(sample) - .FindSharedContent(Tools.Valuer, ContentMap.Extract(Array.Empty())) - .Assert() - .IsEmpty(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/MutatorTool/MutatorTests.cs b/tests/CreateAndFakeTests/Toolbox/MutatorTool/MutatorTests.cs deleted file mode 100644 index 0156dbdc..00000000 --- a/tests/CreateAndFakeTests/Toolbox/MutatorTool/MutatorTests.cs +++ /dev/null @@ -1,143 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.MutatorTool; -using CreateAndFake.Toolbox.ValuerTool; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.MutatorTool; - -public static class MutatorTests -{ - [Fact] - internal static void Mutator_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(Tools.Randomizer, Tools.Valuer, Limiter.Dozen); - } - - [Fact] - internal static void Mutator_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(Tools.Mutator); - } - - [Theory, RandomData] - internal static void Variant_AcceptsNull(string value) - { - Tools.Mutator.Variant(null).Assert().IsNot(null); - Tools.Mutator.Variant(value, null).Assert().IsNot(value).And.IsNot(null); - } - - [Theory, RandomData] - internal static void Variant_ManyValuesWorks(int value, [Size(10000)] int[] data) - { - int result = Tools.Mutator.Variant(value, data); - result.Assert().IsNot(value).Also(data).ContainsNot(result); - } - - [Theory, RandomData] - internal static void Variant_TimesOut([Fake] IValuer fakeValuer, DataSample sample) - { - fakeValuer.Equals(Arg.Any(), Arg.Any()).SetupReturn(true); - - new Mutator(Tools.Randomizer, fakeValuer, new Limiter(3)) - .Assert(t => t.Variant(sample)) - .Throws(); - - fakeValuer.VerifyAllCalls(Times.Exactly(3)); - } - - [Theory, RandomData] - internal static void Variant_RepeatsUntilUnequal([Fake] IValuer fakeValuer, DataSample sample) - { - fakeValuer.Equals(Arg.Any(), Arg.Any()).SetupCall(Behavior.Series(true, true, true, false)); - - new Mutator(Tools.Randomizer, fakeValuer, new Limiter(5)) - .Variant(sample) - .Assert() - .IsNot(null); - - fakeValuer.VerifyAllCalls(Times.Exactly(4)); - } - - [Theory, RandomData] - internal static void Variant_RepeatsUntilBothUnequal( - [Fake] IValuer fakeValuer, DataSample sample1, DataSample sample2) - { - fakeValuer.Equals(Arg.Any(), Arg.Any()).SetupCall( - Behavior.Series(false, true, true, false, true, true, false, false)); - - new Mutator(Tools.Randomizer, fakeValuer, new Limiter(5)) - .Variant(sample1, sample2) - .Assert() - .IsNot(null); - - fakeValuer.VerifyAllCalls(8); - } - - [Theory, RandomData] - internal static void Unique_AcceptsNull(string value) - { - Tools.Mutator.Unique(null).Assert().IsNot(null); - Tools.Mutator.Unique(value, null).Assert().IsNot(value).And.IsNot(null); - } - - [Theory, RandomData] - internal static void Unique_ManyValuesWorks(int value, [Size(10000)] int[] data) - { - int result = Tools.Mutator.Unique(value, data); - result.Assert().IsNot(value).Also(data).ContainsNot(result); - } - - [Theory, RandomData] - internal static void Unique_TimesOut([Fake] IValuer fakeValuer, DataSample sample) - { - fakeValuer.Equals(Arg.Any(), Arg.Any()).SetupReturn(true); - fakeValuer.GetHashCode(Arg.Any()).SetupReturn(0); - - new Mutator(Tools.Randomizer, fakeValuer, new Limiter(3)) - .Assert(t => t.Unique(sample)) - .Throws(); - } - - [Theory, RandomData] - internal static void Unique_RepeatsUntilUnequal([Fake] IValuer fakeValuer, string sample) - { - fakeValuer.Equals(Arg.Any(), Arg.Any()).SetupCall(Behavior.Series(true, true, true, false)); - fakeValuer.GetHashCode(Arg.Any()).SetupReturn(0); - - new Mutator(Tools.Randomizer, fakeValuer, new Limiter(5)) - .Unique(sample) - .Assert() - .IsNot(null); - } - - [Theory, RandomData] - internal static void Unique_RepeatsUntilBothUnequal( - [Fake] IValuer fakeValuer, string sample1, string sample2) - { - fakeValuer.Equals(Arg.Any(), Arg.Any()).SetupCall( - Behavior.Series(false, true, true, false, true, true, false, false)); - fakeValuer.GetHashCode(Arg.Any()).SetupReturn(0); - - new Mutator(Tools.Randomizer, fakeValuer, new Limiter(5)) - .Unique(sample1, sample2) - .Assert() - .IsNot(null); - } - - [Theory, RandomData] - internal static void Modify_DataChanged(DataHolderSample data) - { - DataHolderSample dupe = data.CreateDeepClone(); - - Tools.Mutator.Modify(data).Assert().Is(true); - - data.Assert().IsNot(dupe); - } - - [Theory, RandomData] - internal static void Modify_StatelessUnchanged(StatelessSample data) - { - Tools.Mutator.Modify(data).Assert().Is(false); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/AsyncCollectionCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/AsyncCollectionCreateHintTests.cs deleted file mode 100644 index c90ebeb6..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/AsyncCollectionCreateHintTests.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class AsyncCollectionCreateHintTests : CreateHintTestBase -{ - private static readonly AsyncCollectionCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(IAsyncEnumerable), - typeof(IAsyncEnumerable), - typeof(IAsyncEnumerable) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(object), - typeof(IEnumerable) - ]; - - public AsyncCollectionCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal static async Task GetItems_Empty([Size(0)] IAsyncEnumerable items) - { - IAsyncEnumerator gen = items.GetAsyncEnumerator(); - await using (gen.ConfigureAwait(true)) - { - (await gen.MoveNextAsync().ConfigureAwait(true)).Assert().Is(false); - } - } - - [Theory, RandomData] - internal static async Task GetItems_Repeatable(IAsyncEnumerable items) - { - List first = []; - await foreach (int item in items) - { - first.Add(item); - } - - List second = []; - await foreach (int item in items) - { - second.Add(item); - } - - first.Assert().Is(second); - } - - [Theory, RandomData] - internal static async Task GetItems_Cancel(IAsyncEnumerable items) - { - await items.GetAsyncEnumerator().DisposeAsync().ConfigureAwait(true); - } - - [Theory, RandomData] - internal static async Task GetItems_Interrupt([Size(5)] IAsyncEnumerable items) - { - await items.GetAsyncEnumerator().DisposeAsync().ConfigureAwait(true); - - int count = 0; - await foreach (int item in items) - { - count++; - if (count == 3) - { - break; - } - } - - count = 0; - await foreach (int item in items) - { - count++; - } - count.Assert().Is(5); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/CollectionCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/CollectionCreateHintTests.cs deleted file mode 100644 index 2b9a9055..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/CollectionCreateHintTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Collections; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class CollectionCreateHintTests : CreateHintTestBase -{ - private static readonly CollectionCreateHint _TestInstance = new(); - - private static readonly Type[] _ItemTypes = - [ - typeof(string), - typeof(object), - typeof(int), - typeof(double), - typeof(KeyValuePair) - ]; - - private static readonly Type[] _ValidTypes = CollectionCreateHint.PotentialCollections - .Concat([ - typeof(IEnumerable<>), - typeof(IList<>), - typeof(ISet<>), - typeof(IDictionary<,>), - typeof(IReadOnlyCollection<>), - typeof(IReadOnlyList<>), - typeof(IReadOnlyDictionary<,>), - typeof(int[]), - typeof(string[]), - typeof(object[])]) - .Select(MakeDefined) - .ToArray(); - - private static readonly Type[] _InvalidTypes = - [ - typeof(object), - typeof(IEnumerable), - typeof(IEnumerable<>) - ]; - - public CollectionCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - private static Type MakeDefined(Type type) - { - if (type.IsGenericTypeDefinition) - { - FastRandom random = new(); - return type.MakeGenericType(type.GetGenericArguments().Select( - t => random.NextItem(_ItemTypes)).ToArray()); - } - else - { - return type; - } - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/CommonSystemCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/CommonSystemCreateHintTests.cs deleted file mode 100644 index 3e70f767..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/CommonSystemCreateHintTests.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Globalization; -using System.Reflection; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class CommonSystemCreateHintTests : CreateHintTestBase -{ - private static readonly CommonSystemCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(CultureInfo), - typeof(TimeSpan), - typeof(DateTime), - typeof(Assembly), - typeof(AssemblyName), - typeof(Guid), - typeof(Type), - typeof(Type).GetType(), - typeof(ConstructorInfo), - typeof(PropertyInfo), - typeof(MethodInfo), - typeof(MemberInfo), - typeof(MemberInfo), - typeof(FieldInfo), - typeof(ParameterInfo), - typeof(MethodBase), - typeof(DateTimeOffset), - typeof(Uri), - typeof(UriBuilder) - ]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public CommonSystemCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Fact] - internal static void TryCreate_ContinuesUntilMemberFound() - { - for (int i = 0; i < 50; i++) - { - _ = _TestInstance.TryCreate(typeof(FieldInfo), CreateChainer()); - } - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/DelegateCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/DelegateCreateHintTests.cs deleted file mode 100644 index c11c0db7..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/DelegateCreateHintTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class DelegateCreateHintTests : CreateHintTestBase -{ - private static readonly Type[] _ActionTypes = - [ - typeof(Action), - typeof(Action<>), - typeof(Action<,>), - typeof(Action<,,>), - typeof(Action<,,,>), - typeof(Action<,,,,>), - typeof(Action<,,,,,>), - typeof(Action<,,,,,,>), - typeof(Action<,,,,,,,>), - typeof(Action<,,,,,,,,>), - typeof(Action<,,,,,,,,,>), - typeof(Action<,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,,,,>), - typeof(Action<,,,,,,,,,,,,,,,>) - ]; - - private static readonly Type[] _FuncTypes = - [ - typeof(Func<>), - typeof(Func<,>), - typeof(Func<,,>), - typeof(Func<,,,>), - typeof(Func<,,,,>), - typeof(Func<,,,,,>), - typeof(Func<,,,,,,>), - typeof(Func<,,,,,,,>), - typeof(Func<,,,,,,,,>), - typeof(Func<,,,,,,,,,>), - typeof(Func<,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,,,,>), - typeof(Func<,,,,,,,,,,,,,,,,>) - ]; - - private static readonly DelegateCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(Action), - typeof(Func), - typeof(Delegate), - typeof(Action) - ]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public DelegateCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Fact] - internal static void Create_HandlesAllDelegates() - { - foreach (Type type in _ActionTypes.Concat(_FuncTypes)) - { - _TestInstance.TryCreate(type, CreateChainer()).Item1.Assert().Is(true); - } - } - - [Fact] - internal static void Create_HandlesOutRef() - { - (bool, object) result = _TestInstance.TryCreate(typeof(Action), CreateChainer()); - result.Item1.Assert().Is(true); - - Action action = (Action)result.Item2; - - OutRef sampleInt = new(); - action.Invoke(sampleInt); - sampleInt.Var.Assert().IsNot(default(int)); - - OutRef sampleString = new(); - action.Invoke(sampleString); - sampleString.Var.Assert().IsNot(default(string)); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/EnumCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/EnumCreateHintTests.cs deleted file mode 100644 index 4f4158c4..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/EnumCreateHintTests.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class EnumCreateHintTests : CreateHintTestBase -{ - private static readonly EnumCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(BindingFlags)]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public EnumCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ExceptionCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ExceptionCreateHintTests.cs deleted file mode 100644 index a65eab8c..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ExceptionCreateHintTests.cs +++ /dev/null @@ -1,16 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class ExceptionCreateHintTests : CreateHintTestBase -{ - private static readonly ExceptionCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(Exception)]; - - private static readonly Type[] _InvalidTypes = [typeof(object), typeof(FakeVerifyException)]; - - public ExceptionCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/FakeCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/FakeCreateHintTests.cs deleted file mode 100644 index 27078233..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/FakeCreateHintTests.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class FakeCreateHintTests : CreateHintTestBase -{ - private static readonly FakeCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(Fake), - typeof(Fake), - typeof(Fake>) - ]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public FakeCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/FakedCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/FakedCreateHintTests.cs deleted file mode 100644 index 27a93736..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/FakedCreateHintTests.cs +++ /dev/null @@ -1,16 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class FakedCreateHintTests : CreateHintTestBase -{ - private static readonly FakedCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(IFaked)]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public FakedCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/GenericCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/GenericCreateHintTests.cs deleted file mode 100644 index 7bc0fbe2..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/GenericCreateHintTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class GenericCreateHintTests : CreateHintTestBase -{ - private static readonly GenericCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(IList<>), - typeof(KeyValuePair<,>), - typeof(GenericSample<>), - typeof(ConstraintSample<,>) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(object), - typeof(IList), - typeof(KeyValuePair) - ]; - - public GenericCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/InjectedCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/InjectedCreateHintTests.cs deleted file mode 100644 index b6b09a8a..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/InjectedCreateHintTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; -using CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class InjectedCreateHintTests : CreateHintTestBase -{ - private static readonly InjectedCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(Injected), - typeof(Injected), - typeof(Injected), - typeof(Injected), - typeof(Injected) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(object), - typeof(IUnimplementedSample) - ]; - - public InjectedCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal void Create_ValidInjections(Injected sample) - { - sample.Fake().Assert().IsNot(null); - sample.Fake(1).Assert().IsNot(null).And.IsNot(sample.Fake()); - - sample.Fake().Setup(m => m.FailIfNotMocked(), Behavior.Returns(false, Times.Once)); - sample.Dummy.TestIfMockedSeparately(); - sample.Fake().VerifyAll(Times.Once); - sample.VerifyAll(); - } - - [Fact] - internal void Create_NoConstructorThrows() - { - Tools.Randomizer - .Assert(t => t.Create>()) - .Throws(); - } - - [Theory, RandomData] - internal void Create_ValuesRandom(Injected sample) - { - sample.Dummy.Value1.Assert().IsNot(0); - sample.Dummy.Value2.Assert().IsNot(null); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/LegacyCollectionCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/LegacyCollectionCreateHintTests.cs deleted file mode 100644 index 67c5e280..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/LegacyCollectionCreateHintTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class LegacyCollectionCreateHintTests : CreateHintTestBase -{ - private static readonly LegacyCollectionCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = LegacyCollectionCreateHint.PotentialCollections - .Concat([typeof(IEnumerable), typeof(IList), typeof(IDictionary)]) - .ToArray(); - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public LegacyCollectionCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ObjectCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ObjectCreateHintTests.cs deleted file mode 100644 index 00171dea..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ObjectCreateHintTests.cs +++ /dev/null @@ -1,40 +0,0 @@ -using CreateAndFake.Design; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class ObjectCreateHintTests : CreateHintTestBase -{ - private static readonly ObjectCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(object), - typeof(Arg), - typeof(DataHolderSample), - typeof(IUnimplementedSample), - typeof(FieldSample), - typeof(FactorySample) - ]; - - private static readonly Type[] _InvalidTypes = [typeof(VoidType)]; - - public ObjectCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - public void ObjectCreateHint_CanHandleInfinites(InfiniteSample sample1, ParentLoopSample sample2) - { - sample1.Assert().IsNot(null); - sample2.Assert().IsNot(null); - } - - [Fact] - public async Task Create_RetriesUntilGoodSample() - { - await Limiter.Dozen.Repeat("", - () => typeof(IIsGoodOrBadSample).CreateRandomInstance().Assert().IsNot(null)).ConfigureAwait(true); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/StringCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/StringCreateHintTests.cs deleted file mode 100644 index 4998a594..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/StringCreateHintTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class StringCreateHintTests : CreateHintTestBase -{ - private static readonly StringCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(string)]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public StringCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Fact] - internal static void TryCreate_SizeConstraintsWork() - { - int minSize = 2; - int range = 3; - StringCreateHint hint = new(minSize, range, []); - - for (int i = 0; i < 1000; i++) - { - string result = (string)hint.TryCreate(typeof(string), CreateChainer()).Item2; - - result.Length.Assert().GreaterThanOrEqualTo(minSize, "Result was too small."); - result.Length.Assert().LessThan(minSize + range, "Result was too big."); - } - } - - [Fact] - internal static void TryCreate_UsesCharSet() - { - StringCreateHint hint = new(3, 0, "a"); - object value = "aaa"; - for (int i = 0; i < 100; i++) - { - hint.TryCreate(typeof(string), CreateChainer()).Assert().Is((true, value)); - } - - StringCreateHint hint2 = new(3, 0, "ab"); - for (int i = 0; i < 100; i++) - { - (bool, object) result = hint2.TryCreate(typeof(string), CreateChainer()); - - result.Item1.Assert().Is(true); - ((string)result.Item2).Trim('a', 'b').Length.Assert().Is(0); - } - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/TaskCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/TaskCreateHintTests.cs deleted file mode 100644 index d24c5e7c..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/TaskCreateHintTests.cs +++ /dev/null @@ -1,24 +0,0 @@ -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class TaskCreateHintTests : CreateHintTestBase -{ - private static readonly TaskCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(Task), - typeof(Task), - typeof(Task), - typeof(Task), - typeof(Task), - typeof(Task) - ]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public TaskCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ValueCreateHintTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ValueCreateHintTests.cs deleted file mode 100644 index 475f4b87..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/CreateHints/ValueCreateHintTests.cs +++ /dev/null @@ -1,16 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.RandomizerTool.CreateHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool.CreateHints; - -public sealed class ValueCreateHintTests : CreateHintTestBase -{ - private static readonly ValueCreateHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [.. ValueRandom.ValueTypes]; - - private static readonly Type[] _InvalidTypes = [typeof(object)]; - - public ValueCreateHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/InfiniteLoopExceptionTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/InfiniteLoopExceptionTests.cs deleted file mode 100644 index 1a08cfea..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/InfiniteLoopExceptionTests.cs +++ /dev/null @@ -1,13 +0,0 @@ -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool; - -public sealed class InfiniteLoopExceptionTests : ExceptionTestBase -{ - [Theory, RandomData] - internal static void InfiniteLoopException_HandlesNull(IEnumerable history) - { - _ = new InfiniteLoopException(null, history); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/MethodCallWrapperTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/MethodCallWrapperTests.cs deleted file mode 100644 index 98b2cbc8..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/MethodCallWrapperTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool; - -public static class MethodCallWrapperTests -{ - [Fact] - internal static void MethodCallWrapper_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void MethodCallWrapper_CanRandomize() - { - Tools.Randomizer.Create().Assert().IsNot(null); - } - - [Theory, RandomData] - internal static void MethodCallWrapper_WorksInFake( - [Stub] IRandomizer rand, MethodCallWrapper wrapper, MethodBase method) - { - rand.CreateFor(Arg.Any(), Arg.Any()).SetupReturn(wrapper); - rand.CreateFor(method).Assert().Is(wrapper); - } - - [Theory, RandomData] - internal static void ModifyArg_ThrowsWithUnknownParameter(MethodCallWrapper method, string parameter, object value) - { - method.Assert(m => m.ModifyArg(parameter, value)).Throws(); - } - - [Theory, RandomData] - internal static void ModifyArg_CanMutate(DataSample sample) - { - MethodCallWrapper wrapper = Tools.Randomizer.CreateFor( - typeof(DataHolderSample).GetMethod(nameof(DataHolderSample.HasNested))); - - wrapper.ModifyArg("value", sample); - wrapper.Args.Assert().Contains(sample); - } - - [Theory, RandomData] - internal static void InvokeOn_UsesArgs(DataSample sample) - { - MethodCallWrapper wrapper = Tools.Randomizer.CreateFor( - typeof(DataSample).GetMethod(nameof(Equals))); - - wrapper.InvokeOn(sample).Assert().Is(false); - wrapper.ModifyArg("obj", sample); - wrapper.InvokeOn(sample).Assert().Is(true); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/RandomizerChainerTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/RandomizerChainerTests.cs deleted file mode 100644 index b176dbc8..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/RandomizerChainerTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool; - -public static class RandomizerChainerTests -{ - [Fact] - internal static void RandomizerChainer_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void RandomizerChainer_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Fact] - internal static void Create_HandlesInfinites() - { - new RandomizerChainer(Tools.Faker, Tools.Gen, (t, c) => c.Create()) - .Assert(c => c.Create(typeof(ChildWithParentSample), new ParentLoopSample())) - .Throws(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/RandomizerTests.cs b/tests/CreateAndFakeTests/Toolbox/RandomizerTool/RandomizerTests.cs deleted file mode 100644 index d2c79897..00000000 --- a/tests/CreateAndFakeTests/Toolbox/RandomizerTool/RandomizerTests.cs +++ /dev/null @@ -1,198 +0,0 @@ -using System.Collections; -using CreateAndFake.Design; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.RandomizerTool; - -public static class RandomizerTests -{ - [Fact] - internal static void Randomizer_GuardsNulls() - { - Tools.Asserter.Throws(() => new Randomizer(null, Tools.Gen, Limiter.Few)); - Tools.Asserter.Throws(() => new Randomizer(Tools.Faker, null, Limiter.Few)); - Tools.Asserter.Throws(() => new Randomizer(Tools.Faker, Tools.Gen, null)); - - Tools.Tester.PreventsNullRefException(Tools.Randomizer); - } - - [Fact] - internal static void New_NullHintsValid() - { - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, true, null).Assert().IsNot(null); - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false, null).Assert().IsNot(null); - } - - [Fact] - internal static void Create_NoRulesThrows() - { - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false) - .Assert(r => r.Create()) - .Throws(); - } - - [Theory, RandomData] - internal static void CreateSized_NoRulesThrows(int size) - { - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false) - .Assert(r => r.CreateSized(size)) - .Throws(); - } - - [Theory, RandomData] - internal static void Create_MissingMatchThrows([Stub] CreateHint hint, string data) - { - hint.ToFake().ThrowByDefault = true; - hint.ToFake().Setup( - m => m.TryCreate(data.GetType(), Arg.Any()), - Behavior.Returns((false, (object)null), Times.Once)); - - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false, hint) - .Assert(r => r.Create()) - .Throws(); - - hint.VerifyAllCalls(Times.Once); - } - - [Theory, RandomData] - internal static void CreateSized_MissingMatchThrows([Fake] CreateCollectionHint hint, int size, string data) - { - hint.ToFake().Setup( - m => m.TryCreate(data.GetType(), size, Arg.Any()), - Behavior.Returns((false, (object)null), Times.Once)); - - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false, hint) - .Assert(r => r.CreateSized(size)) - .Throws(); - - hint.VerifyAllCalls(Times.Once); - } - - [Theory, RandomData] - internal static void Create_ValidHintWorks([Stub] CreateHint hint, string data) - { - hint.ToFake().ThrowByDefault = true; - hint.ToFake().Setup( - m => m.TryCreate(data.GetType(), Arg.Any()), - Behavior.Returns((true, (object)data), Times.Once)); - - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false, hint) - .Create() - .Assert() - .Is(data); - - hint.VerifyAllCalls(Times.Once); - } - - [Theory, RandomData] - internal static void CreateSized_ValidHintWorks([Stub] CreateCollectionHint hint, string[] data) - { - hint.ToFake().ThrowByDefault = true; - hint.ToFake().Setup( - m => m.TryCreate(data.GetType(), 1, Arg.Any()), - Behavior.Returns((true, (object)data), Times.Once)); - - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false, hint) - .CreateSized(1) - .Assert() - .Is(data); - - hint.VerifyAllCalls(Times.Once); - } - - [Theory, RandomData] - internal static void Create_InfiniteLoopDetails(Type type, [Fake] CreateHint hint) - { - hint.ToFake().Setup( - m => m.TryCreate(type, Arg.Any()), - Behavior.Throw(Times.Once)); - - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false, hint) - .Assert(r => r.Create(type)) - .Throws().Message - .Assert() - .Contains(type.Name); - } - - [Theory, RandomData] - internal static void CreateSized_InfiniteLoopDetails(Type type, [Fake] CreateCollectionHint hint, int size) - { - hint.ToFake().Setup( - m => m.TryCreate(type, size, Arg.Any()), - Behavior.Throw(Times.Once)); - - new Randomizer(Tools.Faker, new FastRandom(), Limiter.Dozen, false, hint) - .Assert(r => r.CreateSized(type, size)) - .Throws().Message - .Assert() - .Contains(type.Name); - } - - [Fact] - internal static void Create_ConditionMatchReturned() - { - Tools.Randomizer.Create(v => v < 0).Assert().LessThan(0); - } - - [Fact] - internal static void Create_ConditionTimesOut() - { - Tools.Randomizer - .Assert(r => r.Create(d => d < DateTime.MinValue)) - .Throws(); - } - - [Theory, RandomData] - internal static void Inject_SingleFakeInjected(Fake fake, InjectSample holder) - { - holder.Data.Assert().ReferenceEqual(fake.Dummy); - holder.Data2.Assert().ReferenceNotEqual(fake.Dummy); - } - - [Theory, RandomData] - internal static void Inject_DoubleFakeInjected(Fake fake, [Fake] DataSample fake2, InjectSample holder) - { - holder.Data2.Assert().ReferenceEqual(fake.Dummy); - holder.Data.Assert().ReferenceEqual(fake2); - } - - [Theory, RandomData] - internal static void Inject_InterfaceFakesInjected( - Fake fake, Fake fake2, InjectMockSample holder) - { - fake.Verify(Times.Never, f => f.FailIfNotMocked()); - fake2.Verify(Times.Never, f => f.FailIfNotMocked()); - holder.TestIfMockedSeparately(); - fake.Verify(Times.Once, f => f.FailIfNotMocked()); - fake2.Verify(Times.Once, f => f.FailIfNotMocked()); - } - - [Theory, RandomData] - internal static void CreateFor_InterfaceFakesInjected(Fake fake, Fake fake2) - { - Tools.Randomizer - .CreateFor(typeof(InjectMockSample).GetConstructors().Single(), fake, fake2).Args.ToArray() - .Assert() - .Is(new object[] { fake.Dummy, fake2.Dummy }); - } - - [Theory, RandomData] - internal static void CreateFor_InjectedWorks(Injected injected) - { - injected.Dummy.TestIfMockedSeparately(); - } - - [Theory, RandomData] - internal static void CreateFor_InjectedNotManuallyInjected(Fake inner1, - Fake inner2, InjectMockSample sample, Injected injected) - { - injected.Dummy.Assert().IsNot(sample); - injected.Fakes.Contains(inner1).Assert().Is(false); - injected.Fakes.Contains(inner2).Assert().Is(false); - - injected.Dummy.TestIfMockedSeparately(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/ExceptionGuarderTests.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/ExceptionGuarderTests.cs deleted file mode 100644 index 092bcb3b..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/ExceptionGuarderTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.TesterTool; -using CreateAndFakeTests.TestSamples; -using CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.TesterTool; - -public static class ExceptionGuarderTests -{ - [Fact] - internal static void ExceptionGuarder_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void ExceptionGuarder_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Fact] - internal static void CallAllMethods_SuccessfulNoException() - { - Tools.Tester.PassthroughWithNoExceptions(); - } - - [Fact] - internal static void CallAllMethods_FailsWithException() - { - Tools.Tester - .Assert(t => t.PassthroughWithNoExceptions()) - .Throws(); - } - - [Theory, RandomData] - internal static void HandleCheckException_UsesAsserterFail( - GenericFixer fixer, [Fake] Asserter asserter, TimeSpan timeout) - { - asserter.ToFake().Setup( - d => d.Fail(Arg.Any(), Arg.Any()), - Behavior.None(Times.Once)); - - new ExceptionGuarder(fixer, Tools.Randomizer, asserter, timeout) - .CallAllMethods(new MethodThrowsSample(), null); - - asserter.VerifyAllCalls(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/GenericFixerTests.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/GenericFixerTests.cs deleted file mode 100644 index 8f9e587e..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/GenericFixerTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.TesterTool; - -namespace CreateAndFakeTests.Toolbox.TesterTool; - -public static class GenericFixerTests -{ - [Fact] - internal static void GenericFixer_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Theory, RandomData] - internal static void GenericFixer_NoParameterMutation(IRandom gen) - { - Tools.Tester.PreventsParameterMutation(new GenericFixer(gen, Tools.Randomizer)); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/MutationGuarderTests.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/MutationGuarderTests.cs deleted file mode 100644 index e5698e11..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/MutationGuarderTests.cs +++ /dev/null @@ -1,103 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.TesterTool; -using CreateAndFakeTests.TestSamples; -using CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.TesterTool; - -public static class MutationGuarderTests -{ - private static readonly MutationGuarder _ShortTestInstance = new( - new GenericFixer(Tools.Gen, Tools.Randomizer), Tools.Randomizer, - Tools.Duplicator, Tools.Asserter, new TimeSpan(0, 0, 0, 0, 100)); - - private static readonly MutationGuarder _LongTestInstance = new( - new GenericFixer(Tools.Gen, Tools.Randomizer), Tools.Randomizer, - Tools.Duplicator, Tools.Asserter, new TimeSpan(0, 0, 10)); - - [Fact] - internal static void MutationGuarder_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(_ShortTestInstance); - } - - [Fact] - internal static void MutationGuarder_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(_ShortTestInstance); - } - - [Fact] - internal static void PreventsParameterMutation_OnStatics() - { - Tools.Tester - .Assert(t => t.PreventsParameterMutation(typeof(StaticMutationSample))) - .Throws(); - } - - [Fact] - internal static void PreventsParameterMutation_StatelessFine() - { - Tools.Tester.PreventsParameterMutation(); - } - - [Fact] - internal static void PreventsParameterMutation_NullInjectionsFine() - { - Tools.Tester.PreventsParameterMutation((object[])null); - } - - [Theory, RandomData] - internal static void PreventsParameterMutation_InjectsMultipleValues(Fake fake1, Fake fake2) - { - Tools.Tester.PreventsParameterMutation(fake1, fake2); - } - - [Theory, RandomData] - internal static void PreventsParameterMutation_InjectsWithMethods(Fake fake) - { - Tools.Tester.PreventsParameterMutation(fake); - } - - [Fact] - internal static void CallMethod_TimesOut() - { - _ShortTestInstance - .Assert(t => t.PreventsMutationOnStatics(typeof(LongMethodSample), false)) - .Throws(); - } - - [Fact] - internal static void PreventsMutationOnConstructors_Disposes() - { - lock (MockDisposableSample._Lock) - { - MockDisposableSample._ClassDisposes = 0; - MockDisposableSample._FinalizerDisposes = 0; - MockDisposableSample._Fake = Tools.Faker.Stub(); - - _LongTestInstance.PreventsMutationOnConstructors(typeof(MockDisposableSample), true); - Tools.Asserter.Is(1, MockDisposableSample._ClassDisposes); - Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); - MockDisposableSample._Fake.Verify(Times.Once, d => d.Dispose()); - } - } - - [Fact] - internal static void PreventsMutationOnMethods_Disposes() - { - lock (MockDisposableSample._Lock) - { - MockDisposableSample._ClassDisposes = 0; - MockDisposableSample._FinalizerDisposes = 0; - MockDisposableSample._Fake = Tools.Faker.Stub(); - - using MockDisposableSample sample = new(null); - _LongTestInstance.PreventsMutationOnMethods(sample); - Tools.Asserter.Is(0, MockDisposableSample._ClassDisposes); - Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); - MockDisposableSample._Fake.Verify(Times.Once, d => d.Dispose()); - } - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/NullGuarderTests.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/NullGuarderTests.cs deleted file mode 100644 index d490def5..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/NullGuarderTests.cs +++ /dev/null @@ -1,112 +0,0 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.TesterTool; -using CreateAndFakeTests.TestSamples; -using CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.TesterTool; - -public static class NullGuarderTests -{ - private static readonly NullGuarder _ShortTestInstance = new( - new GenericFixer(Tools.Gen, Tools.Randomizer), - Tools.Randomizer, Tools.Asserter, new TimeSpan(0, 0, 0, 0, 100)); - - private static readonly NullGuarder _LongTestInstance = new( - new GenericFixer(Tools.Gen, Tools.Randomizer), - Tools.Randomizer, Tools.Asserter, new TimeSpan(0, 0, 10)); - - [Fact] - internal static void NullGuarder_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(_ShortTestInstance); - } - - [Fact] - internal static void NullGuarder_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(_ShortTestInstance); - } - - [Fact] - internal static void NullCheck_TimesOut() - { - _ShortTestInstance - .Assert(t => t.PreventsNullRefExceptionOnStatics(typeof(LongMethodSample), false)) - .Throws(); - } - - [Fact] - internal static void NullCheck_NullReferenceThrows() - { - _ShortTestInstance - .Assert(t => t.PreventsNullRefExceptionOnConstructors(typeof(NullReferenceSample), true)) - .Throws(); - } - - [Theory, RandomData] - internal static void PreventsNullRefException_InjectsMultipleValues( - Fake fake1, Fake fake2) - { - Tools.Tester.PreventsNullRefException(fake1, fake2); - } - - [Theory, RandomData] - internal static void PreventsNullRefException_InjectsWithMethods(Fake fake) - { - Tools.Tester.PreventsNullRefException(fake); - } - - [Fact] - internal static void PreventsNullRefException_OnStatics() - { - Tools.Tester - .Assert(t => t.PreventsNullRefException(typeof(StaticMutationSample))) - .Throws(); - } - - [Fact] - internal static void PreventsNullRefException_StatelessFine() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void PreventsNullRefException_NullInjectionsFine() - { - Tools.Tester.PreventsNullRefException((object[])null); - } - - [Theory, RandomData] - internal static void PreventsNullRefExceptionOnConstructors_Disposes([Stub] IDisposable disposable) - { - lock (MockDisposableSample._Lock) - { - MockDisposableSample._ClassDisposes = 0; - MockDisposableSample._FinalizerDisposes = 0; - MockDisposableSample._Fake = disposable.ToFake(); - - _LongTestInstance.PreventsNullRefExceptionOnConstructors(typeof(MockDisposableSample), true); - Tools.Asserter.Is(1, MockDisposableSample._ClassDisposes); - Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); - MockDisposableSample._Fake.Verify(Times.Once, d => d.Dispose()); - } - } - - [Theory, RandomData] - internal static void PreventsNullRefExceptionOnMethods_Disposes([Stub] IDisposable disposable) - { - lock (MockDisposableSample._Lock) - { - MockDisposableSample._ClassDisposes = 0; - MockDisposableSample._FinalizerDisposes = 0; - MockDisposableSample._Fake = disposable.ToFake(); - - using MockDisposableSample sample = new(null); - _LongTestInstance.PreventsNullRefExceptionOnMethods(sample); - Tools.Asserter.Is(0, MockDisposableSample._ClassDisposes); - Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); - MockDisposableSample._Fake.Verify(Times.Once, d => d.Dispose()); - } - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/LongMethodSample.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/LongMethodSample.cs deleted file mode 100644 index e8988101..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/LongMethodSample.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -public static class LongMethodSample -{ - [ExcludeFromCodeCoverage] - public static void BeSlow(string data, out T output) where T : new() - { - Thread.Sleep(new TimeSpan(0, 0, 2)); - - output = new T(); - throw new InvalidOperationException(data); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MethodThrowsSample.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MethodThrowsSample.cs deleted file mode 100644 index 7730b967..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MethodThrowsSample.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -public sealed class MethodThrowsSample -{ - public void ThrowSomething() - { - throw new InvalidOperationException(GetType().Name); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MockDisposableSample.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MockDisposableSample.cs deleted file mode 100644 index 9eab3bc9..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MockDisposableSample.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using CreateAndFake.Toolbox.FakerTool; - -#pragma warning disable IDE0060 // Remove unused parameter: For testing. -#pragma warning disable CS9113 // Parameter is unread: For testing. - -namespace CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "For testing.")] -public sealed class MockDisposableSample(object value) : IDisposable -{ - internal static readonly object _Lock = new(); - - internal static Fake _Fake = Tools.Faker.Stub(); - - internal static int _ClassDisposes = 0; - - internal static int _FinalizerDisposes = 0; - - [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Must ignore in finalizer.")] - [ExcludeFromCodeCoverage] - ~MockDisposableSample() - { - try - { - _FinalizerDisposes++; - } - catch { } - } - - public void Dispose() - { - GC.SuppressFinalize(this); - _ClassDisposes++; - } - - public IDisposable DisposePass(object value) - { - return _Fake.Dummy; - } -} - -#pragma warning restore CS9113 // Parameter is unread -#pragma warning restore IDE0060 // Remove unused parameter diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MockMethodPassOnly.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MockMethodPassOnly.cs deleted file mode 100644 index 45243b74..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/MockMethodPassOnly.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -public sealed class MockMethodPassOnly -{ - [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "For testing.")] - public bool MockPassOnly(IOnlyMockSample sample) - { - sample?.FailIfNotMocked(); - return true; - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/NullReferenceSample.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/NullReferenceSample.cs deleted file mode 100644 index 67d9c494..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/NullReferenceSample.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using CreateAndFake.Design.Content; - -namespace CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -public sealed class NullReferenceSample -{ - private readonly IValueEquatable _data; - - internal NullReferenceSample(IValueEquatable data) - { - _data = data; - } - - [ExcludeFromCodeCoverage] - public override string ToString() - { - return _data.ToString(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/StaticMutationSample.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/StaticMutationSample.cs deleted file mode 100644 index ebfca341..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/TestSamples/StaticMutationSample.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -internal static class StaticMutationSample -{ - internal static void Mutate(DataHolderSample data) - { - data.NestedValue = null; - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/TesterTool/TesterTests.cs b/tests/CreateAndFakeTests/Toolbox/TesterTool/TesterTests.cs deleted file mode 100644 index 8cdcff6f..00000000 --- a/tests/CreateAndFakeTests/Toolbox/TesterTool/TesterTests.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.RandomizerTool; -using CreateAndFake.Toolbox.TesterTool; -using CreateAndFakeTests.Toolbox.TesterTool.TestSamples; - -namespace CreateAndFakeTests.Toolbox.TesterTool; - -public static class TesterTests -{ - private static readonly Tester _ShortTestInstance = new(Tools.Gen, - Tools.Randomizer, Tools.Duplicator, Tools.Asserter, new TimeSpan(0, 0, 0, 0, 100)); - - private static readonly Tester _LongTestInstance = new(Tools.Gen, - Tools.Randomizer, Tools.Duplicator, Tools.Asserter, new TimeSpan(0, 0, 10)); - - [Fact] - internal static void Tester_AllMethodsVirtual() - { - Tools.Asserter.IsEmpty(typeof(Tester) - .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) - .Where(m => !m.IsVirtual) - .Select(m => m.Name)); - } - - [Theory, RandomData] - internal static void Tester_GuardsNulls(IRandom gen, IRandomizer randomizer, - IDuplicator duplicator, Asserter asserter, TimeSpan? timeout) - { - Tools.Asserter.Throws(() => new Tester(null, randomizer, duplicator, asserter, timeout)); - Tools.Asserter.Throws(() => new Tester(gen, null, duplicator, asserter, timeout)); - Tools.Asserter.Throws(() => new Tester(gen, randomizer, null, asserter, timeout)); - Tools.Asserter.Throws(() => new Tester(gen, randomizer, duplicator, null, timeout)); - - Tools.Asserter.Throws(() => _ShortTestInstance.PreventsNullRefException(null)); - Tools.Asserter.Throws(() => _ShortTestInstance.PreventsParameterMutation(null)); - } - - [Fact] - internal static void PreventsNullRefException_Disposes() - { - lock (MockDisposableSample._Lock) - { - MockDisposableSample._ClassDisposes = 0; - MockDisposableSample._FinalizerDisposes = 0; - MockDisposableSample._Fake = Tools.Faker.Stub(); - - _LongTestInstance.PreventsNullRefException(); - Tools.Asserter.Is(2, MockDisposableSample._ClassDisposes); - Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); - MockDisposableSample._Fake.Verify(Times.Exactly(2), d => d.Dispose()); - } - } - - [Fact] - internal static void PreventsParameterMutation_Disposes() - { - lock (MockDisposableSample._Lock) - { - MockDisposableSample._ClassDisposes = 0; - MockDisposableSample._FinalizerDisposes = 0; - MockDisposableSample._Fake = Tools.Faker.Stub(); - - _LongTestInstance.PreventsParameterMutation(); - Tools.Asserter.Is(2, MockDisposableSample._ClassDisposes); - Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); - MockDisposableSample._Fake.Verify(Times.Exactly(2), d => d.Dispose()); - } - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ToolSetTests.cs b/tests/CreateAndFakeTests/Toolbox/ToolSetTests.cs deleted file mode 100644 index 0d8850f0..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ToolSetTests.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace CreateAndFakeTests.Toolbox; - -public static class ToolSetTests -{ - [Fact] - internal static void ToolSet_Creatable() - { - ToolSet.CreateViaSeed(0).Assert().IsNot(null); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/AsyncEnumerableCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/AsyncEnumerableCompareHintTests.cs deleted file mode 100644 index 24070a2b..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/AsyncEnumerableCompareHintTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class AsyncEnumerableCompareHintTests : CompareHintTestBase -{ - private static readonly AsyncEnumerableCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(IAsyncEnumerable), - typeof(IAsyncEnumerable), - typeof(IAsyncEnumerable) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(IEnumerable), - typeof(object) - ]; - - public AsyncEnumerableCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal void Supports_NullTest(IAsyncEnumerable data) - { - TestInstance.TryCompare(null, data, CreateChainer()).Item1.Assert().Is(false); - TestInstance.TryCompare(data, null, CreateChainer()).Item1.Assert().Is(false); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/DictionaryCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/DictionaryCompareHintTests.cs deleted file mode 100644 index 77dd01d3..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/DictionaryCompareHintTests.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class DictionaryCompareHintTests : CompareHintTestBase -{ - private static readonly DictionaryCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(IDictionary), - typeof(Dictionary) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(object), - typeof(string), - typeof(IList), - typeof(int) - ]; - - public DictionaryCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal void TryCompare_SameKeyDifferentValuesWorks(Dictionary data) - { - Dictionary dupe = data.CreateDeepClone(); - string key = data.First().Key; - dupe[key] = data[key].CreateVariant(); - - TestInstance.TryCompare(data, dupe, CreateChainer()).Item2.ToArray() - .Assert().IsNotEmpty("Hint didn't find differences with a modified key on '" + data.GetType().Name + "'."); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EarlyFailCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EarlyFailCompareHintTests.cs deleted file mode 100644 index 344f88ed..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EarlyFailCompareHintTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Collections; -using System.Reflection; -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class EarlyFailCompareHintTests : CompareHintTestBase -{ - private static readonly EarlyFailCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(int), - typeof(string), - typeof(BindingFlags), - typeof(Type), - typeof(Delegate) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(IDictionary), - typeof(IEnumerable), - typeof(IAsyncEnumerable) - ]; - - public EarlyFailCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Fact] - internal void TryCompare_NullBehaviorCheck() - { - TestInstance.TryCompare(null, new object(), CreateChainer()).Item1.Assert().Is(true); - TestInstance.TryCompare(null, new object(), CreateChainer()).Item2.Assert().IsNotEmpty(); - - TestInstance.TryCompare(null, null, CreateChainer()).Item1.Assert().Is(true); - TestInstance.TryCompare(null, null, CreateChainer()).Item2.Assert().IsEmpty(); - - TestInstance.TryCompare(new object(), null, CreateChainer()).Item1.Assert().Is(true); - TestInstance.TryCompare(new object(), null, CreateChainer()).Item2.Assert().IsNotEmpty(); - } - - [Fact] - internal void TryGetHashCode_NullBehaviorCheck() - { - TestInstance.TryGetHashCode(null, CreateChainer()).Assert().Is((true, ValueComparer.NullHash)); - } - - [Theory, RandomData] - internal void TryCompare_MismatchedTypesDifferent(int value) - { - TestInstance.TryCompare(value, new object(), CreateChainer()).Item2.Assert().IsNotEmpty(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EnumerableCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EnumerableCompareHintTests.cs deleted file mode 100644 index 7af416eb..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EnumerableCompareHintTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.ValuerTool; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class EnumerableCompareHintTests : CompareHintTestBase -{ - private static readonly EnumerableCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(IList), - typeof(List), - typeof(List>) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(object), - typeof(int) - ]; - - public EnumerableCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal void Compare_SizeMismatchOutOfBounds(List original) - { - List variant = original.CreateDeepClone(); - variant.RemoveAt(variant.Count - 1); - - (bool, IEnumerable) result = TestInstance.TryCompare(original, variant, CreateChainer()); - result.Item1.Assert().Is(true); - result.Item2.Assert().HasCount(1); - result.Item2.Single().ToString().Assert().Contains("outofbounds"); - - result = TestInstance.TryCompare(variant, original, CreateChainer()); - result.Item1.Assert().Is(true); - result.Item2.Assert().HasCount(1); - result.Item2.Single().ToString().Assert().Contains("outofbounds"); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EquatableCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EquatableCompareHintTests.cs deleted file mode 100644 index b83fb82c..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/EquatableCompareHintTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections; -using CreateAndFake.Design; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class EquatableCompareHintTests : CompareHintTestBase -{ - private static readonly EquatableCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(Limiter)]; - - private static readonly Type[] _InvalidTypes = [typeof(IDictionary), typeof(object)]; - - public EquatableCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/FakedCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/FakedCompareHintTests.cs deleted file mode 100644 index f8eb5d62..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/FakedCompareHintTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class FakedCompareHintTests : CompareHintTestBase -{ - private static readonly FakedCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(IFaked)]; - - private static readonly Type[] _InvalidTypes = [typeof(IEnumerable), typeof(string), typeof(int)]; - - public FakedCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ObjectCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ObjectCompareHintTests.cs deleted file mode 100644 index 64a76724..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ObjectCompareHintTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Reflection; -using CreateAndFake.Toolbox.ValuerTool; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class ObjectCompareHintTests : CompareHintTestBase -{ - private static readonly ObjectCompareHint _TestInstance = new(BindingFlags.Public | BindingFlags.Instance); - - private static readonly Type[] _ValidTypes = [typeof(object), typeof(DataHolderSample), typeof(FieldSample)]; - - private static readonly Type[] _InvalidTypes = Type.EmptyTypes; - - public ObjectCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal void Compare_DifferentObjectsDifferences(string value1, string value2) - { - var expected = new { Value = value1 }; - var actual = new { Value = value2 }; - - (bool, IEnumerable) result = TestInstance - .TryCompare(expected, actual, CreateChainer()); - - result.Item1.Assert().Is(true); - result.Item2.Assert().IsNotEmpty(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/StatelessCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/StatelessCompareHintTests.cs deleted file mode 100644 index 69f709ec..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/StatelessCompareHintTests.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class StatelessCompareHintTests : CompareHintTestBase -{ - private static readonly StatelessCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(StatelessSample)]; - - private static readonly Type[] _InvalidTypes = [typeof(object), typeof(string), typeof(IList), typeof(int)]; - - public StatelessCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - public override void TryCompare_SupportsDifferentValidTypes() - { - // Stateless objects can't be different. - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/StringDictionaryCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/StringDictionaryCompareHintTests.cs deleted file mode 100644 index 54dbc35d..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/StringDictionaryCompareHintTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections; -using System.Collections.Specialized; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class StringDictionaryCompareHintTests : CompareHintTestBase -{ - private static readonly StringDictionaryCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(StringDictionary)]; - - private static readonly Type[] _InvalidTypes = [typeof(IDictionary), typeof(object)]; - - public StringDictionaryCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/TaskCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/TaskCompareHintTests.cs deleted file mode 100644 index 2534cf39..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/TaskCompareHintTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -#pragma warning disable CA1849 // Task await synchronously blocks: For testing. - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class TaskCompareHintTests : CompareHintTestBase -{ - private static readonly TaskCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(Task), - typeof(Task), - typeof(Task), - typeof(Task), - typeof(Task), - typeof(Task) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(IEnumerable), - typeof(string), - typeof(int) - ]; - - public TaskCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } - - [Theory, RandomData] - internal void Compare_NonGenericTasksCompareByException(Exception ex) - { - BuildTask(ex) - .Assert() - .IsNot(BuildTask(Tools.Mutator.Variant(ex))) - .And - .IsNot(BuildTask(null)); - } - - private static Task BuildTask(Exception ex) - { - Task task = new(() => - { - if (ex != null) - { - throw ex; - } - }); - try - { - task.Start(); - task.Wait(); - } - catch (AggregateException) - { - // Throw intentional. - } - return task; - } -} - -#pragma warning restore CA1849 // Task await synchronously blocks diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ValueEquatableCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ValueEquatableCompareHintTests.cs deleted file mode 100644 index f6e22fff..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ValueEquatableCompareHintTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Collections; -using CreateAndFake.Design.Content; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class ValueEquatableCompareHintTests : CompareHintTestBase -{ - private static readonly ValueEquatableCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = [typeof(IValueEquatable), typeof(ValueEquatableSample)]; - - private static readonly Type[] _InvalidTypes = [typeof(IDictionary), typeof(object)]; - - public ValueEquatableCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ValuerEquatableCompareHintTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ValuerEquatableCompareHintTests.cs deleted file mode 100644 index 5d467e53..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/CompareHints/ValuerEquatableCompareHintTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Collections; -using CreateAndFake.Toolbox.ValuerTool; -using CreateAndFake.Toolbox.ValuerTool.CompareHints; -using CreateAndFakeTests.TestBases; -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.Toolbox.ValuerTool.CompareHints; - -public sealed class ValuerEquatableCompareHintTests : CompareHintTestBase -{ - private static readonly ValuerEquatableCompareHint _TestInstance = new(); - - private static readonly Type[] _ValidTypes = - [ - typeof(IValuerEquatable), - typeof(ValuerEquatableSample), - typeof(PrivateValuerEquatableSample) - ]; - - private static readonly Type[] _InvalidTypes = - [ - typeof(IDictionary), - typeof(object) - ]; - - public ValuerEquatableCompareHintTests() : base(_TestInstance, _ValidTypes, _InvalidTypes) { } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/DifferenceTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/DifferenceTests.cs deleted file mode 100644 index ca76fd12..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/DifferenceTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFakeTests.Toolbox.ValuerTool; - -public static class DifferenceTests -{ - [Fact] - internal static void Difference_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void Difference_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/ValuerChainerTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/ValuerChainerTests.cs deleted file mode 100644 index 81360437..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/ValuerChainerTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFakeTests.Toolbox.ValuerTool; - -public static class ValuerChainerTests -{ - [Fact] - internal static void ValuerChainer_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(); - } - - [Fact] - internal static void ValuerChainer_NoParameterMutation() - { - Tools.Tester.PreventsParameterMutation(); - } -} diff --git a/tests/CreateAndFakeTests/Toolbox/ValuerTool/ValuerTests.cs b/tests/CreateAndFakeTests/Toolbox/ValuerTool/ValuerTests.cs deleted file mode 100644 index 53545110..00000000 --- a/tests/CreateAndFakeTests/Toolbox/ValuerTool/ValuerTests.cs +++ /dev/null @@ -1,149 +0,0 @@ -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.ValuerTool; - -namespace CreateAndFakeTests.Toolbox.ValuerTool; - -public static class ValuerTests -{ - [Fact] - internal static void Valuer_GuardsNulls() - { - Tools.Tester.PreventsNullRefException(Tools.Valuer); - } - - [Fact] - internal static void New_NullHintsValid() - { - new Valuer(true, null).Assert().Pass(); - new Valuer(false, null).Assert().Pass(); - } - - [Fact] - internal static void GetHashCode_MissingMatchThrows() - { - new Valuer(false) - .Assert(v => v.GetHashCode((object)null)) - .Throws(); - - new Valuer(false) - .Assert(v => v.GetHashCode(new object())) - .Throws(); - } - - [Theory, RandomData] - internal static void GetHashCode_SupportsMultiple(int value1, int value2) - { - Tools.Valuer.GetHashCode(value1, value2).Assert().Is(Tools.Valuer.GetHashCode([value1, value2])); - } - - [Theory, RandomData] - internal static void GetHashCode_ValidHint(object data, int result, [Fake] CompareHint hint) - { - hint.ToFake().Setup("Supports", - [data, data, Arg.LambdaAny()], - Behavior.Returns(true, Times.Once)); - hint.ToFake().Setup("GetHashCode", - [data, Arg.LambdaAny()], - Behavior.Returns(result, Times.Once)); - - new Valuer(false, hint).GetHashCode(data).Assert().Is(result); - hint.VerifyAllCalls(Times.Exactly(2)); - } - - [Fact] - internal static void Compare_MissingMatchThrows() - { - new Valuer(false).Assert(v => v.Compare(null, new object())).Throws(); - new Valuer(false).Assert(v => v.Compare(new object(), new object())).Throws(); - } - - [Theory, RandomData] - internal static void Compare_ReferenceNoDifferences(object data) - { - new Valuer(false).Compare(data, data).Assert().IsEmpty(); - } - - [Theory, RandomData] - internal static void Compare_NullableWorks(int? item) - { - item.Assert().IsNot(null); - item.CreateVariant().Assert().IsNot(item); - item.CreateDeepClone().Assert().Is(item); - - int? none = null; - none.Assert().IsNot(item); - none.Assert().Is(none); - } - - [Theory, RandomData] - internal static void Equals_NoDifferencesTrue(object data1, object data2, Fake hint) - { - hint.Setup("Supports", - [data1, data2, Arg.LambdaAny()], - Behavior.Returns(true, Times.Once)); - hint.Setup("Compare", - [data1, data2, Arg.LambdaAny()], - Behavior.Returns(Enumerable.Empty(), Times.Once)); - - new Valuer(false, hint.Dummy).Equals(data1, data2).Assert().Is(true); - hint.VerifyAll(Times.Exactly(2)); - } - - [Theory, RandomData] - internal static void Equals_DifferencesFalse(object data1, object data2, Fake hint) - { - hint.Setup("Supports", - [data1, data2, Arg.LambdaAny()], - Behavior.Returns(true, Times.Once)); - hint.Setup("Compare", - [data1, data2, Arg.LambdaAny()], - Behavior.Returns(Tools.Randomizer.Create>(), Times.Once)); - - new Valuer(false, hint.Dummy).Equals(data1, data2).Assert().Is(false); - hint.VerifyAll(Times.Exactly(2)); - } - - [Theory, RandomData] - internal static void Compare_InfiniteLoopDetails(object item1, object item2, Fake hint) - { - hint.Setup("Supports", - [item1, item2, Arg.LambdaAny()], - Behavior.Throw(Times.Once)); - - new Valuer(false, hint.Dummy) - .Assert(v => v.Compare(item1, item2)) - .Throws().Message - .Assert() - .Contains(item1.GetType().Name); - } - - [Theory, RandomData] - internal static void GetHashCode_InfiniteLoopDetails(object item, Fake hint) - { - hint.Setup("Supports", - [item, item, Arg.LambdaAny()], - Behavior.Throw(Times.Once)); - - new Valuer(false, hint.Dummy) - .Assert(v => v.GetHashCode(item)) - .Throws().Message - .Assert() - .Contains(item.GetType().Name); - } - - [Fact] - internal static void GetHashCode_CanNotSupportNull() - { - new Valuer(false) - .Assert(v => v.GetHashCode((object)null)) - .Throws(); - } - - [Fact] - internal static void Compare_CanNotSupportNull() - { - new Valuer(false) - .Assert(v => v.Compare(null, new object())) - .Throws(); - } -} diff --git a/tests/CreateAndFakeTests/ToolsTests.cs b/tests/CreateAndFakeTests/ToolsTests.cs deleted file mode 100644 index a0b6238b..00000000 --- a/tests/CreateAndFakeTests/ToolsTests.cs +++ /dev/null @@ -1,149 +0,0 @@ -using System.Reflection; -using CreateAndFake.Design.Content; -using CreateAndFake.Design.Context; -using CreateAndFake.Design.Randomization; -using CreateAndFake.Toolbox; -using CreateAndFake.Toolbox.AsserterTool.Fluent; -using CreateAndFake.Toolbox.DuplicatorTool; -using CreateAndFake.Toolbox.FakerTool; -using CreateAndFake.Toolbox.FakerTool.Proxy; -using CreateAndFake.Toolbox.TesterTool; -using CreateAndFake.Toolbox.ValuerTool; -using CreateAndFakeTests.TestSamples; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests; - -public static class ToolsTests -{ - private const BindingFlags _Mutable = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; - - [Theory, RandomData] - internal static void Tools_IntegrationWorks(DataHolderSample original, [Fake] DataHolderSample faked) - { - DataHolderSample dupe = original.CreateDeepClone(); - - original.Assert().Is(dupe).And.IsNot(original.CreateVariant()); - - faked.HasNested(dupe).SetupReturn(true, Times.Once); - faked.HasNested(original).Assert().Is(true, "Value equality did not work for args."); - faked.VerifyAllCalls(); - } - - [Theory, RandomData] - internal static void Tools_HandlesInfinites(InfiniteSample sample) - { - Tools.Mutator.Assert(m => m.Variant(sample)).Throws(); - - InfiniteSample dupe = Tools.Duplicator.Copy(sample); - - dupe.Assert().Is(sample); - Tools.Valuer.GetHashCode(dupe).Assert().Is(Tools.Valuer.GetHashCode(sample)); - } - - [Fact, ExcludeFromCodeCoverage] - internal static void Tools_AllCreateAndFakeTypesWork() - { - Type[] ignore = [ - typeof(Arg), - typeof(Fake), - typeof(Fake<>), - typeof(VoidType), - typeof(AnyGeneric), - typeof(Injected<>), - typeof(DuplicatorChainer), - typeof(ValuerChainer), - typeof(Emitter), - typeof(Behavior), - typeof(Behavior<>), - typeof(AssertObjectBase<>), - typeof(AssertGroupBase<>), - typeof(AssertTextBase<>), - typeof(AssertBehaviorBase<>), - typeof(AssertComparableBase<>), - typeof(DataRandom), - typeof(BaseDataContext), - typeof(PersonContext), - typeof(ToolSet), - typeof(Tools), - typeof(BaseGuarder), - ]; - - foreach (Type type in typeof(Tools).Assembly.GetTypes() - .Where(t => !(t.IsAbstract && t.IsSealed)) - .Where(t => !t.Inherits()) - .Where(t => !ignore.Contains(t)) - .Where(t => !t.IsNestedPrivate) - .Where(t => t.GetCustomAttribute() == null) - .Where(t => !t.FullName.Contains("")) - .Where(t => !t.FullName.Contains("<>z__ReadOnly"))) - { - try - { - TestTrip(type); - } - catch (Exception e) - { - e.Assert().Fail($"Failed testing type '{type}'."); - throw; - } - } - } - - [Fact] - internal static void Tools_ExceptionTypesWork() - { - Type type = typeof(Exception); - - for (int i = 0; i < 100; i++) - { - TestTrip(type); - } - } - - /// Verifies the type works with the tools. - /// Type to test. - private static void TestTrip(Type type) - { - string failMessage = "Behavior did not work for type '" + type.FullName + "'."; - object - original = null, - variant = null, - dupe = null; - try - { - original = Tools.Randomizer.Create(type); - dupe = Tools.Duplicator.Copy(original); - - Tools.Asserter.ValuesEqual(original, dupe, failMessage); - Tools.Asserter.ValuesEqual( - Tools.Valuer.GetHashCode(original), - Tools.Valuer.GetHashCode(dupe), $"HashCode {failMessage}"); - - if (type.GetProperties(_Mutable).Length != 0 || type.GetFields(_Mutable).Length != 0) - { - variant = Tools.Mutator.Variant(type, original); - - Tools.Asserter.ValuesNotEqual(original, variant, failMessage); - Tools.Asserter.ValuesNotEqual( - Tools.Valuer.GetHashCode(original), - Tools.Valuer.GetHashCode(variant), failMessage); - - if (Tools.Mutator.Modify(original)) - { - Tools.Asserter.ValuesNotEqual(dupe, original); - } - } - - if (Tools.Faker.Supports(type) && !type.Inherits()) - { - Tools.Faker.Mock(type); - } - } - finally - { - Disposer.Cleanup(original, variant, dupe); - } - } -} diff --git a/tests/Design.Tests/ArgumentGuardTests.cs b/tests/Design.Tests/ArgumentGuardTests.cs new file mode 100644 index 00000000..e02ade8a --- /dev/null +++ b/tests/Design.Tests/ArgumentGuardTests.cs @@ -0,0 +1,343 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Properties; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests; + +public sealed class ArgumentGuardTests() : AutoTester(typeof(ArgumentGuard)) +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(IterationLimitException)] }; + + [Fact] + public static Task IsAsynchronous_TrueWithUncompletedTask() + { + Task task = Task.Delay(1000, TestContext.Current.CancellationToken); + ArgumentGuard.IsAsynchronous(task).Assert().Is(true); + ArgumentGuard.IsAsynchronous(Task.CompletedTask).Assert().Is(false); + return task; + } + + [Theory, RandomData] + public static void IsAsynchronous_TrueWithAsyncEnumerable(IAsyncEnumerable data) + { + ArgumentGuard.IsAsynchronous(data).Assert().Is(true); + } + + [Fact] + public static void IsAsynchronous_FalseWithNull() + { + ArgumentGuard.IsAsynchronous(null).Assert().Is(false); + } + + [Theory, RandomData] + public static void IsAsynchronous_FalseWithSyncData(DataSample data) + { + ArgumentGuard.IsAsynchronous(data).Assert().Is(false); + } + + [Fact] + public static void IsAsynchronous_SafeWithTypes() + { + ArgumentGuard.IsAsynchronous(typeof(AsyncList)).Assert().Is(true); + } + + [Theory, RandomData] + public static void ThrowIfAsynchronous_TrueWithTask(string message) + { + Task task = Task.Delay(2000, TestContext.Current.CancellationToken); + task.Assert(x => ArgumentGuard.ThrowIfAsynchronous(x, message)) + .Throws() + .With(e => e.Message) + .Contains(message); + } + + [Theory, RandomData] + public static void ThrowIfAsynchronous_TrueWithAsyncEnumerable( + IAsyncEnumerable data, + string message + ) + { + data.Assert(x => ArgumentGuard.ThrowIfAsynchronous(x, message)) + .Throws() + .With(e => e.Message) + .Contains(message); + } + + [Theory, RandomData] + public static void ThrowIfAsynchronous_PassWithNull(string message) + { + ArgumentGuard.ThrowIfAsynchronous(null, message); + } + + [Theory, RandomData] + public static void ThrowIfAsynchronous_PassWithSyncData(DataSample data, string message) + { + ArgumentGuard.ThrowIfAsynchronous(data, message); + } + + [Fact] + public static void ThrowUponIterationLimit_TestsLimit() + { + DesignDefaults + .IterationLimit.Assert(x => ArgumentGuard.ThrowUponIterationLimit(x - 1, x)) + .ThrowsNo(); + DesignDefaults + .IterationLimit.Assert(x => ArgumentGuard.ThrowUponIterationLimit(x, x)) + .Throws(); + } + + [Theory, RandomData] + public static void ThrowUponIterationLimit_TestsSpecificLimit(int value) + { + value + .Assert(x => ArgumentGuard.ThrowUponIterationLimit(x - 1, x)) + .ThrowsNo(); + value + .Assert(x => ArgumentGuard.ThrowUponIterationLimit(x, x)) + .Throws(); + } + + [Theory, RandomData] + internal static void ThrowIfNull_NoExceptionWithNonNull(object value) + { + ArgumentGuard.ThrowIfNull(value); + ArgumentGuard.ThrowIfNull(value, value); + ArgumentGuard.ThrowIfNull(value, value, value); + ArgumentGuard.ThrowIfNull(value, value, value, value); + ArgumentGuard.ThrowIfNull(value, value, value, value, value); + ArgumentGuard.ThrowIfNull(value, value, value, value, value, value); + ArgumentGuard.ThrowIfNull(value, value, value, value, value, value, value); + ArgumentGuard.ThrowIfNull(value, value, value, value, value, value, value, value); + } + + [Theory, RandomData] + internal static void ThrowIfNull_1_ExceptionWithNull(object nullValue, object value) + { + nullValue = null; + value + .Assert(_ => ArgumentGuard.ThrowIfNull(nullValue)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + } + + [Theory, RandomData] + internal static void ThrowIfNull_2_ExceptionWithNull(object nullValue, object value) + { + nullValue = null; + value + .Assert(x => ArgumentGuard.ThrowIfNull(nullValue, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, nullValue)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + } + + [Theory, RandomData] + internal static void ThrowIfNull_3_ExceptionWithNull(object nullValue, object value) + { + nullValue = null; + value + .Assert(x => ArgumentGuard.ThrowIfNull(nullValue, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, nullValue, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, nullValue)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + } + + [Theory, RandomData] + internal static void ThrowIfNull_4_ExceptionWithNull(object nullValue, object value) + { + nullValue = null; + value + .Assert(x => ArgumentGuard.ThrowIfNull(nullValue, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, nullValue, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, nullValue, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, nullValue)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + } + + [Theory, RandomData] + internal static void ThrowIfNull_5_ExceptionWithNull(object nullValue, object value) + { + nullValue = null; + value + .Assert(x => ArgumentGuard.ThrowIfNull(nullValue, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, nullValue, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, nullValue, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, nullValue, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, nullValue)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + } + + [Theory, RandomData] + internal static void ThrowIfNull_6_ExceptionWithNull(object nullValue, object value) + { + nullValue = null; + value + .Assert(x => ArgumentGuard.ThrowIfNull(nullValue, x, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, nullValue, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, nullValue, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, nullValue, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, nullValue, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, x, nullValue)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + } + + [Theory, RandomData] + internal static void ThrowIfNull_7_ExceptionWithNull(object nullValue, object value) + { + nullValue = null; + value + .Assert(x => ArgumentGuard.ThrowIfNull(nullValue, x, x, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, nullValue, x, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, nullValue, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, nullValue, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, nullValue, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, x, nullValue, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, x, x, nullValue)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + } + + [Theory, RandomData] + internal static void ThrowIfNull_8_ExceptionWithNull(object nullValue, object value) + { + nullValue = null; + value + .Assert(x => ArgumentGuard.ThrowIfNull(nullValue, x, x, x, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, nullValue, x, x, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, nullValue, x, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, nullValue, x, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, nullValue, x, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, x, nullValue, x, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, x, x, nullValue, x)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + value + .Assert(x => ArgumentGuard.ThrowIfNull(x, x, x, x, x, x, x, nullValue)) + .Throws() + .With(e => e.ParamName) + .Is(nameof(nullValue)); + } +} diff --git a/tests/Design.Tests/Comparisons/ReferenceComparerTests.cs b/tests/Design.Tests/Comparisons/ReferenceComparerTests.cs new file mode 100644 index 00000000..e6cbc439 --- /dev/null +++ b/tests/Design.Tests/Comparisons/ReferenceComparerTests.cs @@ -0,0 +1,46 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Design.Tests.Comparisons; + +public sealed class ReferenceComparerTests : AutoTester +{ + [Theory, RandomData] + internal static void Equals_UsesReferenceComparison(DataSample data, [Copy] DataSample dupe) + { + ReferenceComparer.Use.Equals(null, null).Assert().Is(true); + ReferenceComparer.Use.Equals(data, data).Assert().Is(true); + ReferenceComparer.Use.Equals(data, null).Assert().Is(false); + ReferenceComparer.Use.Equals(data, dupe).Assert().Is(false); + } + + [Theory, RandomData] + internal static void GetHashCode_UsesReferenceValue(DataSample data) + { + int originalHash = ReferenceComparer.Use.GetHashCode(data); + + data.Tools().Modify().Assert().Is(true); + ReferenceComparer.Use.GetHashCode(data).Assert().Is(originalHash); + + Limiter.Few.Retry( + "Occasional hash collisions acceptable.", + () => + ReferenceComparer.Use.GetHashCode(data.Tools().Copy()).Assert().IsNot(originalHash), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void GetHashCode_NullIsValid() + { + ReferenceComparer.Use.Assert(x => x.GetHashCode(null)).ThrowsNo(); + } + + [Theory, RandomData] + internal static void Compare_UsesReferenceValue(DataSample data, [Copy] DataSample dupe) + { + ReferenceComparer.Use.Compare(data, data).Assert().Is(0); + ReferenceComparer.Use.Compare(data, dupe).Assert().IsNot(0); + } +} diff --git a/tests/Design.Tests/Comparisons/ValueComparerTests.cs b/tests/Design.Tests/Comparisons/ValueComparerTests.cs new file mode 100644 index 00000000..0e5b373d --- /dev/null +++ b/tests/Design.Tests/Comparisons/ValueComparerTests.cs @@ -0,0 +1,156 @@ +using System.Collections; +using System.Drawing; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Comparisons; + +#pragma warning disable CA1859 // False positive; needed for generic resolution. + +public sealed class ValueComparerTests : AutoTester +{ + protected override ValueComparer TestInstance { get; } = ValueComparer.Use; + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ArgumentOutOfRangeException), + typeof(IterationLimitException), + ], + }; + + [Theory, RandomData] + internal static void Equals_MismatchSizeFalse( + [Size(1)] int[] oneValue, + [Size(2)] int[] twoValues + ) + { + ValueComparer.Use.Equals(oneValue, twoValues).Assert().Is(false); + ValueComparer.Use.Equals(twoValues, oneValue).Assert().Is(false); + ValueComparer.Use.Equals(twoValues.Take(1), twoValues).Assert().Is(false); + ValueComparer.Use.Equals(twoValues, twoValues.Take(1)).Assert().Is(false); + } + + [Theory, RandomData] + internal static void GetHashCode_SupportsParams([Size(3)] List items) + { + Tools.Asserter.Is( + ValueComparer.Use.GetHashCode(items), + ValueComparer.Use.GetHashCode(items[0], items[1], items[2]) + ); + } + + [Theory, RandomData] + internal static void Equals_SupportsValueEquatable( + [Fake] IValueEquatable stub1, + [Fake] IValueEquatable stub2, + bool result + ) + { + stub1.ValuesEqual(stub2).SetupReturn(result); + stub2.ValuesEqual(stub1).SetupReturn(result); + + ValueComparer.Use.Equals(stub1, stub2).Assert().Is(result); + ValueComparer.Use.Equals((object)stub1, stub2).Assert().Is(result); + } + + [Theory, RandomData] + internal static void Equals_SupportsValueEquatableNulls( + [Fake] IValueEquatable stub, + bool result + ) + { + stub.ValuesEqual(null).SetupReturn(result, 2); + ValueComparer.Use.Equals(stub, null).Assert().Is(result); + ValueComparer.Use.Equals(null, stub).Assert().Is(result); + ValueComparer.Use.Equals((IValueEquatable)null, null).Assert().Is(true); + stub.Assert().Called(); + } + + [Theory, RandomData] + internal static void GetHashCode_SupportsValueEquatable([Fake] IValueEquatable stub, int hash) + { + stub.GetValueHash().SetupReturn(hash, 2); + ValueComparer.Use.GetHashCode(stub).Assert().Is(hash); + ValueComparer.Use.GetHashCode((object)stub).Assert().Is(hash); + stub.Assert().Called(); + } + + [Fact] + internal static void ValueComparer_SupportsValueEquatable() + { + TestBehavior(ValueComparer.Use, ValueComparer.Use); + } + + [Fact] + internal static void ValueComparer_SupportsObject() + { + TestBehavior(ValueComparer.Use, ValueComparer.Use); + TestBehavior(ValueComparer.Use, ValueComparer.Use); + } + + [Fact] + internal static void ValueComparer_SupportsIEnumerable() + { + TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); + + TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); + } + + [Fact] + internal static void ValueComparer_SupportsIDictionary() + { + TestBehavior, IDictionary>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); + + TestBehavior, IDictionary>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); + + TestBehavior, IDictionary>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, IEnumerable>(ValueComparer.Use, ValueComparer.Use); + + TestBehavior, IDictionary>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, object>(ValueComparer.Use, ValueComparer.Use); + TestBehavior, IEnumerable>( + ValueComparer.Use, + ValueComparer.Use + ); + } + + private static void TestBehavior( + IComparer comparer, + IEqualityComparer equalityComparer + ) + where TActual : TComparer + { + TActual baseObject = Tools.Randomizer.Create(); + TActual equalObject = Tools.Duplicator.Copy(baseObject); + TActual unequalObject = Tools.Mutator.Variant(baseObject); + + Tools.Asserter.Is(true, equalityComparer.Equals(default, default)); + Tools.Asserter.Is(true, equalityComparer.Equals(baseObject, baseObject)); + Tools.Asserter.Is(true, equalityComparer.Equals(baseObject, equalObject)); + Tools.Asserter.Is(false, equalityComparer.Equals(baseObject, unequalObject)); + Tools.Asserter.Is(false, equalityComparer.Equals(baseObject, default)); + Tools.Asserter.Is(false, equalityComparer.Equals(default, baseObject)); + + Tools.Asserter.Is(0, comparer.Compare(default, default)); + Tools.Asserter.Is(0, comparer.Compare(baseObject, baseObject)); + Tools.Asserter.Is(0, comparer.Compare(baseObject, equalObject)); + Tools.Asserter.IsNot(0, comparer.Compare(baseObject, unequalObject)); + Tools.Asserter.IsNot(0, comparer.Compare(baseObject, default)); + Tools.Asserter.IsNot(0, comparer.Compare(default, baseObject)); + } +} + +#pragma warning restore diff --git a/tests/Design.Tests/Comparisons/ValueComparer{T}Tests.cs b/tests/Design.Tests/Comparisons/ValueComparer{T}Tests.cs new file mode 100644 index 00000000..365e5fa6 --- /dev/null +++ b/tests/Design.Tests/Comparisons/ValueComparer{T}Tests.cs @@ -0,0 +1,28 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Comparisons; + +public sealed class ValueComparer_T_Tests() : AutoTester(typeof(ValueComparer<>)) +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(IterationLimitException)] }; + + [Fact] + internal static Task ValueComparer_VerifyToolSupport() + { + return Tools.Tester.VerifyToolSetSupportAsync>( + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task ValueComparer_PassthroughWithNoExceptions() + { + return Tools.Tester.PassthroughWithNoExceptionsAsync( + ValueComparer.Use, + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Design.Tests/Content/AsyncHashSetTests.cs b/tests/Design.Tests/Content/AsyncHashSetTests.cs new file mode 100644 index 00000000..d98e0e7e --- /dev/null +++ b/tests/Design.Tests/Content/AsyncHashSetTests.cs @@ -0,0 +1,86 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public static class AsyncHashSetTests +{ + [Theory, RandomData] + internal static Task AsyncHashSet_GuardsNulls( + [Cap(6, 9)] int iterationLimit, + [Cap(7, 9)] int size + ) + { + return Tools.Tester.PreventsNullRefExceptionAsync( + typeof(AsyncHashSet), + TestContext.Current.CancellationToken, + opt => + opt with + { + InjectionValues = [iterationLimit, size], + IgnorableExceptions = [typeof(InvalidCastException)], + } + ); + } + + [Theory, RandomData] + internal static Task AsyncHashSet_NoParameterMutation( + [Cap(7, 9)] int iterationLimit, + [Cap(7, 9)] int size + ) + { + return Tools.Tester.PreventsParameterMutationAsync( + typeof(AsyncHashSet), + TestContext.Current.CancellationToken, + opt => + opt with + { + InjectionValues = [iterationLimit, size], + IgnorableExceptions = [typeof(InvalidCastException)], + } + ); + } + + [Theory, RandomData] + internal static Task CreateFromAsync_SetsInitialSyncContent(IEnumerable list) + { + AsyncHashSet set = AsyncHashSet.CreateFromAsync( + list, + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ); + + return set.Assert().IsAsync(list, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task CreateFromAsync_SetsInitialAsyncContent( + IAsyncEnumerable list + ) + { + AsyncHashSet set = AsyncHashSet.CreateFromAsync( + list, + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ); + + return set.Assert().IsAsync(list, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task CreateFromAsync_SameHashAdded(KeyValuePair pair) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + AsyncHashSet set = AsyncHashSet.CreateFromAsync( + AsyncSeriesHelper.CreateFromAsync([pair, pair], 2), + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + canceler + ); + + return set.Assert().HasCountAsync(2, canceler); + } +} diff --git a/tests/Design.Tests/Content/AsyncHashSet{T}Tests.cs b/tests/Design.Tests/Content/AsyncHashSet{T}Tests.cs new file mode 100644 index 00000000..a96b73fa --- /dev/null +++ b/tests/Design.Tests/Content/AsyncHashSet{T}Tests.cs @@ -0,0 +1,376 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public static class AsyncHashSet_T_Tests +{ + [Fact] + internal static void Debug_AsyncHashSet_T_ToString() + { + Tools.Randomizer.Create(typeof(AsyncHashSet<>)).Assert().Debug(); + } + + [Theory, RandomData] + internal static void Debug_AsyncHashSet_T_CompletedToString( + AsyncHashSet sample + ) + { + sample.ToString().Assert().Debug(); + } + + [Fact] + internal static void Debug_AsyncHashSet_T_EmptyToString() + { + new AsyncHashSet(Tools.Valuer.ToAsyncComparer()) + .ToString() + .Assert() + .Debug(); + } + + [Theory, RandomData] + internal static void Debug_AsyncHashSet_T_UncompletedToString(IList sample) + { + CancellationToken ct = TestContext.Current.CancellationToken; + + async IAsyncEnumerable slowlyIterate() + { + foreach (AsyncDataSample item in sample) + { + await Task.Delay(3000, ct); + yield return item; + } + } + + using CancellationTokenSource source = new(); + + AsyncHashSet + .CreateFromAsync( + slowlyIterate(), + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ) + .ToString() + .Assert() + .Debug(); + } + + [Theory, RandomData] + internal static Task Debug_AsyncHashSet_T_EnumerateString(AsyncHashSet sample) + { + return sample.Assert().DebugAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task AsyncHashSet_T_GuardsNulls() + { + return Tools.Tester.PreventsNullRefExceptionAsync( + typeof(AsyncHashSet<>).Tools().CreateRandomInstance(), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task AsyncHashSet_T_NoParameterMutation() + { + return Tools.Tester.PreventsParameterMutationAsync( + typeof(AsyncHashSet<>).Tools().CreateRandomInstance(), + TestContext.Current.CancellationToken, + opt => opt with { MethodsToIgnore = [nameof(AsyncHashSet<>.AddToAsync)] } + ); + } + + [Theory, RandomData] + internal static Task AsyncHashSet_T_AttributeSupport( + AsyncHashSet sample, + [Copy] AsyncHashSet clone, + AsyncHashSet variant + ) + { + return sample + .Assert() + .IsAsync(clone, TestContext.Current.CancellationToken) + .And() + .IsNotAsync(variant, TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task GetAsyncEnumerator_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + size => + AsyncHashSet.CreateFromAsync( + Tools.Randomizer.CreateSized>(size), + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task ByHashesAsync_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + (size, canceler) => + Tools + .Randomizer.CreateSized>(size) + .ByHashesAsync(canceler), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task FindMatchesInAsync_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + (size, canceler) => + { + IEnumerable series = + Tools.Randomizer.CreateSized(size); + + AsyncHashSet setA = AsyncHashSet.CreateFromAsync( + series, + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ); + AsyncHashSet setB = AsyncHashSet.CreateFromAsync( + series, + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ); + + return setA.FindMatchesInAsync(setB, canceler); + }, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task FindMissingFromAsync_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + (size, canceler) => + { + IEnumerable series = + Tools.Randomizer.CreateSized(size); + + AsyncHashSet setA = AsyncHashSet.CreateFromAsync( + [], + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ); + AsyncHashSet setB = AsyncHashSet.CreateFromAsync( + series, + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ); + + return setA.FindMissingFromAsync(setB, canceler); + }, + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static async Task ContainsAsync_UsesObjectByValue( + AsyncDataSample original, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken ct = TestContext.Current.CancellationToken; + + AsyncHashSet set = AsyncHashSet.CreateFromAsync( + [original], + Tools.Valuer.ToAsyncComparer(), + Tools.Valuer.Options.Design.IterationLimit, + ct + ); + + await set.ContainsKeyAsync(await Tools.Valuer.GetHashCodeAsync(clone, ct), ct) + .Assert() + .HasResultAsync(true, ct); + + await set.ContainsAsync(clone, ct).Assert().HasResultAsync(true, ct); + + await set.ContainsAsync(variant, ct).Assert().HasResultAsync(false, ct); + } + + [Theory, RandomData] + internal static async Task ContainsAsync_SameValueHashOkay( + [Stub] IAsyncEqualityComparer comparer, + AsyncDataSample original, + [Copy] AsyncDataSample clone, + AsyncDataSample variant, + int valueHash, + int otherHash + ) + { + CancellationToken ct = TestContext.Current.CancellationToken; + + comparer + .GetHashCodeAsync(Arg.Any(), Arg.Any()) + .SetupReturn(Task.FromResult(valueHash)); + comparer + .EqualsAsync( + Arg.Any(), + Arg.Any(), + Arg.Any() + ) + .SetupReturn( + Behavior.Call( + (AsyncDataSample x, AsyncDataSample y, CancellationToken t) => + Tools.Valuer.EqualsAsync(x, y, t) + ) + ); + + AsyncHashSet set = new(comparer); + + await set.ContainsAsync(original, ct).Assert().HasResultAsync(false, ct); + await set.AddAsync(original, ct).Assert().HasResultAsync(true, ct); + await set.ContainsAsync(original, ct).Assert().HasResultAsync(true, ct); + + await set.ContainsAsync(clone, ct).Assert().HasResultAsync(true, ct); + await set.AddAsync(clone, ct).Assert().HasResultAsync(false, ct); + + await set.ContainsAsync(new KeyValuePair(valueHash, variant), ct) + .Assert() + .HasResultAsync(false, ct); + + await set.ContainsAsync(variant, ct).Assert().HasResultAsync(false, ct); + await set.AddAsync(variant, ct).Assert().HasResultAsync(true, ct); + await set.ContainsAsync(variant, ct).Assert().HasResultAsync(true, ct); + + await set.ContainsAsync(new KeyValuePair(otherHash, original), ct) + .Assert() + .HasResultAsync(false, ct); + await set.ContainsAsync(new KeyValuePair(valueHash, original), ct) + .Assert() + .HasResultAsync(true, ct); + await set.ContainsAsync(original, ct).Assert().HasResultAsync(true, ct); + } + + [Theory, RandomData] + public static Task FindMatchesInAsync_FindsMatches( + AsyncDataSample sampleA, + AsyncDataSample sampleB, + AsyncDataSample sampleC, + AsyncDataSample sampleD, + AsyncDataSample sampleE, + AsyncDataSample sampleF, + int hashABC, + int hashD, + int hashE, + int hashF + ) + { + CancellationToken ct = TestContext.Current.CancellationToken; + + List shared = [sampleA, sampleD]; + + AsyncHashSet set1 = AsyncHashSet.CreateFromAsync( + AsyncSeriesHelper.CreateFromAsync( + [ + new KeyValuePair(hashABC, sampleA), + new KeyValuePair(hashABC, sampleB), + new KeyValuePair(hashD, sampleD), + new KeyValuePair(hashE, sampleE), + ], + 5 + ), + Tools.Valuer.ToAsyncComparer(), + 5, + ct + ); + + AsyncHashSet set2 = AsyncHashSet.CreateFromAsync( + AsyncSeriesHelper.CreateFromAsync( + [ + new KeyValuePair(hashABC, sampleA), + new KeyValuePair(hashABC, sampleC), + new KeyValuePair(hashD, sampleD), + new KeyValuePair(hashF, sampleF), + ], + 5 + ), + Tools.Valuer.ToAsyncComparer(), + 5, + ct + ); + + return set1.FindMatchesInAsync(set2, ct).Assert().IsAsync(shared, ct); + } + + [Theory, RandomData] + public static Task FindMissingFromAsync_FindsMissing( + AsyncDataSample sampleA, + AsyncDataSample sampleB, + AsyncDataSample sampleC, + AsyncDataSample sampleD, + AsyncDataSample sampleE, + AsyncDataSample sampleF, + int hashABC, + int hashD, + int hashE, + int hashF + ) + { + CancellationToken ct = TestContext.Current.CancellationToken; + + List missing1 = [sampleC, sampleF]; + List missing2 = [sampleB, sampleE]; + + AsyncHashSet set1 = AsyncHashSet.CreateFromAsync( + AsyncSeriesHelper.CreateFromAsync( + [ + new KeyValuePair(hashABC, sampleA), + new KeyValuePair(hashABC, sampleB), + new KeyValuePair(hashD, sampleD), + new KeyValuePair(hashE, sampleE), + ], + 5 + ), + Tools.Valuer.ToAsyncComparer(), + 5, + ct + ); + + AsyncHashSet set2 = AsyncHashSet.CreateFromAsync( + AsyncSeriesHelper.CreateFromAsync( + [ + new KeyValuePair(hashABC, sampleA), + new KeyValuePair(hashABC, sampleC), + new KeyValuePair(hashD, sampleD), + new KeyValuePair(hashF, sampleF), + ], + 5 + ), + Tools.Valuer.ToAsyncComparer(), + 5, + ct + ); + + return set1.FindMissingFromAsync(set2, ct) + .Assert() + .IsAsync(missing1, ct) + .Also(() => set2.FindMissingFromAsync(set1, ct)) + .IsAsync(missing2, ct); + } + + [Fact] + internal static Task GetAsyncEnumerator_EmptyWorks() + { + return new AsyncHashSet(Tools.Valuer.ToAsyncComparer()) + .Assert() + .HasCountAsync(0, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Design.Tests/Content/AsyncListTests.cs b/tests/Design.Tests/Content/AsyncListTests.cs new file mode 100644 index 00000000..d1fe4683 --- /dev/null +++ b/tests/Design.Tests/Content/AsyncListTests.cs @@ -0,0 +1,48 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class AsyncListTests() : AutoTester(typeof(AsyncList<>)) +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { InjectionValues = [Tools.Gen.Next(6, 9)] }; + + [Theory, RandomData] + internal static Task AsyncList_AttributeSupport( + AsyncList sample, + [Copy] AsyncList clone, + AsyncList variant + ) + { + return sample + .Assert() + .IsAsync(clone, TestContext.Current.CancellationToken) + .And() + .IsNotAsync(variant, TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task GetAsyncEnumerator_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + size => new AsyncList( + Tools.Randomizer.CreateSized>(size), + size + ), + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static async Task GetAsyncEnumerator_Repeatable(IReadOnlyCollection sample) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + AsyncList instance = new(sample, Tools.Valuer.Options.Design.IterationLimit); + + await instance.Assert().IsAsync(sample, canceler); + await instance.Assert().IsAsync(sample, canceler); + await instance.Assert().HasCountAsync(sample.Count, canceler); + } +} diff --git a/tests/Design.Tests/Content/AsyncSeriesHelperTests.cs b/tests/Design.Tests/Content/AsyncSeriesHelperTests.cs new file mode 100644 index 00000000..dfdf8c80 --- /dev/null +++ b/tests/Design.Tests/Content/AsyncSeriesHelperTests.cs @@ -0,0 +1,461 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Properties; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public static class AsyncSeriesHelperTests +{ + [Theory, RandomData] + internal static Task AsyncSeriesHelper_GuardsNulls([Cap(6, 9)] int iterationLimit) + { + return Tools.Tester.PreventsNullRefExceptionAsync( + typeof(AsyncSeriesHelper), + TestContext.Current.CancellationToken, + opt => opt with { InjectionValues = [iterationLimit] } + ); + } + + [Theory, RandomData] + internal static Task AsyncSeriesHelper_NoParameterMutation([Cap(6, 9)] int iterationLimit) + { + return Tools.Tester.PreventsParameterMutationAsync( + typeof(AsyncSeriesHelper), + TestContext.Current.CancellationToken, + opt => + opt with + { + InjectionValues = [iterationLimit], + IgnorableExceptions = [typeof(IterationLimitException)], + MethodsToIgnore = + [ + nameof(AsyncSeriesHelper.CreateCancelingIterationAsync), + nameof(AsyncSeriesHelper.TriggerCancellationAsync), + ], + } + ); + } + + [Fact] + internal static Task CreateFromAsync_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + size => + AsyncSeriesHelper.CreateFromAsync( + Tools.Randomizer.CreateSized(size), + size + ), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task SelectAsync_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + (size, canceler) => + AsyncSeriesHelper.SelectAsync( + Tools.Randomizer.CreateSized>(size), + size, + canceler, + item => item[0] + ), + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static Task CreateFromAsync_ConvertsObjectsSuccessfully(IList data) + { + return AsyncSeriesHelper + .CreateFromAsync(data, data.Count) + .Assert() + .IsAsync(data, TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task HasAnyAsync_FalseWhenGivenNull() + { + return AsyncSeriesHelper + .HasAnyAsync(null, TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(false), TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task HasAnyAsync_FalseWithNoValues([Size(0)] IAsyncEnumerable data) + { + return AsyncSeriesHelper + .HasAnyAsync(data, TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(false), TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task HasAnyAsync_TrueWithValues(IAsyncEnumerable data) + { + return AsyncSeriesHelper + .HasAnyAsync(data, TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(true), TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task HasAnyAsync_CanBeCanceledInitially([Size(0)] IAsyncEnumerable data) + { + return AsyncSeriesHelper + .HasAnyAsync(data, new CancellationToken(true)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task HasAnyAsync_CanBeCanceledAtIteration() + { + using CancellationTokenSource source = new(); + + await AsyncSeriesHelper + .HasAnyAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(source), + source.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task HasNoneAsync_TrueWhenGivenNull() + { + return AsyncSeriesHelper + .HasNoneAsync(null, TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(true), TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task HasNoneAsync_TrueWithNoValues([Size(0)] IAsyncEnumerable data) + { + return AsyncSeriesHelper + .HasNoneAsync(data, TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(true), TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task HasNoneAsync_FalseWithValues(IAsyncEnumerable data) + { + return AsyncSeriesHelper + .HasNoneAsync(data, TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(false), TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task HasNoneAsync_CanBeCanceledInitially( + [Size(0)] IAsyncEnumerable data + ) + { + return AsyncSeriesHelper + .HasNoneAsync(data, new CancellationToken(true)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task HasNoneAsync_CanBeCanceledAtIteration() + { + using CancellationTokenSource source = new(); + + await AsyncSeriesHelper + .HasNoneAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(source), + source.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task ForEachAsync_IteratesSuccessfully( + [Size(2)] IAsyncEnumerable data + ) + { + List results = []; + await AsyncSeriesHelper.ForEachAsync(data, 2, new CancellationToken(false), results.Add); + await results.Assert().IsAsync(data, TestContext.Current.CancellationToken); + + results.Clear(); + await AsyncSeriesHelper.ForEachAsync( + data, + 2, + new CancellationToken(false), + v => + { + results.Add(v); + return Task.CompletedTask; + } + ); + await results.Assert().IsAsync(data, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task ForEachAsync_HasIterationLimit( + [Size(2)] IAsyncEnumerable data + ) + { + await AsyncSeriesHelper + .ForEachAsync(data, 1, new CancellationToken(false), _ => { }) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + await AsyncSeriesHelper + .ForEachAsync(data, 1, new CancellationToken(false), _ => Task.CompletedTask) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task ForEachAsync_CanBeCanceledInitially( + [Size(0)] IAsyncEnumerable data + ) + { + await AsyncSeriesHelper + .ForEachAsync(data, 0, new CancellationToken(true), _ => { }) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + await AsyncSeriesHelper + .ForEachAsync(data, 0, new CancellationToken(true), _ => Task.CompletedTask) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task ForEachAsync_CanBeCanceledAtIteration() + { + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .ForEachAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(source), + 10, + source.Token, + _ => { } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource source2 = new(); + await AsyncSeriesHelper + .ForEachAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(source2), + 10, + source.Token, + _ => Task.CompletedTask + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task ForEachAsync_CanBeCanceledAfterIterating( + [Size(1)] ICollection data + ) + { + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .ForEachAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(data, source), + data.Count, + source.Token, + _ => { } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource source2 = new(); + await AsyncSeriesHelper + .ForEachAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(data, source2), + data.Count, + source.Token, + _ => Task.CompletedTask + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task SelectAsync_IteratesSuccessfully( + [Size(2)] IAsyncEnumerable data + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IList results = await AsyncSeriesHelper.ToListAsync( + AsyncSeriesHelper.SelectAsync(data, 2, new CancellationToken(false), item => item), + 2, + canceler + ); + await results.Assert().IsAsync(data, canceler); + + results = await AsyncSeriesHelper.ToListAsync( + AsyncSeriesHelper.SelectAsync( + data, + 2, + new CancellationToken(false), + v => Task.FromResult(v) + ), + 2, + canceler + ); + await results.Assert().IsAsync(data, canceler); + } + + [Theory, RandomData] + internal static async Task SelectAsync_HasIterationLimit( + [Size(2)] IAsyncEnumerable data + ) + { + await AsyncSeriesHelper + .SelectAsync(data, 1, new CancellationToken(false), x => x) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + await AsyncSeriesHelper + .SelectAsync(data, 1, new CancellationToken(false), x => Task.FromResult(x)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task ToListAsync_ConvertsValues(IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert() + .IsAsync( + await AsyncSeriesHelper.ToListAsync(data, DesignDefaults.IterationLimit, canceler), + canceler + ); + } + + [Theory, RandomData] + internal static Task ToListAsync_CanBeCanceledInitially([Size(0)] IAsyncEnumerable data) + { + return AsyncSeriesHelper + .ToListAsync(data, 0, new CancellationToken(true)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task ToListAsync_CanBeCanceledAtIteration() + { + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .ToListAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(source), + DesignDefaults.IterationLimit, + source.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task ToListAsync_CanBeCanceledDuringIteration( + [Size(2)] IEnumerable data + ) + { + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .ToListAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(data, source), + 2, + source.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task ToListAsync_CanBeCanceledAfterIterating( + [Size(1)] IEnumerable data + ) + { + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .ToListAsync( + AsyncSeriesHelper.CreateCancelingIterationAsync(data, source), + 1, + source.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task CreateCancelingIterationAsync_EmptyCancelsAtIteration() + { + using CancellationTokenSource source = new(); + await foreach ( + string _ in AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .WithCancellation(TestContext.Current.CancellationToken) + ) + { + source.Assert().Fail(); + } + source.IsCancellationRequested.Assert().Is(true); + } + + [Theory, RandomData] + internal static async Task CreateCancelingIterationAsync_OnlyYieldCancelsAfterIteration( + [Size(1)] IEnumerable data + ) + { + using CancellationTokenSource source = new(); + await foreach ( + string _ in AsyncSeriesHelper + .CreateCancelingIterationAsync(data, source) + .WithCancellation(TestContext.Current.CancellationToken) + ) + { + source.IsCancellationRequested.Assert().Is(false); + } + source.IsCancellationRequested.Assert().Is(true); + } + + [Theory, RandomData] + internal static async Task CreateCancelingIterationAsync_MultipleYieldCancelsDuringIteration( + [Size(2)] IEnumerable data + ) + { + using CancellationTokenSource source = new(); + int i = 0; + await foreach ( + string _ in AsyncSeriesHelper + .CreateCancelingIterationAsync(data, source) + .WithCancellation(TestContext.Current.CancellationToken) + ) + { + if (i++ == 0) + { + source.IsCancellationRequested.Assert().Is(false); + } + else + { + source.IsCancellationRequested.Assert().Is(true); + } + } + i.Assert().Is(2); + } + + [Fact] + internal static async Task TriggerCancellationAsync_Cancels() + { + using CancellationTokenSource source = new(); + await AsyncSeriesHelper.TriggerCancellationAsync(source); + source.IsCancellationRequested.Assert().Is(true); + } +} diff --git a/tests/Design.Tests/Content/AsyncSeriesHelper{T}Tests.cs b/tests/Design.Tests/Content/AsyncSeriesHelper{T}Tests.cs new file mode 100644 index 00000000..0e842085 --- /dev/null +++ b/tests/Design.Tests/Content/AsyncSeriesHelper{T}Tests.cs @@ -0,0 +1,32 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class AsyncSeriesHelper_T_Tests() : AutoTester(typeof(AsyncSeriesHelper<>)) +{ + [Fact] + internal static void Empty_Cached() + { + Tools.Asserter.ReferenceEqual( + AsyncSeriesHelper.Empty, + AsyncSeriesHelper.Empty + ); + } + + [Fact] + internal static Task Empty_IsEmpty() + { + return AsyncSeriesHelper + .Empty.Assert() + .IsEmptyAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task Empty_DefaultCurrent() + { + await using IAsyncEnumerator series = AsyncSeriesHelper.Empty.GetAsyncEnumerator( + TestContext.Current.CancellationToken + ); + series.Current.Assert().Is(default(int)); + } +} diff --git a/tests/Design.Tests/Content/CustomLockTests.cs b/tests/Design.Tests/Content/CustomLockTests.cs new file mode 100644 index 00000000..a056874f --- /dev/null +++ b/tests/Design.Tests/Content/CustomLockTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class CustomLockTests : AutoTester +{ + [Fact] + internal static void CustomLock_Sealed() + { + typeof(CustomLock).IsSealed.Assert().Is(true); + } +} diff --git a/tests/Design.Tests/Content/DisposerTests.cs b/tests/Design.Tests/Content/DisposerTests.cs new file mode 100644 index 00000000..6fa67aab --- /dev/null +++ b/tests/Design.Tests/Content/DisposerTests.cs @@ -0,0 +1,53 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class DisposerTests() : AutoTester(typeof(Disposer)) +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { DisableParameterMutationTests = true }; + + [Theory, RandomData] + internal static void Cleanup_DisposesAllItems( + [Stub] IDisposable item1, + [Stub] IDisposable item2 + ) + { + item1.SetupReturn(m => m.Dispose(), Behavior.None(Times.Once)); + item2.SetupReturn(m => m.Dispose(), Behavior.None(Times.Once)); + + Disposer.Cleanup(item1, new object(), item2, ""); + + item1.Assert().Called().Also(item2).Called(); + } + + [Theory, RandomData] + internal static async Task CleanupAsync_DisposesAllItems( + [Stub] IDisposable item1, + [Stub] IAsyncDisposable item2 + ) + { + item1.SetupReturn(m => m.Dispose(), Behavior.None(Times.Once)); + item2 + .Tools() + .ToFake() + .Setup(m => m.DisposeAsync(), Behavior.Returns(default, Times.Once)); + + await Disposer.CleanupAsync(item1, new object(), item2, ""); + + item1.Assert().Called().Also(item2).Called(); + } + + [Fact] + internal static async Task CleanupAsync_PrioritizesAsync() + { + Fake item = Tools.Faker.Mock(typeof(IDisposable)); + item.Setup(m => m.DisposeAsync(), Behavior.Returns(default, Times.Once)); + + await Disposer.CleanupAsync(item.Dummy); + + item.Verify(); + } +} diff --git a/tests/Design.Tests/Content/ExcludeFromCreateAndFakeAttributeTests.cs b/tests/Design.Tests/Content/ExcludeFromCreateAndFakeAttributeTests.cs new file mode 100644 index 00000000..af5def91 --- /dev/null +++ b/tests/Design.Tests/Content/ExcludeFromCreateAndFakeAttributeTests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class ExcludeFromCreateAndFakeAttributeTests + : AutoTester; diff --git a/tests/Design.Tests/Content/InvokerTests.cs b/tests/Design.Tests/Content/InvokerTests.cs new file mode 100644 index 00000000..8f468709 --- /dev/null +++ b/tests/Design.Tests/Content/InvokerTests.cs @@ -0,0 +1,24 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class InvokerTests() : AutoTester(typeof(Invoker)) +{ + [Theory, RandomData] + internal static Task AwaitAsync_HandlesGenericTasks(string data) + { + return Invoker + .AwaitAsync(Task.FromResult(data)) + .Assert() + .HasResultAsync(data, TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task AwaitAsync_HandlesTasks() + { + return Invoker + .AwaitAsync(Task.CompletedTask) + .Assert() + .HasResultAsync(VoidType.Instance, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Design.Tests/Content/MaybeAsyncCancelerTests.cs b/tests/Design.Tests/Content/MaybeAsyncCancelerTests.cs new file mode 100644 index 00000000..95308f47 --- /dev/null +++ b/tests/Design.Tests/Content/MaybeAsyncCancelerTests.cs @@ -0,0 +1,61 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public static class MaybeAsyncCancelerTests +{ + [Fact] + internal static Task MaybeAsyncCanceler_GuardsNulls() + { + return Tools.Tester.PreventsNullRefExceptionAsync( + MaybeAsyncCanceler.Use, + TestContext.Current.CancellationToken, + opt => opt with { IgnorableExceptions = [typeof(ArgumentException)] } + ); + } + + [Fact] + internal static Task MaybeAsyncCanceler_NoParameterMutation() + { + return Tools.Tester.PreventsParameterMutationAsync( + MaybeAsyncCanceler.Use, + TestContext.Current.CancellationToken, + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException)], + MethodsToIgnore = [nameof(MaybeAsyncCanceler.TriggerCancellationAsync)], + } + ); + } + + [Fact] + internal static void MaybeAsyncCanceler_InternalOnly() + { + typeof(MaybeAsyncCanceler).IsPublic.Assert().IsNot(true); + } + + [Fact] + internal static async Task TriggerCancellationAsync_Cancels() + { + using CancellationTokenSource source = new(); + await MaybeAsyncCanceler.Use.TriggerCancellationAsync(source); + source.IsCancellationRequested.Assert().Is(true); + } + + [Fact] + internal static async Task TriggerCancellationAsync_MultipleCancelSafe() + { + using CancellationTokenSource source = new(); + await MaybeAsyncCanceler.Use.TriggerCancellationAsync(source); + await MaybeAsyncCanceler.Use.TriggerCancellationAsync(source); + } + + [Fact] + internal static async Task TriggerCancellationAsync_SyncFallbackCancels() + { + using CancellationTokenSource source = new(); + await new MaybeAsyncCanceler(null).TriggerCancellationAsync(source); + source.IsCancellationRequested.Assert().Is(true); + } +} diff --git a/tests/Design.Tests/Content/PlainAsyncDisposableTests.cs b/tests/Design.Tests/Content/PlainAsyncDisposableTests.cs new file mode 100644 index 00000000..5b2314de --- /dev/null +++ b/tests/Design.Tests/Content/PlainAsyncDisposableTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class PlainAsyncDisposableTests : AutoTester +{ + [Theory, RandomData] + internal static async Task GrabData_ThrowsWhenDisposed(PlainAsyncDisposable sample) + { + await sample.DisposeAsync(); + sample.Assert(x => x.GrabData()).Throws(); + } +} diff --git a/tests/Design.Tests/Content/SingleCallValueTaskSourceTests.cs b/tests/Design.Tests/Content/SingleCallValueTaskSourceTests.cs new file mode 100644 index 00000000..3e353084 --- /dev/null +++ b/tests/Design.Tests/Content/SingleCallValueTaskSourceTests.cs @@ -0,0 +1,41 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class SingleCallValueTaskSourceTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(NotSupportedException)] }; + + [Theory, RandomData] + internal static async Task GetResult_Prevents2ndAwait( + SingleCallValueTaskSource source, + short token + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ValueTask task = new(source, token); + await task.Assert().ThrowsNoAsync(canceler); + await task.Assert().ThrowsAsync(canceler); + } + + [Theory, RandomData] + internal static Task ExtractFrom_ValidWithSource(SingleCallValueTaskSource source, short token) + { + ValueTask task = new(source, token); + SingleCallValueTaskSource.ExtractFrom(task).Assert().Is(source); + SingleCallValueTaskSource.ExtractTokenFrom(task).Assert().Is(token); + return task.Assert().ThrowsNoAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task ExtractFrom_NullWithoutSource() + { + ValueTask task = new(Task.CompletedTask); + SingleCallValueTaskSource.ExtractFrom(task).Assert().IsNull(); + return task.Assert().ThrowsNoAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/Design.Tests/Content/SingleCallValueTaskSource{T}Tests.cs b/tests/Design.Tests/Content/SingleCallValueTaskSource{T}Tests.cs new file mode 100644 index 00000000..2ca932c6 --- /dev/null +++ b/tests/Design.Tests/Content/SingleCallValueTaskSource{T}Tests.cs @@ -0,0 +1,44 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class SingleCallValueTaskSource_T_Tests() + : AutoTester(typeof(SingleCallValueTaskSource<>)) +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(NotSupportedException)] }; + + [Theory, RandomData] + internal static async Task GetResult_Prevents2ndAwait( + SingleCallValueTaskSource source, + short token + ) + { + ValueTask task = new(source, token); + await task.Assert().HasResultAsync(TestContext.Current.CancellationToken); + await task.Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task ExtractFrom_ValidWithSource( + SingleCallValueTaskSource source, + short token + ) + { + ValueTask task = new(source, token); + SingleCallValueTaskSource.ExtractFrom(task).Assert().Is(source); + SingleCallValueTaskSource.ExtractTokenFrom(task).Assert().Is(token); + return task.Assert().ThrowsNoAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task ExtractFrom_NullWithoutSource(string data) + { + ValueTask task = new(data); + SingleCallValueTaskSource.ExtractFrom(task).Assert().IsNull(); + return task.Assert().HasResultAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/Design.Tests/Content/VoidTypeTests.cs b/tests/Design.Tests/Content/VoidTypeTests.cs new file mode 100644 index 00000000..a1bf6811 --- /dev/null +++ b/tests/Design.Tests/Content/VoidTypeTests.cs @@ -0,0 +1,23 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Content; + +public sealed class VoidTypeTests : AutoTester +{ + [Fact] + internal static void VoidType_PrivateConstructor() + { + ConstructorInfo constructor = TypeDescriber.For().Constructors.All.Single(); + + constructor.IsPrivate.Assert().Is(true); + constructor.Invoke([]).Assert().Pass(); + } + + [Fact] + internal static void Instance_Singleton() + { + VoidType.Instance.Assert().ReferenceEqual(VoidType.Instance); + } +} diff --git a/tests/Design.Tests/Context/BaseDataContextTestBase.cs b/tests/Design.Tests/Context/BaseDataContextTestBase.cs new file mode 100644 index 00000000..06c31c36 --- /dev/null +++ b/tests/Design.Tests/Context/BaseDataContextTestBase.cs @@ -0,0 +1,24 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Context; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Context; + +public abstract class BaseDataContextTestBase : AutoTester + where T : BaseDataContext +{ + [Theory, RandomData] + public void BaseDataContext_MaintainsValues(T testInstance) + { + foreach (PropertyInfo prop in TypeDescriber.For().Properties.All) + { + prop.GetValue(testInstance).Assert().Is(prop.GetValue(testInstance)); + } + } + + [Theory, RandomData] + public void BaseDataContext_DataVaries(T testInstance, T variant) + { + variant.Assert().IsNot(testInstance); + } +} diff --git a/tests/Design.Tests/Context/PersonContextTests.cs b/tests/Design.Tests/Context/PersonContextTests.cs new file mode 100644 index 00000000..b9d4f3d3 --- /dev/null +++ b/tests/Design.Tests/Context/PersonContextTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Context; + +namespace Werecodent.CreateAndFake.Design.Tests.Context; + +public sealed class PersonContextTests : BaseDataContextTestBase; diff --git a/tests/Design.Tests/CreateAndFake.Design.Tests.csproj b/tests/Design.Tests/CreateAndFake.Design.Tests.csproj new file mode 100644 index 00000000..9c473a8e --- /dev/null +++ b/tests/Design.Tests/CreateAndFake.Design.Tests.csproj @@ -0,0 +1,31 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + exe + + + + + + + + + + + + + + + + + + + diff --git a/tests/Design.Tests/Data/NameDataTests.cs b/tests/Design.Tests/Data/NameDataTests.cs new file mode 100644 index 00000000..90e4026d --- /dev/null +++ b/tests/Design.Tests/Data/NameDataTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Data; + +namespace Werecodent.CreateAndFake.Design.Tests.Data; + +public sealed class NameDataTests() : AutoTester(typeof(NameData)) +{ + [Fact] + internal static void Values_Populated() + { + NameData.Values.Assert().IsNotEmpty(); + } +} diff --git a/tests/Design.Tests/DesignTests.cs b/tests/Design.Tests/DesignTests.cs new file mode 100644 index 00000000..7c5d1127 --- /dev/null +++ b/tests/Design.Tests/DesignTests.cs @@ -0,0 +1,8 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests; + +public sealed class DesignTests : AssemblyTester +{ + protected override Assembly CodeAssembly { get; } = Assembly.GetAssembly(typeof(ArgumentGuard)); +} diff --git a/tests/Design.Tests/Exceptions/AsynchronousAccessExceptionTests.cs b/tests/Design.Tests/Exceptions/AsynchronousAccessExceptionTests.cs new file mode 100644 index 00000000..b70fcdc4 --- /dev/null +++ b/tests/Design.Tests/Exceptions/AsynchronousAccessExceptionTests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class AsynchronousAccessExceptionTests + : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/AutoTesterFailureExceptionTests.cs b/tests/Design.Tests/Exceptions/AutoTesterFailureExceptionTests.cs new file mode 100644 index 00000000..cec68705 --- /dev/null +++ b/tests/Design.Tests/Exceptions/AutoTesterFailureExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class AutoTesterFailureExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/BehaviorDefaultThrowExceptionTests.cs b/tests/Design.Tests/Exceptions/BehaviorDefaultThrowExceptionTests.cs new file mode 100644 index 00000000..48c4aad3 --- /dev/null +++ b/tests/Design.Tests/Exceptions/BehaviorDefaultThrowExceptionTests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class BehaviorDefaultThrowExceptionTests + : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/EngineExceptionTests.cs b/tests/Design.Tests/Exceptions/EngineExceptionTests.cs new file mode 100644 index 00000000..dfcbc4be --- /dev/null +++ b/tests/Design.Tests/Exceptions/EngineExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class EngineExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/ExceptionTestBase.cs b/tests/Design.Tests/Exceptions/ExceptionTestBase.cs new file mode 100644 index 00000000..4e94928a --- /dev/null +++ b/tests/Design.Tests/Exceptions/ExceptionTestBase.cs @@ -0,0 +1,36 @@ +using Werecodent.CreateAndFake.Design.Reiteration; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public abstract class ExceptionTestBase : AutoTester + where T : Exception +{ + [Theory, RandomData] + public void Debug_Exception_ToString(T error) + { + error.Assert().Debug(); + } + + [Fact] + public void Exception_DefaultConstructorPrivate() + { + typeof(T).GetConstructor(Type.EmptyTypes).Assert().IsNull(); + Activator.CreateInstance(typeof(T), true).Assert().IsNotNull(); + } + + [Fact] + public void Exception_XmlSerializes() + { + Tools.Tester.VerifyXmlSerialization(); + } + + [Fact] + public void Exception_JsonSerializes() + { + Limiter.Score.Retry( + "Not all System exceptions support json serialization.", + () => Tools.Tester.VerifyJsonSerialization(), + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Design.Tests/Exceptions/IterationLimitExceptionTests.cs b/tests/Design.Tests/Exceptions/IterationLimitExceptionTests.cs new file mode 100644 index 00000000..1093c8f5 --- /dev/null +++ b/tests/Design.Tests/Exceptions/IterationLimitExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class IterationLimitExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/MismatchedAccessExceptionTests.cs b/tests/Design.Tests/Exceptions/MismatchedAccessExceptionTests.cs new file mode 100644 index 00000000..5cb56124 --- /dev/null +++ b/tests/Design.Tests/Exceptions/MismatchedAccessExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class MismatchedAccessExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/RunnerMethodErrorExceptionTests.cs b/tests/Design.Tests/Exceptions/RunnerMethodErrorExceptionTests.cs new file mode 100644 index 00000000..399e1747 --- /dev/null +++ b/tests/Design.Tests/Exceptions/RunnerMethodErrorExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class RunnerMethodErrorExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/RunnerTimeoutException.cs b/tests/Design.Tests/Exceptions/RunnerTimeoutException.cs new file mode 100644 index 00000000..0b9851ea --- /dev/null +++ b/tests/Design.Tests/Exceptions/RunnerTimeoutException.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class RunnerTimeoutExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/TesterFailureExceptionTests.cs b/tests/Design.Tests/Exceptions/TesterFailureExceptionTests.cs new file mode 100644 index 00000000..26a1552f --- /dev/null +++ b/tests/Design.Tests/Exceptions/TesterFailureExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class TesterFailureExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/ToolExceptionTests.cs b/tests/Design.Tests/Exceptions/ToolExceptionTests.cs new file mode 100644 index 00000000..0cf8116a --- /dev/null +++ b/tests/Design.Tests/Exceptions/ToolExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class ToolExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/UnsupportedExceptionTests.cs b/tests/Design.Tests/Exceptions/UnsupportedExceptionTests.cs new file mode 100644 index 00000000..1676abc6 --- /dev/null +++ b/tests/Design.Tests/Exceptions/UnsupportedExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class UnsupportedExceptionTests : ExceptionTestBase; diff --git a/tests/Design.Tests/Exceptions/ValueTaskRepeatedAccessExceptionTests.cs b/tests/Design.Tests/Exceptions/ValueTaskRepeatedAccessExceptionTests.cs new file mode 100644 index 00000000..590396ee --- /dev/null +++ b/tests/Design.Tests/Exceptions/ValueTaskRepeatedAccessExceptionTests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Design.Tests.Exceptions; + +public sealed class ValueTaskRepeatedAccessExceptionTests + : ExceptionTestBase; diff --git a/tests/Design.Tests/Extensions/TypeExtensionsTests.cs b/tests/Design.Tests/Extensions/TypeExtensionsTests.cs new file mode 100644 index 00000000..c6990552 --- /dev/null +++ b/tests/Design.Tests/Extensions/TypeExtensionsTests.cs @@ -0,0 +1,70 @@ +using Werecodent.CreateAndFake.Design.Extensions; + +namespace Werecodent.CreateAndFake.Design.Tests.Extensions; + +public sealed class TypeExtensionsTests() : AutoTester(typeof(TypeExtensions)) +{ + [Fact] + internal static void Inherits_StandardInheritanceWorks() + { + typeof(string).Inherits>().Assert().Is(true); + typeof(IEnumerable).Inherits().Assert().Is(false); + + typeof(string).Inherits(typeof(IEnumerable)).Assert().Is(true); + typeof(IEnumerable).Inherits(typeof(string)).Assert().Is(false); + } + + [Fact] + internal static void Inherits_GenericsWork() + { + typeof(IEnumerable<>).Inherits().Assert().Is(false); + typeof(List<>).Inherits>().Assert().Is(false); + + typeof(string).Inherits(typeof(IEnumerable<>)).Assert().Is(true); + typeof(IEnumerable<>).Inherits(typeof(string)).Assert().Is(false); + typeof(List<>).Inherits(typeof(IList<>)).Assert().Is(true); + typeof(IList<>).Inherits(typeof(List<>)).Assert().Is(false); + typeof(List).Inherits(typeof(List<>)).Assert().Is(true); + typeof(List<>).Inherits(typeof(List)).Assert().Is(false); + } + + [Theory, RandomData] + internal static void Inherits_FalseWhenNull(Type type) + { + type.Inherits(null).Assert().Is(false); + TypeExtensions.Inherits(null).Assert().Is(false); + TypeExtensions.Inherits(null, type).Assert().Is(false); + } + + [Fact] + internal static void IsInheritedBy_StandardInheritanceWorks() + { + typeof(string).IsInheritedBy>().Assert().Is(false); + typeof(IEnumerable).IsInheritedBy().Assert().Is(true); + + typeof(string).IsInheritedBy(typeof(IEnumerable)).Assert().Is(false); + typeof(IEnumerable).IsInheritedBy(typeof(string)).Assert().Is(true); + } + + [Fact] + internal static void IsInheritedBy_GenericsWork() + { + typeof(IEnumerable<>).IsInheritedBy().Assert().Is(true); + typeof(List<>).IsInheritedBy>().Assert().Is(false); + + typeof(string).IsInheritedBy(typeof(IEnumerable<>)).Assert().Is(false); + typeof(IEnumerable<>).IsInheritedBy(typeof(string)).Assert().Is(true); + typeof(List<>).IsInheritedBy(typeof(IList<>)).Assert().Is(false); + typeof(IList<>).IsInheritedBy(typeof(List<>)).Assert().Is(true); + typeof(List).IsInheritedBy(typeof(List<>)).Assert().Is(false); + typeof(List<>).IsInheritedBy(typeof(List)).Assert().Is(true); + } + + [Theory, RandomData] + internal static void IsInheritedBy_FalseWhenNull(Type type) + { + type.IsInheritedBy(null).Assert().Is(false); + TypeExtensions.IsInheritedBy(null).Assert().Is(false); + TypeExtensions.IsInheritedBy(null, type).Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Nullable/DoesNotReturnAttributeTests.cs b/tests/Design.Tests/Nullable/DoesNotReturnAttributeTests.cs new file mode 100644 index 00000000..c0f6daef --- /dev/null +++ b/tests/Design.Tests/Nullable/DoesNotReturnAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Nullable; + +public static class DoesNotReturnAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("DoesNotReturnAttribute"); + + [Fact] + internal static Task DoesNotReturnAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task DoesNotReturnAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void DoesNotReturnAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Nullable/MaybeNullAttributeTests.cs b/tests/Design.Tests/Nullable/MaybeNullAttributeTests.cs new file mode 100644 index 00000000..1b9e1c86 --- /dev/null +++ b/tests/Design.Tests/Nullable/MaybeNullAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Nullable; + +public static class MaybeNullAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("MaybeNullAttribute"); + + [Fact] + internal static Task MaybeNullAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task MaybeNullAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void MaybeNullAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Nullable/NotNullAttributeTests.cs b/tests/Design.Tests/Nullable/NotNullAttributeTests.cs new file mode 100644 index 00000000..5ce7be27 --- /dev/null +++ b/tests/Design.Tests/Nullable/NotNullAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Nullable; + +public static class NotNullAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("NotNullAttribute"); + + [Fact] + internal static Task NotNullAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task NotNullAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void NotNullAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Nullable/NotNullIfNotNullAttributeTests.cs b/tests/Design.Tests/Nullable/NotNullIfNotNullAttributeTests.cs new file mode 100644 index 00000000..da706680 --- /dev/null +++ b/tests/Design.Tests/Nullable/NotNullIfNotNullAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Nullable; + +public static class NotNullIfNotNullAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("NotNullIfNotNullAttribute"); + + [Fact] + internal static Task NotNullIfNotNullAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task NotNullIfNotNullAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void NotNullIfNotNullAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Nullable/NotNullWhenAttributeTests.cs b/tests/Design.Tests/Nullable/NotNullWhenAttributeTests.cs new file mode 100644 index 00000000..af16673e --- /dev/null +++ b/tests/Design.Tests/Nullable/NotNullWhenAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Nullable; + +public static class NotNullWhenAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("NotNullWhenAttribute"); + + [Fact] + internal static Task NotNullWhenAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task NotNullWhenAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void NotNullWhenAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Properties/CallerArgumentExpressionAttributeTests.cs b/tests/Design.Tests/Properties/CallerArgumentExpressionAttributeTests.cs new file mode 100644 index 00000000..8e2534d9 --- /dev/null +++ b/tests/Design.Tests/Properties/CallerArgumentExpressionAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Properties; + +public static class CallerArgumentExpressionAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("CallerArgumentExpressionAttribute"); + + [Fact] + internal static Task CallerArgumentExpressionAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task CallerArgumentExpressionAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void CallerArgumentExpressionAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Properties/CompilerFeatureRequiredAttributeTests.cs b/tests/Design.Tests/Properties/CompilerFeatureRequiredAttributeTests.cs new file mode 100644 index 00000000..344ee708 --- /dev/null +++ b/tests/Design.Tests/Properties/CompilerFeatureRequiredAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Properties; + +public static class CompilerFeatureRequiredAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("CompilerFeatureRequiredAttribute"); + + [Fact] + internal static Task CompilerFeatureRequiredAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task CompilerFeatureRequiredAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void CompilerFeatureRequiredAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Properties/DesignDefaultsTests.cs b/tests/Design.Tests/Properties/DesignDefaultsTests.cs new file mode 100644 index 00000000..41ddbf3b --- /dev/null +++ b/tests/Design.Tests/Properties/DesignDefaultsTests.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Properties; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Properties; + +public sealed class DesignDefaultsTests() : AutoTester(typeof(DesignDefaults)) +{ + [Fact] + internal static void IterationLimit_DoubleObjectSubclassMinimum() + { + (2 * TypeDescriber.For().FindLoadedSubclasses().Count()) + .Assert() + .LessThan(DesignDefaults.IterationLimit); + } +} diff --git a/tests/Design.Tests/Properties/IsExternalInitTests.cs b/tests/Design.Tests/Properties/IsExternalInitTests.cs new file mode 100644 index 00000000..374f20a7 --- /dev/null +++ b/tests/Design.Tests/Properties/IsExternalInitTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Properties; + +public static class IsExternalInitTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("IsExternalInit"); + + [Fact] + internal static Task IsExternalInit_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task IsExternalInit_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void IsExternalInit_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Properties/RequiredMemberAttributeTests.cs b/tests/Design.Tests/Properties/RequiredMemberAttributeTests.cs new file mode 100644 index 00000000..343b0d41 --- /dev/null +++ b/tests/Design.Tests/Properties/RequiredMemberAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Properties; + +public static class RequiredMemberAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("RequiredMemberAttribute"); + + [Fact] + internal static Task RequiredMemberAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task RequiredMemberAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void RequiredMemberAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Properties/SetsRequiredMembersAttributeTests.cs b/tests/Design.Tests/Properties/SetsRequiredMembersAttributeTests.cs new file mode 100644 index 00000000..14aaa48a --- /dev/null +++ b/tests/Design.Tests/Properties/SetsRequiredMembersAttributeTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Design.Tests.Properties; + +public static class SetsRequiredMembersAttributeTests +{ + private static readonly Type _TestType = Assembly + .GetAssembly(typeof(ArgumentGuard)) + .GetType("SetsRequiredMembersAttribute"); + + [Fact] + internal static Task SetsRequiredMembersAttribute_GuardsNulls() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsNullRefExceptionAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task SetsRequiredMembersAttribute_NoParameterMutation() + { + return _TestType == null + ? Task.CompletedTask + : Tools.Tester.PreventsParameterMutationAsync( + _TestType, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void SetsRequiredMembersAttribute_InternalOnly() + { + _TestType?.IsPublic.Assert().IsNot(true); + } +} diff --git a/tests/Design.Tests/Randomization/BoundaryCheckerTests.cs b/tests/Design.Tests/Randomization/BoundaryCheckerTests.cs new file mode 100644 index 00000000..a1080334 --- /dev/null +++ b/tests/Design.Tests/Randomization/BoundaryCheckerTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization; + +public sealed class BoundaryCheckerTests() : AutoTester(typeof(BoundaryChecker)) +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + DisableNullRefExceptionTests = true, + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(InvalidCastException), + typeof(ArgumentOutOfRangeException), + ], + }; +} diff --git a/tests/Design.Tests/Randomization/DataRandomTests.cs b/tests/Design.Tests/Randomization/DataRandomTests.cs new file mode 100644 index 00000000..f482cf18 --- /dev/null +++ b/tests/Design.Tests/Randomization/DataRandomTests.cs @@ -0,0 +1,80 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization; + +public sealed class DataRandomTests : AutoTester +{ + [Theory, RandomData] + internal static void DataRandom_MaintainsValues(DataRandom testInstance) + { + foreach (PropertyInfo prop in TypeDescriber.For(typeof(DataRandom)).Properties.All) + { + prop.GetValue(testInstance).Assert().Is(prop.GetValue(testInstance)); + } + } + + [Theory, RandomData] + internal static void DataRandom_DataVaries(DataRandom testInstance, DataRandom variant) + { + variant.Assert().IsNot(testInstance); + } + + [Theory, RandomData] + internal static void Find_AllSearchable(DataRandom testInstance) + { + foreach (string item in DataRandom.SupportedProperties) + { + testInstance.Find(item).Assert().IsNotNull(); + } + } + + [Theory, RandomData] + internal static void Find_IgnoresSpecialChars(DataRandom testInstance) + { + testInstance + .Find("_" + Tools.Gen.NextItem(DataRandom.SupportedProperties)) + .Assert() + .IsNotNull(); + } + + [Theory, RandomData] + internal static void Find_NullWithMissingName(DataRandom testInstance, string name) + { + testInstance.Find(name).Assert().IsNull(); + } + + [Theory, RandomData] + internal static void Find_FieldNamesWork(DataRandom testInstance) + { + Type type = typeof(SampleNameData); + testInstance.Find(type.GetField(nameof(SampleNameData._firstName))).Assert().IsNotNull(); + testInstance.Find(type.GetField(nameof(SampleNameData._lastName))).Assert().IsNotNull(); + testInstance.Find(type.GetField(nameof(SampleNameData._bad))).Assert().IsNull(); + } + + [Theory, RandomData] + internal static void Find_PropertyNamesWork(DataRandom testInstance) + { + Type type = typeof(SampleNameData); + testInstance.Find(type.GetProperty(nameof(SampleNameData.FirstName))).Assert().IsNotNull(); + testInstance.Find(type.GetProperty(nameof(SampleNameData.LastName))).Assert().IsNotNull(); + testInstance.Find(type.GetProperty(nameof(SampleNameData.Bad))).Assert().IsNull(); + } + + private sealed class SampleNameData + { + public object _firstName = default; + + public string _lastName = default; + + public string _bad = default; + + public object FirstName { get; } = default; + + public string LastName { get; } = default; + + public string Bad { get; } = default; + } +} diff --git a/tests/Design.Tests/Randomization/FastRandomTests.cs b/tests/Design.Tests/Randomization/FastRandomTests.cs new file mode 100644 index 00000000..28b4d086 --- /dev/null +++ b/tests/Design.Tests/Randomization/FastRandomTests.cs @@ -0,0 +1,72 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Reiteration; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization; + +public sealed class FastRandomTests() : ValueRandomTestBase(new()) +{ + private static readonly double[] _BadDoubles = + [ + double.NaN, + double.NegativeInfinity, + double.PositiveInfinity, + ]; + + private static readonly float[] _BadFloats = + [ + float.NaN, + float.NegativeInfinity, + float.PositiveInfinity, + ]; + + [Fact] + internal static void Next_InvalidValuesPossible() + { + FastRandom random = new(10, false); + + new Limiter(20000).StallUntil( + "Trying to create bad double.", + () => _BadDoubles.Contains(random.Next()), + TestContext.Current.CancellationToken + ); + Limiter.Myriad.StallUntil( + "Trying to create bad float.", + () => _BadFloats.Contains(random.Next()), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void Next_OnlyValidValuesPreventsInvalids() + { + FastRandom random = new(10, true); + + Limiter.Myriad.Repeat( + "Trying to avoid bad doubles.", + () => _BadDoubles.Assert().ContainsNot(random.Next()), + TestContext.Current.CancellationToken + ); + Limiter.Myriad.Repeat( + "Trying to avoid bad floats.", + () => _BadFloats.Assert().ContainsNot(random.Next()), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static void NextSequence_SizeCapped() + { + static IEnumerable generate(int count) + { + for (int i = 0; i < count; i++) + { + yield return i; + } + } + + FastRandom gen = new(2); + gen.NextSequence(generate(2)).Assert().HasCount(2); + gen.Assert(x => x.NextSequence(generate(3)).Count()).Throws(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/BFloat16ValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/BFloat16ValueHandlerTests.cs new file mode 100644 index 00000000..3871f47f --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/BFloat16ValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class BFloat16ValueHandlerTests +{ + [Fact] + internal static void BFloat16ValueHandler_InternalOnly() + { + typeof(BFloat16ValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => BFloat16ValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/BigIntegerValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/BigIntegerValueHandlerTests.cs new file mode 100644 index 00000000..98f0d84b --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/BigIntegerValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class BigIntegerValueHandlerTests +{ + [Fact] + internal static void BigIntegerValueHandler_InternalOnly() + { + typeof(BigIntegerValueHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/BoolValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/BoolValueHandlerTests.cs new file mode 100644 index 00000000..9ceba618 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/BoolValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class BoolValueHandlerTests +{ + [Fact] + internal static void BoolValueHandler_InternalOnly() + { + typeof(BoolValueHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/DateOnlyValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/DateOnlyValueHandlerTests.cs new file mode 100644 index 00000000..333a16fa --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/DateOnlyValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class DateOnlyValueHandlerTests +{ + [Fact] + internal static void DateOnlyValueHandler_InternalOnly() + { + typeof(DateOnlyValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => DateOnlyValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/DateTimeOffsetValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/DateTimeOffsetValueHandlerTests.cs new file mode 100644 index 00000000..f7c3d9f8 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/DateTimeOffsetValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class DateTimeOffsetValueHandlerTests +{ + [Fact] + internal static void DateTimeOffsetValueHandler_InternalOnly() + { + typeof(DateTimeOffsetValueHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/DateTimeValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/DateTimeValueHandlerTests.cs new file mode 100644 index 00000000..cc83d7c4 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/DateTimeValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class DateTimeValueHandlerTests +{ + [Fact] + internal static void DateTimeValueHandler_InternalOnly() + { + typeof(DateTimeValueHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/Decimal128ValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/Decimal128ValueHandlerTests.cs new file mode 100644 index 00000000..3729322b --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/Decimal128ValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class Decimal128ValueHandlerTests +{ + [Fact] + internal static void Decimal128ValueHandler_InternalOnly() + { + typeof(Decimal128ValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => Decimal128ValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/Decimal32ValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/Decimal32ValueHandlerTests.cs new file mode 100644 index 00000000..ff4d4a04 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/Decimal32ValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class Decimal32ValueHandlerTests +{ + [Fact] + internal static void Decimal32ValueHandler_InternalOnly() + { + typeof(Decimal32ValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => Decimal32ValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/Decimal64ValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/Decimal64ValueHandlerTests.cs new file mode 100644 index 00000000..4d29aea6 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/Decimal64ValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class Decimal64ValueHandlerTests +{ + [Fact] + internal static void Decimal64ValueHandler_InternalOnly() + { + typeof(Decimal64ValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => Decimal64ValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/DecimalValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/DecimalValueHandlerTests.cs new file mode 100644 index 00000000..9aed2e68 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/DecimalValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class DecimalValueHandlerTests +{ + [Fact] + internal static void DecimalValueHandler_InternalOnly() + { + typeof(DecimalValueHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/DoubleValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/DoubleValueHandlerTests.cs new file mode 100644 index 00000000..2238bb37 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/DoubleValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class DoubleValueHandlerTests +{ + [Fact] + internal static void DoubleValueHandler_InternalOnly() + { + typeof(DoubleValueHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/FloatValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/FloatValueHandlerTests.cs new file mode 100644 index 00000000..916196b5 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/FloatValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class FloatValueHandlerTests +{ + [Fact] + internal static void FloatValueHandler_InternalOnly() + { + typeof(FloatValueHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/GuidValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/GuidValueHandlerTests.cs new file mode 100644 index 00000000..e0ed6c4b --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/GuidValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class GuidValueHandlerTests +{ + [Fact] + internal static void GuidValueHandler_InternalOnly() + { + typeof(GuidValueHandler).IsPublic.Assert().Is(false); + } + + [Theory, RandomData] + internal static void ToBigInteger_RoundTripsWithToGuid(Guid value) + { + GuidValueHandler.ToGuid(GuidValueHandler.ToBigInteger(value)).Assert().Is(value); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/HalfValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/HalfValueHandlerTests.cs new file mode 100644 index 00000000..4c5f98ec --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/HalfValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class HalfValueHandlerTests +{ + [Fact] + internal static void HalfValueHandler_InternalOnly() + { + typeof(HalfValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => HalfValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/Int128ValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/Int128ValueHandlerTests.cs new file mode 100644 index 00000000..435bfb6e --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/Int128ValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class Int128ValueHandlerTests +{ + [Fact] + internal static void Int128ValueHandler_InternalOnly() + { + typeof(Int128ValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => Int128ValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/IntPtrValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/IntPtrValueHandlerTests.cs new file mode 100644 index 00000000..e91b2953 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/IntPtrValueHandlerTests.cs @@ -0,0 +1,64 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class IntPtrValueHandlerTests +{ + [Fact] + internal static void IntPtrValueHandler_InternalOnly() + { + typeof(IntPtrValueHandler).IsPublic.Assert().Is(false); + } + + [Theory, RandomData] + internal static void CreateSupported_Size4IsInt([Cap(int.MaxValue)] int rawMax) + { + IntPtr min = new(Tools.Gen.Next(rawMax)); + IntPtr max = new(rawMax); + + IntPtrValueHandler instance = new(4); + instance + .CreateSupported(Tools.Gen) + .Assert() + .IsA() + .With(x => x.ToInt32()) + .LessThanOrEqualTo(int.MaxValue) + .And() + .GreaterThanOrEqualTo(int.MinValue); + + instance + .CreateSupported(Tools.Gen, min, max) + .Assert() + .IsA() + .With(x => x.ToInt32()) + .LessThanOrEqualTo(max.ToInt32()) + .And() + .GreaterThanOrEqualTo(min.ToInt32()); + } + + [Theory, RandomData] + internal static void CreateSupported_Size8IsLong([Cap(long.MaxValue)] long rawMax) + { + IntPtr min = new(Tools.Gen.Next(rawMax)); + IntPtr max = new(rawMax); + + IntPtrValueHandler instance = new(8); + instance + .CreateSupported(Tools.Gen) + .Assert() + .IsA() + .With(x => x.ToInt64()) + .LessThanOrEqualTo(long.MaxValue) + .And() + .GreaterThanOrEqualTo(long.MinValue); + + instance + .CreateSupported(Tools.Gen, min, max) + .Assert() + .IsA() + .With(x => x.ToInt64()) + .LessThanOrEqualTo(max.ToInt64()) + .And() + .GreaterThanOrEqualTo(min.ToInt64()); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/IntegralValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/IntegralValueHandlerTests.cs new file mode 100644 index 00000000..3a07ab56 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/IntegralValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class IntegralValueHandlerTests +{ + [Fact] + internal static void IntegralValueHandler_InternalOnly() + { + typeof(IntegralValueHandler<>).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/NFloatValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/NFloatValueHandlerTests.cs new file mode 100644 index 00000000..8479df63 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/NFloatValueHandlerTests.cs @@ -0,0 +1,75 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; +#if NET6_0_OR_GREATER +using System.Runtime.InteropServices; +#endif + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class NFloatValueHandlerTests +{ + [Fact] + internal static void NFloatValueHandler_InternalOnly() + { + typeof(NFloatValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => NFloatValueHandler.TryToCreate()).ThrowsNo(); + } + +#if NET6_0_OR_GREATER + [Theory, RandomData] + internal static void CreateSupported_Size4IsFloat([Cap(float.MaxValue)] float rawMax) + { + NFloat min = new(Tools.Gen.Next(rawMax)); + NFloat max = new(rawMax); + + NFloatValueHandler instance = NFloatValueHandler.TryToCreate(4); + instance + .CreateSupported(Tools.Gen) + .Assert() + .IsA() + .With(x => x) + .LessThanOrEqualTo((NFloat)float.MaxValue) + .And() + .GreaterThanOrEqualTo((NFloat)float.MinValue); + + instance + .CreateSupported(Tools.Gen, min, max) + .Assert() + .IsA() + .With(x => x) + .LessThanOrEqualTo(max) + .And() + .GreaterThanOrEqualTo(min); + } + + [Theory, RandomData] + internal static void CreateSupported_Size8IsDouble([Cap(double.MaxValue)] double rawMax) + { + NFloat min = new(Tools.Gen.Next(rawMax)); + NFloat max = new(rawMax); + + NFloatValueHandler instance = NFloatValueHandler.TryToCreate(8); + instance + .CreateSupported(Tools.Gen) + .Assert() + .IsA() + .With(x => x) + .LessThanOrEqualTo((NFloat)double.MaxValue) + .And() + .GreaterThanOrEqualTo((NFloat)double.MinValue); + + instance + .CreateSupported(Tools.Gen, min, max) + .Assert() + .IsA() + .With(x => x) + .LessThanOrEqualTo(max) + .And() + .GreaterThanOrEqualTo(min); + } +#endif +} diff --git a/tests/Design.Tests/Randomization/Handlers/RuneValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/RuneValueHandlerTests.cs new file mode 100644 index 00000000..3049c5de --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/RuneValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class RuneValueHandlerTests +{ + [Fact] + internal static void RuneValueHandler_InternalOnly() + { + typeof(RuneValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => RuneValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/TimeOnlyValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/TimeOnlyValueHandlerTests.cs new file mode 100644 index 00000000..4e77fbc2 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/TimeOnlyValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class TimeOnlyValueHandlerTests +{ + [Fact] + internal static void TimeOnlyValueHandler_InternalOnly() + { + typeof(TimeOnlyValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => TimeOnlyValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/TimeSpanValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/TimeSpanValueHandlerTests.cs new file mode 100644 index 00000000..f8d67c38 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/TimeSpanValueHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class TimeSpanValueHandlerTests +{ + [Fact] + internal static void TimeSpanValueHandler_InternalOnly() + { + typeof(TimeSpanValueHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/UInt128ValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/UInt128ValueHandlerTests.cs new file mode 100644 index 00000000..d3d0b631 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/UInt128ValueHandlerTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class UInt128ValueHandlerTests +{ + [Fact] + internal static void UInt128ValueHandler_InternalOnly() + { + typeof(UInt128ValueHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void TryToCreate_NoException() + { + 1.Assert(_ => UInt128ValueHandler.TryToCreate()).ThrowsNo(); + } +} diff --git a/tests/Design.Tests/Randomization/Handlers/UIntPtrValueHandlerTests.cs b/tests/Design.Tests/Randomization/Handlers/UIntPtrValueHandlerTests.cs new file mode 100644 index 00000000..6166f647 --- /dev/null +++ b/tests/Design.Tests/Randomization/Handlers/UIntPtrValueHandlerTests.cs @@ -0,0 +1,64 @@ +using Werecodent.CreateAndFake.Design.Randomization.Handlers; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization.Handlers; + +public static class UIntPtrValueHandlerTests +{ + [Fact] + internal static void UIntPtrValueHandler_InternalOnly() + { + typeof(UIntPtrValueHandler).IsPublic.Assert().Is(false); + } + + [Theory, RandomData] + internal static void CreateSupported_Size4IsInt([Cap(uint.MaxValue)] uint rawMax) + { + UIntPtr min = new(Tools.Gen.Next(rawMax)); + UIntPtr max = new(rawMax); + + UIntPtrValueHandler instance = new(4); + instance + .CreateSupported(Tools.Gen) + .Assert() + .IsA() + .With(x => x.ToUInt32()) + .LessThanOrEqualTo(uint.MaxValue) + .And() + .GreaterThanOrEqualTo(uint.MinValue); + + instance + .CreateSupported(Tools.Gen, min, max) + .Assert() + .IsA() + .With(x => x.ToUInt32()) + .LessThanOrEqualTo(max.ToUInt32()) + .And() + .GreaterThanOrEqualTo(min.ToUInt32()); + } + + [Theory, RandomData] + internal static void CreateSupported_Size8IsLong([Cap(ulong.MaxValue)] ulong rawMax) + { + UIntPtr min = new(Tools.Gen.Next(rawMax)); + UIntPtr max = new(rawMax); + + UIntPtrValueHandler instance = new(8); + instance + .CreateSupported(Tools.Gen) + .Assert() + .IsA() + .With(x => x.ToUInt64()) + .LessThanOrEqualTo(ulong.MaxValue) + .And() + .GreaterThanOrEqualTo(ulong.MinValue); + + instance + .CreateSupported(Tools.Gen, min, max) + .Assert() + .IsA() + .With(x => x.ToUInt64()) + .LessThanOrEqualTo(max.ToUInt64()) + .And() + .GreaterThanOrEqualTo(min.ToUInt64()); + } +} diff --git a/tests/Design.Tests/Randomization/SecureRandomTests.cs b/tests/Design.Tests/Randomization/SecureRandomTests.cs new file mode 100644 index 00000000..d1cae65d --- /dev/null +++ b/tests/Design.Tests/Randomization/SecureRandomTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Randomization; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization; + +public sealed class SecureRandomTests() : ValueRandomTestBase(new()); diff --git a/tests/Design.Tests/Randomization/SeededRandomTests.cs b/tests/Design.Tests/Randomization/SeededRandomTests.cs new file mode 100644 index 00000000..3240594f --- /dev/null +++ b/tests/Design.Tests/Randomization/SeededRandomTests.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.Design.Randomization; + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization; + +public sealed class SeededRandomTests() + : ValueRandomTestBase(Tools.Randomizer.Create()) +{ + [Fact] + internal static void Seed_Deterministic() + { + SeededRandom random1 = new(10); + SeededRandom random2 = new(random1.Seed); + + random1.Next().Assert().Is(random2.Next()); + random1.Next().Assert().Is(random2.Next()); + + random2 = new SeededRandom(random1.Seed); + + random1.Next().Assert().Is(random2.Next()); + random1.Seed.Assert().Is(random2.Seed); + } +} diff --git a/tests/Design.Tests/Randomization/ValueRandomTestBase.cs b/tests/Design.Tests/Randomization/ValueRandomTestBase.cs new file mode 100644 index 00000000..1d6b3627 --- /dev/null +++ b/tests/Design.Tests/Randomization/ValueRandomTestBase.cs @@ -0,0 +1,798 @@ +using System.Numerics; +using System.Reflection; +using Microsoft.CSharp.RuntimeBinder; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Extensions; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Randomization.Handlers; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; +#if NET6_0_OR_GREATER +using System.Runtime.InteropServices; +#endif +#if NET5_0_OR_GREATER +using System.Text; +#endif + +namespace Werecodent.CreateAndFake.Design.Tests.Randomization; + +public abstract class ValueRandomTestBase(T testInstance) : AutoTester + where T : ValueRandom +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = [(short)Tools.Gen.Next(20, 30)], + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(ArgumentOutOfRangeException), + typeof(IterationLimitException), + typeof(UnsupportedException), + typeof(InvalidCastException), + typeof(RuntimeBinderException), + typeof(TargetInvocationException), + ], + }; + + [Fact] + public void NextBytes_PreventsNegatives() + { + Tools + .Gen.Next(short.MinValue, (short)-1) + .Assert(testInstance.NextBytes) + .Throws(); + } + + [Fact] + public void Supports_InvalidTypeFalse() + { + testInstance.Supports(typeof(object)).Assert().Is(false); + } + + [Fact] + public void Supports_FullCompatibility() + { + TypeDescriber + .For() + .FindLoadedSubclasses() + .Where(t => t.IsValueType) + .Where(t => t.Inherits(typeof(IComparable<>))) + .Where(t => t.Inherits(typeof(IEquatable<>))) + .Where(t => + GenericConverter.AsConcreteType(t, typeof(IComparable<>)).GetGenericArguments()[0] + == t + ) + .Where(t => + GenericConverter.AsConcreteType(t, typeof(IEquatable<>)).GetGenericArguments()[0] + == t + ) + .Where(t => !testInstance.Supports(t)) + .Where(t => t != typeof(ValueTuple)) + .Where(t => t != typeof(StructSample)) + .Assert() + .IsEmpty(); + } + + [Fact] + public void Supports_Int() + { + TestBasicSupport(default); + TestNextRange(int.MinValue, int.MaxValue, v => v + 1, v => v - 1); + TestNextOverflow(int.MinValue / 2 - 1, int.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_UInt() + { + TestBasicSupport(default); + TestNextRange(uint.MinValue, uint.MaxValue, v => v + 1, v => v - 1); + } + + [Fact] + public void Supports_Long() + { + TestBasicSupport(default); + TestNextRange(long.MinValue, long.MaxValue, v => v + 1, v => v - 1); + TestNextOverflow(long.MinValue / 2 - 1, long.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_ULong() + { + TestBasicSupport(default); + TestNextRange(ulong.MinValue, ulong.MaxValue, v => v + 1, v => v - 1); + } + + [Fact] + public void Supports_Short() + { + TestBasicSupport(default); + TestNextRange(short.MinValue, short.MaxValue, v => (short)(v + 1), v => (short)(v - 1)); + TestNextOverflow((short)(short.MinValue / 2 - 1), (short)(short.MaxValue / 2 + 1)); + } + + [Fact] + public void Supports_UShort() + { + TestBasicSupport(default); + TestNextRange(ushort.MinValue, ushort.MaxValue, v => (ushort)(v + 1), v => (ushort)(v - 1)); + } + + [Fact] + public void Supports_Byte() + { + TestBasicSupport(default); + TestNextRange(byte.MinValue, byte.MaxValue, v => (byte)(v + 1), v => (byte)(v - 1)); + } + + [Fact] + public void Supports_SByte() + { + TestBasicSupport(default); + TestNextRange(sbyte.MinValue, sbyte.MaxValue, v => (sbyte)(v + 1), v => (sbyte)(v - 1)); + TestNextOverflow((sbyte)(sbyte.MinValue / 2 - 1), (sbyte)(sbyte.MaxValue / 2 + 1)); + } + + [Fact] + public void Supports_Char() + { + TestBasicSupport(default); + TestNextRange(char.MinValue, char.MaxValue, v => (char)(v + 1), v => (char)(v - 1)); + } + + [Fact] + public void Supports_Guid() + { + TestBasicSupport(Guid.Empty); + TestNextRange( + Guid.Empty, + new Guid(0xFFFFFFFF, 0xFFFF, 0xFFFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF), + v => GuidValueHandler.ToGuid(GuidValueHandler.ToBigInteger(v) + 1), + v => GuidValueHandler.ToGuid(GuidValueHandler.ToBigInteger(v) - 1) + ); + } + + [Fact] + public void Supports_Decimal() + { + TestBasicSupport(default); + TestNextRange(decimal.MinValue, decimal.MaxValue, v => v + 1m, v => v - 1m); + TestNextOverflow(decimal.MinValue / 2 - 1, decimal.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_Float() + { + TestBasicSupport(default); + TestNextRange(float.MinValue, float.MaxValue, v => v + 1f, v => v - 1f); + TestNextOverflow(float.MinValue / 2 - 1, float.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_Double() + { + TestBasicSupport(default); + TestNextRange(double.MinValue, double.MaxValue, v => v + 1d, v => v - 1d); + TestNextOverflow(double.MinValue / 2 - 1, double.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_BigInteger() + { + BigInteger min = new(long.MinValue); + BigInteger max = new(long.MaxValue); + + TestBasicSupport(default); + TestNextRange(min, max, v => v + 1, v => v - 1); + TestNextOverflow(min / 2 - 1, max / 2 + 1); + } + + [Fact] + public void Supports_TimeSpan() + { + TestBasicSupport(default); + TestNextRange( + TimeSpan.MinValue, + TimeSpan.MaxValue, + v => v.Add(TimeSpan.FromTicks(1)), + v => v.Subtract(TimeSpan.FromTicks(1)) + ); + TestNextOverflow( + TimeSpan.FromTicks(TimeSpan.MinValue.Ticks / 2 - 1), + TimeSpan.FromTicks(TimeSpan.MaxValue.Ticks / 2 + 1) + ); + } + + [Fact] + public void Supports_DateTime() + { + TestBasicSupport(default); + TestNextRange( + DateTime.MinValue, + DateTime.MaxValue, + v => v.AddTicks(1), + v => v.AddTicks(-1) + ); + } + + [Fact] + public void Supports_DateTimeOffset() + { + TestNext(DateTimeOffset.MinValue, DateTimeOffset.MinValue); + TestNext(DateTimeOffset.MaxValue.AddTicks(-61), DateTimeOffset.MaxValue.AddTicks(-60)); + TestBasicSupport(default); + TestNextRange( + DateTimeOffset.MinValue, + DateTimeOffset.MaxValue, + v => v.AddTicks(1), + v => v.AddTicks(-1) + ); + } + +#if NET11_0_OR_GREATER + [Fact] + public void Supports_BFloat16() + { + TestBasicSupport(default); + TestNextRange( + BFloat16.MinValue, + BFloat16.MaxValue, + v => v + (BFloat16)1f, + v => v - (BFloat16)1f + ); + TestNextOverflow( + BFloat16.MinValue / (BFloat16)2 - (BFloat16)1, + BFloat16.MaxValue / (BFloat16)2 + (BFloat16)1 + ); + } + + [Fact] + public void Supports_Decimal32() + { + TestBasicSupport(default); + TestNextRange( + Decimal32.MinValue, + Decimal32.MaxValue, + v => v + (Decimal32)1, + v => v - (Decimal32)1 + ); + TestNextOverflow( + Decimal32.MinValue / (Decimal32)2 - (Decimal32)1, + Decimal32.MaxValue / (Decimal32)2 + (Decimal32)1 + ); + } + + [Fact] + public void Next_HandlesDecimal32SpecialValues() + { + TestNext(Decimal32.NegativeInfinity, Decimal32.NegativeInfinity); + TestNext(Decimal32.PositiveInfinity, Decimal32.PositiveInfinity); + + testInstance + .Next(default, Decimal32.PositiveInfinity) + .Assert() + .LessThanOrEqualTo(Decimal32.MaxValue); + testInstance + .Next(Decimal32.NegativeInfinity, default) + .Assert() + .GreaterThanOrEqualTo(Decimal32.MinValue); + testInstance + .Next(Decimal32.NegativeInfinity, Decimal32.PositiveInfinity) + .Assert() + .GreaterThanOrEqualTo(Decimal32.MinValue) + .And() + .LessThanOrEqualTo(Decimal32.MaxValue); + + testInstance.Next(Decimal32.NaN, default).Assert().Is(Decimal32.NaN); + testInstance.Next(Decimal32.NaN, Decimal32.NaN).Assert().Is(Decimal32.NaN); + } + + [Fact] + public void Supports_Decimal64() + { + TestBasicSupport(default); + TestNextRange( + Decimal64.MinValue, + Decimal64.MaxValue, + v => v + (Decimal64)1, + v => v - (Decimal64)1 + ); + TestNextOverflow( + Decimal32.MinValue / (Decimal64)2 - (Decimal64)1, + Decimal32.MaxValue / (Decimal64)2 + (Decimal64)1 + ); + } + + [Fact] + public void Next_HandlesDecimal64SpecialValues() + { + TestNext(Decimal64.NegativeInfinity, Decimal64.NegativeInfinity); + TestNext(Decimal64.PositiveInfinity, Decimal64.PositiveInfinity); + + testInstance + .Next(default, Decimal64.PositiveInfinity) + .Assert() + .LessThanOrEqualTo(Decimal64.MaxValue); + testInstance + .Next(Decimal64.NegativeInfinity, default) + .Assert() + .GreaterThanOrEqualTo(Decimal64.MinValue); + testInstance + .Next(Decimal64.NegativeInfinity, Decimal64.PositiveInfinity) + .Assert() + .GreaterThanOrEqualTo(Decimal64.MinValue) + .And() + .LessThanOrEqualTo(Decimal64.MaxValue); + + testInstance.Next(Decimal64.NaN, default).Assert().Is(Decimal64.NaN); + testInstance.Next(Decimal64.NaN, Decimal64.NaN).Assert().Is(Decimal64.NaN); + } + + [Fact] + public void Supports_Decimal128() + { + TestBasicSupport(default); + TestNextRange( + Decimal128.MinValue, + Decimal128.MaxValue, + v => v + (Decimal128)1, + v => v - (Decimal128)1 + ); + TestNextOverflow( + Decimal128.MinValue / (Decimal128)2 - (Decimal128)1, + Decimal128.MaxValue / (Decimal128)2 + (Decimal128)1 + ); + } + + [Fact] + public void Next_HandlesDecimal128SpecialValues() + { + TestNext(Decimal128.NegativeInfinity, Decimal128.NegativeInfinity); + TestNext(Decimal128.PositiveInfinity, Decimal128.PositiveInfinity); + + testInstance + .Next(default, Decimal128.PositiveInfinity) + .Assert() + .LessThanOrEqualTo(Decimal128.MaxValue); + testInstance + .Next(Decimal128.NegativeInfinity, default) + .Assert() + .GreaterThanOrEqualTo(Decimal128.MinValue); + testInstance + .Next(Decimal128.NegativeInfinity, Decimal128.PositiveInfinity) + .Assert() + .GreaterThanOrEqualTo(Decimal128.MinValue) + .And() + .LessThanOrEqualTo(Decimal128.MaxValue); + + testInstance.Next(Decimal128.NaN, default).Assert().Is(Decimal128.NaN); + testInstance.Next(Decimal128.NaN, Decimal128.NaN).Assert().Is(Decimal128.NaN); + } +#endif + +#if NET7_0_OR_GREATER + [Fact] + public void Supports_IntPtr() + { + TestBasicSupport(default); + TestNextRange(IntPtr.MinValue, IntPtr.MaxValue, v => v + 1, v => v - 1); + TestNextOverflow(IntPtr.MinValue / 2 - 1, IntPtr.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_NInt() + { + TestBasicSupport(default); + TestNextRange(nint.MinValue, nint.MaxValue, v => v + 1, v => v - 1); + TestNextOverflow(nint.MinValue / 2 - 1, nint.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_UIntPtr() + { + TestBasicSupport(default); + TestNextRange(UIntPtr.MinValue, UIntPtr.MaxValue, v => v + 1, v => v - 1); + } + + [Fact] + public void Supports_NUInt() + { + TestBasicSupport(default); + TestNextRange(nuint.MinValue, nuint.MaxValue, v => v + 1, v => v - 1); + } + + [Fact] + public void Supports_Int128() + { + TestBasicSupport(default); + TestNextRange(Int128.MinValue, Int128.MaxValue, v => v + 1, v => v - 1); + TestNextOverflow(Int128.MinValue / 2 - 1, Int128.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_UInt128() + { + TestBasicSupport(default); + TestNextRange(UInt128.MinValue, UInt128.MaxValue, v => v + 1, v => v - 1); + } +#endif + +#if NET6_0_OR_GREATER + [Fact] + public void Supports_NFloat() + { + TestBasicSupport(default); + TestNextRange(NFloat.MinValue, NFloat.MaxValue, v => v + 1, v => v - 1); + TestNextOverflow(NFloat.MinValue / 2 - 1, NFloat.MaxValue / 2 + 1); + } + + [Fact] + public void Supports_TimeOnly() + { + TestBasicSupport(default); + TestNextRange( + TimeOnly.MinValue, + TimeOnly.MaxValue, + v => v.Add(TimeSpan.FromTicks(1)), + v => v.Add(TimeSpan.FromTicks(-1)) + ); + } + + [Fact] + public void Supports_DateOnly() + { + TestBasicSupport(default); + TestNextRange(DateOnly.MinValue, DateOnly.MaxValue, v => v.AddDays(1), v => v.AddDays(-1)); + } +#endif + +#if NET5_0_OR_GREATER + [Fact] + public void Supports_Half() + { + TestBasicSupport(default); + TestNextRange(Half.MinValue, Half.MaxValue, v => v + (Half)1f, v => v - (Half)1f); + TestNextOverflow(Half.MinValue / (Half)2 - (Half)1, Half.MaxValue / (Half)2 + (Half)1); + } + + [Fact] + public void Supports_Rune() + { + TestBasicSupport(default); + TestNext(new Rune(0x0000), new Rune(0x10FFFF)); + TestNextRange( + new Rune(0x0000), + new Rune(0xD7FF), + v => new Rune(v.Value + 1), + v => new Rune(v.Value - 1) + ); + TestNextRange( + new Rune(0xE000), + new Rune(0x10FFFF), + v => new Rune(v.Value + 1), + v => new Rune(v.Value - 1) + ); + TestNext(new Rune(0xD7FF), new Rune(0xE000)); + } +#endif + + [Fact] + public void Supports_Bool() + { + TestBasicSupport(default); + TestNext(false, true); + + bool sample = testInstance.Next(false, true); + Limiter.Hundred.StallUntil( + "Variance testing.", + () => sample != testInstance.Next(false, true), + TestContext.Current.CancellationToken + ); + + testInstance.Next(false, false).Assert().Is(false); + testInstance.Next(true, true).Assert().Is(true); + testInstance.Assert(x => x.Next(true, false)).Throws(); + } + + private void TestBasicSupport(TValueType zero) + where TValueType : struct, IComparable, IComparable, IEquatable + { + testInstance.Supports().Assert().Is(true); + testInstance.Supports(typeof(TValueType)).Assert().Is(true); + testInstance.Next().Assert().IsNotNull(); + testInstance.Next(typeof(TValueType)).Assert().IsNotNull(); + testInstance.Next(zero).Assert().Is(zero); + testInstance.Next(zero, zero).Assert().Is(zero); + + TValueType sample = testInstance.Next(); + Limiter.Hundred.StallUntil( + $"Variance testing against value {sample}.", + () => !sample.Equals(testInstance.Next()), + TestContext.Current.CancellationToken + ); + + Limiter.Myriad.Repeat( + "Random max testing.", + () => + { + TValueType sample = testInstance.Next(); + if (sample.CompareTo(zero) > 0) + { + TestNext(sample); + } + }, + TestContext.Current.CancellationToken + ); + } + + private void TestNextRange( + TValueType min, + TValueType max, + Func addSome, + Func subtractSome + ) + where TValueType : struct, IComparable, IComparable, IEquatable + { + TestNext(max); + TestNext(min, max); + + min.Assert(x => testInstance.Next(max, x)).Throws(); + + Limiter.Myriad.Repeat( + "Minimal range adherence testing.", + () => + { + TestNext(min, addSome(min)); + TestNext(subtractSome(max), max); + + TValueType sample = testInstance.Next(addSome(min), subtractSome(max)); + TestNext(subtractSome(sample), sample); + TestNext(sample, sample); + TestNext(sample, addSome(sample)); + }, + TestContext.Current.CancellationToken + ); + + Limiter.Myriad.Repeat( + "Random range testing.", + () => + { + TValueType sample1 = testInstance.Next(); + TValueType sample2 = testInstance.Next(); + if (sample1.CompareTo(sample2) < 0) + { + TestNext(sample1, sample2); + } + else if (sample1.CompareTo(sample2) > 0) + { + TestNext(sample2, sample1); + } + }, + TestContext.Current.CancellationToken + ); + } + + private void TestNextOverflow(TValueType halfMin, TValueType halfMax) + where TValueType : struct, IComparable, IComparable, IEquatable + { + Limiter.Myriad.Repeat( + "Potential overflow testing.", + () => TestNext(halfMin, halfMax), + TestContext.Current.CancellationToken + ); + } + + private void TestNext(TValueType max) + where TValueType : struct, IComparable, IComparable, IEquatable + { + TValueType min = default; + testInstance.Next(max).Assert().GreaterThanOrEqualTo(min).And().LessThan(max); + } + + private void TestNext(TValueType min, TValueType max) + where TValueType : struct, IComparable, IComparable, IEquatable + { + testInstance.Next(min, max).Assert().GreaterThanOrEqualTo(min).And().LessThanOrEqualTo(max); + } + + [Theory, RandomData] + public void Next_UnsupportedTypeThrows(StructSample sample) + { + testInstance.Assert(x => x.Next()).Throws(); + testInstance.Assert(x => x.Next(typeof(StructSample))).Throws(); + testInstance.Assert(x => x.Next(sample)).Throws(); + testInstance.Assert(x => x.Next(sample, sample)).Throws(); + } + + [Fact] + public void Next_SignedMinValueIncluded() + { + const sbyte min = sbyte.MinValue / 2 - 1; + const sbyte max = sbyte.MaxValue / 2 + 1; + + Limiter.Myriad.StallUntil( + "Finding max value.", + () => testInstance.Next(max) == default, + TestContext.Current.CancellationToken + ); + Limiter.Myriad.StallUntil( + "Finding min value.", + () => testInstance.Next(min, max) == min, + TestContext.Current.CancellationToken + ); + } + + [Fact] + public void Next_UnsignedMinValueIncluded() + { + const byte min = byte.MaxValue / 4; + const byte max = byte.MaxValue / 4 * 3; + + Limiter.Myriad.StallUntil( + "Finding max value.", + () => testInstance.Next(max) == default, + TestContext.Current.CancellationToken + ); + Limiter.Myriad.StallUntil( + "Finding min value.", + () => testInstance.Next(min, max) == min, + TestContext.Current.CancellationToken + ); + } + + [Fact] + public void Next_SignedMaxValueIncludedOnlyWithMin() + { + const sbyte min = sbyte.MinValue / 2 - 1; + const sbyte max = sbyte.MaxValue / 2 + 1; + + Limiter.Myriad.StallUntil( + "Finding max value.", + () => testInstance.Next(max) != max, + TestContext.Current.CancellationToken + ); + Limiter.Myriad.StallUntil( + "Finding max value.", + () => testInstance.Next(min, max) == max, + TestContext.Current.CancellationToken + ); + } + + [Fact] + public void Next_UnsignedMaxValueIncludedOnlyWithMin() + { + const byte min = byte.MaxValue / 4; + const byte max = byte.MaxValue / 4 * 3; + + Limiter.Myriad.StallUntil( + "Finding max value.", + () => testInstance.Next(max) != max, + TestContext.Current.CancellationToken + ); + Limiter.Myriad.StallUntil( + "Finding max value.", + () => testInstance.Next(min, max) == max, + TestContext.Current.CancellationToken + ); + } + + [Fact] + public void Next_HandlesDoubleSpecialValues() + { + TestNext(double.NegativeInfinity, double.NegativeInfinity); + TestNext(double.PositiveInfinity, double.PositiveInfinity); + + testInstance.Next(0, double.PositiveInfinity).Assert().LessThanOrEqualTo(double.MaxValue); + testInstance + .Next(double.NegativeInfinity, 0) + .Assert() + .GreaterThanOrEqualTo(double.MinValue); + testInstance + .Next(double.NegativeInfinity, double.PositiveInfinity) + .Assert() + .GreaterThanOrEqualTo(double.MinValue) + .And() + .LessThanOrEqualTo(double.MaxValue); + + testInstance.Next(double.NaN, 0).Assert().Is(double.NaN); + testInstance.Next(double.NaN, double.NaN).Assert().Is(double.NaN); + } + + [Fact] + public void Next_HandlesFloatSpecialValues() + { + TestNext(float.NegativeInfinity, float.NegativeInfinity); + TestNext(float.PositiveInfinity, float.PositiveInfinity); + + testInstance.Next(0, float.PositiveInfinity).Assert().LessThanOrEqualTo(float.MaxValue); + testInstance.Next(float.NegativeInfinity, 0).Assert().GreaterThanOrEqualTo(float.MinValue); + testInstance + .Next(float.NegativeInfinity, float.PositiveInfinity) + .Assert() + .GreaterThanOrEqualTo(float.MinValue) + .And() + .LessThanOrEqualTo(float.MaxValue); + + testInstance.Next(float.NaN, 0).Assert().Is(float.NaN); + testInstance.Next(float.NaN, float.NaN).Assert().Is(float.NaN); + } + + [Fact] + public void Next_MinMustBeSmallerThanMax() + { + testInstance.Assert(x => x.Next(1, -1)).Throws(); + } + + [Theory, RandomData] + public void NextItem_CollectionsWork(ICollection data) + { + data.Assert().Contains(testInstance.NextItem(data)); + } + + [Theory, RandomData] + public void NextItem_ReadOnlyCollectionsWork(IReadOnlyCollection data) + { + data.Assert().Contains(testInstance.NextItem(data)); + } + + [Fact] + public void NextItem_YieldWorks() + { + testInstance.NextItem(CreateSeries(1)).Assert().IsNotNull(); + testInstance.NextItem(CreateSeries(2)).Assert().IsNotNull(); + testInstance.NextItem(CreateSeries(3)).Assert().IsNotNull(); + } + + [Fact] + public void NextItem_EmptyThrows() + { + testInstance.Assert(x => x.NextItem(CreateSeries(0))).Throws(); + testInstance + .Assert(x => x.NextItem(Array.Empty())) + .Throws(); + } + + [Theory, RandomData] + public void NextItemOrDefault_SingleValueGivesIt(int value, object item) + { + testInstance.NextItemOrDefault([value]).Assert().Is(value); + testInstance.NextItemOrDefault(CreateSeries(1)).Assert().IsNotNull(); + testInstance.NextItemOrDefault(new Queue([item])).Assert().Is(item); + } + + [Fact] + public void NextItemOrDefault_EmptyGivesDefault() + { + testInstance.NextItemOrDefault((int[])null).Assert().Is(0); + testInstance.NextItemOrDefault(CreateSeries(0)).Assert().IsNull(); + testInstance.NextItemOrDefault((object[])null).Assert().IsNull(); + testInstance.NextItemOrDefault(Array.Empty()).Assert().IsNull(); + } + + [Theory, RandomData] + public void NextSequence_ShufflesValues([Size(3)] int[] items) + { + Limiter.Hundred.StallUntil( + "Testing shuffle randomization.", + () => testInstance.NextSequence(items).First() == items[0], + TestContext.Current.CancellationToken + ); + Limiter.Hundred.StallUntil( + "Testing shuffle randomization.", + () => testInstance.NextSequence(items).First() == items[2], + TestContext.Current.CancellationToken + ); + } + + private static IEnumerable CreateSeries(int size) + { + for (int i = 0; i < size; i++) + { + yield return new object(); + } + } +} diff --git a/tests/Design.Tests/Reiteration/Limiter.AsyncTests.cs b/tests/Design.Tests/Reiteration/Limiter.AsyncTests.cs new file mode 100644 index 00000000..f7d7f49b --- /dev/null +++ b/tests/Design.Tests/Reiteration/Limiter.AsyncTests.cs @@ -0,0 +1,644 @@ +using System.Diagnostics; +using Werecodent.CreateAndFake.Design.Reiteration; + +namespace Werecodent.CreateAndFake.Design.Tests.Reiteration; + +public static class LimiterAsyncTests +{ + private const int _WaitAccuracy = 5; + + private static readonly TimeSpan _SmallDelay = new(0, 0, 0, 0, 1); + + [Theory, InlineData(1), InlineData(5)] + internal static Task RepeatAsync_TryLimited(int tries) + { + int attempts = 0; + + return new Limiter(tries) + .RepeatAsync(GetAMessage(), () => attempts++, TestContext.Current.CancellationToken) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task StallUntilAsync_TryLimited(int tries) + { + int attempts = 0; + + return new Limiter(tries) + .StallUntilAsync( + GetAMessage(), + () => attempts++, + () => false, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task RetryAsync_TryLimited(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + + return new Limiter(tries) + .RetryAsync( + GetAMessage(), + () => + { + attempts++; + throw exception; + }, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .With(x => x.InnerException) + .ValuesEqual(exception) + .Also(() => attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task AttemptAsync_TryLimited(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + + return new Limiter(tries) + .AttemptAsync( + GetAMessage(), + () => + { + attempts++; + throw exception; + }, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries); + } + + [Fact] + internal static Task RepeatAsync_TimeoutLimited() + { + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(_SmallDelay) + .RepeatAsync(GetAMessage(), () => { }, TestContext.Current.CancellationToken) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + } + + [Fact] + internal static Task StallUntilAsync_TimeoutLimited() + { + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(_SmallDelay) + .StallUntilAsync( + GetAMessage(), + () => { }, + () => false, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + } + + [Theory, RandomData] + internal static Task RetryAsync_TimeoutLimited(Exception exception) + { + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(_SmallDelay) + .RetryAsync(GetAMessage(), () => throw exception, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .With(x => x.InnerException) + .ValuesEqual(exception) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + } + + [Theory, RandomData] + internal static Task AttemptAsync_TimeoutLimited(Exception exception) + { + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(_SmallDelay) + .AttemptAsync( + GetAMessage(), + () => watch.IsRunning ? throw exception : new object(), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNull() + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + } + + [Theory, InlineData(1), InlineData(2), InlineData(3)] + internal static Task RepeatAsync_DelayOccurs(int tries) + { + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(tries, _SmallDelay) + .RepeatAsync(GetAMessage(), () => attempts++, TestContext.Current.CancellationToken) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo((_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); + } + + [Theory, InlineData(1), InlineData(2), InlineData(3)] + internal static Task StallUntilAsync_DelayOccurs(int tries) + { + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(tries, _SmallDelay) + .StallUntilAsync( + GetAMessage(), + () => ++attempts == tries, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo((_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); + } + + [Theory, InlineData(1), InlineData(2), InlineData(3)] + internal static Task RetryAsync_DelayOccurs(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(tries, _SmallDelay) + .RetryAsync( + GetAMessage(), + () => + { + if (++attempts < tries) + { + throw exception; + } + }, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo((_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); + } + + [Theory, InlineData(1), InlineData(2), InlineData(3)] + internal static Task AttemptAsync_DelayOccurs(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(tries, _SmallDelay) + .AttemptAsync( + GetAMessage(), + () => + { + if (++attempts < tries) + { + throw exception; + } + }, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo((_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); + } + + [Fact] + internal static async Task RepeatAsync_Cancelable() + { + await Limiter + .Slow.RepeatAsync(GetAMessage(), () => { }, new CancellationToken(true)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource = new(); + + await Limiter + .Few.RepeatAsync(GetAMessage(), tokenSource.Cancel, tokenSource.Token) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task StallUntilAsync_Cancelable() + { + await Limiter + .Fast.StallUntilAsync(GetAMessage(), () => false, new CancellationToken(true)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource = new(); + + await Limiter + .Few.StallUntilAsync(GetAMessage(), tokenSource.Cancel, () => false, tokenSource.Token) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task RetryAsync_Cancelable(Exception exception) + { + await Limiter + .Slow.RetryAsync(GetAMessage(), () => throw exception, new CancellationToken(true)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource = new(); + + await Limiter + .Few.RetryAsync( + GetAMessage(), + () => throw exception, + tokenSource.Cancel, + tokenSource.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task AttemptAsync_Cancelable(Exception exception) + { + await Limiter + .Slow.AttemptAsync(GetAMessage(), () => throw exception, new CancellationToken(true)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource = new(); + + await Limiter + .Few.AttemptAsync( + GetAMessage(), + () => throw exception, + tokenSource.Cancel, + tokenSource.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task RepeatAsync_ResultsValid(List data) + { + int attemptAsync = 0; + + return new Limiter(data.Count) + .RepeatAsync( + GetAMessage(), + () => data[attemptAsync++], + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(data.AsReadOnly()); + } + + [Theory, RandomData] + internal static Task StallUntilAsync_ResultsValid(List data) + { + int attemptAsync = 0; + + return new Limiter(data.Count) + .StallUntilAsync( + GetAMessage(), + () => data[attemptAsync++], + () => attemptAsync == data.Count, + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(data.AsReadOnly()); + } + + [Theory, RandomData] + internal static Task RetryAsync_ResultsValid(int data) + { + return new Limiter(1) + .RetryAsync(GetAMessage(), () => data, TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(data), TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task RetryAsync_Continues() + { + int calls = 0; + + await new Limiter(2) + .RetryAsync( + GetAMessage(), + () => + { + calls++; + if (calls == 1) + { + throw new ArithmeticException(); + } + }, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => calls) + .Is(2); + + await new Limiter(2) + .RetryAsync( + GetAMessage(), + () => + { + calls++; + if (calls == 3) + { + throw new ArithmeticException(); + } + }, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => calls) + .Is(4); + } + + [Theory, RandomData] + internal static Task AttemptAsync_ResultsValid(int data) + { + return new Limiter(1) + .AttemptAsync(GetAMessage(), () => data, TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(data), TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task AttemptAsync_Continues() + { + int calls = 0; + + await new Limiter(2) + .AttemptAsync( + GetAMessage(), + () => + { + calls++; + if (calls == 1) + { + throw new ArithmeticException(); + } + }, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => calls) + .Is(2); + + await new Limiter(2) + .AttemptAsync( + GetAMessage(), + () => + { + calls++; + if (calls == 3) + { + throw new ArithmeticException(); + } + }, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => calls) + .Is(4); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task StallUntilAsync_CheckStateBehavior(int tries) + { + int attemptAsync = 0; + int checkAttemptAsync = 0; + + return new Limiter(tries) + .StallUntilAsync( + GetAMessage(), + () => attemptAsync++, + () => ++checkAttemptAsync == tries, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => checkAttemptAsync) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task RetryAsync_ResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + int resetAttemptAsync = 0; + + return new Limiter(tries) + .RetryAsync( + GetAMessage(), + () => + { + if (++attemptAsync < tries) + { + throw exception; + } + }, + () => resetAttemptAsync++, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task RetryAsync_ReturnResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + int resetAttemptAsync = 0; + + int result = Tools.Randomizer.Create(); + int resetBehavior() + { + return (++attemptAsync == tries) ? result : throw exception; + } + + return new Limiter(tries) + .RetryAsync( + GetAMessage(), + resetBehavior, + () => resetAttemptAsync++, + TestContext.Current.CancellationToken + ) + .Assert() + .IsAsync(Task.FromResult(result), TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + } + + [Theory, RandomData] + internal static async Task RetryAsync_WrongExceptionThrows(NotSupportedException exception) + { + await new Limiter(3) + .RetryAsync( + GetAMessage(), + (Action)(() => throw exception), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .That() + .Is(exception); + + IOException exception2 = new(); + + await new Limiter(3) + .RetryAsync( + GetAMessage(), + (Func)(() => throw exception2), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .That() + .Is(exception2); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task AttemptAsync_ResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + int resetAttemptAsync = 0; + + return new Limiter(tries) + .AttemptAsync( + GetAMessage(), + () => + { + if (++attemptAsync < tries) + { + throw exception; + } + }, + () => resetAttemptAsync++, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task AttemptAsync_ReturnResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + int resetAttemptAsync = 0; + + int result = Tools.Randomizer.Create(); + int resetBehavior() + { + return (++attemptAsync == tries) ? result : throw exception; + } + + return new Limiter(tries) + .AttemptAsync( + GetAMessage(), + resetBehavior, + () => resetAttemptAsync++, + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(result) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + } + + [Theory, RandomData] + internal static async Task AttemptAsync_WrongExceptionThrows(NotSupportedException exception) + { + await new Limiter(3) + .AttemptAsync( + GetAMessage(), + (Action)(() => throw exception), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .That() + .Is(exception); + + IOException exception2 = new(); + + await new Limiter(3) + .AttemptAsync( + GetAMessage(), + (Func)(() => throw exception2), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .That() + .Is(exception2); + } + + private static string GetAMessage() + { + return Tools.Gen.NextItem(["", null, "Test."]); + } +} diff --git a/tests/Design.Tests/Reiteration/Limiter.SyncTests.cs b/tests/Design.Tests/Reiteration/Limiter.SyncTests.cs new file mode 100644 index 00000000..2fc492fa --- /dev/null +++ b/tests/Design.Tests/Reiteration/Limiter.SyncTests.cs @@ -0,0 +1,536 @@ +using System.Diagnostics; +using Werecodent.CreateAndFake.Design.Reiteration; + +namespace Werecodent.CreateAndFake.Design.Tests.Reiteration; + +public static class LimiterSyncTests +{ + [Fact] + internal static void Limiter_SyncTimeoutWorks() + { + // All sync timeout tests reduced to one test in order to reduce any risk of deadlock. + // Async methods should be preferred for timeout limits. + + TimeSpan timeout = new(0, 0, 0, 0, 190); + TimeSpan delay = new(0, 0, 0, 0, 100); + Limiter testInstance = new(timeout, delay); + + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + testInstance + .Repeat("Timeout test.", () => attempts++, TestContext.Current.CancellationToken) + .Assert() + .HasCount(2) + .Also(watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(20d); + + attempts = 0; + watch.Restart(); + + testInstance + .Assert(x => + x.StallUntil( + "Timeout test.", + () => attempts++, + () => false, + TestContext.Current.CancellationToken + ) + ) + .Throws() + .Also(attempts) + .Is(2) + .Also(watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(20d); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void Repeat_TryLimited(int tries) + { + int attempts = 0; + + new Limiter(tries) + .Repeat(GetAMessage(), () => attempts++, TestContext.Current.CancellationToken) + .Assert() + .HasCount(tries) + .Also(attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void StallUntil_TryLimited(int tries) + { + int attempts = 0; + + new Limiter(tries) + .Assert(x => + x.StallUntil( + GetAMessage(), + () => attempts++, + () => false, + TestContext.Current.CancellationToken + ) + ) + .Throws() + .Also(attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void Retry_TryLimited(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + + new Limiter(tries) + .Assert(x => + x.Retry( + GetAMessage(), + () => + { + attempts++; + throw exception; + }, + TestContext.Current.CancellationToken + ) + ) + .Throws() + .With(e => e.InnerException) + .Is(exception) + .Also(attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void Attempt_TryLimited(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + + new Limiter(tries) + .Assert(x => + x.Attempt( + GetAMessage(), + () => + { + attempts++; + throw exception; + }, + TestContext.Current.CancellationToken + ) + ) + .ThrowsNo() + .Also(attempts) + .Is(tries); + } + + [Fact] + internal static void Repeat_Cancelable() + { + Limiter + .Few.Assert(x => x.Repeat(GetAMessage(), () => { }, new CancellationToken(true))) + .Throws(); + + using CancellationTokenSource tokenSource = new(); + + Limiter + .Few.Assert(x => x.Repeat(GetAMessage(), () => tokenSource.Cancel(), tokenSource.Token)) + .Throws(); + } + + [Fact] + internal static void StallUntil_Cancelable() + { + Limiter + .Few.Assert(x => x.StallUntil(GetAMessage(), () => false, new CancellationToken(true))) + .Throws(); + + using CancellationTokenSource tokenSource = new(); + + Limiter + .Few.Assert(x => + x.StallUntil( + GetAMessage(), + () => tokenSource.Cancel(), + () => false, + tokenSource.Token + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal static void Retry_Cancelable(Exception exception) + { + Limiter + .Few.Assert(x => + x.Retry(GetAMessage(), () => throw exception, new CancellationToken(true)) + ) + .Throws(); + + using CancellationTokenSource tokenSource = new(); + + Limiter + .Few.Assert(x => + x.Retry( + GetAMessage(), + () => throw exception, + () => tokenSource.Cancel(), + tokenSource.Token + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal static void Attempt_Cancelable(Exception exception) + { + Limiter + .Few.Assert(x => x.Attempt(null, () => throw exception, new CancellationToken(true))) + .Throws(); + + using CancellationTokenSource tokenSource = new(); + + Limiter + .Few.Assert(x => + x.Attempt( + GetAMessage(), + () => throw exception, + () => tokenSource.Cancel(), + tokenSource.Token + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal static void Repeat_ResultsValid(List data) + { + int attempt = 0; + + new Limiter(data.Count) + .Repeat(GetAMessage(), () => data[attempt++], TestContext.Current.CancellationToken) + .Assert() + .Is(data.AsReadOnly()); + } + + [Theory, RandomData] + internal static void StallUntil_ResultsValid(List data) + { + int attempt = 0; + + new Limiter(data.Count) + .StallUntil( + GetAMessage(), + () => data[attempt++], + () => attempt == data.Count, + TestContext.Current.CancellationToken + ) + .Assert() + .Is(data.AsReadOnly()); + } + + [Theory, RandomData] + internal static void Retry_ResultsValid(int data) + { + new Limiter(1) + .Retry(GetAMessage(), () => data, TestContext.Current.CancellationToken) + .Assert() + .Is(data); + } + + [Fact] + internal static void Retry_Continues() + { + int calls = 0; + + new Limiter(2) + .Assert(x => + x.Retry( + GetAMessage(), + () => + { + calls++; + if (calls == 1) + { + throw new ArithmeticException(); + } + }, + TestContext.Current.CancellationToken + ) + ) + .ThrowsNo() + .Also(calls) + .Is(2); + + new Limiter(2) + .Assert(x => + x.Retry( + GetAMessage(), + () => + { + calls++; + if (calls == 3) + { + throw new ArithmeticException(); + } + }, + TestContext.Current.CancellationToken + ) + ) + .ThrowsNo() + .Also(calls) + .Is(4); + } + + [Theory, RandomData] + internal static void Attempt_ResultsValid(int data) + { + new Limiter(1) + .Attempt(GetAMessage(), () => data, TestContext.Current.CancellationToken) + .Assert() + .Is(data); + } + + [Fact] + internal static void Attempt_Continues() + { + int calls = 0; + + new Limiter(2) + .Assert(x => + x.Attempt( + GetAMessage(), + () => + { + calls++; + if (calls == 1) + { + throw new ArithmeticException(); + } + }, + TestContext.Current.CancellationToken + ) + ) + .ThrowsNo() + .Also(calls) + .Is(2); + + new Limiter(2) + .Assert(x => + x.Attempt( + GetAMessage(), + () => + { + calls++; + if (calls == 3) + { + throw new ArithmeticException(); + } + }, + TestContext.Current.CancellationToken + ) + ) + .ThrowsNo() + .Also(calls) + .Is(4); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void StallUntil_CheckStateBehavior(int tries) + { + int attempt = 0; + int checkAttempt = 0; + + new Limiter(tries) + .StallUntil( + GetAMessage(), + () => attempt++, + () => ++checkAttempt == tries, + TestContext.Current.CancellationToken + ) + .Assert() + .HasCount(tries) + .Also(checkAttempt) + .Is(attempt) + .And() + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void Retry_ResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempt = 0; + int resetAttempt = 0; + + new Limiter(tries) + .Assert(x => + x.Retry( + GetAMessage(), + () => + { + if (++attempt < tries) + { + throw exception; + } + }, + () => resetAttempt++, + TestContext.Current.CancellationToken + ) + ) + .ThrowsNo() + .Also(attempt) + .Is(tries) + .Also(resetAttempt) + .Is(tries - 1); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void Retry_ReturnResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempt = 0; + int resetAttempt = 0; + + int result = Tools.Randomizer.Create(); + int resetBehavior() + { + return (++attempt == tries) ? result : throw exception; + } + + new Limiter(tries) + .Retry( + GetAMessage(), + resetBehavior, + () => resetAttempt++, + TestContext.Current.CancellationToken + ) + .Assert() + .Is(result) + .Also(attempt) + .Is(tries) + .Also(resetAttempt) + .Is(tries - 1); + } + + [Theory, RandomData] + internal static void Retry_WrongExceptionThrows(NotSupportedException exception) + { + new Limiter(3) + .Assert(x => + x.Retry( + GetAMessage(), + (Action)(() => throw exception), + TestContext.Current.CancellationToken + ) + ) + .Throws() + .That() + .Is(exception); + + IOException exception2 = new(); + new Limiter(3) + .Assert(x => + x.Retry( + GetAMessage(), + () => throw exception2, + TestContext.Current.CancellationToken + ) + ) + .Throws() + .That() + .Is(exception2); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void Attempt_ResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempt = 0; + int resetAttempt = 0; + + new Limiter(tries) + .Assert(x => + x.Attempt( + GetAMessage(), + () => + { + if (++attempt < tries) + { + throw exception; + } + }, + () => resetAttempt++, + TestContext.Current.CancellationToken + ) + ) + .ThrowsNo() + .Also(attempt) + .Is(tries) + .Also(resetAttempt) + .Is(tries - 1); + } + + [Theory, InlineData(1), InlineData(3)] + internal static void Attempt_ReturnResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempt = 0; + int resetAttempt = 0; + + int result = Tools.Randomizer.Create(); + int resetBehavior() + { + return (++attempt == tries) ? result : throw exception; + } + + new Limiter(tries) + .Attempt( + GetAMessage(), + resetBehavior, + () => resetAttempt++, + TestContext.Current.CancellationToken + ) + .Assert() + .Is(result) + .Also(attempt) + .Is(tries) + .Also(resetAttempt) + .Is(tries - 1); + } + + [Theory, RandomData] + internal static void Attempt_WrongExceptionThrows(NotSupportedException exception) + { + Limiter + .Once.Assert(x => + x.Attempt( + null, + (Action)(() => throw exception), + TestContext.Current.CancellationToken + ) + ) + .Throws() + .That() + .Is(exception); + + IOException exception2 = new(); + Limiter + .Once.Assert(x => + x.Attempt( + "Wrong subclass exception test.", + () => throw exception2, + TestContext.Current.CancellationToken + ) + ) + .Throws() + .That() + .Is(exception2); + } + + private static string GetAMessage() + { + return Tools.Gen.NextItem(["", null, "Test."]); + } +} diff --git a/tests/Design.Tests/Reiteration/Limiter.TaskTests.cs b/tests/Design.Tests/Reiteration/Limiter.TaskTests.cs new file mode 100644 index 00000000..262e6b54 --- /dev/null +++ b/tests/Design.Tests/Reiteration/Limiter.TaskTests.cs @@ -0,0 +1,996 @@ +using System.Diagnostics; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Reiteration; + +namespace Werecodent.CreateAndFake.Design.Tests.Reiteration; + +public static class LimiterTaskTests +{ + private const int _WaitAccuracy = 5; + + private static readonly TimeSpan _SmallDelay = new(0, 0, 0, 0, 1); + + [Theory, InlineData(1), InlineData(5)] + internal static Task RepeatAsync_TryLimited(int tries) + { + int attempts = 0; + + return new Limiter(tries) + .RepeatAsync( + GetAMessage(), + ToTask(() => attempts++), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static async Task StallUntilAsync_TryLimited(int tries) + { + int attempts = 0; + await new Limiter(tries) + .StallUntilAsync( + GetAMessage(), + ToTask(() => attempts++), + () => false, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries); + + attempts = 0; + await new Limiter(tries) + .StallUntilAsync( + GetAMessage(), + ToTask(() => attempts++), + () => Task.FromResult(false), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task RetryAsync_TryLimited(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + + return new Limiter(tries) + .RetryAsync( + GetAMessage(), + ToTask(() => + { + attempts++; + throw exception; + }), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .With(x => x.InnerException) + .ValuesEqual(exception) + .Also(() => attempts) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static Task AttemptAsync_TryLimited(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + + return new Limiter(tries) + .AttemptAsync( + GetAMessage(), + ToTask(() => + { + attempts++; + throw exception; + }), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries); + } + + [Fact] + internal static Task RepeatAsync_TimeoutLimited() + { + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(_SmallDelay) + .RepeatAsync( + GetAMessage(), + () => Task.CompletedTask, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + } + + [Fact] + internal static async Task StallUntilAsync_TimeoutLimited() + { + Stopwatch watch = Stopwatch.StartNew(); + await new Limiter(_SmallDelay) + .StallUntilAsync( + GetAMessage(), + () => Task.CompletedTask, + () => false, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + + watch.Restart(); + await new Limiter(_SmallDelay) + .StallUntilAsync( + GetAMessage(), + () => Task.CompletedTask, + () => Task.FromResult(false), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + } + + [Theory, RandomData] + internal static Task RetryAsync_TimeoutLimited(Exception exception) + { + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(_SmallDelay) + .RetryAsync( + GetAMessage(), + () => Task.FromException(exception), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .With(x => x.InnerException) + .ValuesEqual(exception) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + } + + [Theory, RandomData] + internal static Task AttemptAsync_TimeoutLimited(Exception exception) + { + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(_SmallDelay) + .AttemptAsync( + GetAMessage(), + ToTask(() => watch.IsRunning ? throw exception : new object()), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNull() + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo(_SmallDelay.TotalMilliseconds - _WaitAccuracy); + } + + [Theory, InlineData(1), InlineData(2), InlineData(3)] + internal static Task RepeatAsync_DelayOccurs(int tries) + { + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(tries, _SmallDelay) + .RepeatAsync( + GetAMessage(), + ToTask(() => attempts++), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attempts) + .Is(tries) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo((_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); + } + + [Theory, InlineData(1), InlineData(2), InlineData(3)] + internal static Task StallUntilAsync_DelayOccurs(int tries) + { + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(tries, _SmallDelay) + .StallUntilAsync( + GetAMessage(), + ToTask(() => ++attempts == tries), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo((_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); + } + + [Theory, InlineData(1), InlineData(2), InlineData(3)] + internal static Task RetryAsync_DelayOccurs(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(tries, _SmallDelay) + .RetryAsync( + GetAMessage(), + ToTask(() => + { + if (++attempts < tries) + { + throw exception; + } + }), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo((_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); + } + + [Theory, InlineData(1), InlineData(2), InlineData(3)] + internal static Task AttemptAsync_DelayOccurs(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attempts = 0; + Stopwatch watch = Stopwatch.StartNew(); + + return new Limiter(tries, _SmallDelay) + .AttemptAsync( + GetAMessage(), + ToTask(() => + { + if (++attempts < tries) + { + throw exception; + } + }), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => watch.Elapsed.TotalMilliseconds) + .GreaterThanOrEqualTo((_SmallDelay.TotalMilliseconds - _WaitAccuracy) * (tries - 1)); + } + + [Fact] + internal static async Task RepeatAsync_Cancelable() + { + await Limiter + .Slow.RepeatAsync(GetAMessage(), () => Task.CompletedTask, new CancellationToken(true)) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource = new(); + + await Limiter + .Few.RepeatAsync( + GetAMessage(), + () => AsyncSeriesHelper.TriggerCancellationAsync(tokenSource), + tokenSource.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task StallUntilAsync_Cancelable() + { + await Limiter + .Fast.StallUntilAsync( + GetAMessage(), + () => Task.FromResult(false), + new CancellationToken(true) + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource = new(); + await Limiter + .Few.StallUntilAsync( + GetAMessage(), + () => AsyncSeriesHelper.TriggerCancellationAsync(tokenSource), + () => false, + tokenSource.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource2 = new(); + await Limiter + .Few.StallUntilAsync( + GetAMessage(), + () => AsyncSeriesHelper.TriggerCancellationAsync(tokenSource2), + () => Task.FromResult(false), + tokenSource2.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task RetryAsync_Cancelable(Exception exception) + { + await Limiter + .Slow.RetryAsync( + GetAMessage(), + () => Task.FromException(exception), + new CancellationToken(true) + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource = new(); + await Limiter + .Few.RetryAsync( + GetAMessage(), + () => Task.FromException(exception), + tokenSource.Cancel, + tokenSource.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource2 = new(); + await Limiter + .Few.RetryAsync( + GetAMessage(), + () => Task.FromException(exception), + () => AsyncSeriesHelper.TriggerCancellationAsync(tokenSource2), + tokenSource2.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task AttemptAsync_Cancelable(Exception exception) + { + await Limiter + .Slow.AttemptAsync( + GetAMessage(), + () => Task.FromException(exception), + new CancellationToken(true) + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource = new(); + await Limiter + .Few.AttemptAsync( + GetAMessage(), + () => Task.FromException(exception), + tokenSource.Cancel, + tokenSource.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + using CancellationTokenSource tokenSource2 = new(); + await Limiter + .Few.AttemptAsync( + GetAMessage(), + () => Task.FromException(exception), + () => AsyncSeriesHelper.TriggerCancellationAsync(tokenSource2), + tokenSource2.Token + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task RepeatAsync_ResultsValid(List data) + { + int attemptAsync = 0; + + return new Limiter(data.Count) + .RepeatAsync( + GetAMessage(), + ToTask(() => data[attemptAsync++]), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(data.AsReadOnly()); + } + + [Theory, RandomData] + internal static Task StallUntilAsync_ResultsValid(List data) + { + int attemptAsync = 0; + + return new Limiter(data.Count) + .StallUntilAsync( + GetAMessage(), + ToTask(() => data[attemptAsync++]), + ToTask(() => attemptAsync == data.Count), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(data.AsReadOnly()); + } + + [Theory, RandomData] + internal static Task RetryAsync_ResultsValid(int data) + { + return new Limiter(1) + .RetryAsync( + GetAMessage(), + () => Task.FromResult(data), + TestContext.Current.CancellationToken + ) + .Assert() + .IsAsync(Task.FromResult(data), TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task RetryAsync_Continues() + { + int calls = 0; + + await new Limiter(2) + .RetryAsync( + GetAMessage(), + ToTask(() => + { + calls++; + if (calls == 1) + { + throw new ArithmeticException(); + } + }), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => calls) + .Is(2); + + await new Limiter(2) + .RetryAsync( + GetAMessage(), + ToTask(() => + { + calls++; + if (calls == 3) + { + throw new ArithmeticException(); + } + }), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => calls) + .Is(4); + } + + [Theory, RandomData] + internal static Task AttemptAsync_ResultsValid(int data) + { + return new Limiter(1) + .AttemptAsync( + GetAMessage(), + () => Task.FromResult(data), + TestContext.Current.CancellationToken + ) + .Assert() + .IsAsync(Task.FromResult(data), TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task AttemptAsync_Continues() + { + int calls = 0; + + await new Limiter(2) + .AttemptAsync( + GetAMessage(), + ToTask(() => + { + calls++; + if (calls == 1) + { + throw new ArithmeticException(); + } + }), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => calls) + .Is(2); + + await new Limiter(2) + .AttemptAsync( + GetAMessage(), + ToTask(() => + { + calls++; + if (calls == 3) + { + throw new ArithmeticException(); + } + }), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => calls) + .Is(4); + } + + [Theory, RandomData] + internal static Task AttemptAsync_DefaultOnFail(Exception error) + { + return new Limiter(1) + .AttemptAsync( + GetAMessage(), + ToTask(() => error != null ? throw error : 1), + ToTask(() => Task.FromResult(null)), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(0); + } + + [Theory, InlineData(1), InlineData(3)] + internal static async Task StallUntilAsync_CheckStateBehavior(int tries) + { + int attemptAsync = 0; + int checkAttemptAsync = 0; + + await new Limiter(tries) + .StallUntilAsync( + GetAMessage(), + ToTask(() => attemptAsync++), + () => ++checkAttemptAsync == tries, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => checkAttemptAsync) + .Is(tries); + + attemptAsync = 0; + checkAttemptAsync = 0; + + await new Limiter(tries) + .StallUntilAsync( + GetAMessage(), + ToTask(() => attemptAsync++), + ToTask(() => ++checkAttemptAsync == tries), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => checkAttemptAsync) + .Is(tries); + } + + [Theory, InlineData(1), InlineData(3)] + internal static async Task RetryAsync_ResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + int resetAttemptAsync = 0; + + await new Limiter(tries) + .RetryAsync( + GetAMessage(), + ToTask(() => + { + if (++attemptAsync < tries) + { + throw exception; + } + }), + () => resetAttemptAsync++, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + + attemptAsync = 0; + resetAttemptAsync = 0; + + await new Limiter(tries) + .RetryAsync( + GetAMessage(), + ToTask(() => + { + if (++attemptAsync < tries) + { + throw exception; + } + }), + ToTask((Action)(() => _ = resetAttemptAsync++)), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + } + + [Theory, InlineData(1), InlineData(3)] + internal static async Task RetryAsync_ReturnResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + int resetAttemptAsync = 0; + + int result = Tools.Randomizer.Create(); + int resetBehavior() + { + return (++attemptAsync == tries) ? result : throw exception; + } + + await new Limiter(tries) + .RetryAsync( + GetAMessage(), + ToTask(resetBehavior), + () => resetAttemptAsync++, + TestContext.Current.CancellationToken + ) + .Assert() + .IsAsync(Task.FromResult(result), TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + + attemptAsync = 0; + resetAttemptAsync = 0; + await new Limiter(tries) + .RetryAsync( + GetAMessage(), + ToTask(resetBehavior), + ToTask((Action)(() => _ = resetAttemptAsync++)), + TestContext.Current.CancellationToken + ) + .Assert() + .IsAsync(Task.FromResult(result), TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + } + + [Theory, RandomData] + internal static async Task RetryAsync_WrongExceptionThrows(NotSupportedException exception) + { + await new Limiter(3) + .RetryAsync( + GetAMessage(), + () => Task.FromException(exception), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .That() + .Is(exception); + + IOException exception2 = new(); + + await new Limiter(3) + .RetryAsync( + GetAMessage(), + ToTask(() => exception2 != null ? throw exception2 : false), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .That() + .Is(exception2); + } + + [Theory, InlineData(1), InlineData(3)] + internal static async Task AttemptAsync_ResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + int resetAttemptAsync = 0; + + await new Limiter(tries) + .AttemptAsync( + GetAMessage(), + ToTask(() => + { + if (++attemptAsync < tries) + { + throw exception; + } + }), + () => resetAttemptAsync++, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + + attemptAsync = 0; + resetAttemptAsync = 0; + + await new Limiter(tries) + .AttemptAsync( + GetAMessage(), + ToTask(() => + { + if (++attemptAsync < tries) + { + throw exception; + } + }), + ToTask((Action)(() => _ = resetAttemptAsync++)), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + } + + [Theory, InlineData(1), InlineData(3)] + internal static async Task AttemptAsync_ReturnResetStateBehavior(int tries) + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + int resetAttemptAsync = 0; + + int result = Tools.Randomizer.Create(); + int resetBehavior() + { + return (++attemptAsync == tries) ? result : throw exception; + } + + await new Limiter(tries) + .AttemptAsync( + GetAMessage(), + ToTask(resetBehavior), + () => resetAttemptAsync++, + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(result) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + + attemptAsync = 0; + resetAttemptAsync = 0; + + await new Limiter(tries) + .AttemptAsync( + GetAMessage(), + ToTask(resetBehavior), + ToTask((Action)(() => _ = resetAttemptAsync++)), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(result) + .Also(() => attemptAsync) + .Is(tries) + .Also(() => resetAttemptAsync) + .Is(tries - 1); + } + + [Theory, RandomData] + internal static async Task AttemptAsync_WrongExceptionThrows(NotSupportedException exception) + { + await new Limiter(3) + .AttemptAsync( + GetAMessage(), + () => Task.FromException(exception), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .That() + .Is(exception); + + IOException exception2 = new(); + + await new Limiter(3) + .AttemptAsync( + GetAMessage(), + ToTask(() => exception2 != null ? throw exception2 : false), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken) + .That() + .Is(exception2); + } + +#pragma warning disable MA0022, RCS1210, VSTHRD114 // For testing. + [Fact] + internal static async Task RepeatAsync_BehaviorReturningNullThrows() + { + await new Limiter(2) + .RepeatAsync( + GetAMessage(), + (Func>)null, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + await new Limiter(2) + .RepeatAsync( + GetAMessage(), + () => (Task)null, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + await new Limiter(2) + .RepeatAsync( + GetAMessage(), + (Func>)null, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + await new Limiter(2) + .RepeatAsync( + GetAMessage(), + () => (Task)null, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task AttemptAsync_ResetReturningNullIgnored() + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + + await new Limiter(2) + .AttemptAsync( + GetAMessage(), + ToTask(() => + { + if (++attemptAsync < 2) + { + throw exception; + } + }), + null, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(2); + + await new Limiter(2) + .AttemptAsync( + GetAMessage(), + ToTask(() => + { + if (++attemptAsync < 4) + { + throw exception; + } + }), + () => null, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(4); + } + + [Fact] + internal static async Task RetryAsync_ResetReturningNullIgnored() + { + Exception exception = Tools.Randomizer.Create(); + int attemptAsync = 0; + + await new Limiter(2) + .RetryAsync( + GetAMessage(), + ToTask(() => + { + if (++attemptAsync < 2) + { + throw exception; + } + }), + null, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(2); + + await new Limiter(2) + .RetryAsync( + GetAMessage(), + ToTask(() => + { + if (++attemptAsync < 4) + { + throw exception; + } + }), + () => null, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => attemptAsync) + .Is(4); + } +#pragma warning restore MA0022, RCS1210, VSTHRD114 + + private static Func ToTask(Action behavior) + { + return () => Task.Run(behavior, TestContext.Current.CancellationToken); + } + + private static Func> ToTask(Func behavior) + { + return () => Task.Run(behavior, TestContext.Current.CancellationToken); + } + + private static string GetAMessage() + { + return Tools.Gen.NextItem(["", null, "Test."]); + } +} diff --git a/tests/Design.Tests/Reiteration/LimiterTests.cs b/tests/Design.Tests/Reiteration/LimiterTests.cs new file mode 100644 index 00000000..6e8ad26a --- /dev/null +++ b/tests/Design.Tests/Reiteration/LimiterTests.cs @@ -0,0 +1,178 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Reiteration; + +public sealed class LimiterTests : AutoTester +{ + protected override Limiter TestInstance { get; } = Limiter.Few; + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ArgumentOutOfRangeException), + typeof(TimeoutException), + typeof(FormatException), + ], + }; + + [Fact] + internal static void Debug_Limiter_NamesWithDurationEstimates() + { + Limiter customLimiter = new(TimeSpan.FromSeconds(1), 2, null); + + new Dictionary() + { + { Limiter.Once, Limiter.Once.GetMaxDurationEstimate() }, + { Limiter.Few, Limiter.Few.GetMaxDurationEstimate() }, + { Limiter.Dozen, Limiter.Dozen.GetMaxDurationEstimate() }, + { Limiter.Score, Limiter.Score.GetMaxDurationEstimate() }, + { Limiter.Hundred, Limiter.Hundred.GetMaxDurationEstimate() }, + { Limiter.Myriad, Limiter.Myriad.GetMaxDurationEstimate() }, + { Limiter.Quick, Limiter.Quick.GetMaxDurationEstimate() }, + { Limiter.Fast, Limiter.Fast.GetMaxDurationEstimate() }, + { Limiter.Slow, Limiter.Slow.GetMaxDurationEstimate() }, + { customLimiter, customLimiter.GetMaxDurationEstimate() }, + } + .Assert() + .Debug(); + } + + [Fact] + internal static void Limiter_DefaultsConvertible() + { + foreach ( + PropertyInfo info in TypeDescriber + .For() + .Properties.OnlyPublic.Where(p => p.PropertyType == typeof(Limiter)) + ) + { + Limiter instance = (Limiter)info.GetValue(null); + Limiter.ConvertFrom(instance.ToString(), null).Assert().ReferenceEqual(instance); + } + } + + [Fact] + internal static void Limiter_CompareWorks() + { + Limiter + .Once.Equals((ILimiter)Limiter.Once) + .Assert() + .Is(true, ".Equals") + .Also(Limiter.Dozen.Equals(Limiter.Few)) + .Is(false, ".Equals") + .Also(Limiter.Myriad == Limiter.Myriad) + .Is(true, "==") + .Also(Limiter.Myriad == Limiter.Hundred) + .Is(false, "==") + .Also(Limiter.Fast != Limiter.Once) + .Is(true, "!=") + .Also(Limiter.Dozen != Limiter.Dozen) + .Is(false, "!=") + .Also(Limiter.Dozen > Limiter.Few) + .Is(true, ">") + .Also(Limiter.Once > Limiter.Few) + .Is(false, ">") + .Also(Limiter.Hundred >= Limiter.Hundred) + .Is(true, ">=") + .Also(Limiter.Quick >= Limiter.Slow) + .Is(false, ">=") + .Also(Limiter.Once < Limiter.Fast) + .Is(true, "<") + .Also(Limiter.Myriad < Limiter.Few) + .Is(false, "<") + .Also(Limiter.Slow <= Limiter.Slow) + .Is(true, "<=") + .Also(Limiter.Myriad <= Limiter.Hundred) + .Is(false, "<="); + } + + [Fact] + internal static void Limiter_PositiveTimesOnly() + { + new Limiter(TimeSpan.FromTicks(1), 1, TimeSpan.Zero) + .Assert() + .IsNotNull() + .Also(() => new Limiter(TimeSpan.Zero, 1, TimeSpan.Zero)) + .Throws() + .Also(() => new Limiter(TimeSpan.FromTicks(1), 0, TimeSpan.Zero)) + .Throws() + .Also(() => new Limiter(TimeSpan.FromTicks(1), 1, TimeSpan.FromTicks(-1))) + .Throws() + .Also(new Limiter(TimeSpan.FromTicks(1), 1, null)) + .IsNotNull() + .Also(new Limiter(TimeSpan.FromTicks(1), 1, TimeSpan.FromTicks(1))); + } + + [Fact] + internal static void Equals_MatchesValue() + { + int tries = Tools.Gen.Next(int.MaxValue); + TimeSpan elapsed = Tools.Gen.Next(TimeSpan.MaxValue); + + Limiter original = new(tries, elapsed); + Limiter dupe = new(tries, elapsed); + Limiter variant1 = new(Tools.Gen.Next(int.MaxValue), elapsed); + Limiter variant2 = new(tries, Tools.Gen.Next(TimeSpan.MaxValue)); + + true + .Assert() + .Is(original.Equals(original)) + .And() + .Is(original.Equals(dupe)) + .And() + .IsNot(original.Equals(variant1)) + .And() + .IsNot(original.Equals(variant2)) + .Also(original.GetHashCode()) + .Is(original.GetHashCode()) + .And() + .Is(dupe.GetHashCode()) + .And() + .IsNot(variant1.GetHashCode()) + .And() + .IsNot(variant2.GetHashCode()); + } + + [Fact] + internal static void ToString_Readable() + { + int tries = Tools.Gen.Next(int.MaxValue); + TimeSpan timeout = Tools.Gen.Next(TimeSpan.MaxValue); + TimeSpan delay = Tools.Gen.Next(TimeSpan.MaxValue); + + new Limiter(timeout, tries, delay).ToString().Assert().Is($"{tries}-{timeout}-{delay}"); + } + + [Fact] + internal static void ConvertFrom_ToString() + { + int tries = Tools.Gen.Next(int.MaxValue); + TimeSpan timeout = Tools.Gen.Next(TimeSpan.MaxValue); + TimeSpan delay = Tools.Gen.Next(TimeSpan.MaxValue); + + Limiter tryLimiter = new(tries); + Limiter tryDelayLimiter = new(tries, delay); + Limiter timeoutLimiter = new(timeout); + Limiter timeoutDelayLimiter = new(timeout, delay); + Limiter fullLimiter = new(timeout, tries, delay); + + Limiter.ConvertFrom(tryLimiter.ToString(), null).Assert().Is(tryLimiter); + Limiter.ConvertFrom(tryDelayLimiter.ToString(), null).Assert().Is(tryDelayLimiter); + Limiter.ConvertFrom(timeoutLimiter.ToString(), null).Assert().Is(timeoutLimiter); + Limiter.ConvertFrom(timeoutDelayLimiter.ToString(), null).Assert().Is(timeoutDelayLimiter); + Limiter.ConvertFrom(fullLimiter.ToString(), null).Assert().Is(fullLimiter); + } + + [Fact] + internal static void GetMaxDurationEstimate_ThrowsWithNegative() + { + Limiter.Once.Assert(x => x.GetMaxDurationEstimate(0)).Throws(); + Limiter.Few.Assert(x => x.GetMaxDurationEstimate(-1)).Throws(); + } +} diff --git a/tests/Design.Tests/Reiteration/LimiterTypeConverterTests.cs b/tests/Design.Tests/Reiteration/LimiterTypeConverterTests.cs new file mode 100644 index 00000000..7e4a5c7b --- /dev/null +++ b/tests/Design.Tests/Reiteration/LimiterTypeConverterTests.cs @@ -0,0 +1,49 @@ +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Reiteration; + +public sealed class LimiterTypeConverterTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + OnlyDeclaredMethods = true, + IgnorableExceptions = + [ + typeof(FormatException), + typeof(ArgumentException), + typeof(InvalidCastException), + typeof(ArgumentOutOfRangeException), + ], + }; + + private static readonly LimiterTypeConverter _TestInstance = new(); + + [Theory, RandomData] + public void ConvertFrom_Tries(int tries) + { + _TestInstance.CanConvertFrom(typeof(int)).Assert().Is(true); + _TestInstance.ConvertFrom(Math.Abs(tries)).Assert().Is(new Limiter(Math.Abs(tries))); + } + + [Theory, RandomData] + public void ConvertFrom_ConvertToRoundtrip(Limiter limiter) + { + _TestInstance.CanConvertTo(typeof(string)).Assert().Is(true); + _TestInstance.CanConvertFrom(typeof(string)).Assert().Is(true); + + string result = (string)_TestInstance.ConvertTo(limiter, typeof(string)); + + _TestInstance.ConvertFrom(result).Assert().Is(limiter); + } + + [Theory, RandomData] + public void ConvertTo_InvalidTypesThrow(DataSample item) + { + _TestInstance.Assert(x => x.ConvertTo(item, typeof(string))).Throws(); + _TestInstance.Assert(x => x.ConvertFrom(item)).Throws(); + } +} diff --git a/tests/Design.Tests/Tooling/ConfigurableOptionAttributeTests.cs b/tests/Design.Tests/Tooling/ConfigurableOptionAttributeTests.cs new file mode 100644 index 00000000..ec8146ae --- /dev/null +++ b/tests/Design.Tests/Tooling/ConfigurableOptionAttributeTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.Design.Tests.Tooling; + +public sealed class ConfigurableOptionAttributeTests : AutoTester; diff --git a/tests/Design.Tests/Tooling/DesignOptionsTests.cs b/tests/Design.Tests/Tooling/DesignOptionsTests.cs new file mode 100644 index 00000000..a96e43ef --- /dev/null +++ b/tests/Design.Tests/Tooling/DesignOptionsTests.cs @@ -0,0 +1,8 @@ +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.Design.Tests.Tooling; + +public sealed class DesignOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; +} diff --git a/tests/Design.Tests/Types/ConstructorScannerTests.cs b/tests/Design.Tests/Types/ConstructorScannerTests.cs new file mode 100644 index 00000000..55fc6aac --- /dev/null +++ b/tests/Design.Tests/Types/ConstructorScannerTests.cs @@ -0,0 +1,53 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +#pragma warning disable IDE0051, MA0017, RCS1160, S3442 // For testing. + +public sealed class ConstructorScannerTests : AutoTester +{ + internal abstract class BaseMembers + { + public BaseMembers() { } + + public BaseMembers(string _) { } + } + + internal sealed class Members : BaseMembers + { + public Members() + : base() { } + + public Members(int _) + : base() { } + + internal Members(string text) + : base(text) { } + + private Members(short _) + : base() { } + } + + [Fact] + internal static void All_ConstructorsFound() + { + new ConstructorScanner(typeof(Members)).All.Assert().HasCount(4); + } + + [Fact] + internal static void PublicOrInternal_ConstructorsFound() + { + ConstructorScanner scanner = new(typeof(Members)); + scanner.PublicOrInternal.Assert().HasCount(3); + + scanner.Visible.Assert().Is(scanner.PublicOrInternal); + } + + [Fact] + internal static void OnlyPublic_ConstructorsFound() + { + new ConstructorScanner(typeof(Members)).OnlyPublic.Assert().HasCount(2); + } +} + +#pragma warning restore diff --git a/tests/Design.Tests/Types/FactoryScannerTests.cs b/tests/Design.Tests/Types/FactoryScannerTests.cs new file mode 100644 index 00000000..105cce6b --- /dev/null +++ b/tests/Design.Tests/Types/FactoryScannerTests.cs @@ -0,0 +1,85 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +public sealed class FactoryScannerTests : AutoTester +{ + private const BindingFlags _AllScope = + BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + + internal abstract class BaseMembers + { + public static Members BaseInvalidMaker() + { + return null; + } + } + + internal sealed class Members : BaseMembers + { + private Members() { } + + public static Members PublicMaker() + { + return new(); + } + + public static Members PublicMakerWithParam(int _) + { + return new(); + } + + internal static Members InternalMaker() + { + return PrivateMaker(); + } + + private static Members PrivateMaker() + { + return new(); + } + } + + [Fact] + internal static void All_FactoriesFound() + { + HashSet expectedFactories = + [ + typeof(Members).GetMethod("PrivateMaker", _AllScope), + typeof(Members).GetMethod(nameof(Members.PublicMaker), _AllScope), + typeof(Members).GetMethod(nameof(Members.PublicMakerWithParam), _AllScope), + typeof(Members).GetMethod(nameof(Members.InternalMaker), _AllScope), + ]; + + new FactoryScanner(typeof(Members)).All.ToHashSet().Assert().Is(expectedFactories); + } + + [Fact] + internal static void PublicOrInternal_FactoriesFound() + { + HashSet expectedFactories = + [ + typeof(Members).GetMethod(nameof(Members.PublicMaker), _AllScope), + typeof(Members).GetMethod(nameof(Members.PublicMakerWithParam), _AllScope), + typeof(Members).GetMethod(nameof(Members.InternalMaker), _AllScope), + ]; + + FactoryScanner scanner = new(typeof(Members)); + scanner.PublicOrInternal.ToHashSet().Assert().Is(expectedFactories); + + scanner.Visible.Assert().Is(scanner.PublicOrInternal); + } + + [Fact] + internal static void OnlyPublic_FactoriesFound() + { + HashSet expectedFactories = + [ + typeof(Members).GetMethod(nameof(Members.PublicMaker), _AllScope), + typeof(Members).GetMethod(nameof(Members.PublicMakerWithParam), _AllScope), + ]; + + new FactoryScanner(typeof(Members)).OnlyPublic.ToHashSet().Assert().Is(expectedFactories); + } +} diff --git a/tests/Design.Tests/Types/FieldScannerTests.cs b/tests/Design.Tests/Types/FieldScannerTests.cs new file mode 100644 index 00000000..2c2e5ccc --- /dev/null +++ b/tests/Design.Tests/Types/FieldScannerTests.cs @@ -0,0 +1,122 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +#pragma warning disable CA1823, CS0169, CS0414, IDE0044, IDE0051, RCS1169, RCS1213, S1144, S2933 // For testing. + +public sealed class FieldScannerTests : AutoTester +{ + private const BindingFlags _AllScope = + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + private abstract class BaseMemberHolder + { + public static int _StaticBaseField = 0; + + private int _privateBaseMutateField = 0; + + private readonly int _privateBaseField = 0; + + internal int _internalBaseMutateField = 0; + + internal readonly int _internalBaseField = 0; + + public int _publicBaseMutateField = 0; + + public readonly int _publicBaseField = 0; + } + + private sealed class MemberHolder : BaseMemberHolder + { + public static int _StaticField = 0; + + private int _privateMutateField = 0; + + private readonly int _privateField = 0; + + internal int _internalMutateField = 0; + + internal readonly int _internalField = 0; + + public int _publicMutateField = 0; + + public readonly int _publicField = 0; + } + + [Fact] + internal static void All_FieldsFound() + { + HashSet expectedFields = + [ + typeof(BaseMemberHolder).GetField("_privateBaseMutateField", _AllScope), + typeof(BaseMemberHolder).GetField("_privateBaseField", _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._internalBaseField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._internalBaseMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicBaseField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicBaseMutateField), _AllScope), + typeof(MemberHolder).GetField("_privateField", _AllScope), + typeof(MemberHolder).GetField("_privateMutateField", _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._internalField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._internalMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicMutateField), _AllScope), + ]; + + new FieldScanner(typeof(MemberHolder)).All.Assert().Is(expectedFields); + } + + [Fact] + internal static void PublicOrInternal_FieldsFound() + { + HashSet expectedFields = + [ + typeof(MemberHolder).GetField(nameof(MemberHolder._internalBaseField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._internalBaseMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicBaseField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicBaseMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._internalField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._internalMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicMutateField), _AllScope), + ]; + + FieldScanner scanner = new(typeof(MemberHolder)); + scanner + .PublicOrInternal.ToHashSet() + .Assert() + .Is(expectedFields) + .And() + .Is(scanner.Visible.ToHashSet()); + } + + [Fact] + internal static void OnlyPublic_FieldsFound() + { + HashSet expectedFields = + [ + typeof(MemberHolder).GetField(nameof(MemberHolder._publicBaseField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicBaseMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicMutateField), _AllScope), + ]; + + new FieldScanner(typeof(MemberHolder)).OnlyPublic.ToHashSet().Assert().Is(expectedFields); + } + + [Fact] + internal static void Writable_FieldsFound() + { + HashSet expectedFields = + [ + typeof(MemberHolder).GetField(nameof(MemberHolder._internalBaseMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicBaseMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._internalMutateField), _AllScope), + typeof(MemberHolder).GetField(nameof(MemberHolder._publicMutateField), _AllScope), + ]; + + new FieldScanner(typeof(MemberHolder)).Writable.ToHashSet().Assert().Is(expectedFields); + } +} + +#pragma warning restore diff --git a/tests/Design.Tests/Types/GenericConverterTests.cs b/tests/Design.Tests/Types/GenericConverterTests.cs new file mode 100644 index 00000000..a51a7425 --- /dev/null +++ b/tests/Design.Tests/Types/GenericConverterTests.cs @@ -0,0 +1,139 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +public sealed class GenericConverterTests() : AutoTester(typeof(GenericConverter)) +{ + private static readonly MethodInfo _TestMethod = typeof(GenericConverterTests).GetMethod( + nameof(HiddenTestName), + BindingFlags.Static | BindingFlags.NonPublic + ); + + protected override Func OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(InvalidOperationException)] }; + + [Fact] + internal static void Debug_GenericConverter_BuildTestName() + { + GenericConverter.BuildTestName(_TestMethod).Assert().Debug(); + } + + [Fact] + internal static void Debug_GenericConverter_ExpandName() + { + GenericConverter.ExpandName>().Assert().Debug(); + } + + [Fact] + internal static void FindConcreteType_FindsBaseClasses() + { + GenericConverter + .FindConcreteType>(typeof(IList<>)) + .Assert() + .Is(typeof(IList)); + GenericConverter + .FindConcreteType>(typeof(IEnumerable<>)) + .Assert() + .Is(typeof(IEnumerable)); + GenericConverter.FindConcreteType>(typeof(Task<>)); + } + + [Fact] + internal static void FindConcreteType_ThrowsWhenMissing() + { + typeof(List<>) + .Assert(GenericConverter.FindConcreteType>) + .Throws(); + typeof(int) + .Assert(GenericConverter.FindConcreteType) + .Throws(); + } + + [Fact] + internal static void AsConcreteType_NullWhenMissing() + { + GenericConverter.AsConcreteType>(typeof(List<>)).Assert().IsNull(); + GenericConverter.AsConcreteType(typeof(int)).Assert().IsNull(); + GenericConverter.AsConcreteType(null, typeof(IEnumerable<>)).Assert().IsNull(); + } + + [Fact] + internal static void AsConcreteType_ExcludesGenericTypeDefinitions() + { + GenericConverter.AsConcreteType(typeof(IList<>), typeof(IList<>)).Assert().IsNull(); + } + + [Fact] + internal static void AsGenericBase_ConvertsGenerics() + { + GenericConverter.AsGenericBase(typeof(List)).Assert().Is(typeof(List<>)); + } + + [Fact] + internal static void AsGenericBase_NullForNonGeneric() + { + GenericConverter.AsGenericBase(typeof(string)).Assert().IsNull(); + } + + [Fact] + internal static void AsMatchedGeneric_FindsConcreteType() + { + GenericConverter + .AsMatchedGeneric(typeof(IEnumerable<>), typeof(List)) + .Assert() + .Is(typeof(IEnumerable)); + } + + [Fact] + internal static void AsMatchedGeneric_NullWithoutBaseDefinition() + { + GenericConverter + .AsMatchedGeneric(typeof(IEnumerable), typeof(List)) + .Assert() + .IsNull(); + } + + [Theory, RandomData] + internal static void ExpandName_ObjectGetType(IList data) + { + GenericConverter.ExpandName(data).Assert().Contains(nameof(Int32)); + } + + [Fact] + internal static void ExpandName_SameWithoutGenerics() + { + GenericConverter.ExpandName().Assert().Is(nameof(DataSample)); + } + + [Fact] + internal static void ExpandName_IncludesGenerics() + { + GenericConverter + .ExpandName>() + .Assert() + .Contains(nameof(Int32)) + .And() + .Contains(nameof(String)); + } + + [Fact] + internal static void BuildTestName_IncludesParameters() + { + GenericConverter + .BuildTestName(_TestMethod) + .Assert() + .Contains(nameof(HiddenTestName)) + .And() + .Contains(nameof(String)) + .And() + .Contains(nameof(Int32)); + } + + private static void HiddenTestName(string value, int num) + { + ArgumentGuard.ThrowIfNull(value, num); + } +} diff --git a/tests/Design.Tests/Types/MethodScannerTests.cs b/tests/Design.Tests/Types/MethodScannerTests.cs new file mode 100644 index 00000000..4186cb58 --- /dev/null +++ b/tests/Design.Tests/Types/MethodScannerTests.cs @@ -0,0 +1,121 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +#pragma warning disable CS0628, IDE0051, CA1822, RCS1213, S1144, S1186 // For testing. + +public sealed class MethodScannerTests : AutoTester +{ + private const BindingFlags _AllScope = + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + internal abstract class BaseMembers + { + public static void BaseStaticMethod() { } + + public void BasePublicMethod() { } + + protected void BaseProtectedMethod() { } + + protected internal void BaseProtectedInternalMethod() { } + + internal void BaseInternalMethod() { } + + private void BasePrivateMethod() { } + } + + internal sealed class Members : BaseMembers + { + public static void StaticMethod() { } + + public void PublicMethod() { } + + protected void ProtectedMethod() { } + + protected internal void ProtectedInternalMethod() { } + + internal void InternalMethod() { } + + private void PrivateMethod() { } + } + + [Fact] + internal static void All_MethodsFound() + { + HashSet expectedMethods = + [ + typeof(BaseMembers).GetMethod("BasePrivateMethod", _AllScope), + typeof(Members).GetMethod("BaseProtectedMethod", _AllScope), + typeof(Members).GetMethod("PrivateMethod", _AllScope), + typeof(Members).GetMethod("ProtectedMethod", _AllScope), + typeof(Members).GetMethod(nameof(Members.BasePublicMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.BaseProtectedInternalMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.BaseInternalMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.PublicMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.ProtectedInternalMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.InternalMethod), _AllScope), + ]; + + new MethodScanner(typeof(Members)) + .All.Where(m => m.DeclaringType != typeof(object)) + .ToHashSet() + .Assert() + .Is(expectedMethods); + } + + [Fact] + internal static void PublicOrInternal_MethodsFound() + { + HashSet expectedMethods = + [ + typeof(Members).GetMethod(nameof(Members.BasePublicMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.BaseProtectedInternalMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.BaseInternalMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.PublicMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.ProtectedInternalMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.InternalMethod), _AllScope), + ]; + + MethodScanner scanner = new(typeof(Members)); + scanner + .PublicOrInternal.Where(m => m.DeclaringType != typeof(object)) + .ToHashSet() + .Assert() + .Is(expectedMethods); + + scanner + .Visible.ToHashSet() + .Assert() + .Is(scanner.PublicOrInternal.Where(m => m.Name != "MemberwiseClone").ToHashSet()); + } + + [Fact] + internal static void Visible_FilteredByAccess() + { + HashSet expectedMethods = [.. typeof(RunnerTimeoutException).GetMethods()]; + + new MethodScanner(typeof(RunnerTimeoutException)) + .Visible.ToHashSet() + .Assert() + .Is(expectedMethods); + } + + [Fact] + internal static void OnlyPublic_MethodsFound() + { + HashSet expectedMethods = + [ + typeof(Members).GetMethod(nameof(Members.BasePublicMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.PublicMethod), _AllScope), + .. typeof(object) + .GetMethods(BindingFlags.Instance | BindingFlags.Public) + .Select(m => typeof(Members).GetMethod(m.Name, _AllScope)), + ]; + + new MethodScanner(typeof(Members)).OnlyPublic.ToHashSet().Assert().Is(expectedMethods); + } +} + +#pragma warning restore diff --git a/tests/Design.Tests/Types/PropertyScannerTests.cs b/tests/Design.Tests/Types/PropertyScannerTests.cs new file mode 100644 index 00000000..88ee007e --- /dev/null +++ b/tests/Design.Tests/Types/PropertyScannerTests.cs @@ -0,0 +1,140 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +#pragma warning disable IDE0032, IDE0051, RCS1170, RCS1213, S2376 // For testing. + +public sealed class PropertyScannerTests : AutoTester +{ + private const BindingFlags _AllScope = + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + internal interface IScopeMembers + { + string InterfaceInternalGetter { internal get; set; } + string InterfaceInternalSetter { get; internal set; } + int InterfacePublicProp { get; set; } + } + + internal abstract class BaseMembers : IScopeMembers + { + private int _privateSetterBacking = 0; + public static int BaseStaticProp { get; set; } = 0; + public string InterfaceInternalGetter { get; set; } + public string InterfaceInternalSetter { get; set; } + public int InterfacePublicProp { get; set; } + internal int BaseInternalGetter => _privateSetterBacking; + internal int BaseInternalSetter + { + set => _privateSetterBacking = value; + } + private string BasePrivateProp { get; set; } = ""; + } + + internal sealed class Members : BaseMembers + { + public static int StaticProp { get; set; } = 0; + public double InternalGetterWithSet { internal get; set; } + public double InternalSetterWithGet { get; internal set; } + internal int PrivateGetterWithInternalSet { private get; set; } + internal int PrivateSetterWithInternalGet { get; private set; } + } + + [Fact] + internal static void All_PropertiesFound() + { + HashSet expectedProperties = + [ + typeof(BaseMembers).GetProperty("BasePrivateProp", _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalGetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalSetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfacePublicProp), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.BaseInternalGetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.BaseInternalSetter), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalGetterWithSet), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalSetterWithGet), _AllScope), + typeof(Members).GetProperty(nameof(Members.PrivateGetterWithInternalSet), _AllScope), + typeof(Members).GetProperty(nameof(Members.PrivateSetterWithInternalGet), _AllScope), + ]; + + new PropertyScanner(typeof(Members)).All.ToHashSet().Assert().Is(expectedProperties); + } + + [Fact] + internal static void PublicOrInternal_PropertiesFound() + { + HashSet expectedProperties = + [ + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalGetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalSetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfacePublicProp), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.BaseInternalGetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.BaseInternalSetter), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalGetterWithSet), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalSetterWithGet), _AllScope), + typeof(Members).GetProperty(nameof(Members.PrivateGetterWithInternalSet), _AllScope), + typeof(Members).GetProperty(nameof(Members.PrivateSetterWithInternalGet), _AllScope), + ]; + + PropertyScanner scanner = new(typeof(Members)); + scanner + .PublicOrInternal.ToHashSet() + .Assert() + .Is(expectedProperties) + .And() + .Is(scanner.Visible.ToHashSet()); + } + + [Fact] + internal static void OnlyPublic_PropertiesFound() + { + HashSet expectedProperties = + [ + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalGetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalSetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfacePublicProp), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalGetterWithSet), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalSetterWithGet), _AllScope), + ]; + + new PropertyScanner(typeof(Members)).OnlyPublic.ToHashSet().Assert().Is(expectedProperties); + } + + [Fact] + internal static void SetAndGetable_PropertiesFound() + { + HashSet expectedProperties = + [ + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalGetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalSetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfacePublicProp), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalGetterWithSet), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalSetterWithGet), _AllScope), + ]; + + new PropertyScanner(typeof(Members)) + .SetAndGetable.ToHashSet() + .Assert() + .Is(expectedProperties); + } + + [Fact] + internal static void Settable_PropertiesFound() + { + HashSet expectedProperties = + [ + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalGetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfaceInternalSetter), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.InterfacePublicProp), _AllScope), + typeof(Members).GetProperty(nameof(BaseMembers.BaseInternalSetter), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalGetterWithSet), _AllScope), + typeof(Members).GetProperty(nameof(Members.InternalSetterWithGet), _AllScope), + typeof(Members).GetProperty(nameof(Members.PrivateGetterWithInternalSet), _AllScope), + ]; + + new PropertyScanner(typeof(Members)).Settable.ToHashSet().Assert().Is(expectedProperties); + } +} + +#pragma warning restore diff --git a/tests/Design.Tests/Types/RuntimeDetailsTests.cs b/tests/Design.Tests/Types/RuntimeDetailsTests.cs new file mode 100644 index 00000000..544af0fc --- /dev/null +++ b/tests/Design.Tests/Types/RuntimeDetailsTests.cs @@ -0,0 +1,81 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +public sealed class RuntimeDetailsTests() : AutoTester(typeof(RuntimeDetails)) +{ + [Fact] + internal static void RuntimeType_CorrectType() + { + RuntimeDetails.RuntimeType.FullName.Assert().Is("System.RuntimeType"); + } + + [Fact] + internal static void RuntimeConstructorInfoType_CorrectType() + { + RuntimeDetails + .RuntimeConstructorInfoType.FullName.Assert() + .Is("System.Reflection.RuntimeConstructorInfo"); + } + + [Fact] + internal static void RuntimeMethodInfoType_CorrectType() + { + RuntimeDetails + .RuntimeMethodInfoType.FullName.Assert() + .Is("System.Reflection.RuntimeMethodInfo"); + } + + [Fact] + internal static void RuntimePropertyInfoType_CorrectType() + { + RuntimeDetails + .RuntimePropertyInfoType.FullName.Assert() + .Is("System.Reflection.RuntimePropertyInfo"); + } + + [Fact] + internal static void RtFieldInfoType_CorrectType() + { + RuntimeDetails.RtFieldInfoType.FullName.Assert().Is("System.Reflection.RtFieldInfo"); + } + + [Fact] + internal static void MdFieldInfoType_CorrectType() + { + RuntimeDetails.MdFieldInfoType.FullName.Assert().Is("System.Reflection.MdFieldInfo"); + } + + [Fact] + internal static void RuntimeParameterInfoType_CorrectType() + { + RuntimeDetails + .RuntimeParameterInfoType.FullName.Assert() + .Is("System.Reflection.RuntimeParameterInfo"); + } + + [Fact] + internal static void RuntimeAssemblyType_CorrectType() + { + RuntimeDetails + .RuntimeAssemblyType.FullName.Assert() + .Is("System.Reflection.RuntimeAssembly"); + } + + [Fact] + internal static void RuntimeTypes_HasAll() + { + RuntimeDetails + .RuntimeTypes.Distinct() + .Count() + .Assert() + .Is(typeof(RuntimeDetails).GetProperties().Length - 1); + } + + [Theory, RandomData] + internal static void InnerClassValidation_Functions(string x, string y) + { + RuntimeDetails.InnerClassValidation(x, y).Assert().Is(false); + RuntimeDetails.InnerClassValidation(x, x).Assert().Is(true); + } +} diff --git a/tests/Design.Tests/Types/ScopeCheckerTests.cs b/tests/Design.Tests/Types/ScopeCheckerTests.cs new file mode 100644 index 00000000..12f19464 --- /dev/null +++ b/tests/Design.Tests/Types/ScopeCheckerTests.cs @@ -0,0 +1,70 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +public sealed class ScopeCheckerTests() : AutoTester(typeof(ScopeChecker)) +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(InvalidOperationException)] }; + + [Fact] + internal static void FindLoadedSpecificTypes_IncludesOnlyClasses() + { + ScopeChecker + .FindLoadedSpecificTypes(typeof(DataSample).Assembly) + .Assert() + .Contains(typeof(DataSample)) + .And() + .ContainsNot(typeof(IIsGoodOrBadSample)); + } + + [Theory, RandomData] + internal static void FindLoadedTypes_IgnoresMissingAssembly( + [Stub] Assembly assembly, + FileNotFoundException error + ) + { + assembly.GetTypes().SetupReturn(Behavior.Throw(error, Times.Once)); + ScopeChecker.FindLoadedTypes(assembly).Assert().IsEmpty(); + assembly.Assert().Called(); + } + + [Theory, RandomData] + internal static void FindLoadedTypes_IgnoresReflectError( + [Stub] Assembly assembly, + ReflectionTypeLoadException error + ) + { + assembly.GetTypes().SetupReturn(Behavior.Throw(error, Times.Once)); + ScopeChecker.FindLoadedTypes(assembly).Assert().IsEmpty(); + assembly.Assert().Called(); + } + + [Fact] + internal static void IsVisible_TrueForPublicClasses() + { + ScopeChecker.IsVisible(typeof(string).Assembly.GetName()).Assert().Is(true); + } + + [Fact] + internal static void IsVisible_TrueForInternalsWithAttribute() + { + ScopeChecker + .IsVisible(Assembly.GetExecutingAssembly().GetName()) + .Assert() + .Is(true); + } + + [Fact] + internal static void IsVisible_FalseForInternalsWithoutAttribute() + { + ScopeChecker + .IsVisible(typeof(string).Assembly.GetName()) + .Assert() + .Is(false); + } +} diff --git a/tests/Design.Tests/Types/StaticMethodScannerTests.cs b/tests/Design.Tests/Types/StaticMethodScannerTests.cs new file mode 100644 index 00000000..03a6c09f --- /dev/null +++ b/tests/Design.Tests/Types/StaticMethodScannerTests.cs @@ -0,0 +1,84 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +#pragma warning disable CS0628, IDE0051, CA1822, RCS1213, S1144, S1186 // For testing. + +public sealed class StaticMethodScannerTests : AutoTester +{ + private const BindingFlags _AllScope = + BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + + internal abstract class BaseMembers + { + public void BasePublicMethod() { } + + public static void BaseStaticMethod() { } + } + + internal sealed class Members : BaseMembers + { + public void PublicMethod() { } + + public static void StaticMethod() { } + + protected static void ProtectedStaticMethod() { } + + protected internal static void ProtectedInternalStaticMethod() { } + + internal static void InternalStaticMethod() { } + + private static void PrivateStaticMethod() { } + } + + [Fact] + internal static void All_StaticMethodsFound() + { + HashSet expectedMethods = + [ + typeof(Members).GetMethod("PrivateStaticMethod", _AllScope), + typeof(Members).GetMethod("ProtectedStaticMethod", _AllScope), + typeof(Members).GetMethod(nameof(Members.StaticMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.ProtectedInternalStaticMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.InternalStaticMethod), _AllScope), + ]; + + new StaticMethodScanner(typeof(Members)).All.ToHashSet().Assert().Is(expectedMethods); + } + + [Fact] + internal static void PublicOrInternal_StaticMethodsFound() + { + HashSet expectedMethods = + [ + typeof(Members).GetMethod(nameof(Members.StaticMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.ProtectedInternalStaticMethod), _AllScope), + typeof(Members).GetMethod(nameof(Members.InternalStaticMethod), _AllScope), + ]; + + StaticMethodScanner scanner = new(typeof(Members)); + scanner + .PublicOrInternal.ToHashSet() + .Assert() + .Is(expectedMethods) + .And() + .Is(scanner.Visible.ToHashSet()); + } + + [Fact] + internal static void OnlyPublic_StaticMethodsFound() + { + HashSet expectedMethods = + [ + typeof(Members).GetMethod(nameof(Members.StaticMethod), _AllScope), + ]; + + new StaticMethodScanner(typeof(Members)) + .OnlyPublic.ToHashSet() + .Assert() + .Is(expectedMethods); + } +} + +#pragma warning restore diff --git a/tests/Design.Tests/Types/TypeDescriberTests.cs b/tests/Design.Tests/Types/TypeDescriberTests.cs new file mode 100644 index 00000000..6cd3d93e --- /dev/null +++ b/tests/Design.Tests/Types/TypeDescriberTests.cs @@ -0,0 +1,116 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.Design.Randomization.Handlers; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +public sealed class TypeDescriberTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { DisableToolSetSupportTests = true }; + + protected override TypeDescriber TestInstance { get; } = TypeDescriber.For(null); + + [Fact] + internal static void For_Cached() + { + TypeDescriber.For().Assert().ReferenceEqual(TypeDescriber.For()); + } + + [Fact] + internal static void For_NullCachedAsEmpty() + { + TypeDescriber nullTracker = TypeDescriber.For(null); + TypeDescriber.For(null).Assert().ReferenceEqual(nullTracker); + nullTracker.InheritedTypes.Assert().IsEmpty(); + } + + [Fact] + internal static void Inherits_IncludesGenerics() + { + TypeDescriber collection = TypeDescriber.For>(); + collection.Inherits>().Assert().Is(false); + collection.Inherits>().Assert().Is(false); + collection.Inherits>().Assert().Is(true); + } + + [Fact] + internal static void Inherits_IncludesGenericBases() + { + TypeDescriber collection = TypeDescriber.For(typeof(IList<>)); + collection.Inherits>().Assert().Is(false); + collection.Inherits>().Assert().Is(false); + collection.Inherits(typeof(List<>)).Assert().Is(false); + collection.Inherits(typeof(IEnumerable<>)).Assert().Is(true); + } + + [Fact] + internal static void Inherits_SelfIncluded() + { + TypeDescriber.For().Inherits().Assert().Is(true); + } + + [Fact] + internal static void FindLocalSubclasses_ExcludesOtherAssemblies() + { + TypeDescriber + .For() + .FindLocalSubclasses() + .Assert() + .ContainsNot(typeof(PrivateValuerEquatableSample)); + } + + [Fact] + internal static void FindLocalSubclasses_SelfIncluded() + { + TypeDescriber + .For() + .FindLocalSubclasses() + .Assert() + .Contains(typeof(ValueComparer)); + } + + [Fact] + internal static void FindLoadedSubclasses_IncludesFromDifferentAssemblies() + { + TypeDescriber + .For() + .FindLoadedSubclasses() + .Assert() + .Contains(typeof(PrivateValuerEquatableSample)); + } + + [Fact] + internal static void FindLoadedSubclasses_SelfIncluded() + { + TypeDescriber + .For() + .FindLoadedSubclasses() + .Assert() + .Contains(typeof(ValueComparer)); + } + + [Fact] + internal static void FindLoadedSubclasses_ExcludesExclusionAttribute() + { + TypeDescriber + .For() + .FindLoadedSubclasses() + .Assert() + .ContainsNot(typeof(RuneValueHandler)); + } + + [Fact] + internal static void IsStatic_IdentifiesStaticClasses() + { + TypeDescriber.For(typeof(ArgumentGuard)).IsStatic().Assert().Is(true); + TypeDescriber.For().IsStatic().Assert().Is(false); + TypeDescriber.For().IsStatic().Assert().Is(false); + TypeDescriber.For().IsStatic().Assert().Is(false); + TypeDescriber.For().IsStatic().Assert().Is(false); + } +} diff --git a/tests/Design.Tests/Types/TypeSupporterTests.cs b/tests/Design.Tests/Types/TypeSupporterTests.cs new file mode 100644 index 00000000..956ba480 --- /dev/null +++ b/tests/Design.Tests/Types/TypeSupporterTests.cs @@ -0,0 +1,84 @@ +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Design.Tests.Types; + +public sealed class TypeSupporterTests() : AutoTester(typeof(TypeSupporter)) +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + MethodsToIgnore = [nameof(TypeSupporter.GroupBySubclasses)], + IgnorableExceptions = [typeof(ArgumentException)], + }; + + [Theory, RandomData] + internal static void GroupBySupportedType_GroupsSuccessfully(ITypeSupporter item) + { + ITypeSupporter item2 = item.Tools().Unique(); + + TypeSupporter + .GroupBySupportedType([item, item2]) + .Assert() + .Contains(new KeyValuePair(item.SupportedType, item)) + .And() + .Contains(new KeyValuePair(item2.SupportedType, item2)); + } + + [Fact] + internal static void GroupBySupportedType_IgnoresNullSupportedType() + { + TypeSupporter.GroupBySupportedType([TypeDescriber.For(null)]).Assert().IsEmpty(); + } + + [Theory, RandomData] + internal static void GroupByInheritance_JoinsWithInherited( + [Stub] ITypeSupporter item1, + [Stub] ITypeSupporter item2 + ) + { + item1.SupportedType.SetupReturn(typeof(string)); + item2.SupportedType.SetupReturn(typeof(object)); + TypeSupporter + .GroupByInheritance([item1, item2])[typeof(object)] + .Assert() + .Contains(item1) + .And() + .Contains(item2); + } + + [Fact] + internal static void GroupByInheritance_IgnoresNullSupportedType() + { + TypeSupporter.GroupByInheritance([TypeDescriber.For(null)]).Assert().IsEmpty(); + } + + [Fact] + internal static void GroupBySubclasses_NullSafe() + { + TypeSupporter.GroupBySubclasses(null).Assert().IsEmpty(); + } + + [Theory, RandomData] + internal static void GroupBySubclasses_JoinsWithSubclass( + [Stub] ITypeSupporter item1, + [Stub] ITypeSupporter item2 + ) + { + item1.SupportedType.SetupReturn(typeof(object)); + item2.SupportedType.SetupReturn(typeof(string)); + TypeSupporter + .GroupBySubclasses([item1, item2])[typeof(string)] + .Assert() + .Contains(item1) + .And() + .Contains(item2); + } + + [Fact] + internal static void GroupBySubclasses_IgnoresNullSupportedType() + { + TypeSupporter.GroupBySubclasses([TypeDescriber.For(null)]).Assert().IsEmpty(); + } +} diff --git a/tests/Design.Tests/testsettings.json b/tests/Design.Tests/testsettings.json new file mode 100644 index 00000000..f624980e --- /dev/null +++ b/tests/Design.Tests/testsettings.json @@ -0,0 +1,14 @@ +{ + "CreateAndFake": { + "Design": {}, + "Asserter": {}, + "Duplicator": {}, + "Extractor": {}, + "Faker": {}, + "Mutator": {}, + "Randomizer": {}, + "Runner": {}, + "Tester": {}, + "Valuer": {} + } +} \ No newline at end of file diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props index 6e752bb4..249a8517 100644 --- a/tests/Directory.Build.props +++ b/tests/Directory.Build.props @@ -1,15 +1,51 @@ latest + enable false true All true + false + false + Werecodent.$(MSBuildProjectName) + + + true - $(MSBuildThisFileDirectory)..\artifacts\obj\$(MSBuildProjectName)\ - $(MSBuildThisFileDirectory)..\artifacts\bin\$(MSBuildProjectName)\$(Configuration)\ $(MSBuildThisFileDirectory)..\artifacts\bin\$(MSBuildProjectName)\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName).xml + $(MSBuildThisFileDirectory)..\artifacts\obj\$(MSBuildProjectName) + $(MSBuildThisFileDirectory)..\artifacts\bin\$(MSBuildProjectName) + $(MSBuildThisFileDirectory)..\artifacts\bin\$(MSBuildProjectName)\$(Configuration)\ $(MSBuildThisFileDirectory)TestSettings.runsettings true + true - \ No newline at end of file + + + + Always + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/MSTest.v3.Tests/AutoTesterTests.cs b/tests/MSTest.v3.Tests/AutoTesterTests.cs new file mode 100644 index 00000000..59fb3420 --- /dev/null +++ b/tests/MSTest.v3.Tests/AutoTesterTests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class AutoTesterTests() : AutoTester(typeof(DataSample)); diff --git a/tests/MSTest.v3.Tests/AutoTester{T}Tests.cs b/tests/MSTest.v3.Tests/AutoTester{T}Tests.cs new file mode 100644 index 00000000..58996205 --- /dev/null +++ b/tests/MSTest.v3.Tests/AutoTester{T}Tests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class AutoTester_T_Tests : AutoTester; diff --git a/tests/MSTest.v3.Tests/CapAttributeTests.cs b/tests/MSTest.v3.Tests/CapAttributeTests.cs new file mode 100644 index 00000000..cb89eec4 --- /dev/null +++ b/tests/MSTest.v3.Tests/CapAttributeTests.cs @@ -0,0 +1,30 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class CapAttributeTests : AutoTester +{ + protected override CapAttribute TestInstance { get; } = new(5, 10); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentOutOfRangeException)], + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CapAttribute))), + ], + }; + + [TestMethod] + public void Clone_BranchesOnMinSet() + { + new CapAttribute(1).Clone().Assert().Is(new CapAttribute(1)); + new CapAttribute(1, 2).Clone().Assert().Is(new CapAttribute(1, 2)); + } +} diff --git a/tests/MSTest.v3.Tests/CopyAttributeTests.cs b/tests/MSTest.v3.Tests/CopyAttributeTests.cs new file mode 100644 index 00000000..eb7b3908 --- /dev/null +++ b/tests/MSTest.v3.Tests/CopyAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class CopyAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CopyAttribute))), + ], + }; +} diff --git a/tests/MSTest.v3.Tests/CreateAndFake.MSTest.v3.Tests.csproj b/tests/MSTest.v3.Tests/CreateAndFake.MSTest.v3.Tests.csproj new file mode 100644 index 00000000..7782b074 --- /dev/null +++ b/tests/MSTest.v3.Tests/CreateAndFake.MSTest.v3.Tests.csproj @@ -0,0 +1,26 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + + + + + + + + + + + + + + + diff --git a/tests/MSTest.v3.Tests/FakeAttributeTests.cs b/tests/MSTest.v3.Tests/FakeAttributeTests.cs new file mode 100644 index 00000000..bf27ce96 --- /dev/null +++ b/tests/MSTest.v3.Tests/FakeAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class FakeAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(FakeAttribute))), + ], + }; +} diff --git a/tests/MSTest.v3.Tests/InjectAttributeTests.cs b/tests/MSTest.v3.Tests/InjectAttributeTests.cs new file mode 100644 index 00000000..373d0261 --- /dev/null +++ b/tests/MSTest.v3.Tests/InjectAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class InjectAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(InjectAttribute))), + ], + }; +} diff --git a/tests/MSTest.v3.Tests/IntegrationTests.cs b/tests/MSTest.v3.Tests/IntegrationTests.cs new file mode 100644 index 00000000..4cd44749 --- /dev/null +++ b/tests/MSTest.v3.Tests/IntegrationTests.cs @@ -0,0 +1,78 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class IntegrationTests +{ + internal static MethodInfo AttributeMethod { get; } = + typeof(IntegrationTests).GetMethod( + nameof(Integration_AllAttributesWork), + BindingFlags.Instance | BindingFlags.Public + ); + + public sealed class Wrapper(IRandom gen) + { + public string NextName => gen.NextItem([]); + } + + [TestMethod, RandomData] + public void Integration_UsesParameterAttributes( + [Stub] IRandom gen, + [Inject] Wrapper context, + [Size(2)] string name + ) + { + name.Length.Assert().Is(2); + gen.NextItem(Arg.Any()).SetupReturn(name); + context.NextName.Assert().Is(name); + } + + [TestMethod, RandomData] + public void Integration_AllAttributesWork( + [Cap(5)] int intCapMax, + [Copy] int intCopyMax, + [Cap(8, 11)] int intCapRange, + [Cap(5d)] double doubleCapMax, + [Cap(20f, 24f)] float floatCapRange, + [Copy] int intCopyRange, + [Stub] IRandom stubGen, + [Inject] Wrapper stubContext, + [Fake] IRandom fakeGen, + [Inject] Wrapper fakeContext, + [Size(2)] string[] stringSizeSet, + [Size(3, 5)] string[] stringSizeRange, + string stringNone, + [Unique] string stringUnique + ) + { + intCapMax.Assert().GreaterThanOrIs(0).And().LessThan(5); + intCopyMax.Assert().Is(intCapMax); + intCapRange.Assert().GreaterThanOrIs(8).And().LessThanOrIs(11); + doubleCapMax.Assert().GreaterThanOrIs(0d).And().LessThan(5d); + floatCapRange.Assert().GreaterThanOrIs(20f).And().LessThanOrIs(24f); + intCopyRange.Assert().Is(intCapRange); + stubGen.NextBytes(0).Assert().IsNull(); + stubContext.NextName.Assert().IsNull(); + fakeGen.NextBytes(0).Assert().IsNotNull(); + fakeContext.NextName.Assert().IsNotNull(); + stringSizeSet.Assert().HasCount(2); + stringSizeRange.Assert().HasCountMoreOrExactly(3).And().HasCountLessOrExactly(5); + stringNone.Assert().IsNot(stringSizeSet).And().IsNot(stringSizeRange); + stringUnique + .Assert() + .IsNot(stringNone) + .And() + .IsNot(stringSizeSet) + .And() + .IsNot(stringSizeRange); + } + + [TestMethod, RandomData] + public void Issue118_FixesStubTypeRandomData([Stub] Type type) + { + type.Assert().IsNotNull(); + } +} diff --git a/tests/MSTest.v3.Tests/MSTestTests.cs b/tests/MSTest.v3.Tests/MSTestTests.cs new file mode 100644 index 00000000..52204349 --- /dev/null +++ b/tests/MSTest.v3.Tests/MSTestTests.cs @@ -0,0 +1,14 @@ +using System.Reflection; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class MSTestTests : AssemblyTester +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { AllowedTestNamePrefixes = ["Issue118"] }; + + protected override Assembly CodeAssembly { get; } = + Assembly.GetAssembly(typeof(RandomDataAttribute)); +} diff --git a/tests/MSTest.v3.Tests/RandomDataAttributeTests.cs b/tests/MSTest.v3.Tests/RandomDataAttributeTests.cs new file mode 100644 index 00000000..4184d49b --- /dev/null +++ b/tests/MSTest.v3.Tests/RandomDataAttributeTests.cs @@ -0,0 +1,63 @@ +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class RandomDataAttributeTests : AutoTester +{ + protected override RandomDataAttribute TestInstance { get; } = new() { Trials = 3 }; + + protected override Func OptionConfiguration { get; } = + opt => opt with { InjectionValues = [3, GetGeneratableMethod()] }; + + [TestMethod] + public void GetData_UsesTrials() + { + new RandomDataAttribute() { Trials = 0 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(0); + new RandomDataAttribute() { Trials = 1 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(1); + new RandomDataAttribute() { Trials = 2 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(2); + } + + [TestMethod, RandomData, DoNotParallelize] + public void GetData_HandlesException([Fake] MethodInfo method) + { + method.IsGenericMethodDefinition.SetupReturn(Behavior.Throw(Times.Once)); + + using StringWriter writer = new(); + + TextWriter errorConsole = Console.Error; + Console.SetError(writer); + try + { + new RandomDataAttribute().GetData(method).Assert().IsEmpty().Also(method).Called(); + } + finally + { + Console.SetError(errorConsole); + } + } + + private static MethodInfo GetGeneratableMethod() + { + return Tools.Randomizer.Create(opt => + opt with + { + FinalCondition = m => + m is MethodInfo info + && !info.IsGenericMethod + && !info.IsGenericMethodDefinition, + } + ); + } +} diff --git a/tests/MSTest.v3.Tests/SizeAttributeTests.cs b/tests/MSTest.v3.Tests/SizeAttributeTests.cs new file mode 100644 index 00000000..9baa8b3a --- /dev/null +++ b/tests/MSTest.v3.Tests/SizeAttributeTests.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class SizeAttributeTests : AutoTester +{ + protected override SizeAttribute TestInstance => + new(Tools.Gen.Next(1, 3), Tools.Gen.Next(3, 5)); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(SizeAttribute))), + ], + }; +} diff --git a/tests/MSTest.v3.Tests/StubAttributeTests.cs b/tests/MSTest.v3.Tests/StubAttributeTests.cs new file mode 100644 index 00000000..5773ef64 --- /dev/null +++ b/tests/MSTest.v3.Tests/StubAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class StubAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(StubAttribute))), + ], + }; +} diff --git a/tests/MSTest.v3.Tests/UniqueAttributeTests.cs b/tests/MSTest.v3.Tests/UniqueAttributeTests.cs new file mode 100644 index 00000000..e0b9c8ad --- /dev/null +++ b/tests/MSTest.v3.Tests/UniqueAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v3.Tests; + +[TestClass] +public sealed class UniqueAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(UniqueAttribute))), + ], + }; +} diff --git a/tests/MSTest.v3.Tests/testsettings.json b/tests/MSTest.v3.Tests/testsettings.json new file mode 100644 index 00000000..feb93701 --- /dev/null +++ b/tests/MSTest.v3.Tests/testsettings.json @@ -0,0 +1,14 @@ +{ + "CreateAndFake": { + "Design": {}, + "Asserter": {}, + "Duplicator": {}, + "Extractor": {}, + "Faker": {}, + "Mutator": {}, + "Randomizer": {}, + "Runner": {}, + "Tester": {}, + "Valuer": {} + } +} diff --git a/tests/MSTest.v4.Tests/AutoTesterTests.cs b/tests/MSTest.v4.Tests/AutoTesterTests.cs new file mode 100644 index 00000000..062163ff --- /dev/null +++ b/tests/MSTest.v4.Tests/AutoTesterTests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class AutoTesterTests() : AutoTester(typeof(DataSample)); diff --git a/tests/MSTest.v4.Tests/AutoTester{T}Tests.cs b/tests/MSTest.v4.Tests/AutoTester{T}Tests.cs new file mode 100644 index 00000000..8563eabf --- /dev/null +++ b/tests/MSTest.v4.Tests/AutoTester{T}Tests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class AutoTester_T_Tests : AutoTester; diff --git a/tests/MSTest.v4.Tests/CapAttributeTests.cs b/tests/MSTest.v4.Tests/CapAttributeTests.cs new file mode 100644 index 00000000..a8ea1b45 --- /dev/null +++ b/tests/MSTest.v4.Tests/CapAttributeTests.cs @@ -0,0 +1,30 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class CapAttributeTests : AutoTester +{ + protected override CapAttribute TestInstance { get; } = new(5, 10); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentOutOfRangeException)], + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CapAttribute))), + ], + }; + + [TestMethod] + public void Clone_BranchesOnMinSet() + { + new CapAttribute(1).Clone().Assert().Is(new CapAttribute(1)); + new CapAttribute(1, 2).Clone().Assert().Is(new CapAttribute(1, 2)); + } +} diff --git a/tests/MSTest.v4.Tests/CopyAttributeTests.cs b/tests/MSTest.v4.Tests/CopyAttributeTests.cs new file mode 100644 index 00000000..51c1080b --- /dev/null +++ b/tests/MSTest.v4.Tests/CopyAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class CopyAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CopyAttribute))), + ], + }; +} diff --git a/tests/MSTest.v4.Tests/CreateAndFake.MSTest.v4.Tests.csproj b/tests/MSTest.v4.Tests/CreateAndFake.MSTest.v4.Tests.csproj new file mode 100644 index 00000000..4822acb8 --- /dev/null +++ b/tests/MSTest.v4.Tests/CreateAndFake.MSTest.v4.Tests.csproj @@ -0,0 +1,26 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + + + + + + + + + + + + + + + diff --git a/tests/MSTest.v4.Tests/FakeAttributeTests.cs b/tests/MSTest.v4.Tests/FakeAttributeTests.cs new file mode 100644 index 00000000..cc221ffd --- /dev/null +++ b/tests/MSTest.v4.Tests/FakeAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class FakeAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(FakeAttribute))), + ], + }; +} diff --git a/tests/MSTest.v4.Tests/InjectAttributeTests.cs b/tests/MSTest.v4.Tests/InjectAttributeTests.cs new file mode 100644 index 00000000..afed9639 --- /dev/null +++ b/tests/MSTest.v4.Tests/InjectAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class InjectAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(InjectAttribute))), + ], + }; +} diff --git a/tests/MSTest.v4.Tests/IntegrationTests.cs b/tests/MSTest.v4.Tests/IntegrationTests.cs new file mode 100644 index 00000000..06259c77 --- /dev/null +++ b/tests/MSTest.v4.Tests/IntegrationTests.cs @@ -0,0 +1,78 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class IntegrationTests +{ + internal static MethodInfo AttributeMethod { get; } = + typeof(IntegrationTests).GetMethod( + nameof(Integration_AllAttributesWork), + BindingFlags.Instance | BindingFlags.Public + ); + + public sealed class Wrapper(IRandom gen) + { + public string NextName => gen.NextItem([]); + } + + [TestMethod, RandomData] + public void Integration_UsesParameterAttributes( + [Stub] IRandom gen, + [Inject] Wrapper context, + [Size(2)] string name + ) + { + name.Length.Assert().Is(2); + gen.NextItem(Arg.Any()).SetupReturn(name); + context.NextName.Assert().Is(name); + } + + [TestMethod, RandomData] + public void Integration_AllAttributesWork( + [Cap(5)] int intCapMax, + [Copy] int intCopyMax, + [Cap(8, 11)] int intCapRange, + [Cap(5d)] double doubleCapMax, + [Cap(20f, 24f)] float floatCapRange, + [Copy] int intCopyRange, + [Stub] IRandom stubGen, + [Inject] Wrapper stubContext, + [Fake] IRandom fakeGen, + [Inject] Wrapper fakeContext, + [Size(2)] string[] stringSizeSet, + [Size(3, 5)] string[] stringSizeRange, + string stringNone, + [Unique] string stringUnique + ) + { + intCapMax.Assert().GreaterThanOrIs(0).And().LessThan(5); + intCopyMax.Assert().Is(intCapMax); + intCapRange.Assert().GreaterThanOrIs(8).And().LessThanOrIs(11); + doubleCapMax.Assert().GreaterThanOrIs(0d).And().LessThan(5d); + floatCapRange.Assert().GreaterThanOrIs(20f).And().LessThanOrIs(24f); + intCopyRange.Assert().Is(intCapRange); + stubGen.NextBytes(0).Assert().IsNull(); + stubContext.NextName.Assert().IsNull(); + fakeGen.NextBytes(0).Assert().IsNotNull(); + fakeContext.NextName.Assert().IsNotNull(); + stringSizeSet.Assert().HasCount(2); + stringSizeRange.Assert().HasCountMoreOrExactly(3).And().HasCountLessOrExactly(5); + stringNone.Assert().IsNot(stringSizeSet).And().IsNot(stringSizeRange); + stringUnique + .Assert() + .IsNot(stringNone) + .And() + .IsNot(stringSizeSet) + .And() + .IsNot(stringSizeRange); + } + + [TestMethod, RandomData] + public void Issue118_FixesStubTypeRandomData([Stub] Type type) + { + type.Assert().IsNotNull(); + } +} diff --git a/tests/MSTest.v4.Tests/MSTestTests.cs b/tests/MSTest.v4.Tests/MSTestTests.cs new file mode 100644 index 00000000..7de34b0e --- /dev/null +++ b/tests/MSTest.v4.Tests/MSTestTests.cs @@ -0,0 +1,14 @@ +using System.Reflection; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class MSTestTests : AssemblyTester +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { AllowedTestNamePrefixes = ["Issue118"] }; + + protected override Assembly CodeAssembly { get; } = + Assembly.GetAssembly(typeof(RandomDataAttribute)); +} diff --git a/tests/MSTest.v4.Tests/Properties/AssemblyInfo.cs b/tests/MSTest.v4.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..279b7bce --- /dev/null +++ b/tests/MSTest.v4.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1 @@ +[assembly: Parallelize] diff --git a/tests/MSTest.v4.Tests/RandomDataAttributeTests.cs b/tests/MSTest.v4.Tests/RandomDataAttributeTests.cs new file mode 100644 index 00000000..7596e66c --- /dev/null +++ b/tests/MSTest.v4.Tests/RandomDataAttributeTests.cs @@ -0,0 +1,63 @@ +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class RandomDataAttributeTests : AutoTester +{ + protected override RandomDataAttribute TestInstance { get; } = new() { Trials = 3 }; + + protected override Func OptionConfiguration { get; } = + opt => opt with { InjectionValues = [3, GetGeneratableMethod()] }; + + [TestMethod] + public void GetData_UsesTrials() + { + new RandomDataAttribute() { Trials = 0 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(0); + new RandomDataAttribute() { Trials = 1 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(1); + new RandomDataAttribute() { Trials = 2 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(2); + } + + [TestMethod, RandomData, ResourceLock(WellKnownResources.Console)] + public void GetData_HandlesException([Fake] MethodInfo method) + { + method.IsGenericMethodDefinition.SetupReturn(Behavior.Throw(Times.Once)); + + using StringWriter writer = new(); + + TextWriter errorConsole = Console.Error; + Console.SetError(writer); + try + { + new RandomDataAttribute().GetData(method).Assert().IsEmpty().Also(method).Called(); + } + finally + { + Console.SetError(errorConsole); + } + } + + private static MethodInfo GetGeneratableMethod() + { + return Tools.Randomizer.Create(opt => + opt with + { + FinalCondition = m => + m is MethodInfo info + && !info.IsGenericMethod + && !info.IsGenericMethodDefinition, + } + ); + } +} diff --git a/tests/MSTest.v4.Tests/SizeAttributeTests.cs b/tests/MSTest.v4.Tests/SizeAttributeTests.cs new file mode 100644 index 00000000..00577e6b --- /dev/null +++ b/tests/MSTest.v4.Tests/SizeAttributeTests.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class SizeAttributeTests : AutoTester +{ + protected override SizeAttribute TestInstance { get; } = + new SizeAttribute(Tools.Gen.Next(1, 3), Tools.Gen.Next(3, 5)); + + protected override Func OptionConfiguration => + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(SizeAttribute))), + ], + }; +} diff --git a/tests/MSTest.v4.Tests/StubAttributeTests.cs b/tests/MSTest.v4.Tests/StubAttributeTests.cs new file mode 100644 index 00000000..22d3cf16 --- /dev/null +++ b/tests/MSTest.v4.Tests/StubAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class StubAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(StubAttribute))), + ], + }; +} diff --git a/tests/MSTest.v4.Tests/UniqueAttributeTests.cs b/tests/MSTest.v4.Tests/UniqueAttributeTests.cs new file mode 100644 index 00000000..430754e9 --- /dev/null +++ b/tests/MSTest.v4.Tests/UniqueAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.MSTest.v4.Tests; + +[TestClass] +public sealed class UniqueAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(UniqueAttribute))), + ], + }; +} diff --git a/tests/MSTest.v4.Tests/testsettings.json b/tests/MSTest.v4.Tests/testsettings.json new file mode 100644 index 00000000..feb93701 --- /dev/null +++ b/tests/MSTest.v4.Tests/testsettings.json @@ -0,0 +1,14 @@ +{ + "CreateAndFake": { + "Design": {}, + "Asserter": {}, + "Duplicator": {}, + "Extractor": {}, + "Faker": {}, + "Mutator": {}, + "Randomizer": {}, + "Runner": {}, + "Tester": {}, + "Valuer": {} + } +} diff --git a/tests/NUnit.v3.Tests/AutoTesterTests.cs b/tests/NUnit.v3.Tests/AutoTesterTests.cs new file mode 100644 index 00000000..82d54d08 --- /dev/null +++ b/tests/NUnit.v3.Tests/AutoTesterTests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class AutoTesterTests() : AutoTester(typeof(DataSample)); diff --git a/tests/NUnit.v3.Tests/AutoTester{T}Tests.cs b/tests/NUnit.v3.Tests/AutoTester{T}Tests.cs new file mode 100644 index 00000000..a0d275ed --- /dev/null +++ b/tests/NUnit.v3.Tests/AutoTester{T}Tests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class AutoTester_T_Tests : AutoTester; diff --git a/tests/NUnit.v3.Tests/CancellationTokenProviderTests.cs b/tests/NUnit.v3.Tests/CancellationTokenProviderTests.cs new file mode 100644 index 00000000..c0bea0ea --- /dev/null +++ b/tests/NUnit.v3.Tests/CancellationTokenProviderTests.cs @@ -0,0 +1,11 @@ +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class CancellationTokenProviderTests() : AutoTester(typeof(CancellationTokenProvider)) +{ + [Test] + public static void Get_SuccessfullyGetsToken() + { + CancellationTokenProvider.Get().Assert().Is(TestContext.CurrentContext.CancellationToken); + } +} diff --git a/tests/NUnit.v3.Tests/CapAttributeTests.cs b/tests/NUnit.v3.Tests/CapAttributeTests.cs new file mode 100644 index 00000000..e74d0356 --- /dev/null +++ b/tests/NUnit.v3.Tests/CapAttributeTests.cs @@ -0,0 +1,30 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class CapAttributeTests : AutoTester +{ + protected override CapAttribute TestInstance { get; } = new(5, 10); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentOutOfRangeException)], + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CapAttribute))), + ], + }; + + [Test] + public static void Clone_BranchesOnMinSet() + { + new CapAttribute(1).Clone().Assert().Is(new CapAttribute(1)); + new CapAttribute(1, 2).Clone().Assert().Is(new CapAttribute(1, 2)); + } +} diff --git a/tests/NUnit.v3.Tests/CopyAttributeTests.cs b/tests/NUnit.v3.Tests/CopyAttributeTests.cs new file mode 100644 index 00000000..27b32cae --- /dev/null +++ b/tests/NUnit.v3.Tests/CopyAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class CopyAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CopyAttribute))), + ], + }; +} diff --git a/tests/NUnit.v3.Tests/CreateAndFake.NUnit.v3.Tests.csproj b/tests/NUnit.v3.Tests/CreateAndFake.NUnit.v3.Tests.csproj new file mode 100644 index 00000000..4f94e6ba --- /dev/null +++ b/tests/NUnit.v3.Tests/CreateAndFake.NUnit.v3.Tests.csproj @@ -0,0 +1,27 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + + + + + + + + + + + + + + + + diff --git a/tests/NUnit.v3.Tests/FakeAttributeTests.cs b/tests/NUnit.v3.Tests/FakeAttributeTests.cs new file mode 100644 index 00000000..8dcff83d --- /dev/null +++ b/tests/NUnit.v3.Tests/FakeAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class FakeAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(FakeAttribute))), + ], + }; +} diff --git a/tests/NUnit.v3.Tests/InjectAttributeTests.cs b/tests/NUnit.v3.Tests/InjectAttributeTests.cs new file mode 100644 index 00000000..9e96d4e5 --- /dev/null +++ b/tests/NUnit.v3.Tests/InjectAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class InjectAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(InjectAttribute))), + ], + }; +} diff --git a/tests/NUnit.v3.Tests/IntegrationTests.cs b/tests/NUnit.v3.Tests/IntegrationTests.cs new file mode 100644 index 00000000..7179db8c --- /dev/null +++ b/tests/NUnit.v3.Tests/IntegrationTests.cs @@ -0,0 +1,78 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public static class IntegrationTests +{ + internal static MethodInfo AttributeMethod { get; } = + typeof(IntegrationTests).GetMethod( + nameof(Integration_AllAttributesWork), + BindingFlags.Static | BindingFlags.Public + ); + + public sealed class Wrapper(IRandom gen) + { + public string NextName => gen.NextItem([]); + } + + [RandomData] + public static void Integration_UsesParameterAttributes( + [Fake] IRandom gen, + [Inject] Wrapper context, + [Size(2)] string name + ) + { + name.Length.Assert().Is(2); + gen.NextItem(Arg.Any()).SetupReturn(name); + context.NextName.Assert().Is(name); + } + + [RandomData] + public static void Integration_AllAttributesWork( + [Cap(5)] int intCapMax, + [Copy] int intCopyMax, + [Cap(8, 11)] int intCapRange, + [Cap(5d)] double doubleCapMax, + [Cap(20f, 24f)] float floatCapRange, + [Copy] int intCopyRange, + [Stub] IRandom stubGen, + [Inject] Wrapper stubContext, + [Fake] IRandom fakeGen, + [Inject] Wrapper fakeContext, + [Size(2)] string[] stringSizeSet, + [Size(3, 5)] string[] stringSizeRange, + string stringNone, + [Unique] string stringUnique + ) + { + intCapMax.Assert().GreaterThanOrIs(0).And().LessThan(5); + intCopyMax.Assert().Is(intCapMax); + intCapRange.Assert().GreaterThanOrIs(8).And().LessThanOrIs(11); + doubleCapMax.Assert().GreaterThanOrIs(0d).And().LessThan(5d); + floatCapRange.Assert().GreaterThanOrIs(20f).And().LessThanOrIs(24f); + intCopyRange.Assert().Is(intCapRange); + stubGen.NextBytes(0).Assert().IsNull(); + stubContext.NextName.Assert().IsNull(); + fakeGen.NextBytes(0).Assert().IsNotNull(); + fakeContext.NextName.Assert().IsNotNull(); + stringSizeSet.Assert().HasCount(2); + stringSizeRange.Assert().HasCountMoreOrExactly(3).And().HasCountLessOrExactly(5); + stringNone.Assert().IsNot(stringSizeSet).And().IsNot(stringSizeRange); + stringUnique + .Assert() + .IsNot(stringNone) + .And() + .IsNot(stringSizeSet) + .And() + .IsNot(stringSizeRange); + } + + [RandomData] + public static void Issue118_FixesStubTypeRandomData([Stub] Type type) + { + type.Assert().IsNotNull(); + } +} diff --git a/tests/NUnit.v3.Tests/MethodWrapperCreateHintTests.cs b/tests/NUnit.v3.Tests/MethodWrapperCreateHintTests.cs new file mode 100644 index 00000000..63f918a9 --- /dev/null +++ b/tests/NUnit.v3.Tests/MethodWrapperCreateHintTests.cs @@ -0,0 +1,13 @@ +using NUnit.Framework.Internal; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class MethodWrapperCreateHintTests : AutoTester +{ + [Test] + public static void Create_AddedSupport() + { + Tools.Randomizer.Create().Assert().IsNotNull(); + } +} diff --git a/tests/NUnit.v3.Tests/NUnitTests.cs b/tests/NUnit.v3.Tests/NUnitTests.cs new file mode 100644 index 00000000..ba3705ff --- /dev/null +++ b/tests/NUnit.v3.Tests/NUnitTests.cs @@ -0,0 +1,14 @@ +using System.Reflection; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class NUnitTests : AssemblyTester +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { AllowedTestNamePrefixes = ["Issue118"] }; + + protected override Assembly CodeAssembly { get; } = + Assembly.GetAssembly(typeof(RandomDataAttribute)); +} diff --git a/tests/NUnit.v3.Tests/RandomDataAttributeTests.cs b/tests/NUnit.v3.Tests/RandomDataAttributeTests.cs new file mode 100644 index 00000000..a4a39b0d --- /dev/null +++ b/tests/NUnit.v3.Tests/RandomDataAttributeTests.cs @@ -0,0 +1,112 @@ +using System.Reflection; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public static class RandomDataAttributeTests +{ + [RandomData] + public static Task RandomDataAttribute_GuardsNulls([Stub] Test testStub) + { + return Tools.Tester.PreventsNullRefExceptionAsync( + new RandomDataAttribute() { Trials = 3 }, + TestContext.CurrentContext.CancellationToken, + opt => opt with { InjectionValues = [3, GetGeneratableMethod(), testStub] } + ); + } + + [RandomData] + public static Task RandomDataAttribute_NoParameterMutation( + [Stub] Test testStub, + [Stub] ICopyHint copyStub + ) + { + copyStub + .TryCopy(Arg.Any(), Arg.Any()) + .SetupReturn( + Behavior.Call( + (w, _) => + (w != null) + ? new(new MethodWrapper(w.TypeInfo.Type, w.MethodInfo)) + : CopyHintResult.None + ) + ); + + return Tools.Tester.PreventsParameterMutationAsync( + new RandomDataAttribute() { Trials = 3 }, + TestContext.CurrentContext.CancellationToken, + opt => + opt with + { + InjectionValues = [3, GetGeneratableMethod(), testStub], + Duplicator = new Duplicator( + Tools.Duplicator.Options with + { + Hints = [copyStub], + } + ), + } + ); + } + + [RandomData] + public static void GetData_UsesTrials([Stub] Test testStub) + { + MethodInfo method = GetGeneratableMethod(); + MethodWrapper wrapper = new(method.ReflectedType, method); + new RandomDataAttribute() { Trials = 0 } + .BuildFrom(wrapper, testStub) + .Assert() + .HasCount(0); + new RandomDataAttribute() { Trials = 1 } + .BuildFrom(wrapper, testStub) + .Assert() + .HasCount(1); + new RandomDataAttribute() { Trials = 2 } + .BuildFrom(wrapper, testStub) + .Assert() + .HasCount(2); + } + + [RandomData] + public static void GetData_HandlesException([Stub] Test suite, [Fake] IMethodInfo method) + { + method.MethodInfo.SetupReturn(Behavior.Throw(Times.Once)); + + using StringWriter writer = new(); + + TextWriter errorConsole = Console.Error; + Console.SetError(writer); + try + { + new RandomDataAttribute() + .BuildFrom(method, suite) + .Assert() + .IsEmpty() + .Also(method) + .Called(); + } + finally + { + Console.SetError(errorConsole); + } + } + + private static MethodInfo GetGeneratableMethod() + { + return Tools.Randomizer.Create(opt => + opt with + { + FinalCondition = m => + m is MethodInfo info + && !info.IsGenericMethod + && !info.IsGenericMethodDefinition, + } + ); + } +} diff --git a/tests/NUnit.v3.Tests/SizeAttributeTests.cs b/tests/NUnit.v3.Tests/SizeAttributeTests.cs new file mode 100644 index 00000000..530f74b1 --- /dev/null +++ b/tests/NUnit.v3.Tests/SizeAttributeTests.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class SizeAttributeTests : AutoTester +{ + protected override SizeAttribute TestInstance => + new(Tools.Gen.Next(1, 3), Tools.Gen.Next(3, 5)); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(SizeAttribute))), + ], + }; +} diff --git a/tests/NUnit.v3.Tests/StubAttributeTests.cs b/tests/NUnit.v3.Tests/StubAttributeTests.cs new file mode 100644 index 00000000..0bee2423 --- /dev/null +++ b/tests/NUnit.v3.Tests/StubAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class StubAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(StubAttribute))), + ], + }; +} diff --git a/tests/NUnit.v3.Tests/UniqueAttributeTests.cs b/tests/NUnit.v3.Tests/UniqueAttributeTests.cs new file mode 100644 index 00000000..7876e071 --- /dev/null +++ b/tests/NUnit.v3.Tests/UniqueAttributeTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.NUnit.v3.Tests; + +[TestFixture] +public sealed class UniqueAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(UniqueAttribute))), + ], + }; +} diff --git a/tests/NUnit.v3.Tests/testsettings.json b/tests/NUnit.v3.Tests/testsettings.json new file mode 100644 index 00000000..feb93701 --- /dev/null +++ b/tests/NUnit.v3.Tests/testsettings.json @@ -0,0 +1,14 @@ +{ + "CreateAndFake": { + "Design": {}, + "Asserter": {}, + "Duplicator": {}, + "Extractor": {}, + "Faker": {}, + "Mutator": {}, + "Randomizer": {}, + "Runner": {}, + "Tester": {}, + "Valuer": {} + } +} diff --git a/tests/Samples.Tests/BasicData/CollectionDtoTests.cs b/tests/Samples.Tests/BasicData/CollectionDtoTests.cs new file mode 100644 index 00000000..eb8284ee --- /dev/null +++ b/tests/Samples.Tests/BasicData/CollectionDtoTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.BasicData; + +namespace Werecodent.CreateAndFake.Samples.Tests.BasicData; + +public sealed class CollectionDtoTests : AutoTester; diff --git a/tests/Samples.Tests/BasicData/CollectionDto{T}Tests.cs b/tests/Samples.Tests/BasicData/CollectionDto{T}Tests.cs new file mode 100644 index 00000000..907a31fb --- /dev/null +++ b/tests/Samples.Tests/BasicData/CollectionDto{T}Tests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.BasicData; + +namespace Werecodent.CreateAndFake.Samples.Tests.BasicData; + +public sealed class CollectionDto_T_Tests() : AutoTester(typeof(CollectionDto<>)); diff --git a/tests/Samples.Tests/BasicData/CompleteDtoTests.cs b/tests/Samples.Tests/BasicData/CompleteDtoTests.cs new file mode 100644 index 00000000..ac94fda6 --- /dev/null +++ b/tests/Samples.Tests/BasicData/CompleteDtoTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.BasicData; + +namespace Werecodent.CreateAndFake.Samples.Tests.BasicData; + +public sealed class CompleteDtoTests : AutoTester; diff --git a/tests/Samples.Tests/BasicData/NestedDtoTests.cs b/tests/Samples.Tests/BasicData/NestedDtoTests.cs new file mode 100644 index 00000000..1cfb0c88 --- /dev/null +++ b/tests/Samples.Tests/BasicData/NestedDtoTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.BasicData; + +namespace Werecodent.CreateAndFake.Samples.Tests.BasicData; + +public sealed class NestedDtoTests : AutoTester; diff --git a/tests/Samples.Tests/BasicData/RecursiveDtoTests.cs b/tests/Samples.Tests/BasicData/RecursiveDtoTests.cs new file mode 100644 index 00000000..5bebe406 --- /dev/null +++ b/tests/Samples.Tests/BasicData/RecursiveDtoTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.BasicData; + +namespace Werecodent.CreateAndFake.Samples.Tests.BasicData; + +public sealed class RecursiveDtoTests : AutoTester; diff --git a/tests/Samples.Tests/BasicData/SimpleDtoTests.cs b/tests/Samples.Tests/BasicData/SimpleDtoTests.cs new file mode 100644 index 00000000..11bea38e --- /dev/null +++ b/tests/Samples.Tests/BasicData/SimpleDtoTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.BasicData; + +namespace Werecodent.CreateAndFake.Samples.Tests.BasicData; + +public sealed class SimpleDtoTests : AutoTester; diff --git a/tests/Samples.Tests/CreateAndFake.Samples.Tests.csproj b/tests/Samples.Tests/CreateAndFake.Samples.Tests.csproj new file mode 100644 index 00000000..f5b67dbc --- /dev/null +++ b/tests/Samples.Tests/CreateAndFake.Samples.Tests.csproj @@ -0,0 +1,30 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + exe + + + + + + + + + + + + + + + + + + diff --git a/tests/Samples.Tests/DoubleValue/HolderTests.cs b/tests/Samples.Tests/DoubleValue/HolderTests.cs new file mode 100644 index 00000000..feac92ef --- /dev/null +++ b/tests/Samples.Tests/DoubleValue/HolderTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.DoubleValue; + +namespace Werecodent.CreateAndFake.Samples.Tests.DoubleValue; + +public sealed class HolderTests() : AutoTester(typeof(Holder<,>)); diff --git a/tests/Samples.Tests/DoubleValue/ReadableHolderTests.cs b/tests/Samples.Tests/DoubleValue/ReadableHolderTests.cs new file mode 100644 index 00000000..02bf45e4 --- /dev/null +++ b/tests/Samples.Tests/DoubleValue/ReadableHolderTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.DoubleValue; + +namespace Werecodent.CreateAndFake.Samples.Tests.DoubleValue; + +public sealed class ReadableHolderTests() : AutoTester(typeof(ReadableHolder<,>)); diff --git a/tests/Samples.Tests/DoubleValue/WriteableHolderTests.cs b/tests/Samples.Tests/DoubleValue/WriteableHolderTests.cs new file mode 100644 index 00000000..fd9855cd --- /dev/null +++ b/tests/Samples.Tests/DoubleValue/WriteableHolderTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.DoubleValue; + +namespace Werecodent.CreateAndFake.Samples.Tests.DoubleValue; + +public sealed class WriteableHolderTests() : AutoTester(typeof(WriteableHolder<,>)); diff --git a/tests/Samples.Tests/ErrorCases/FactoryAlterSampleTests.cs b/tests/Samples.Tests/ErrorCases/FactoryAlterSampleTests.cs new file mode 100644 index 00000000..24a227ab --- /dev/null +++ b/tests/Samples.Tests/ErrorCases/FactoryAlterSampleTests.cs @@ -0,0 +1,10 @@ +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Samples.Tests.ErrorCases; + +public sealed class FactoryAlterSampleTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { DisableToolSetSupportTests = true }; +} diff --git a/tests/Samples.Tests/ErrorCases/InjectMockSampleTests.cs b/tests/Samples.Tests/ErrorCases/InjectMockSampleTests.cs new file mode 100644 index 00000000..16a7090a --- /dev/null +++ b/tests/Samples.Tests/ErrorCases/InjectMockSampleTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Samples.ErrorCases; + +namespace Werecodent.CreateAndFake.Samples.Tests.ErrorCases; + +public static class InjectMockSampleTests +{ + [Theory, RandomData] + public static void InjectMockSample_CanBeInjected([Inject] InjectMockSample sample) + { + sample.TestIfMockedSeparately(); + } +} diff --git a/tests/Samples.Tests/ErrorCases/InvalidCreateSampleTests.cs b/tests/Samples.Tests/ErrorCases/InvalidCreateSampleTests.cs new file mode 100644 index 00000000..556e4680 --- /dev/null +++ b/tests/Samples.Tests/ErrorCases/InvalidCreateSampleTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Samples.ErrorCases; + +namespace Werecodent.CreateAndFake.Samples.Tests.ErrorCases; + +public static class InvalidCreateSampleTests +{ + [Fact] + public static void InvalidCreateSample_CannotBeCreated() + { + true.Assert(_ => new InvalidCreateSample()).Throws(); + } +} diff --git a/tests/Samples.Tests/ErrorCases/IsBadSampleTests.cs b/tests/Samples.Tests/ErrorCases/IsBadSampleTests.cs new file mode 100644 index 00000000..10fadf84 --- /dev/null +++ b/tests/Samples.Tests/ErrorCases/IsBadSampleTests.cs @@ -0,0 +1,44 @@ +using Werecodent.CreateAndFake.Samples.ErrorCases; + +namespace Werecodent.CreateAndFake.Samples.Tests.ErrorCases; + +public static class IsBadSampleTests +{ + [Fact] + public static Task IsBadSample_GuardsNulls() + { + return Tools.Tester.PreventsNullRefExceptionAsync( + TestContext.Current.CancellationToken, + opt => + opt with + { + IgnorableExceptions = [typeof(NotImplementedException)], + Randomizer = opt.Randomizer.WithOptions(o => + o with + { + RequireRandomizedContents = false, + } + ), + } + ); + } + + [Fact] + public static Task IsBadSample_NoParameterMutation() + { + return Tools.Tester.PreventsParameterMutationAsync( + TestContext.Current.CancellationToken, + opt => + opt with + { + IgnorableExceptions = [typeof(NotImplementedException)], + Randomizer = opt.Randomizer.WithOptions(o => + o with + { + RequireRandomizedContents = false, + } + ), + } + ); + } +} diff --git a/tests/Samples.Tests/ErrorCases/ObsoleteSampleTests.cs b/tests/Samples.Tests/ErrorCases/ObsoleteSampleTests.cs new file mode 100644 index 00000000..3144cff0 --- /dev/null +++ b/tests/Samples.Tests/ErrorCases/ObsoleteSampleTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Samples.ErrorCases; + +namespace Werecodent.CreateAndFake.Samples.Tests.ErrorCases; + +public sealed class ObsoleteSampleTests : AutoTester +{ + [Fact] + public static Task ObsoleteSample_NoParameterMutationCanIncludeObsolete() + { + return Tools + .Tester.PreventsParameterMutationAsync( + TestContext.Current.CancellationToken, + opt => opt with { IgnoreObsoleteMethods = false } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/Samples.Tests/ErrorCases/PrivateCreateSampleTests.cs b/tests/Samples.Tests/ErrorCases/PrivateCreateSampleTests.cs new file mode 100644 index 00000000..87631f34 --- /dev/null +++ b/tests/Samples.Tests/ErrorCases/PrivateCreateSampleTests.cs @@ -0,0 +1,19 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.Samples.ErrorCases; + +namespace Werecodent.CreateAndFake.Samples.Tests.ErrorCases; + +public static class PrivateCreateSampleTests +{ + [Fact] + internal static void PrivateCreateSample_PrivateConstructor() + { + ConstructorInfo constructor = TypeDescriber + .For() + .Constructors.All.Single(); + + constructor.IsPrivate.Assert().Is(true); + constructor.Invoke([]).Assert().Pass(); + } +} diff --git a/tests/Samples.Tests/InvalidSampleAttributeTests.cs b/tests/Samples.Tests/InvalidSampleAttributeTests.cs new file mode 100644 index 00000000..744fbbd6 --- /dev/null +++ b/tests/Samples.Tests/InvalidSampleAttributeTests.cs @@ -0,0 +1,3 @@ +namespace Werecodent.CreateAndFake.Samples.Tests; + +public sealed class InvalidSampleAttributeTests : AutoTester; diff --git a/tests/Samples.Tests/SampleGeneratorTests.cs b/tests/Samples.Tests/SampleGeneratorTests.cs new file mode 100644 index 00000000..d8604d5a --- /dev/null +++ b/tests/Samples.Tests/SampleGeneratorTests.cs @@ -0,0 +1,10 @@ +namespace Werecodent.CreateAndFake.Samples.Tests; + +public sealed class SampleGeneratorTests() : AutoTester(typeof(SampleGenerator)) +{ + [Fact] + internal static void Debug_SampleGenerator_AllValidSamples() + { + SampleGenerator.AllValidDataSamples.Assert().Debug(); + } +} diff --git a/tests/Samples.Tests/SamplesTests.cs b/tests/Samples.Tests/SamplesTests.cs new file mode 100644 index 00000000..a7f5ef4a --- /dev/null +++ b/tests/Samples.Tests/SamplesTests.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Samples.Tests; + +public sealed class SamplesTests : AssemblyTester +{ + private static readonly Assembly _SampleAssembly = Assembly.GetAssembly( + typeof(SampleGenerator) + ); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + ClassCoverageExclusions = + [ + .. _SampleAssembly + .GetTypes() + .Where(t => Attribute.IsDefined(t, typeof(InvalidSampleAttribute))) + .Select(t => t.Name), + ], + }; + + protected override Assembly CodeAssembly { get; } = _SampleAssembly; + + [Fact] + internal static Task Samples_ValidSamplesWork() + { + return Tools.Tester.VerifyToolSetSupportAsync( + SampleGenerator.AllValidDataSamples, + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Samples.Tests/Scenarios/AsyncDataSampleTests.cs b/tests/Samples.Tests/Scenarios/AsyncDataSampleTests.cs new file mode 100644 index 00000000..cbe5494a --- /dev/null +++ b/tests/Samples.Tests/Scenarios/AsyncDataSampleTests.cs @@ -0,0 +1,39 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class AsyncDataSampleTests : AutoTester +{ + [Fact] + public static Task ReadFromNumberValueAsync_InitialDefault() + { + return new AsyncDataSample() + .ReadFromNumberValueAsync() + .Assert() + .HasResultAsync(default, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + public static Task ReadFromNumberValueAsync_CorrectValue(int value) + { + return new AsyncDataSample() { NumberValue = Task.FromResult(value) } + .ReadFromNumberValueAsync() + .Assert() + .HasResultAsync(value, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + public static Task ReadFromNumberValueAsync_WithDelay(int value) + { + async Task getNumber() + { + await Task.Delay(1000, TestContext.Current.CancellationToken); + return value; + } + + return new AsyncDataSample() { NumberValue = getNumber() } + .ReadFromNumberValueAsync() + .Assert() + .HasResultAsync(value, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Samples.Tests/Scenarios/ChildWithParentSampleTests.cs b/tests/Samples.Tests/Scenarios/ChildWithParentSampleTests.cs new file mode 100644 index 00000000..a9a791e3 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ChildWithParentSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ChildWithParentSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/ConstraintSampleTests.cs b/tests/Samples.Tests/Scenarios/ConstraintSampleTests.cs new file mode 100644 index 00000000..4469eff7 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ConstraintSampleTests.cs @@ -0,0 +1,31 @@ +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public static class ConstraintSampleTests +{ + [Theory, RandomData] + public static async Task ConstraintSample_GuardsNulls( + [Fake] ConstraintSample data + ) + { + data.ToString().SetupReturn(Behavior.Base()); + + await Tools.Tester.PreventsNullRefExceptionAsync( + data, + TestContext.Current.CancellationToken + ); + + data.Assert().Called(); + } + + [Fact] + public static Task ConstraintSample_NoParameterMutation() + { + return Tools.Tester.PreventsParameterMutationAsync( + typeof(ConstraintSample<,>), + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Samples.Tests/Scenarios/ContentEnumerableSampleTests.cs b/tests/Samples.Tests/Scenarios/ContentEnumerableSampleTests.cs new file mode 100644 index 00000000..644c904c --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ContentEnumerableSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ContentEnumerableSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/DataHolderSampleTests.cs b/tests/Samples.Tests/Scenarios/DataHolderSampleTests.cs new file mode 100644 index 00000000..25ca22e1 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/DataHolderSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class DataHolderSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/DataSampleTests.cs b/tests/Samples.Tests/Scenarios/DataSampleTests.cs new file mode 100644 index 00000000..ad4a228c --- /dev/null +++ b/tests/Samples.Tests/Scenarios/DataSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class DataSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/DoubleEnumerableSampleTests.cs b/tests/Samples.Tests/Scenarios/DoubleEnumerableSampleTests.cs new file mode 100644 index 00000000..2873f9f5 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/DoubleEnumerableSampleTests.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class DoubleEnumerableSampleTests : AutoTester +{ + [Theory, RandomData] + public static void GetEnumerator_ImplicitIntWorks( + IEnumerable ints, + IEnumerable strings + ) + { + ((IEnumerable)new DoubleEnumerableSample(ints, strings)) + .GetEnumerator() + .Assert() + .IsNotNull(); + + ((IEnumerable)new DoubleEnumerableSample(null, strings)) + .GetEnumerator() + .Assert() + .IsNotNull(); + } +} diff --git a/tests/Samples.Tests/Scenarios/ExtractableSampleTests.cs b/tests/Samples.Tests/Scenarios/ExtractableSampleTests.cs new file mode 100644 index 00000000..f1cd3a80 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ExtractableSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ExtractableSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/FieldSampleTests.cs b/tests/Samples.Tests/Scenarios/FieldSampleTests.cs new file mode 100644 index 00000000..e0d21d1c --- /dev/null +++ b/tests/Samples.Tests/Scenarios/FieldSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class FieldSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/GenericSampleTests.cs b/tests/Samples.Tests/Scenarios/GenericSampleTests.cs new file mode 100644 index 00000000..321f727d --- /dev/null +++ b/tests/Samples.Tests/Scenarios/GenericSampleTests.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public static class GenericSampleTests +{ + [Theory, RandomData] + public static async Task GenericSample_GuardsNulls([Fake] GenericSample data) + { + data.ToString().SetupReturn(Behavior.Base()); + + await Tools.Tester.PreventsNullRefExceptionAsync( + data, + TestContext.Current.CancellationToken + ); + + data.Assert().Called(); + } + + [Fact] + public static Task GenericSample_NoParameterMutation() + { + return Tools.Tester.PreventsParameterMutationAsync( + typeof(GenericSample<>), + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Samples.Tests/Scenarios/GoodOrBadSampleHolderTests.cs b/tests/Samples.Tests/Scenarios/GoodOrBadSampleHolderTests.cs new file mode 100644 index 00000000..f30eb66f --- /dev/null +++ b/tests/Samples.Tests/Scenarios/GoodOrBadSampleHolderTests.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class GoodOrBadSampleHolderTests : AutoTester> +{ + [Fact] + public static void GoodOrBadSampleHolder_CanInject() + { + for (int i = 0; i < 10; i++) + { + _ = Tools.Randomizer.Inject(typeof(GoodOrBadSampleHolder<>), []); + } + } +} diff --git a/tests/Samples.Tests/Scenarios/InheritedPrivatesSampleTests.cs b/tests/Samples.Tests/Scenarios/InheritedPrivatesSampleTests.cs new file mode 100644 index 00000000..c5c277c1 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/InheritedPrivatesSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class InheritedPrivatesSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/InjectSampleTests.cs b/tests/Samples.Tests/Scenarios/InjectSampleTests.cs new file mode 100644 index 00000000..8a9bd33b --- /dev/null +++ b/tests/Samples.Tests/Scenarios/InjectSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class InjectSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/IsGoodSampleTests.cs b/tests/Samples.Tests/Scenarios/IsGoodSampleTests.cs new file mode 100644 index 00000000..a5053879 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/IsGoodSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class IsGoodSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/ParentLoopSampleTests.cs b/tests/Samples.Tests/Scenarios/ParentLoopSampleTests.cs new file mode 100644 index 00000000..a181c0bc --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ParentLoopSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ParentLoopSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/PrivateValuerEquatableSampleTests.cs b/tests/Samples.Tests/Scenarios/PrivateValuerEquatableSampleTests.cs new file mode 100644 index 00000000..dbc6f922 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/PrivateValuerEquatableSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class PrivateValuerEquatableSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/ScopeSampleTests.cs b/tests/Samples.Tests/Scenarios/ScopeSampleTests.cs new file mode 100644 index 00000000..663a2696 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ScopeSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ScopeSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/SelfReferencingDisposableTests.cs b/tests/Samples.Tests/Scenarios/SelfReferencingDisposableTests.cs new file mode 100644 index 00000000..406ba5a1 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/SelfReferencingDisposableTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class SelfReferencingDisposableTests : AutoTester +{ + [Theory, RandomData] + internal static void GrabData_ThrowsWhenDisposed(SelfReferencingDisposable sample) + { + sample.Dispose(); + sample.Assert(x => x.GrabData()).Throws(); + } + + [Theory, RandomData] + internal static async Task GetSelf_ThrowsWhenDisposed(SelfReferencingDisposable sample) + { + await sample.DisposeAsync(); + sample.Assert(x => x.GetSelf()).Throws(); + } +} diff --git a/tests/Samples.Tests/Scenarios/StatelessSampleTests.cs b/tests/Samples.Tests/Scenarios/StatelessSampleTests.cs new file mode 100644 index 00000000..1825c814 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/StatelessSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class StatelessSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/StructSampleTests.cs b/tests/Samples.Tests/Scenarios/StructSampleTests.cs new file mode 100644 index 00000000..8aad94f1 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/StructSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class StructSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/ValueEquatableSampleTests.cs b/tests/Samples.Tests/Scenarios/ValueEquatableSampleTests.cs new file mode 100644 index 00000000..a3f8e505 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ValueEquatableSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ValueEquatableSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/ValuerAsyncComparableSampleTests.cs b/tests/Samples.Tests/Scenarios/ValuerAsyncComparableSampleTests.cs new file mode 100644 index 00000000..5c3c20da --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ValuerAsyncComparableSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ValuerAsyncComparableSampleTests : AutoTester; diff --git a/tests/Samples.Tests/Scenarios/ValuerComparableSampleTests.cs b/tests/Samples.Tests/Scenarios/ValuerComparableSampleTests.cs new file mode 100644 index 00000000..53027a33 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ValuerComparableSampleTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ValuerComparableSampleTests : AutoTester +{ + [Theory, RandomData] + public static void Compare_CloneHasNoDifferences(ValuerComparableSample data) + { + data.Compare(data.Tools().Copy(), Tools.Valuer).Assert().IsEmpty(); + } + + [Theory, RandomData] + public static void Compare_UniqueHasDifferences(ValuerComparableSample data) + { + data.Compare(data.Tools().Unique(), Tools.Valuer).ToArray().Assert().IsNotEmpty(); + } +} diff --git a/tests/Samples.Tests/Scenarios/ValuerEquatableSampleTests.cs b/tests/Samples.Tests/Scenarios/ValuerEquatableSampleTests.cs new file mode 100644 index 00000000..4b346ee2 --- /dev/null +++ b/tests/Samples.Tests/Scenarios/ValuerEquatableSampleTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Samples.Tests.Scenarios; + +public sealed class ValuerEquatableSampleTests : AutoTester; diff --git a/tests/Samples.Tests/SingleValue/HolderTests.cs b/tests/Samples.Tests/SingleValue/HolderTests.cs new file mode 100644 index 00000000..7550b682 --- /dev/null +++ b/tests/Samples.Tests/SingleValue/HolderTests.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.Tests.SingleValue; + +public sealed class HolderTests() : AutoTester(typeof(Holder<>)) +{ + [Fact] + public static Task Holder_GuardsNullsWithDisposable() + { + return Tools.Tester.PreventsNullRefExceptionAsync>( + TestContext.Current.CancellationToken + ); + } + + [Fact] + public static Task Holder_NoParameterMutationWithDisposable() + { + return Tools.Tester.PreventsParameterMutationAsync>( + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Samples.Tests/SingleValue/ReadableHolderTests.cs b/tests/Samples.Tests/SingleValue/ReadableHolderTests.cs new file mode 100644 index 00000000..79cd5721 --- /dev/null +++ b/tests/Samples.Tests/SingleValue/ReadableHolderTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.Tests.SingleValue; + +public sealed class ReadableHolderTests() : AutoTester(typeof(ReadableHolder<>)); diff --git a/tests/Samples.Tests/SingleValue/WriteableHolderTests.cs b/tests/Samples.Tests/SingleValue/WriteableHolderTests.cs new file mode 100644 index 00000000..0276654e --- /dev/null +++ b/tests/Samples.Tests/SingleValue/WriteableHolderTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Samples.Tests.SingleValue; + +public sealed class WriteableHolderTests() : AutoTester(typeof(WriteableHolder<>)); diff --git a/tests/Samples.Tests/ValidSampleAttributeTests.cs b/tests/Samples.Tests/ValidSampleAttributeTests.cs new file mode 100644 index 00000000..e7f3aab3 --- /dev/null +++ b/tests/Samples.Tests/ValidSampleAttributeTests.cs @@ -0,0 +1,3 @@ +namespace Werecodent.CreateAndFake.Samples.Tests; + +public sealed class ValidSampleAttributeTests : AutoTester; diff --git a/tests/Samples.Tests/testsettings.json b/tests/Samples.Tests/testsettings.json new file mode 100644 index 00000000..feb93701 --- /dev/null +++ b/tests/Samples.Tests/testsettings.json @@ -0,0 +1,14 @@ +{ + "CreateAndFake": { + "Design": {}, + "Asserter": {}, + "Duplicator": {}, + "Extractor": {}, + "Faker": {}, + "Mutator": {}, + "Randomizer": {}, + "Runner": {}, + "Tester": {}, + "Valuer": {} + } +} diff --git a/tests/TestSettings.runsettings b/tests/TestSettings.runsettings index db62968b..2e2d2242 100644 --- a/tests/TestSettings.runsettings +++ b/tests/TestSettings.runsettings @@ -2,5 +2,6 @@ ../artifacts/testing + 600000 diff --git a/tests/CreateAndFakeTests/Toolbox/AsserterTool/AssertExceptionTests.cs b/tests/Toolbox.Tests/AsserterTool/AssertExceptionTests.cs similarity index 84% rename from tests/CreateAndFakeTests/Toolbox/AsserterTool/AssertExceptionTests.cs rename to tests/Toolbox.Tests/AsserterTool/AssertExceptionTests.cs index b6f9e17a..4fce829c 100644 --- a/tests/CreateAndFakeTests/Toolbox/AsserterTool/AssertExceptionTests.cs +++ b/tests/Toolbox.Tests/AsserterTool/AssertExceptionTests.cs @@ -1,41 +1,49 @@ -using CreateAndFake.Toolbox.AsserterTool; -using CreateAndFakeTests.TestBases; - -namespace CreateAndFakeTests.Toolbox.AsserterTool; - -public sealed class AssertExceptionTests : ExceptionTestBase -{ - [Fact] - internal static void AssertException_UnknownMessageDefault() - { - new AssertException(null, null, null).Message.Assert().Is("Unknown assert failure."); - } - - [Theory, RandomData] - internal static void AssertException_MessageFormat( - string message, string details, string content, int seed, Exception ex) - { - new AssertException(message, null, null).Message.Assert().Contains(message); - new AssertException(message, null, seed).Message.Assert().Contains($"{seed}"); - - new AssertException(message, details, seed).Message.Assert().Contains(message); - new AssertException(message, details, seed).Message.Assert().Contains(details); - new AssertException(message, details, seed).Message.Assert().Contains($"{seed}"); - new AssertException(message, details, seed, ex).Message.Assert().ContainsNot(ex.ToString()); - - new AssertException(message, null, seed, content).Message.Assert().Contains(message); - new AssertException(message, null, seed, content).Message.Assert().Contains(content); - new AssertException(message, null, seed, content).Message.Assert().Contains($"{seed}"); - - new AssertException(message, details, seed, content).Message.Assert().Contains(message); - new AssertException(message, details, seed, content).Message.Assert().Contains(details); - new AssertException(message, details, seed, content).Message.Assert().Contains(content); - new AssertException(message, details, seed, content).Message.Assert().Contains($"{seed}"); - - new AssertException(message, details, seed, content, ex).Message.Assert().Contains(message); - new AssertException(message, details, seed, content, ex).Message.Assert().Contains(details); - new AssertException(message, details, seed, content, ex).Message.Assert().Contains(content); - new AssertException(message, details, seed, content, ex).Message.Assert().Contains($"{seed}"); - new AssertException(message, details, seed, content, ex).Message.Assert().ContainsNot(ex.ToString()); - } -} +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool; + +public sealed class AssertExceptionTests : ExceptionTestBase +{ + [Fact] + internal static void AssertException_UnknownMessageDefault() + { + new AssertException(null, null, null).Message.Assert().Is("Unknown assert failure."); + } + + [Theory, RandomData] + internal static void AssertException_MessageFormat( + string message, + string details, + string content, + int seed, + Exception ex + ) + { + new AssertException(message, null, null).Message.Assert().Contains(message); + new AssertException(message, null, seed).Message.Assert().Contains($"{seed}"); + + new AssertException(message, details, seed).Message.Assert().Contains(message); + new AssertException(message, details, seed).Message.Assert().Contains(details); + new AssertException(message, details, seed).Message.Assert().Contains($"{seed}"); + new AssertException(message, details, seed, ex).Message.Assert().ContainsNot(ex.ToString()); + + new AssertException(message, null, seed, content).Message.Assert().Contains(message); + new AssertException(message, null, seed, content).Message.Assert().Contains(content); + new AssertException(message, null, seed, content).Message.Assert().Contains($"{seed}"); + + new AssertException(message, details, seed, content).Message.Assert().Contains(message); + new AssertException(message, details, seed, content).Message.Assert().Contains(details); + new AssertException(message, details, seed, content).Message.Assert().Contains(content); + new AssertException(message, details, seed, content).Message.Assert().Contains($"{seed}"); + + new AssertException(message, details, seed, content, ex).Message.Assert().Contains(message); + new AssertException(message, details, seed, content, ex).Message.Assert().Contains(details); + new AssertException(message, details, seed, content, ex).Message.Assert().Contains(content); + new AssertException(message, details, seed, content, ex) + .Message.Assert() + .Contains($"{seed}"); + new AssertException(message, details, seed, content, ex) + .Message.Assert() + .ContainsNot(ex.ToString()); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/AsserterOptionsTests.cs b/tests/Toolbox.Tests/AsserterTool/AsserterOptionsTests.cs new file mode 100644 index 00000000..69b6fdaa --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/AsserterOptionsTests.cs @@ -0,0 +1,18 @@ +global using AsserterMod = System.Func< + Werecodent.CreateAndFake.AsserterTool.AsserterOptions, + Werecodent.CreateAndFake.AsserterTool.AsserterOptions +>; +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool; + +public sealed class AsserterOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void AsserterOptions_ModFormRandomizable() + { + typeof(AsserterMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/AsserterTests.cs b/tests/Toolbox.Tests/AsserterTool/AsserterTests.cs new file mode 100644 index 00000000..96c17b9d --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/AsserterTests.cs @@ -0,0 +1,133 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool; + +public sealed class AsserterTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(AssertException), + typeof(ToolException), + typeof(FakeVerifyException), + typeof(TimeoutException), + typeof(UnsupportedException), + typeof(TargetException), + typeof(InvalidCastException), + typeof(ValueTaskRepeatedAccessException), + ], + }; + + private readonly AsserterMod _config; + + private bool _configCalled; + + public AsserterTests() + { + _configCalled = false; + _config = opt => + { + _configCalled = true; + return opt; + }; + } + + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Fact] + internal static void Asserter_AllMethodsVirtual() + { + Tools.Asserter.IsEmpty( + typeof(Asserter) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .Where(m => !m.IsVirtual) + .Select(m => m.Name) + .Where(n => n is not nameof(Asserter.Is) and not nameof(Asserter.IsNot)) + .Where(n => n is not $"get_{nameof(Asserter.Options)}") + ); + } + + [Fact] + internal void Fail_Throws() + { + _testInstance.Assert(x => x.Fail()).Throws(); + } + + [Theory, RandomData] + internal void Fail_ThrowsWithException(Exception error) + { + _testInstance + .Assert(x => x.Fail(error)) + .Throws() + .With(e => e.InnerException) + .Is(error); + } + + [Theory, RandomData] + internal void Fail_ThrowsWithSample(DataSample sample) + { + sample.Assert(x => x.Assert().Fail()).Throws(); + sample.Assert(x => x.Assert().Fail()).Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void Fail_OnlyThrows([Stub] IAsserter asserter, DataSample sample) + { + AssertObject instance = new(asserter, sample); + instance.Fail(); + instance.Fail(_config); + } + + [Theory, RandomData] + internal void Pass_Works(DataSample sample) + { + sample.Assert().Pass(); + sample.Assert().Pass(_config); + _configCalled.Assert().Is(true); + } + + [Fact] + internal void CheckAll_RunsEachValidCase() + { + bool ran1 = false; + bool ran2 = false; + + _testInstance.CheckAll(() => ran1 = true, () => ran2 = true); + + ran1.Assert().Is(true).Also(ran2).Is(true); + } + + [Theory, RandomData] + internal void CheckAll_SingleErrorThrows(Exception error) + { + bool ran2 = false; + + _testInstance + .Assert(x => x.CheckAll(() => throw error, () => ran2 = true)) + .Throws() + .With(e => e.InnerExceptions) + .Is(new[] { error }) + .Also(ran2) + .Is(true); + } + + [Theory, RandomData] + internal void CheckAll_RunsEachErrorCase(Exception error1, Exception error2) + { + _testInstance + .Assert(x => x.CheckAll(() => throw error1, () => throw error2)) + .Throws() + .With(e => e.InnerExceptions) + .Is(new[] { error1, error2 }); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.AsyncEnumerableTests.cs b/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.AsyncEnumerableTests.cs new file mode 100644 index 00000000..459918eb --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.AsyncEnumerableTests.cs @@ -0,0 +1,395 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.AsyncImplementation; + +public sealed class AsserterAsyncEnumerableTests +{ + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Theory, RandomData] + internal Task FailAsync_Throws(IAsyncEnumerable series) + { + return _testInstance + .FailAsync(series, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal async Task FailAsync_ModAppliesOnce(IAsyncEnumerable series) + { + int appliedCount = 0; + + await _testInstance + .FailAsync( + series, + TestContext.Current.CancellationToken, + opt => + { + appliedCount++; + return opt; + } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + appliedCount.Assert().Is(1); + } + + [Theory, RandomData] + internal Task DebugAsync_DoesNotThrow(IAsyncEnumerable series) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + return _testInstance + .DebugAsync(series, canceler, opt => opt with { TriggerFailureForDebugAsserts = false }) + .Assert() + .ThrowsNoAsync(canceler); + } + + [Theory, RandomData] + internal Task DebugAsync_ThrowsWhenConfigured(IAsyncEnumerable series) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + return _testInstance + .DebugAsync(series, canceler, opt => opt with { TriggerFailureForDebugAsserts = true }) + .Assert() + .ThrowsAsync(canceler); + } + + [Theory, RandomData] + internal Task IsEmptyAsync_NoThrowWithNone([Size(0)] IAsyncEnumerable series) + { + return _testInstance + .IsEmptyAsync(series, TestContext.Current.CancellationToken) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task IsEmptyAsync_ThrowWithSome([Size(1)] IAsyncEnumerable series) + { + return _testInstance + .IsEmptyAsync(series, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal Task IsNotEmptyAsync_ThrowWithNull() + { + return _testInstance + .IsNotEmptyAsync((IAsyncEnumerable)null, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task IsNotEmptyAsync_ThrowWithNone([Size(0)] IAsyncEnumerable series) + { + return _testInstance + .IsNotEmptyAsync(series, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task IsNotEmptyAsync_NoThrowWithSome([Size(1)] IAsyncEnumerable series) + { + return _testInstance + .IsNotEmptyAsync(series, TestContext.Current.CancellationToken) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal async Task HasCountAsync_ThrowUnlessSame([Size(1)] IAsyncEnumerable series) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await _testInstance + .HasCountAsync(0, (IAsyncEnumerable)null, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountAsync(0, series, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountAsync(1, series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + + await _testInstance + .HasCountAsync(2, series, canceler) + .Assert() + .ThrowsAsync(canceler); + } + + [Theory, RandomData] + internal async Task HasCountLessThanAsync_ThrowUnlessLess( + [Size(1)] IAsyncEnumerable series + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await _testInstance + .HasCountLessThanAsync(0, (IAsyncEnumerable)null, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountLessThanAsync(0, series, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountLessThanAsync(1, series, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountLessThanAsync(2, series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + } + + [Theory, RandomData] + internal async Task HasCountLessOrExactlyAsync_ThrowWhenGreater( + [Size(1)] IAsyncEnumerable series + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await _testInstance + .HasCountLessOrExactlyAsync(0, (IAsyncEnumerable)null, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountLessOrExactlyAsync(0, series, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountLessOrExactlyAsync(1, series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + + await _testInstance + .HasCountLessOrExactlyAsync(2, series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + } + + [Theory, RandomData] + internal async Task HasCountMoreThanAsync_ThrowUnlessGreater( + [Size(1)] IAsyncEnumerable series + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await _testInstance + .HasCountMoreThanAsync(0, (IAsyncEnumerable)null, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountMoreThanAsync(0, series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + + await _testInstance + .HasCountMoreThanAsync(1, series, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountMoreThanAsync(2, series, canceler) + .Assert() + .ThrowsAsync(canceler); + } + + [Theory, RandomData] + internal async Task HasCountMoreOrExactlyAsync_ThrowUnlessGreater( + [Size(1)] IAsyncEnumerable series + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await _testInstance + .HasCountMoreOrExactlyAsync(0, (IAsyncEnumerable)null, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .HasCountMoreOrExactlyAsync(0, series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + + await _testInstance + .HasCountMoreOrExactlyAsync(1, series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + + await _testInstance + .HasCountMoreOrExactlyAsync(2, series, canceler) + .Assert() + .ThrowsAsync(canceler); + } + + [Theory, RandomData] + internal async Task ContainsAsync_ThrowWithoutContent([Size(1)] IAsyncEnumerable series) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + object item = (await AsyncSeriesHelper.ToListAsync(series, 2, canceler)).Single(); + + await _testInstance + .ContainsAsync(0, null, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .ContainsAsync(item, series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + + await _testInstance + .ContainsAsync(await item.Tools().VariantAsync(canceler), series, canceler) + .Assert() + .ThrowsAsync(canceler); + } + + [Theory, RandomData] + internal async Task ContainsNotAsync_ThrowWithContent([Size(1)] IAsyncEnumerable series) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + object item = (await AsyncSeriesHelper.ToListAsync(series, 2, canceler)).Single(); + + await _testInstance + .ContainsNotAsync(0, null, canceler) + .Assert() + .ThrowsNoAsync(canceler); + + await _testInstance + .ContainsNotAsync(item, series, canceler) + .Assert() + .ThrowsAsync(canceler); + + await _testInstance + .ContainsNotAsync(await item.Tools().VariantAsync(canceler), series, canceler) + .Assert() + .ThrowsNoAsync(canceler); + } + + [Theory, RandomData] + internal Task ThrowsAsync_ThrowWithNoError([Size(1)] IAsyncEnumerable series) + { + return _testInstance + .ThrowsExceptionAsync(series, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal async Task ThrowsAsync_MustMatchType(InvalidOperationException error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async IAsyncEnumerable throwError() + { + await Task.Delay(0, canceler); + yield return 1; + throw error; + } + + await _testInstance + .ThrowsAsync(throwError(), canceler) + .Assert() + .HasResultAsync(error, canceler); + + await _testInstance + .ThrowsExceptionAsync(throwError(), canceler) + .Assert() + .HasResultAsync(error, canceler); + + await _testInstance + .ThrowsAsync(throwError(), canceler) + .Assert() + .ThrowsAsync(canceler); + } + + [Theory, RandomData] + internal Task ThrowsAsync_UnwrapsError(ArgumentException error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async IAsyncEnumerable throwError() + { + await Task.Delay(0, canceler); + yield return 1; + throw new AggregateException(error); + } + + return _testInstance + .ThrowsAsync(throwError(), canceler) + .Assert() + .HasResultAsync(error, canceler); + } + + [Theory, RandomData] + internal async Task ThrowsAsync_AggregateWorks(Exception error1, Exception error2) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + AggregateException oneError = new(error1); + AggregateException twoErrors = new(error1, error2); + + async IAsyncEnumerable throwError(AggregateException error) + { + await Task.Delay(0, canceler); + yield return 1; + throw error; + } + + await _testInstance + .ThrowsAsync(throwError(oneError), canceler) + .Assert() + .HasResultAsync(oneError, canceler); + + await _testInstance + .ThrowsAsync(throwError(twoErrors), canceler) + .Assert() + .HasResultAsync(twoErrors, canceler); + } + + [Theory, RandomData] + internal Task ThrowsAsync_RethrowsIfConfigured(ArgumentException error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async IAsyncEnumerable throwError() + { + await Task.Delay(0, canceler); + yield return 1; + throw error; + } + + return _testInstance + .ThrowsAsync( + throwError(), + canceler, + opt => opt with { DisableCatchingForThrowAsserts = true } + ) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.AsyncObjectTests.cs b/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.AsyncObjectTests.cs new file mode 100644 index 00000000..ab2f79d8 --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.AsyncObjectTests.cs @@ -0,0 +1,75 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.AsyncImplementation; + +public sealed class AsserterAsyncObjectTests +{ + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Theory, RandomData] + internal Task IsAsync_NoThrowWithSame(object item, [Copy] object item2) + { + return _testInstance + .IsAsync(item, item2, TestContext.Current.CancellationToken) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task IsAsync_ThrowsWithVariant(object item, object item2) + { + return _testInstance + .IsAsync(item, item2, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task IsNotAsync_NoThrowWithVariant(object item, object item2) + { + return _testInstance + .IsNotAsync(item, item2, TestContext.Current.CancellationToken) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task IsNotAsync_ThrowsWithSame(object item, [Copy] object item2) + { + return _testInstance + .IsNotAsync(item, item2, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal Task IsNotAsync_ThrowsWithSameNull() + { + return _testInstance + .IsNotAsync(null, null, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task AreUniqueAsync_ThrowsWithSame(AsyncDataSample item, [Copy] AsyncDataSample item2) + { + return _testInstance + .AreUniqueAsync(item, item2, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task AreUniqueAsync_NoThrowWithUnique( + AsyncDataSample item, + [Unique] AsyncDataSample item2 + ) + { + return _testInstance + .AreUniqueAsync(item, item2, TestContext.Current.CancellationToken) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.TaskTests.cs b/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.TaskTests.cs new file mode 100644 index 00000000..f4c3baab --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.TaskTests.cs @@ -0,0 +1,26 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.AsyncImplementation; + +public sealed class AsserterTaskTests +{ + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Theory, RandomData] + internal Task HasResultAsync_ReturnsResult(int value) + { + return _testInstance + .HasResultAsync(Task.FromResult(value), TestContext.Current.CancellationToken) + .Assert() + .IsAsync(Task.FromResult(value), TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task ThrowsNoAsync_IgnoresDifferentException(InvalidOperationException error) + { + return _testInstance.ThrowsNoAsync( + Task.FromException(error), + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.ValueTaskTests.cs b/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.ValueTaskTests.cs new file mode 100644 index 00000000..e5244f2c --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/AsyncImplementation/Asserter.ValueTaskTests.cs @@ -0,0 +1,17 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.AsyncImplementation; + +public sealed class AsserterValueTaskTests +{ + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Theory, RandomData] + internal Task HasResultAsync_Throws(IAsyncEnumerable series) + { + return _testInstance + .FailAsync(series, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ActionTests.cs b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ActionTests.cs new file mode 100644 index 00000000..5fda6688 --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ActionTests.cs @@ -0,0 +1,131 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.Implementation; + +public sealed class AsserterActionTests +{ + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Fact] + internal void Throws_ActionThrows() + { + _testInstance.Throws(() => + throw new InvalidOperationException() + ); + } + + [Fact] + internal void Throws_ActionTypeMismatch() + { + _testInstance + .Assert(x => x.Throws(() => throw new NotSupportedException())) + .Throws(); + } + + [Fact] + internal void Throws_ActionNoThrow() + { + _testInstance + .Assert(x => x.Throws(() => { })) + .Throws(); + } + + [Fact] + internal Task Throws_HandlesAsyncNoError() + { + return _testInstance.ThrowsAsync( + WaitTest(), + TestContext.Current.CancellationToken + ); + } + + private static async Task WaitTest() + { + await Task.Delay(0, TestContext.Current.CancellationToken); + throw new InvalidDataException(); + } + + [Fact] + internal void Throws_ActionNullCase() + { + _testInstance + .Assert(x => x.Throws(null)) + .Throws(); + } + + [Fact] + internal void Throws_FuncThrows() + { + _testInstance.Throws(() => + throw new InvalidOperationException() + ); + } + + [Fact] + internal void Throws_FuncTypeMismatch() + { + _testInstance + .Assert(x => x.Throws(() => throw new NotSupportedException())) + .Throws(); + } + + [Fact] + internal void Throws_FuncNoThrow() + { + _testInstance + .Assert(x => x.Throws(() => true)) + .Throws(); + } + + [Fact] + internal void Throws_FuncNullCase() + { + _testInstance + .Assert(x => x.Throws(null)) + .Throws(); + } + + [Theory, RandomData] + internal void Throws_Disposes([Stub] IDisposable disposable) + { + disposable.SetupReturn(d => d.Dispose(), Behavior.None(Times.Once)); + + _testInstance.Assert(x => x.Throws(() => disposable)).Throws(); + + disposable.Assert().Called(); + } + + [Theory, RandomData] + internal void Throws_AggregateUnwraps(InvalidOperationException ex) + { + _testInstance + .Throws(() => throw new AggregateException(ex)) + .Assert() + .Is(ex); + } + + [Theory, RandomData] + internal void Throws_AggregateExtraInternal(InvalidOperationException error1, Exception error2) + { + AggregateException ex = new(error1, error2); + + _testInstance + .Assert(x => x.Throws(() => throw ex)) + .Throws() + .With(e => e.InnerException) + .Is(ex); + } + + [Theory, RandomData] + internal void Throws_AggregateWrongInternals(InvalidOperationException error) + { + AggregateException ex = new(error); + + _testInstance + .Assert(x => x.Throws(() => throw ex)) + .Throws() + .With(e => e.InnerException) + .Is(ex); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.DelegateTests.cs b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.DelegateTests.cs new file mode 100644 index 00000000..20908ece --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.DelegateTests.cs @@ -0,0 +1,172 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.Implementation; + +public sealed class AsserterDelegateTests +{ + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Fact] + internal void Throws_ActionThrows() + { + _testInstance.Throws(() => + throw new InvalidOperationException() + ); + } + + [Fact] + internal void Throws_ActionTypeMismatch() + { + _testInstance + .Assert(x => x.Throws(() => throw new NotSupportedException())) + .Throws(); + } + + [Fact] + internal void Throws_ActionNoThrow() + { + _testInstance + .Assert(x => x.Throws(() => { })) + .Throws(); + } + + [Fact] + internal Task Throws_HandlesAsyncNoError() + { + return _testInstance.ThrowsAsync( + WaitTest(), + TestContext.Current.CancellationToken + ); + } + + private static async Task WaitTest() + { + await Task.Delay(0, TestContext.Current.CancellationToken); + throw new InvalidDataException(); + } + + [Fact] + internal void Throws_ActionNullCase() + { + _testInstance + .Assert(x => x.Throws(null)) + .Throws(); + } + + [Fact] + internal void Throws_FuncThrows() + { + _testInstance.Throws(() => + throw new InvalidOperationException() + ); + } + + [Fact] + internal void Throws_FuncTypeMismatch() + { + _testInstance + .Assert(x => x.Throws(() => throw new NotSupportedException())) + .Throws(); + } + + [Fact] + internal void Throws_FuncNoThrow() + { + _testInstance + .Assert(x => x.Throws(() => true)) + .Throws(); + } + + [Fact] + internal void Throws_FuncNullCase() + { + _testInstance + .Assert(x => x.Throws(null)) + .Throws(); + } + + [Theory, RandomData] + internal void Throws_Disposes([Stub] IDisposable disposable) + { + disposable.Tools().ToFake().Setup(m => m.Dispose(), Behavior.None(Times.Once)); + + _testInstance.Assert(x => x.Throws(() => disposable)).Throws(); + + disposable.Assert().Called(); + } + + [Theory, RandomData] + internal void Throws_AggregateUnwraps(InvalidOperationException ex) + { + _testInstance + .Throws(() => throw new AggregateException(ex)) + .Assert() + .Is(ex); + } + + [Theory, RandomData] + internal void Throws_AggregateExtraInternal(InvalidOperationException error1, Exception error2) + { + AggregateException ex = new(error1, error2); + + _testInstance + .Assert(x => x.Throws(() => throw ex)) + .Throws() + .With(e => e.InnerException) + .Is(ex); + } + + [Theory, RandomData] + internal void Throws_AggregateWrongInternals(InvalidOperationException error) + { + AggregateException ex = new(error); + + _testInstance + .Assert(x => x.Throws(() => throw ex)) + .Throws() + .With(e => e.InnerException) + .Is(ex); + } + + [Theory, RandomData] + internal void Throws_RethrowsWhenCatchingDisabled(ArgumentException error) + { + _testInstance + .Assert(x => + x.Throws( + () => throw error, + opt => opt with { DisableCatchingForThrowAsserts = true } + ) + ) + .Throws() + .That() + .Is(error); + } + + [Fact] + internal void Throws_StaticRequired() + { + _testInstance + .Assert(x => x.Throws(HasThisMethod)) + .Throws(); + } + + [Fact] + internal void Throws_ParameterlessRequired() + { + _testInstance + .Assert(x => x.Throws(HasParameterMethod)) + .Throws(); + } + + private Asserter HasThisMethod() + { + return _testInstance; + } + + private static object HasParameterMethod(object item) + { + return item; + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.EnumerableTests.cs b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.EnumerableTests.cs new file mode 100644 index 00000000..ff046318 --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.EnumerableTests.cs @@ -0,0 +1,160 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.Implementation; + +public sealed class AsserterEnumerableTests +{ + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + private readonly AsserterMod _config; + + private bool _configCalled; + + public AsserterEnumerableTests() + { + _configCalled = false; + _config = opt => + { + _configCalled = true; + return opt; + }; + } + + [Theory, RandomData] + internal void IsEmpty_Works(IEnumerable data) + { + _testInstance.IsEmpty(Array.Empty()); + + _testInstance.Assert(x => x.IsEmpty(null)).Throws(); + _testInstance.Assert(x => x.IsEmpty(data)).Throws(); + } + + [Theory, RandomData] + internal void IsNotEmpty_Works(IEnumerable data) + { + _testInstance.IsNotEmpty(data); + + _testInstance.Assert(x => x.IsNotEmpty(null)).Throws(); + _testInstance.Assert(x => x.IsNotEmpty(Array.Empty())).Throws(); + } + + [Theory, RandomData] + internal void HasCount_Works(IEnumerable data) + { + _testInstance.HasCount(data.Count(), data); + + _testInstance.Assert(x => x.HasCount(data.Count(), null)).Throws(); + _testInstance.Assert(x => x.HasCount(data.Count() - 1, data)).Throws(); + _testInstance.Assert(x => x.HasCount(data.Count() + 1, data)).Throws(); + } + + [Theory, RandomData] + internal void IsEmpty_NoItems([Size(0)] IEnumerable items) + { + items.Assert().IsEmpty(); + items.Assert().IsEmpty(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void IsEmpty_WithItems(IEnumerable items) + { + items.Assert(x => x.Assert().IsEmpty()).Throws(); + items.Assert(x => x.Assert().IsEmpty()).Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void IsNotEmpty_WithItems(IEnumerable items) + { + items.Assert().IsNotEmpty(); + items.Assert().IsNotEmpty(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void IsNotEmpty_NoItems([Size(0)] IEnumerable items) + { + items.Assert(x => x.Assert().IsNotEmpty()).Throws(); + items.Assert(x => x.Assert().IsNotEmpty()).Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void HasCount_SameSize(ICollection items) + { + items.Assert().HasCount(items.Count); + items.Assert().HasCount(items.Count, _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void HasCount_MismatchedSize(ICollection items) + { + items + .Assert(x => x.Assert().HasCount(items.Count.Tools().Variant())) + .Throws(); + items + .Assert(x => x.Assert().HasCount(items.Count.Tools().Variant())) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void Contains_UsingSubitem(ICollection items) + { + items.Assert().Contains(Tools.Gen.NextItem(items)); + items.Assert().Contains(Tools.Gen.NextItem(items), _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void Contains_RandomOther(ICollection items) + { + items + .Assert(x => x.Assert().Contains(Tools.Mutator.Variant(items))) + .Throws(); + items + .Assert(x => x.Assert().Contains(Tools.Mutator.Variant(items))) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ContainsNot_RandomOther(ICollection items) + { + items.Assert().ContainsNot(Tools.Mutator.Variant(items)); + items.Assert().ContainsNot(Tools.Mutator.Variant(items), _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ContainsNot_UsingSubitem(ICollection items) + { + items + .Assert(x => x.Assert().ContainsNot(Tools.Gen.NextItem(items))) + .Throws(); + items + .Assert(x => x.Assert().ContainsNot(Tools.Gen.NextItem(items))) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void Fail_Throws(IEnumerable items) + { + items.Assert(x => x.Assert().Fail()).Throws(); + items.Assert(x => x.Assert().Fail()).Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void Fail_OnlyThrows([Stub] IAsserter asserter, IEnumerable items) + { + AssertEnumerable instance = new(asserter, items); + instance.Fail(); + instance.Fail(_config); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ErrorTests.cs b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ErrorTests.cs new file mode 100644 index 00000000..5909341e --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ErrorTests.cs @@ -0,0 +1,37 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.Implementation; + +public sealed class AsserterErrorTests +{ + private readonly AsserterMod _config; + + private bool _configCalled; + + public AsserterErrorTests() + { + _configCalled = false; + _config = opt => + { + _configCalled = true; + return opt; + }; + } + + [Theory, RandomData] + internal void Fail_Throws(Exception sample) + { + sample.Assert(x => x.Assert().Fail()).Throws(); + sample.Assert(x => x.Assert().Fail()).Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void Fail_OnlyThrows([Stub] IAsserter asserter, Exception sample) + { + AssertError instance = new(asserter, sample); + instance.Fail(); + instance.Fail(_config); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.FuncTests.cs b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.FuncTests.cs new file mode 100644 index 00000000..b32c502a --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.FuncTests.cs @@ -0,0 +1,14 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.Implementation; + +public sealed class AsserterFuncTests +{ + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Theory, RandomData] + internal void HasResult_ReturnsResult(int num) + { + _testInstance.HasResult(() => num).Assert().Is(num); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ObjectTests.cs b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ObjectTests.cs new file mode 100644 index 00000000..462122c8 --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.ObjectTests.cs @@ -0,0 +1,282 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.Implementation; + +public sealed class AsserterObjectTests +{ + private readonly AsserterMod _config; + + private bool _configCalled; + + public AsserterObjectTests() + { + _configCalled = false; + _config = opt => + { + _configCalled = true; + return opt; + }; + } + + private readonly Asserter _testInstance = new(Tools.Asserter.Options); + + [Theory, RandomData] + internal void ReferenceEqual_NotByValue([Stub] object fake) + { + fake.Equals(Arg.Any()).SetupReturn(true, Times.Never); + + _testInstance.ReferenceEqual(fake, fake); + _testInstance.Assert(x => x.ReferenceEqual(fake, fake.Tools().Copy())); + + fake.Assert().Called(Times.Never); + } + + [Theory, RandomData] + internal void ReferenceNotEqual_NotByValue([Stub] object fake) + { + fake.Equals(Arg.Any()).SetupReturn(false, Times.Never); + + _testInstance.ReferenceNotEqual(fake, fake.Tools().Copy()); + _testInstance.Assert(x => x.ReferenceNotEqual(fake, fake)).Throws(); + + fake.Assert().Called(Times.Never); + } + + [Theory, RandomData] + internal void ValuesEqual_EqualValid(object value) + { + _testInstance.ValuesEqual(value, value.Tools().Copy()); + } + + [Theory, RandomData] + internal void ValuesEqual_UnequalInvalid(string value) + { + _testInstance + .Assert(x => x.ValuesEqual(value, value.Tools().Variant())) + .Throws(); + _testInstance.Assert(x => x.ValuesEqual(null, value)).Throws(); + } + + [Theory, RandomData] + internal void ValuesEqual_CanHandleNullsNotEqual(object value) + { + _testInstance.Assert(x => x.ValuesEqual(value, null)).Throws(); + _testInstance.Assert(x => x.ValuesEqual(null, value)).Throws(); + } + + [Theory, RandomData] + internal void ValuesNotEqual_UnequalValid(string value) + { + _testInstance.ValuesNotEqual(value, value.Tools().Variant()); + _testInstance.ValuesNotEqual(null, value); + _testInstance.ValuesNotEqual(value, null); + } + + [Theory, RandomData] + internal void ValuesNotEqual_EqualInvalid(string value) + { + _testInstance + .Assert(x => x.ValuesNotEqual(value, value.Tools().Copy())) + .Throws(); + _testInstance.Assert(x => x.ValuesNotEqual(value, value)).Throws(); + _testInstance.Assert(x => x.ValuesNotEqual(null, null)).Throws(); + } + + [Theory, RandomData] + internal void AreUnique_UnequalValid(string value) + { + _testInstance.AreUnique(value, value.Tools().Variant()); + _testInstance.AreUnique(null, value); + _testInstance.AreUnique(value, null); + } + + [Theory, RandomData] + internal void AreUnique_EqualInvalid(string value) + { + _testInstance + .Assert(x => x.AreUnique(value, value.Tools().Copy())) + .Throws(); + _testInstance.Assert(x => x.AreUnique(value, value)).Throws(); + _testInstance.Assert(x => x.AreUnique(null, null)).Throws(); + } + + [Theory, RandomData] + internal void Is_UsesValueQualityPass(DataSample sample) + { + sample.Assert().Is(sample.Tools().Copy()); + sample.Assert().Is(sample.Tools().Copy(), _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void Is_UsesValueQualityFail(DataSample sample) + { + sample.Assert(x => x.Assert().Is(sample.Tools().Variant())).Throws(); + sample + .Assert(x => x.Assert().Is(sample.Tools().Variant())) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void IsNot_UsesValueQualityPass(DataSample sample) + { + sample.Assert().IsNot(sample.Tools().Variant()); + sample.Assert().IsNot(sample.Tools().Variant(), _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void IsNot_UsesValueQualityFail(DataSample sample) + { + sample.Assert(x => x.Assert().IsNot(sample.Tools().Copy())).Throws(); + sample + .Assert(x => x.Assert().IsNot(sample.Tools().Copy())) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ReferenceEqual_SameObject(DataSample sample) + { + sample.Assert().ReferenceEqual(sample); + sample.Assert().ReferenceEqual(sample, _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ReferenceEqual_DifferentObject(DataSample sample) + { + sample + .Assert(x => x.Assert().ReferenceEqual(sample.Tools().Copy())) + .Throws(); + sample + .Assert(x => x.Assert().ReferenceEqual(sample.Tools().Copy())) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ReferenceNotEqual_DifferentObject(DataSample sample) + { + sample.Assert().ReferenceNotEqual(sample.Tools().Variant()); + sample.Assert().ReferenceNotEqual(sample.Tools().Variant(), _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ReferenceNotEqual_SameObject(DataSample sample) + { + sample.Assert(x => x.Assert().ReferenceNotEqual(sample)).Throws(); + sample.Assert(x => x.Assert().ReferenceNotEqual(sample)).Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ValuesEqual_UsesValueQualityPass(DataSample sample) + { + sample.Assert().ValuesEqual(sample.Tools().Copy()); + sample.Assert().ValuesEqual(sample.Tools().Copy(), _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ValuesEqual_UsesValueQualityFail(DataSample sample) + { + sample + .Assert(x => x.Assert().ValuesEqual(sample.Tools().Variant())) + .Throws(); + sample + .Assert(x => x.Assert().ValuesEqual(sample.Tools().Variant())) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ValuesNotEqual_UsesValueQualityPass(DataSample sample) + { + sample.Assert().ValuesNotEqual(sample.Tools().Variant()); + sample.Assert().ValuesNotEqual(sample.Tools().Variant(), _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void ValuesNotEqual_UsesValueQualityFail(DataSample sample) + { + sample + .Assert(x => x.Assert().ValuesNotEqual(sample.Tools().Copy())) + .Throws(); + sample + .Assert(x => x.Assert().ValuesNotEqual(sample.Tools().Copy())) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void AreUnique_NoSharedPass(DataSample sample) + { + sample.Assert().UniqueFrom(sample.Tools().Variant()); + sample.Assert().UniqueFrom(sample.Tools().Variant(), _config); + _configCalled.Assert().Is(true); + } + + [Theory, RandomData] + internal void AreUnique_SharedFail(DataSample sample) + { + sample.Assert(x => x.Assert().UniqueFrom(sample.Tools().Copy())).Throws(); + sample + .Assert(x => x.Assert().UniqueFrom(sample.Tools().Copy())) + .Throws(_config); + _configCalled.Assert().Is(true); + } + + [Fact] + internal static void Inherits_ParentToChild() + { + typeof(IChildType).Assert().Inherits().And().Inherits(typeof(IParentType)); + } + + [Theory, RandomData] + internal static void Inherits_ParentToChildWithOptions(AsserterMod mod) + { + typeof(IChildType) + .Assert() + .Inherits(mod) + .And() + .Inherits(typeof(IParentType), mod); + } + + [Fact] + internal static void Inherits_ChildToParent() + { + typeof(IParentType) + .Assert(x => x.Assert().Inherits()) + .Throws(); + typeof(IParentType) + .Assert(x => x.Assert().Inherits(typeof(IChildType))) + .Throws(); + } + + [Fact] + internal static void InheritedBy_ChildToParent() + { + typeof(IParentType) + .Assert() + .InheritedBy() + .And() + .InheritedBy(typeof(IChildType)); + } + + [Fact] + internal static void InheritedBy_ParentToChild() + { + typeof(IChildType) + .Assert(x => x.Assert().InheritedBy()) + .Throws(); + typeof(IChildType) + .Assert(x => x.Assert().InheritedBy(typeof(IParentType))) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.StringTests.cs b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.StringTests.cs new file mode 100644 index 00000000..0a6e179c --- /dev/null +++ b/tests/Toolbox.Tests/AsserterTool/Implementation/Asserter.StringTests.cs @@ -0,0 +1,90 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.AsserterTool.Implementation; + +public static class AsserterStringTests +{ + [Theory, RandomData] + internal static void Contains_UsingSubstring(ICollection sample) + { + string.Concat(sample).Assert().Contains(Tools.Gen.NextItem(sample)); + } + + [Theory, RandomData] + internal static void Contains_RandomOther(string sample) + { + sample + .Assert(x => x.Assert().Contains(Tools.Mutator.Variant(sample))) + .Throws(); + } + + [Theory, RandomData] + internal static void ContainsNot_RandomOther(string sample) + { + sample.Assert().ContainsNot(Tools.Mutator.Variant(sample)); + } + + [Theory, RandomData] + internal static void ContainsNot_UsingSubstring(ICollection sample) + { + string.Concat(sample) + .Assert(x => x.Assert().ContainsNot(Tools.Gen.NextItem(sample))) + .Throws(); + } + + [Theory, RandomData] + internal static void StartsWith_UsingFirstString(ICollection sample) + { + string.Concat(sample).Assert().StartsWith(sample.First()); + } + + [Theory, RandomData] + internal static void StartsWith_UsingNonFirstString([Size(3)] ICollection sample) + { + string.Concat(sample) + .Assert(x => x.Assert().StartsWith(Tools.Gen.NextItem(sample.Skip(1)))) + .Throws(); + } + + [Theory, RandomData] + internal static void StartsNotWith_UsingNonFirstString([Size(3)] ICollection sample) + { + string.Concat(sample).Assert().StartsNotWith(Tools.Gen.NextItem(sample.Skip(1))); + } + + [Theory, RandomData] + internal static void StartsNotWith_UsingFirstString(ICollection sample) + { + string.Concat(sample) + .Assert(x => x.Assert().StartsNotWith(sample.First())) + .Throws(); + } + + [Theory, RandomData] + internal static void EndsWith_UsingLastString(ICollection sample) + { + string.Concat(sample).Assert().EndsWith(sample.Last()); + } + + [Theory, RandomData] + internal static void EndsWith_UsingNonLstString([Size(3)] ICollection sample) + { + string.Concat(sample) + .Assert(x => x.Assert().EndsWith(Tools.Gen.NextItem(sample.Reverse().Skip(1)))) + .Throws(); + } + + [Theory, RandomData] + internal static void EndsNotWith_UsingNonLastString([Size(3)] ICollection sample) + { + string.Concat(sample).Assert().EndsNotWith(Tools.Gen.NextItem(sample.Reverse().Skip(1))); + } + + [Theory, RandomData] + internal static void EndsNotWith_UsingLstString(ICollection sample) + { + string.Concat(sample) + .Assert(x => x.Assert().EndsNotWith(sample.Last())) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/ConfiguredDesignOptionsTests.cs b/tests/Toolbox.Tests/ConfiguredDesignOptionsTests.cs new file mode 100644 index 00000000..e69d4dcb --- /dev/null +++ b/tests/Toolbox.Tests/ConfiguredDesignOptionsTests.cs @@ -0,0 +1,6 @@ +namespace Werecodent.CreateAndFake.Tests; + +public sealed class ConfiguredDesignOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; +} diff --git a/tests/Toolbox.Tests/CreateAndFake.Tests.csproj b/tests/Toolbox.Tests/CreateAndFake.Tests.csproj new file mode 100644 index 00000000..349b9371 --- /dev/null +++ b/tests/Toolbox.Tests/CreateAndFake.Tests.csproj @@ -0,0 +1,38 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + LEGACY + + + + exe + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Toolbox.Tests/DuplicatorTool/CopyHintTestBase.cs b/tests/Toolbox.Tests/DuplicatorTool/CopyHintTestBase.cs new file mode 100644 index 00000000..dea14483 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/CopyHintTestBase.cs @@ -0,0 +1,119 @@ +using System.Reflection; +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool; + +/// Handles testing copy hints. +/// Copy hint to test. +/// Types that can be copied by the hint. +/// Types that can't be copied by the hint. +public abstract class CopyHintTestBase( + IEnumerable validTypes = null, + IEnumerable invalidTypes = null +) : AutoTester + where T : CopyHint, new() +{ + /// + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ToolException), + typeof(ArgumentException), + typeof(UnsupportedException), + typeof(NotSupportedException), + typeof(ArgumentNullException), + typeof(SerializationException), + typeof(PlatformNotSupportedException), + typeof(TargetParameterCountException), + ], + }; + + /// Types that can be copied by the hint. + private readonly IEnumerable _validTypes = validTypes ?? new T().SupportedTypes; + + /// Types that can't be copied by the hint. + private readonly IEnumerable _invalidTypes = invalidTypes ?? [typeof(DataHolderSample)]; + + /// Verifies the hint supports the correct types. + [Fact] + public async Task TryCopy_SupportsValidTypes() + { + foreach (Type type in _validTypes) + { + object data = null; + CopyHintResult result = CopyHintResult.None; + try + { + data = type.Tools().CreateRandomInstance(); + result = TestInstance.TryCopy(data, CreateChainer()); + + await result + .HasData.Assert() + .Is( + true, + $"Hint '{GenericConverter.ExpandName()}' failed to support " + + $"value of type '{GenericConverter.ExpandName(type)}'. " + + $"Actual type '{GenericConverter.ExpandName(data)}'." + ) + .Also(result.Data) + .IsAsync( + data, + TestContext.Current.CancellationToken, + $"Hint '{GenericConverter.ExpandName()}' failed to create clone that's " + + $"equal by value for type '{GenericConverter.ExpandName(type)}'. " + + $"Actual type '{GenericConverter.ExpandName(data)}'." + ); + } + finally + { + await Disposer.CleanupAsync(data, result.Data); + } + } + } + + /// Verifies the hint doesn't support the wrong types. + [Fact] + public async Task TryCopy_InvalidTypesFail() + { + foreach (Type type in _invalidTypes) + { + object data = type.Tools().CreateRandomInstance(); + try + { + await TestInstance + .TryCopy(data, CreateChainer()) + .Assert() + .IsAsync( + CopyHintResult.None, + TestContext.Current.CancellationToken, + $"Hint '{GenericConverter.ExpandName()}' should not support " + + $"value of type '{GenericConverter.ExpandName(type)}'. " + + $"Actual type '{GenericConverter.ExpandName(data)}'." + ); + } + finally + { + await Disposer.CleanupAsync(data); + } + } + } + + /// Create a chainer to use for testing. + /// Modifications of options to apply for this call. + /// Chainer to use for testing. + protected static IDuplicatorChainer CreateChainer(DuplicatorMod optionConfiguration = null) + { + return new DuplicatorChainer( + optionConfiguration?.Invoke(Tools.Duplicator.Options) ?? Tools.Duplicator.Options, + new DuplicatorEngine() + ); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/DuplicatorOptionsTests.cs b/tests/Toolbox.Tests/DuplicatorTool/DuplicatorOptionsTests.cs new file mode 100644 index 00000000..a32665ca --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/DuplicatorOptionsTests.cs @@ -0,0 +1,18 @@ +global using DuplicatorMod = System.Func< + Werecodent.CreateAndFake.DuplicatorTool.DuplicatorOptions, + Werecodent.CreateAndFake.DuplicatorTool.DuplicatorOptions +>; +using Werecodent.CreateAndFake.DuplicatorTool; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool; + +public sealed class DuplicatorOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void DuplicatorOptions_ModFormRandomizable() + { + typeof(DuplicatorMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/DuplicatorTests.cs b/tests/Toolbox.Tests/DuplicatorTool/DuplicatorTests.cs new file mode 100644 index 00000000..857f9261 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/DuplicatorTests.cs @@ -0,0 +1,73 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool; + +public sealed class DuplicatorTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ToolException)] }; + + [Fact] + internal static void Copy_MissingMatchThrows() + { + new Duplicator(Tools.Duplicator.Options with { IncludeFrameworkHints = false }) + .Assert(x => x.Copy(new object())) + .Throws(); + } + + [Fact] + internal static void Copy_NullWorks() + { + new Duplicator(Tools.Duplicator.Options with { IncludeFrameworkHints = false }) + .Copy(null) + .Assert() + .IsNull(); + } + + [Theory, RandomData] + internal static void Copy_ValidHintWorks(object data, [Stub] CopyHint hint) + { + hint.TryCopy(data, Arg.Any()) + .SetupReturn(new CopyHintResult(data), Times.Once); + + new Duplicator( + Tools.Duplicator.Options with + { + IncludeFrameworkHints = false, + Hints = [hint], + } + ) + .Copy(data) + .Assert() + .Is(data); + + hint.Assert().Called(); + } + + [Theory, RandomData] + internal static void Copy_InfiniteLoopDetails(object instance, [Stub] CopyHint hint) + { + hint.Tools() + .ToFake() + .Setup( + m => m.TryCopy(instance, Arg.Any()), + Behavior.Throw(Times.Once) + ); + + new Duplicator( + Tools.Duplicator.Options with + { + IncludeFrameworkHints = false, + Hints = [hint], + } + ) + .Assert(x => x.Copy(instance)) + .Throws() + .With(e => e.Message) + .Contains(GenericConverter.ExpandName(instance)); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Engine/CopyHintResultTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Engine/CopyHintResultTests.cs new file mode 100644 index 00000000..9a347a06 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Engine/CopyHintResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Engine; + +public sealed class CopyHintResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + CopyHintResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Engine/CopyPriorityTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Engine/CopyPriorityTests.cs new file mode 100644 index 00000000..d7a7f687 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Engine/CopyPriorityTests.cs @@ -0,0 +1,52 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Engine; + +public sealed class CopyPriorityTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(FormatException)], + }; + + [Fact] + internal static void Disabled_SetToMin() + { + ((int)CopyPriority.Disabled).Assert().Is(int.MinValue); + } + + [Fact] + internal static void None_DefaultAtZero() + { + ((int)CopyPriority.None).Assert().Is(0); + } + + [Fact] + internal static void Highest_AtCap() + { + ((int)CopyPriority.Highest).Assert().Is(Enum.GetValues(typeof(CopyPriority)).Length - 2); + } + + [Fact] + internal static void Values_AllPositive() + { + Enum.GetValues(typeof(CopyPriority)) + .Cast() + .Except([(int)CopyPriority.Disabled]) + .Where(v => v < 0) + .Assert() + .IsEmpty(); + } + + [Fact] + internal static void Values_Unique() + { + Enum.GetValues(typeof(CopyPriority)) + .Cast() + .ToHashSet() + .Assert() + .HasCount(Enum.GetValues(typeof(CopyPriority)).Length); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Engine/DuplicatorChainerTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Engine/DuplicatorChainerTests.cs new file mode 100644 index 00000000..98c7a941 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Engine/DuplicatorChainerTests.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Engine; + +public sealed class DuplicatorChainerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(UnsupportedException), + typeof(TargetParameterCountException), + typeof(ArgumentException), + typeof(ToolException), + ], + }; +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Engine/DuplicatorEngineTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Engine/DuplicatorEngineTests.cs new file mode 100644 index 00000000..1a6dbb1c --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Engine/DuplicatorEngineTests.cs @@ -0,0 +1,24 @@ +using System.Collections.Frozen; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Engine; + +public sealed class DuplicatorEngineTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = [Tools.Duplicator.Options], + MethodsToIgnore = FrozenSet.ToFrozenSet(["SelectHints"]), + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(TargetParameterCountException), + typeof(UnsupportedException), + typeof(ToolException), + ], + }; +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Handlers/FactoryCopyHandlerTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Handlers/FactoryCopyHandlerTests.cs new file mode 100644 index 00000000..5de63c21 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Handlers/FactoryCopyHandlerTests.cs @@ -0,0 +1,9 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Handlers; + +public sealed class FactoryCopyHandlerTests() : AutoTester(typeof(FactoryCopyHandler<>)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(InvalidCastException)] }; +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Handlers/LegacyCollectionCopyHandlersTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Handlers/LegacyCollectionCopyHandlersTests.cs new file mode 100644 index 00000000..c91dc780 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Handlers/LegacyCollectionCopyHandlersTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Handlers; + +public sealed class LegacyCollectionCopyHandlersTests() + : AutoTester(typeof(LegacyCollectionCopyHandlers)) +{ + [Fact] + internal static void LegacyCollectionCopyHandlers_InternalOnly() + { + typeof(LegacyCollectionCopyHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Handlers/RefCopyHandlerTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Handlers/RefCopyHandlerTests.cs new file mode 100644 index 00000000..e8d68ae5 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Handlers/RefCopyHandlerTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Handlers; + +public sealed class RefCopyHandlerTests() : AutoTester(typeof(RefCopyHandler)); diff --git a/tests/Toolbox.Tests/DuplicatorTool/Handlers/ReflectionCopyHandlersTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Handlers/ReflectionCopyHandlersTests.cs new file mode 100644 index 00000000..1458638f --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Handlers/ReflectionCopyHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Handlers; + +public sealed class ReflectionCopyHandlersTests() : AutoTester(typeof(ReflectionCopyHandlers)) +{ + [Fact] + internal static void ReflectionCopyHandlers_InternalOnly() + { + typeof(ReflectionCopyHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Handlers/SelfCopyHandlersTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Handlers/SelfCopyHandlersTests.cs new file mode 100644 index 00000000..4178e562 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Handlers/SelfCopyHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Handlers; + +public sealed class SelfCopyHandlersTests() : AutoTester(typeof(SelfCopyHandlers)) +{ + [Fact] + internal static void SelfCopyHandlers_InternalOnly() + { + typeof(SelfCopyHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Handlers/SystemCopyHandlersTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Handlers/SystemCopyHandlersTests.cs new file mode 100644 index 00000000..43b2d571 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Handlers/SystemCopyHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Handlers; + +public sealed class SystemCopyHandlersTests() : AutoTester(typeof(SystemCopyHandlers)) +{ + [Fact] + internal static void SystemCopyHandlers_InternalOnly() + { + typeof(SystemCopyHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Handlers/ValueCopyHandlersTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Handlers/ValueCopyHandlersTests.cs new file mode 100644 index 00000000..6ffd3dad --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Handlers/ValueCopyHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Handlers; + +public sealed class ValueCopyHandlersTests() : AutoTester(typeof(ValueCopyHandlers)) +{ + [Fact] + internal static void ValueCopyHandlers_InternalOnly() + { + typeof(ValueCopyHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/AsyncCollectionCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/AsyncCollectionCopyHintTests.cs new file mode 100644 index 00000000..51cfa3fc --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/AsyncCollectionCopyHintTests.cs @@ -0,0 +1,60 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class AsyncCollectionCopyHintTests : CopyHintTestBase +{ + [Theory, RandomData] + internal static Task TryCopy_Empty([Size(0)] IAsyncEnumerable items) + { + return Tools.Asserter.IsAsync( + items, + items.Tools().Copy(), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal Task CopyAsync_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + size => + (IAsyncEnumerable) + TestInstance + .TryCopy( + Tools.Randomizer.CreateSized>(size), + CreateChainer() + ) + .Data, + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static async Task CopyAsync_Interrupt([Size(5)] IAsyncEnumerable original) + { + IAsyncEnumerable items = original.Tools().Copy(); + + await items.GetAsyncEnumerator(TestContext.Current.CancellationToken).DisposeAsync(); + + int count = 0; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + count++; + if (count == 3) + { + break; + } + } + count.Assert().Is(3); + + count = 0; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + count++; + } + count.Assert().Is(5); + + await Tools.Asserter.IsAsync(original, items, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/AsyncDesignCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/AsyncDesignCopyHintTests.cs new file mode 100644 index 00000000..5428719d --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/AsyncDesignCopyHintTests.cs @@ -0,0 +1,17 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class AsyncDesignCopyHintTests : CopyHintTestBase +{ + [Theory, RandomData] + internal static Task TryCopy_Empty([Size(0)] AsyncList items) + { + return Tools.Asserter.IsAsync( + items, + items.Tools().Copy(), + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/BasicCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/BasicCopyHintTests.cs new file mode 100644 index 00000000..62119816 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/BasicCopyHintTests.cs @@ -0,0 +1,12 @@ +using System.Reflection; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class BasicCopyHintTests : CopyHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(BindingFlags), typeof(int)]; + + public BasicCopyHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/CloneableCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/CloneableCopyHintTests.cs new file mode 100644 index 00000000..ae593099 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/CloneableCopyHintTests.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class CloneableCopyHintTests : CopyHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(string)]; + + public CloneableCopyHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/CollectionCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/CollectionCopyHintTests.cs new file mode 100644 index 00000000..28847294 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/CollectionCopyHintTests.cs @@ -0,0 +1,38 @@ +using System.Collections; +using System.Collections.Concurrent; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class CollectionCopyHintTests : CopyHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(List<>), + typeof(Queue<>), + typeof(Stack<>), + typeof(HashSet<>), + typeof(LinkedList<>), + typeof(ConcurrentQueue<>), + typeof(ConcurrentStack<>), + typeof(ConcurrentDictionary<,>), + typeof(Dictionary<,>), + typeof(int[]), + typeof(string[]), + typeof(ArrayList), + typeof(Queue), + typeof(Stack), + typeof(Array), + ]; + + private static readonly Type[] _InvalidTypes = + [ + typeof(DoubleEnumerableSample), + typeof(ContentEnumerableSample), + typeof(DataHolderSample), + ]; + + public CollectionCopyHintTests() + : base(_ValidTypes, _InvalidTypes) { } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/DeepCloneableCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/DeepCloneableCopyHintTests.cs new file mode 100644 index 00000000..cec46918 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/DeepCloneableCopyHintTests.cs @@ -0,0 +1,44 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class DeepCloneableCopyHintTests : CopyHintTestBase +{ + private class InnerCloneable(string data) : IDeepCloneable + { + public InnerCloneable DeepClone() + { + return new InnerCloneable(data); + } + } + + private sealed class InheritedCloneable(string data) : InnerCloneable(data); + + private sealed class OuterCloneable(string data) + : InnerCloneable(""), + IDeepCloneable + { + public new OuterCloneable DeepClone() + { + return new OuterCloneable(data); + } + } + + private static readonly Type[] _ValidTypes = + [ + typeof(IDeepCloneable<>), + typeof(InnerCloneable), + typeof(OuterCloneable), + ]; + + private static readonly Type[] _InvalidTypes = + [ + typeof(DataHolderSample), + typeof(InheritedCloneable), + ]; + + public DeepCloneableCopyHintTests() + : base(_ValidTypes, _InvalidTypes) { } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/DuplicatableCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/DuplicatableCopyHintTests.cs new file mode 100644 index 00000000..f76d58a1 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/DuplicatableCopyHintTests.cs @@ -0,0 +1,44 @@ +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class DuplicatableCopyHintTests : CopyHintTestBase +{ + private class InnerCloneable(string data) : IDuplicatable + { + public InnerCloneable DeepClone(IDuplicator duplicator) + { + return new InnerCloneable(data); + } + } + + private sealed class InheritedCloneable(string data) : InnerCloneable(data); + + private sealed class OuterCloneable(string data) + : InnerCloneable(""), + IDuplicatable + { + public new OuterCloneable DeepClone(IDuplicator duplicator) + { + return new OuterCloneable(data); + } + } + + private static readonly Type[] _ValidTypes = + [ + typeof(IDuplicatable<>), + typeof(InnerCloneable), + typeof(OuterCloneable), + ]; + + private static readonly Type[] _InvalidTypes = + [ + typeof(DataHolderSample), + typeof(InheritedCloneable), + ]; + + public DuplicatableCopyHintTests() + : base(_ValidTypes, _InvalidTypes) { } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/FrozenCollectionCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/FrozenCollectionCopyHintTests.cs new file mode 100644 index 00000000..b5e276ec --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/FrozenCollectionCopyHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class FrozenCollectionCopyHintTests : CopyHintTestBase; diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/HandlerCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/HandlerCopyHintTests.cs new file mode 100644 index 00000000..3a137ee0 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/HandlerCopyHintTests.cs @@ -0,0 +1,93 @@ +using System.Globalization; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class HandlerCopyHintTests : CopyHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + .. new HandlerCopyHint().SupportedTypes.Except([typeof(object)]), + ]; + + public HandlerCopyHintTests() + : base(_ValidTypes) { } + + [Fact] + internal void TryCopy_HandlesBaseObject() + { + object data = new(); + CopyHintResult result = TestInstance.TryCopy(data, CreateChainer()); + + result.Assert().Is(new CopyHintResult(data)); + result.Data.Assert().ReferenceEqual(data); + } + + [Fact] + internal void TryCopy_HandlesDateTimeFormatInfoReadability() + { + DateTimeFormatInfo readable = new(); + readable.IsReadOnly.Assert().Is(false); + + CopyHintResult readableResult = TestInstance.TryCopy(readable, CreateChainer()); + readableResult.Data.Assert().Is(readable); + + DateTimeFormatInfo unreadable = DateTimeFormatInfo.ReadOnly(readable); + unreadable.IsReadOnly.Assert().Is(true); + + CopyHintResult unreadableResult = TestInstance.TryCopy(unreadable, CreateChainer()); + unreadableResult.Data.Assert().Is(unreadable); + } + + [Fact] + internal void TryCopy_HandlesNumberFormatInfoReadability() + { + NumberFormatInfo readable = new(); + readable.IsReadOnly.Assert().Is(false); + + CopyHintResult readableResult = TestInstance.TryCopy(readable, CreateChainer()); + readableResult.Data.Assert().Is(readable); + + NumberFormatInfo unreadable = NumberFormatInfo.ReadOnly(readable); + unreadable.IsReadOnly.Assert().Is(true); + + CopyHintResult unreadableResult = TestInstance.TryCopy(unreadable, CreateChainer()); + unreadableResult.Data.Assert().Is(unreadable); + } + + [Theory, RandomData] + internal void TryCopy_HandlesCultureInfoReadability(CultureInfo sample) + { + CultureInfo readable = new(sample.Name); + readable.IsReadOnly.Assert().Is(false); + + CopyHintResult readableResult = TestInstance.TryCopy(readable, CreateChainer()); + readableResult.Data.Assert().Is(readable); + + CultureInfo unreadable = CultureInfo.ReadOnly(readable); + unreadable.IsReadOnly.Assert().Is(true); + + CopyHintResult unreadableResult = TestInstance.TryCopy(unreadable, CreateChainer()); + unreadableResult.Data.Assert().Is(unreadable); + } + + [Fact] + internal void TryCopy_CancellationTokenSourceSupport() + { + using CancellationTokenSource source = new(); + + using CancellationTokenSource result = (CancellationTokenSource) + TestInstance.TryCopy(source, CreateChainer()).Data; + + result.IsCancellationRequested.Assert().Is(false); + + source.Cancel(); + result.IsCancellationRequested.Assert().Is(false); + + using CancellationTokenSource canceledResult = (CancellationTokenSource) + TestInstance.TryCopy(source, CreateChainer()).Data; + + canceledResult.IsCancellationRequested.Assert().Is(true); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/ImmutableCollectionCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/ImmutableCollectionCopyHintTests.cs new file mode 100644 index 00000000..b81a3783 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/ImmutableCollectionCopyHintTests.cs @@ -0,0 +1,6 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class ImmutableCollectionCopyHintTests + : CopyHintTestBase; diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/ObjectCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/ObjectCopyHintTests.cs new file mode 100644 index 00000000..31e80c23 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/ObjectCopyHintTests.cs @@ -0,0 +1,48 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class ObjectCopyHintTests : CopyHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(PrivateValuerEquatableSample), + typeof(IUnimplementedSample), + typeof(DataHolderSample), + typeof(FieldSample), + typeof(DataHolderSample), + ]; + + private static readonly Type[] _InvalidTypes = + [ + typeof(MismatchDataSample), + typeof(FactoryAlterSample), + ]; + + public ObjectCopyHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + public override Task Tester_NoParameterMutation() + { + return Task.CompletedTask; + } + + [Fact] + internal void Copy_IgnoresBadSetters() + { + IsBadSample sample = new(); + TestInstance.TryCopy(sample, CreateChainer()).Data.Assert().Is(sample); + } + + [Theory, RandomData] + internal void Copy_DuplicateAware(DataSample sample, DataSample fakeClone) + { + IDuplicatorChainer chainer = CreateChainer(); + chainer.AddToHistory(sample, fakeClone); + + TestInstance.TryCopy(sample, chainer).Data.Assert().Is(fakeClone); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/SerializableCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/SerializableCopyHintTests.cs new file mode 100644 index 00000000..b61fdd7e --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/SerializableCopyHintTests.cs @@ -0,0 +1,25 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class SerializableCopyHintTests : CopyHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(Exception), + typeof(AggregateException), + typeof(IOException), + typeof(AssertException), + ]; + + public SerializableCopyHintTests() + : base(_ValidTypes) { } + + [Theory, RandomData] + internal void TryCopy_InvalidDataContractExceptionRethrown([Stub] ISerializable data) + { + TestInstance.Assert(x => x.TryCopy(data, CreateChainer())).Throws(); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/StreamCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/StreamCopyHintTests.cs new file mode 100644 index 00000000..e17dcbeb --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/StreamCopyHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class StreamCopyHintTests : CopyHintTestBase; diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/TaskCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/TaskCopyHintTests.cs new file mode 100644 index 00000000..8eca11df --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/TaskCopyHintTests.cs @@ -0,0 +1,107 @@ +using Werecodent.CreateAndFake.DuplicatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class TaskCopyHintTests : CopyHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(Task), + typeof(Task), + typeof(Task), + ]; + + public TaskCopyHintTests() + : base(_ValidTypes) { } + + [Fact] + internal Task TryCopy_CopiesNonGenericTaskWhenCanceled() + { + Task task = Task.FromCanceled(new CancellationToken(true)); + return TestInstance + .TryCopy(task, CreateChainer()) + .Data.Assert() + .IsAsync(task, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryCopy_CopiesNonGenericTaskWhenFaulted(Exception error) + { + Task task = Task.FromException(error); + + task.Exception.InnerException.Assert().Is(error); + + return TestInstance + .TryCopy(task, CreateChainer()) + .Data.Assert() + .IsAsync(task, TestContext.Current.CancellationToken); + } + + [Fact] + internal Task TryCopy_CopiesNonGenericTaskWhenCompleted() + { + Task task = Task.CompletedTask; + return TestInstance + .TryCopy(task, CreateChainer()) + .Data.Assert() + .IsAsync(task, TestContext.Current.CancellationToken); + } + + [Fact] + internal Task TryCopy_CopiesNonGenericTaskWhenOngoing() + { + Task task = Task.Delay(1000, TestContext.Current.CancellationToken); + return TestInstance + .TryCopy(task, CreateChainer()) + .Data.Assert() + .IsAsync(task, TestContext.Current.CancellationToken); + } + + [Fact] + internal Task TryCopy_CopiesGenericTaskWhenCanceled() + { + Task task = Task.FromCanceled(new CancellationToken(true)); + return TestInstance + .TryCopy(task, CreateChainer()) + .Data.Assert() + .IsAsync(task, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryCopy_CopiesGenericTaskWhenFaulted(Exception error) + { + Task task = Task.FromException(error); + + task.Exception.InnerException.Assert().Is(error); + + return TestInstance + .TryCopy(task, CreateChainer()) + .Data.Assert() + .IsAsync(task, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryCopy_CopiesGenericTaskWhenCompleted(string data) + { + Task task = Task.FromResult(data); + return TestInstance + .TryCopy(task, CreateChainer()) + .Data.Assert() + .IsAsync(task, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryCopy_CopiesGenericTaskWhenOngoing(string data) + { + Task task = Task.Run(async () => + { + await Task.Delay(1000, TestContext.Current.CancellationToken); + return data; + }); + return TestInstance + .TryCopy(task, CreateChainer()) + .Data.Assert() + .IsAsync(task, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/DuplicatorTool/Hints/ValueTaskCopyHintTests.cs b/tests/Toolbox.Tests/DuplicatorTool/Hints/ValueTaskCopyHintTests.cs new file mode 100644 index 00000000..ae0a9c36 --- /dev/null +++ b/tests/Toolbox.Tests/DuplicatorTool/Hints/ValueTaskCopyHintTests.cs @@ -0,0 +1,39 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.DuplicatorTool.Hints; + +public sealed class ValueTaskCopyHintTests : CopyHintTestBase +{ + [Fact] + internal async Task TryCopy_PreventsCloningExternalValueTasks() + { + ValueTask task = new(Task.CompletedTask); + try + { + TestInstance + .Assert(x => x.TryCopy(task, CreateChainer())) + .Throws(); + } + finally + { + await task; + } + } + + [Theory, RandomData] + internal async Task TryCopy_PreventsCloningExternalGenericValueTasks(string data) + { + ValueTask task = new(Task.FromResult(data)); + try + { + TestInstance + .Assert(x => x.TryCopy(task, CreateChainer())) + .Throws(); + } + finally + { + await task; + } + } +} diff --git a/tests/Toolbox.Tests/ExceptionTestBase.cs b/tests/Toolbox.Tests/ExceptionTestBase.cs new file mode 100644 index 00000000..86da9ea4 --- /dev/null +++ b/tests/Toolbox.Tests/ExceptionTestBase.cs @@ -0,0 +1,36 @@ +namespace Werecodent.CreateAndFake.Tests; + +public abstract class ExceptionTestBase : AutoTester + where T : Exception +{ + [Theory, RandomData] + public void Debug_Exception_ToString(T error) + { + error.Assert().Debug(); + } + + [Fact] + public void Exception_DefaultConstructorPrivate() + { + typeof(T).GetConstructor(Type.EmptyTypes).Assert().IsNull(); + Activator.CreateInstance(typeof(T), true).Assert().IsNotNull(); + } + + [Theory, RandomData] + public void Exception_XmlSerializes(T original) + { + Tools.Tester.VerifyXmlSerialization(original); + } + + [Fact] + public void Exception_JsonSerializes() + { + T original; + do + { + original = Tools.Randomizer.Create(); + } while (original.InnerException != null); + + Tools.Tester.VerifyJsonSerialization(original); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/AsyncContentMapTests.cs b/tests/Toolbox.Tests/ExtractorTool/AsyncContentMapTests.cs new file mode 100644 index 00000000..d2d69baa --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/AsyncContentMapTests.cs @@ -0,0 +1,346 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool; + +public sealed class AsyncContentMapTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = [Tools.Extractor.Options], + IgnorableExceptions = [typeof(ToolException)], + }; + + [Fact] + internal static Task GetAsyncEnumerator_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + size => new AsyncContentMap( + Tools.Randomizer.CreateSized>(size), + Tools.Extractor.Options + ), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task FindAllAsync_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + static (size, canceler) => + new AsyncContentMap( + AsyncHashSet.CreateFromAsync( + Tools.Randomizer.CreateSized>(size), + Tools.Valuer, + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ), + Tools.Extractor.Options + ).FindAllAsync(typeof(DataSample), canceler), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task FindAllAsync_T_CanCancel() + { + return Tools.Tester.VerifySupportsCancellationAsync( + (size, canceler) => + new AsyncContentMap( + AsyncHashSet.CreateFromAsync( + Tools.Randomizer.CreateSized>(size).Cast(), + Tools.Valuer, + size, + TestContext.Current.CancellationToken + ), + Tools.Extractor.Options + ).FindAllAsync(canceler), + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static async Task HasContentAsync_UsesObjectByValue(DataHolderSample sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + await map.HasContentAsync( + await sample + .NestedValue.Tools() + .VariantAsync(TestContext.Current.CancellationToken), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(false, TestContext.Current.CancellationToken); + await map.HasContentAsync( + sample.NestedValue.Tools().Copy(), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(true, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task HasContentAsync_UsesValueByValue(DataHolderSample sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + await map.HasContentAsync( + sample.NestedValue.NumberValue.Tools().Variant(), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(false, TestContext.Current.CancellationToken); + await map.HasContentAsync( + sample.NestedValue.NumberValue.Tools().Copy(), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(true, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task HasContentAsync_UsesStringByValue(DataHolderSample sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + await map.HasContentAsync( + sample.NestedValue.StringValue.Tools().Variant(), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(false, TestContext.Current.CancellationToken); + await map.HasContentAsync( + sample.NestedValue.StringValue.Tools().Copy(), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(true, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task FindAllAsync_ContainsNestedObjects(DataHolderSample sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + await map.FindAllAsync(TestContext.Current.CancellationToken) + .Assert() + .ContainsAsync(sample.NestedValue, TestContext.Current.CancellationToken); + await map.FindAllAsync(typeof(DataSample), TestContext.Current.CancellationToken) + .Assert() + .ContainsAsync(sample.NestedValue, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task FindAllAsync_ContainsNestedValues(DataHolderSample sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + await map.FindAllAsync(TestContext.Current.CancellationToken) + .Assert() + .ContainsAsync(sample.NestedValue.NumberValue, TestContext.Current.CancellationToken); + await map.FindAllAsync(typeof(int), TestContext.Current.CancellationToken) + .Assert() + .ContainsAsync(sample.NestedValue.NumberValue, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task GetAllAsync_TypeSafe(Holder doubleHolder) + { + CancellationToken ct = TestContext.Current.CancellationToken; + + IAsyncContentMap doubleMap = await Tools.Extractor.ExtractAsync(doubleHolder, ct); + await doubleMap.FindAllAsync(typeof(double), ct).Assert().HasCountAsync(1, ct); + await doubleMap.FindAllAsync(typeof(Type), ct).Assert().IsEmptyAsync(ct); + + Holder typeHolder = new(typeof(string)); + + IAsyncContentMap typeMap = await Tools.Extractor.ExtractAsync(typeHolder, ct); + await typeMap.FindAllAsync(typeof(double), ct).Assert().IsEmptyAsync(ct); + await typeMap.FindAllAsync(typeof(Type), ct).Assert().HasCountAsync(1, ct); + } + + [Theory, RandomData] + internal static async Task GetAsyncEnumerator_ContainsEverything(DataHolderSample sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + await map.Assert().ContainsAsync(sample.NestedValue, TestContext.Current.CancellationToken); + await map.Assert() + .ContainsAsync(sample.NestedValue.NumberValue, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task FindSharedContentAsync_ObjectValuesFound(DataHolderSample sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + IAsyncContentMap test = await Tools.Extractor.ExtractAsync( + sample.NestedValue, + TestContext.Current.CancellationToken + ); + await map.FindSharedContentAsync(test, TestContext.Current.CancellationToken) + .Assert() + .ContainsAsync(sample.NestedValue, TestContext.Current.CancellationToken); + await map.HasSharedContentAsync(test, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(true, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task FindSharedContentAsync_ValueValuesFound(DataHolderSample sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + IAsyncContentMap test = await Tools.Extractor.ExtractAsync( + sample.NestedValue.NumberValue, + TestContext.Current.CancellationToken + ); + await map.FindSharedContentAsync(test, TestContext.Current.CancellationToken) + .Assert() + .ContainsAsync(sample.NestedValue.NumberValue, TestContext.Current.CancellationToken); + await map.HasSharedContentAsync(test, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(true, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task HasSharedContentAsync_FalseWithNothingShared(string sample) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + IAsyncContentMap test = await Tools.Extractor.ExtractAsync( + sample.Tools().Variant(), + TestContext.Current.CancellationToken + ); + await map.HasSharedContentAsync(test, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(false, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task HasSharedContentAsync_IgnoresSimpleTypes( + char sample1, + bool sample2, + BindingFlags sample3 + ) + { + IAsyncContentMap map1 = await Tools.Extractor.ExtractAsync( + sample1, + TestContext.Current.CancellationToken + ); + await map1.HasSharedContentAsync( + await Tools.Extractor.ExtractAsync( + sample1.Tools().Copy(), + TestContext.Current.CancellationToken + ), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(false, TestContext.Current.CancellationToken); + + IAsyncContentMap map2 = await Tools.Extractor.ExtractAsync( + sample2, + TestContext.Current.CancellationToken + ); + await map2.HasSharedContentAsync( + await Tools.Extractor.ExtractAsync( + sample2.Tools().Copy(), + TestContext.Current.CancellationToken + ), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(false, TestContext.Current.CancellationToken); + + IAsyncContentMap map3 = await Tools.Extractor.ExtractAsync( + sample3, + TestContext.Current.CancellationToken + ); + await map3.HasSharedContentAsync( + await Tools.Extractor.ExtractAsync( + sample3.Tools().Copy(), + TestContext.Current.CancellationToken + ), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(false, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task FindSharedContentAsync_EmptyCollectionsIgnored( + [Size(0)] object[] sample + ) + { + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + + await map.FindSharedContentAsync( + await Tools.Extractor.ExtractAsync( + Array.Empty(), + TestContext.Current.CancellationToken + ), + TestContext.Current.CancellationToken + ) + .Assert() + .IsEmptyAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task CompareAsync_LibrarySupport( + AsyncContentMap original, + [Copy] AsyncContentMap dupe, + AsyncContentMap variant + ) + { + await original + .CompareAsync(dupe, Tools.Valuer, TestContext.Current.CancellationToken) + .Assert() + .IsEmptyAsync(TestContext.Current.CancellationToken); + + await original + .CompareAsync(variant, Tools.Valuer, TestContext.Current.CancellationToken) + .Assert() + .HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + + await original + .CompareAsync(new object(), Tools.Valuer, TestContext.Current.CancellationToken) + .Assert() + .HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + + await original + .Assert() + .IsAsync(original, TestContext.Current.CancellationToken) + .And() + .IsAsync(dupe, TestContext.Current.CancellationToken) + .And() + .IsNotAsync(variant, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/ContentMapTests.cs b/tests/Toolbox.Tests/ExtractorTool/ContentMapTests.cs new file mode 100644 index 00000000..83a752ae --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/ContentMapTests.cs @@ -0,0 +1,124 @@ +using System.Reflection; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool; + +public sealed class ContentMapTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ArgumentException)] }; + + protected override ContentMap TestInstance => + (ContentMap)Tools.Extractor.Extract(Tools.Randomizer.Create()); + + [Theory, RandomData] + internal static void HasContent_UsesObjectByValue(DataHolderSample sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + map.HasContent(sample.NestedValue.Tools().Variant()).Assert().Is(false); + map.HasContent(sample.NestedValue.Tools().Copy()).Assert().Is(true); + } + + [Theory, RandomData] + internal static void HasContent_UsesValueByValue(DataHolderSample sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + map.HasContent(sample.NestedValue.NumberValue.Tools().Variant()).Assert().Is(false); + map.HasContent(sample.NestedValue.NumberValue.Tools().Copy()).Assert().Is(true); + } + + [Theory, RandomData] + internal static void HasContent_UsesStringByValue(DataHolderSample sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + map.HasContent(sample.NestedValue.StringValue.Tools().Variant()).Assert().Is(false); + map.HasContent(sample.NestedValue.StringValue.Tools().Copy()).Assert().Is(true); + } + + [Theory, RandomData] + internal static void FindAll_ContainsNestedObjects(DataHolderSample sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + map.FindAll().Assert().Contains(sample.NestedValue); + map.FindAll(typeof(DataSample)).Assert().Contains(sample.NestedValue); + } + + [Theory, RandomData] + internal static void FindAll_ContainsNestedValues(DataHolderSample sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + map.FindAll().Assert().Contains(sample.NestedValue.NumberValue); + map.FindAll(typeof(int)).Assert().Contains(sample.NestedValue.NumberValue); + } + + [Theory, RandomData] + internal static void GetEnumerator_ContainsEverything(DataHolderSample sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + map.Assert().Contains(sample.NestedValue); + map.Assert().Contains(sample.NestedValue.NumberValue); + } + + [Theory, RandomData] + internal static void FindSharedContent_ObjectValuesFound(DataHolderSample sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + IContentMap test = Tools.Extractor.Extract(sample.NestedValue); + map.FindSharedContent(test).Assert().Contains(sample.NestedValue); + map.HasSharedContent(test).Assert().Is(true); + } + + [Theory, RandomData] + internal static void FindSharedContent_ValueValuesFound(DataHolderSample sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + IContentMap test = Tools.Extractor.Extract(sample.NestedValue.NumberValue); + map.FindSharedContent(test).Assert().Contains(sample.NestedValue.NumberValue); + map.HasSharedContent(test).Assert().Is(true); + } + + [Theory, RandomData] + internal static void HasSharedContent_FalseWithNothingShared(string sample) + { + IContentMap map = Tools.Extractor.Extract(sample); + IContentMap test = Tools.Extractor.Extract(sample.Tools().Variant()); + map.HasSharedContent(test).Assert().Is(false); + } + + [Theory, RandomData] + internal static void HasSharedContent_IgnoresSimpleTypes( + char sample1, + bool sample2, + BindingFlags sample3 + ) + { + Tools + .Extractor.Extract(sample1) + .HasSharedContent(Tools.Extractor.Extract(sample1.Tools().Copy())) + .Assert() + .Is(false); + + Tools + .Extractor.Extract(sample2) + .HasSharedContent(Tools.Extractor.Extract(sample2.Tools().Copy())) + .Assert() + .Is(false); + + Tools + .Extractor.Extract(sample3) + .HasSharedContent(Tools.Extractor.Extract(sample3.Tools().Copy())) + .Assert() + .Is(false); + } + + [Theory, RandomData] + internal static void FindSharedContent_EmptyCollectionsIgnored([Size(0)] object[] sample) + { + Tools + .Extractor.Extract(sample) + .FindSharedContent(Tools.Extractor.Extract(Array.Empty())) + .Assert() + .IsEmpty(); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractHintResultTests.cs b/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractHintResultTests.cs new file mode 100644 index 00000000..1e788022 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractHintResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Engine; + +public sealed class ExtractHintResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + ExtractHintResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractPriorityTests.cs b/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractPriorityTests.cs new file mode 100644 index 00000000..88c08aca --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractPriorityTests.cs @@ -0,0 +1,54 @@ +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Engine; + +public sealed class ExtractPriorityTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(FormatException)], + }; + + [Fact] + internal static void Disabled_SetToMin() + { + ((int)ExtractPriority.Disabled).Assert().Is(int.MinValue); + } + + [Fact] + internal static void None_DefaultAtZero() + { + ((int)ExtractPriority.None).Assert().Is(0); + } + + [Fact] + internal static void Highest_AtCap() + { + ((int)ExtractPriority.Highest) + .Assert() + .Is(Enum.GetValues(typeof(ExtractPriority)).Length - 2); + } + + [Fact] + internal static void Values_AllPositive() + { + Enum.GetValues(typeof(ExtractPriority)) + .Cast() + .Except([(int)ExtractPriority.Disabled]) + .Where(v => v < 0) + .Assert() + .IsEmpty(); + } + + [Fact] + internal static void Values_Unique() + { + Enum.GetValues(typeof(ExtractPriority)) + .Cast() + .ToHashSet() + .Assert() + .HasCount(Enum.GetValues(typeof(ExtractPriority)).Length); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractorChainerTests.cs b/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractorChainerTests.cs new file mode 100644 index 00000000..4b0da833 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractorChainerTests.cs @@ -0,0 +1,53 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.ExtractorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Engine; + +public sealed class ExtractorChainerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(UnsupportedException), + typeof(ToolException), + typeof(TargetParameterCountException), + typeof(MismatchedAccessException), + ], + }; + + [Theory, RandomData] + internal static async Task AddFoundValue_CannotUseAfterAsyncCall( + ExtractorChainer chainer, + object item1, + object item2 + ) + { + await chainer + .AddFoundValueAsync(item1, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(true, TestContext.Current.CancellationToken); + + chainer.Assert(x => x.AddFoundValue(item2)).Throws(); + } + +#pragma warning disable MA0042, VSTHRD103 // Behavior specifically being tested. + + [Theory, RandomData] + internal static void AddFoundValueAsync_CannotUseAfterSyncCall( + ExtractorChainer chainer, + object item1, + object item2 + ) + { + chainer.AddFoundValue(item1).Assert().Is(true); + chainer + .Assert(x => x.AddFoundValueAsync(item2, TestContext.Current.CancellationToken)) + .Throws(); + } + +#pragma warning restore MA0042, VSTHRD103 +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractorEngineTests.cs b/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractorEngineTests.cs new file mode 100644 index 00000000..10df5a8a --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Engine/ExtractorEngineTests.cs @@ -0,0 +1,76 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.ExtractorTool.Engine; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Engine; + +public sealed class ExtractorEngineTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ToolException), + typeof(UnsupportedException), + typeof(TargetParameterCountException), + typeof(InvalidOperationException), + ], + }; + + [Theory, RandomData] + internal void Extract_NoHintsUnsupported(object data) + { + TestInstance + .Assert(x => x.Extract(data, CreateHintChainer(null))) + .Throws(); + } + + [Theory, RandomData] + internal void Extract_NullResultSafe([Stub] IExtractHint hint, object data) + { + TestInstance + .Assert(x => x.Extract(data, CreateHintChainer(hint))) + .Throws(); + } + + [Theory, RandomData] + internal Task ExtractAsync_NoHintsUnsupported(object data) + { + return TestInstance + .ExtractAsync(data, CreateHintChainer(null), TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task ExtractAsync_NullResultSafe([Stub] IExtractHint hint, object data) + { + hint.TryToExtractAsync( + Arg.Any(), + Arg.Any(), + Arg.Any() + ) + .SetupReturn(Task.FromResult(null)); + + return TestInstance + .ExtractAsync(data, CreateHintChainer(hint), TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + private static ExtractorChainer CreateHintChainer(IExtractHint hint) + { + return new ExtractorChainer( + Tools.Extractor.Options with + { + IncludeFoundHints = false, + IncludeFrameworkHints = false, + Hints = hint != null ? [hint] : [], + }, + new ExtractorEngine() + ); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/ExtractHintTestBase.cs b/tests/Toolbox.Tests/ExtractorTool/ExtractHintTestBase.cs new file mode 100644 index 00000000..32940a48 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/ExtractHintTestBase.cs @@ -0,0 +1,157 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.ExtractorTool.Engine; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool; + +#pragma warning disable MA0042, VSTHRD103 // For testing. + +/// Handles testing extract hints. +/// Extract hint to test. +/// +/// +public abstract class ExtractHintTestBase( + IEnumerable validTypes = null, + IEnumerable invalidTypes = null +) : AutoTester + where T : IExtractHint, new() +{ + /// Types that can be created by the hint. + private readonly IEnumerable _validTypes = validTypes ?? new T().SupportedTypes; + + /// Types that can't be created by the hint. + private readonly IEnumerable _invalidTypes = invalidTypes ?? [typeof(DataHolderSample)]; + + /// Verifies the hint supports the correct types. + [Fact] + public async Task TryToExtract_SupportsValidTypes() + { + foreach (Type type in _validTypes) + { + IExtractorChainer chainer = CreateChainer(); + object value = Tools.Randomizer.Create(type); + try + { + TestInstance + .TryToExtract(value, chainer) + .Assert() + .Is( + new ExtractHintResult(true), + "Hint '" + typeof(T).Name + "' did not support type '" + type.Name + "'." + ); + + TestInstance + .TryToExtract(value, chainer) + .Assert() + .Is( + new ExtractHintResult(false), + "Hint '" + typeof(T).Name + "' did not ignore repeated '" + type.Name + "'." + ); + } + finally + { + await Disposer.CleanupAsync(value); + } + } + } + + /// Verifies the hint supports the correct types. + [Fact] + public async Task TryToExtractAsync_SupportsValidTypes() + { + foreach (Type type in _validTypes) + { + IExtractorChainer chainer = CreateChainer(); + object value = Tools.Randomizer.Create(type); + try + { + await TestInstance + .TryToExtractAsync(value, chainer, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync( + new ExtractHintResult(true), + TestContext.Current.CancellationToken, + "Hint '" + typeof(T).Name + "' did not support type '" + type.Name + "'." + ); + + await TestInstance + .TryToExtractAsync(value, chainer, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync( + new ExtractHintResult(false), + TestContext.Current.CancellationToken, + "Hint '" + typeof(T).Name + "' did not ignore repeated '" + type.Name + "'." + ); + } + finally + { + await Disposer.CleanupAsync(value); + } + } + } + + /// Verifies the hint doesn't support the wrong types. + [Fact] + public async Task TryToExtract_InvalidTypesFail() + { + foreach (Type type in _invalidTypes) + { + object value = Tools.Randomizer.Create(type); + try + { + await TestInstance + .TryToExtract(value, CreateChainer()) + .Assert() + .IsAsync( + ExtractHintResult.None, + TestContext.Current.CancellationToken, + "Hint '" + typeof(T).Name + "' should not support type '" + type.Name + "'." + ); + } + finally + { + await Disposer.CleanupAsync(value); + } + } + } + + /// Verifies the hint doesn't support the wrong types. + [Fact] + public async Task TryToExtractAsync_InvalidTypesFail() + { + foreach (Type type in _invalidTypes) + { + object value = Tools.Randomizer.Create(type); + try + { + await TestInstance + .TryToExtractAsync( + value, + CreateChainer(), + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync( + ExtractHintResult.None, + TestContext.Current.CancellationToken, + "Hint '" + typeof(T).Name + "' should not support type '" + type.Name + "'." + ); + } + finally + { + await Disposer.CleanupAsync(value); + } + } + } + + /// Create a chainer to use for testing. + /// Chainer to use for testing. + /// Options to pass via the chainer. + protected static IExtractorChainer CreateChainer(ExtractorOptions options = null) + { + return new ExtractorChainer(options ?? Tools.Extractor.Options, new ExtractorEngine()); + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/ExtractorTool/ExtractorOptionsTests.cs b/tests/Toolbox.Tests/ExtractorTool/ExtractorOptionsTests.cs new file mode 100644 index 00000000..2d071b28 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/ExtractorOptionsTests.cs @@ -0,0 +1,18 @@ +global using ExtractorMod = System.Func< + Werecodent.CreateAndFake.ExtractorTool.ExtractorOptions, + Werecodent.CreateAndFake.ExtractorTool.ExtractorOptions +>; +using Werecodent.CreateAndFake.ExtractorTool; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool; + +public sealed class ExtractorOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void ExtractorOptions_ModFormRandomizable() + { + typeof(ExtractorMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/ExtractorTests.cs b/tests/Toolbox.Tests/ExtractorTool/ExtractorTests.cs new file mode 100644 index 00000000..60491f68 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/ExtractorTests.cs @@ -0,0 +1,56 @@ +using Werecodent.CreateAndFake.Design; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool; + +public sealed class ExtractorTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ToolException)] }; + + [Fact] + internal static void Extract_CollectionsWork() + { + foreach ( + Type type in CollectionCreateHint.PotentialCollections.Where(t => + !ArgumentGuard.IsAsynchronous(t) + ) + ) + { + Tools.Extractor.Extract(Tools.Randomizer.Create(type)).Assert().IsNotEmpty(); + } + } + + [Fact] + internal static void Extract_LegacyCollectionsWork() + { + foreach (Type type in LegacyCollectionCreateHint.PotentialCollections) + { + Tools.Extractor.Extract(Tools.Randomizer.Create(type)).Assert().IsNotEmpty(); + } + } + +#pragma warning disable MA0042, VSTHRD103 // Behavior specifically being tested. + + [Theory, RandomData] + internal static async Task ExtractAsync_MatchesExtract(DataHolderSample sample) + { + ISet asyncContent = ( + await AsyncSeriesHelper.ToListAsync( + await Tools.Extractor.ExtractAsync(sample, TestContext.Current.CancellationToken), + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ) + ).ToHashSet(); + + ISet syncContent = Tools.Extractor.Extract(sample).ToHashSet(); + + asyncContent.Assert().Is(syncContent); + } + +#pragma warning restore MA0042, VSTHRD103 +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Handlers/ConvertExtractHandlerTests.cs b/tests/Toolbox.Tests/ExtractorTool/Handlers/ConvertExtractHandlerTests.cs new file mode 100644 index 00000000..0562cb54 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Handlers/ConvertExtractHandlerTests.cs @@ -0,0 +1,34 @@ +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ExtractorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Handlers; + +public sealed class ConvertExtractHandlerTests() : AutoTester(typeof(ConvertExtractHandler)) +{ + [Fact] + internal static void ConvertExtractHandler_InternalOnly() + { + typeof(ConvertExtractHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void ExtractSupported_IgnoresDuplicates() + { + TypeDescriber describer = TypeDescriber.For(); + object[] content = [describer, describer]; + + Tools.Extractor.Extract(content).FindAll().Assert().HasCount(1); + } + + [Fact] + internal static async Task ExtractSupportedAsync_IgnoresDuplicates() + { + TypeDescriber describer = TypeDescriber.For(); + object[] content = [describer, describer]; + + await (await Tools.Extractor.ExtractAsync(content, TestContext.Current.CancellationToken)) + .FindAllAsync(TestContext.Current.CancellationToken) + .Assert() + .HasCountAsync(1, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Handlers/ConvertExtractHandler{T}Tests.cs b/tests/Toolbox.Tests/ExtractorTool/Handlers/ConvertExtractHandler{T}Tests.cs new file mode 100644 index 00000000..70be6c8f --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Handlers/ConvertExtractHandler{T}Tests.cs @@ -0,0 +1,14 @@ +using Werecodent.CreateAndFake.ExtractorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Handlers; + +public sealed class ConvertExtractHandler_T_Tests() : AutoTester(typeof(ConvertExtractHandler<>)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableToolSetSupportTests = true, + IgnorableExceptions = [typeof(InvalidCastException)], + }; +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Handlers/ReflectionExtractHandlersTests.cs b/tests/Toolbox.Tests/ExtractorTool/Handlers/ReflectionExtractHandlersTests.cs new file mode 100644 index 00000000..ef55f057 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Handlers/ReflectionExtractHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ExtractorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Handlers; + +public sealed class ReflectionExtractHandlersTests() : AutoTester(typeof(ReflectionExtractHandlers)) +{ + [Fact] + internal static void ReflectionExtractHandlers_InternalOnly() + { + typeof(ReflectionExtractHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Handlers/SelfExtractHandlerTests.cs b/tests/Toolbox.Tests/ExtractorTool/Handlers/SelfExtractHandlerTests.cs new file mode 100644 index 00000000..73c24ad4 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Handlers/SelfExtractHandlerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ExtractorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Handlers; + +public sealed class SelfExtractHandlerTests() : AutoTester(typeof(SelfExtractHandler)) +{ + [Fact] + internal static void SelfExtractHandler_InternalOnly() + { + typeof(SelfExtractHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Handlers/SystemExtractHandlersTests.cs b/tests/Toolbox.Tests/ExtractorTool/Handlers/SystemExtractHandlersTests.cs new file mode 100644 index 00000000..36910b70 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Handlers/SystemExtractHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ExtractorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Handlers; + +public sealed class SystemExtractHandlersTests() : AutoTester(typeof(SystemExtractHandlers)) +{ + [Fact] + internal static void SystemExtractHandlers_InternalOnly() + { + typeof(SystemExtractHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Handlers/ValueExtractHandlersTests.cs b/tests/Toolbox.Tests/ExtractorTool/Handlers/ValueExtractHandlersTests.cs new file mode 100644 index 00000000..31a007f8 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Handlers/ValueExtractHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ExtractorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Handlers; + +public sealed class ValueExtractHandlersTests() : AutoTester(typeof(ValueExtractHandlers)) +{ + [Fact] + internal static void ValueExtractHandlers_InternalOnly() + { + typeof(ValueExtractHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/DelegateExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/DelegateExtractHintTests.cs new file mode 100644 index 00000000..09574959 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/DelegateExtractHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class DelegateExtractHintTests : ExtractHintTestBase; diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/DictionaryExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/DictionaryExtractHintTests.cs new file mode 100644 index 00000000..0f6b5a9a --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/DictionaryExtractHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class DictionaryExtractHintTests : ExtractHintTestBase; diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/EndingExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/EndingExtractHintTests.cs new file mode 100644 index 00000000..a63ca5c8 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/EndingExtractHintTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ExtractorTool.Engine; +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class EndingExtractHintTests : ExtractHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(ExtractPriority)]; + + public EndingExtractHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/EnumerableExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/EnumerableExtractHintTests.cs new file mode 100644 index 00000000..d12751df --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/EnumerableExtractHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class EnumerableExtractHintTests : ExtractHintTestBase; diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/ExtractableExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/ExtractableExtractHintTests.cs new file mode 100644 index 00000000..e5210d60 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/ExtractableExtractHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class ExtractableExtractHintTests : ExtractHintTestBase; diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/FakedExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/FakedExtractHintTests.cs new file mode 100644 index 00000000..c204415f --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/FakedExtractHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class FakedExtractHintTests : ExtractHintTestBase; diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/HandlerExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/HandlerExtractHintTests.cs new file mode 100644 index 00000000..40ada587 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/HandlerExtractHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class HandlerExtractHintTests : ExtractHintTestBase; diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/ObjectExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/ObjectExtractHintTests.cs new file mode 100644 index 00000000..f5c258f6 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/ObjectExtractHintTests.cs @@ -0,0 +1,66 @@ +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.ExtractorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class ObjectExtractHintTests : ExtractHintTestBase +{ + private sealed class HiddenData + { + private readonly string _data = "A"; + + private string Data { get; } = "B"; + + public override string ToString() + { + return Data + _data; + } + } + + private static readonly Type[] _ValidTypes = [typeof(DataHolderSample)]; + + public ObjectExtractHintTests() + : base(_ValidTypes, []) { } + + public override Task Tester_NoParameterMutation() + { + return Task.CompletedTask; + } + + [Fact] + internal void Extract_UtilizesExtractPrivateMembersFlag() + { + HiddenData sample = new(); + object[] publics = [sample]; + object[] privates = [sample, "B", "A"]; + + Tools.Extractor.Extract(sample).Assert().Is(publics); + + Tools + .Extractor.Extract(sample, opt => opt with { ExtractPrivateMembers = true }) + .Assert() + .Is(privates); + } + + [Fact] + internal async Task ExtractAsync_UtilizesExtractPrivateMembersFlag() + { + HiddenData sample = new(); + object[] publics = [sample]; + object[] privates = [sample, "B", "A"]; + + IAsyncContentMap map = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken + ); + await map.Assert().IsAsync(publics, TestContext.Current.CancellationToken); + + IAsyncContentMap map2 = await Tools.Extractor.ExtractAsync( + sample, + TestContext.Current.CancellationToken, + opt => opt with { ExtractPrivateMembers = true } + ); + await map2.Assert().IsAsync(privates, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/StreamExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/StreamExtractHintTests.cs new file mode 100644 index 00000000..e993d590 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/StreamExtractHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class StreamExtractHintTests : ExtractHintTestBase; diff --git a/tests/Toolbox.Tests/ExtractorTool/Hints/TaskExtractHintTests.cs b/tests/Toolbox.Tests/ExtractorTool/Hints/TaskExtractHintTests.cs new file mode 100644 index 00000000..ab173599 --- /dev/null +++ b/tests/Toolbox.Tests/ExtractorTool/Hints/TaskExtractHintTests.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.ExtractorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ExtractorTool.Hints; + +public sealed class TaskExtractHintTests : ExtractHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(Task), + typeof(Task), + typeof(Task), + ]; + + public TaskExtractHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/FakerTool/AnyGenericTests.cs b/tests/Toolbox.Tests/FakerTool/AnyGenericTests.cs new file mode 100644 index 00000000..3e180ccb --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/AnyGenericTests.cs @@ -0,0 +1,18 @@ +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public static class AnyGenericTests +{ + [Fact] + internal static void AnyGeneric_VoidTypePrivateConstructor() + { + ConstructorInfo constructor = typeof(AnyGeneric) + .GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Single(); + + constructor.IsPrivate.Assert().Is(true); + constructor.Invoke([]).Assert().IsNotNull(); + } +} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/ArgTests.cs b/tests/Toolbox.Tests/FakerTool/ArgTests.cs similarity index 76% rename from tests/CreateAndFakeTests/Toolbox/FakerTool/ArgTests.cs rename to tests/Toolbox.Tests/FakerTool/ArgTests.cs index 5655e8b3..bc4c13d8 100644 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/ArgTests.cs +++ b/tests/Toolbox.Tests/FakerTool/ArgTests.cs @@ -1,109 +1,112 @@ -using System.Reflection; -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.Toolbox.FakerTool; - -public static class ArgTests -{ - [Fact] - internal static void Arg_PairsWithLambda() - { - string[] methods = typeof(Arg) - .GetMethods(BindingFlags.Static | BindingFlags.Public) - .Select(m => m.Name) - .ToArray(); - - methods - .Where(m => !m.StartsWith("Lambda", StringComparison.InvariantCulture)) - .Where(m => !methods.Contains("Lambda" + m)) - .Assert().IsEmpty("Methods should have a lambda version to convert to."); - } - - [Fact] - internal static void Arg_Random() - { - Arg.Any().Assert().IsNot(default(int)); - Arg.Where(null).Assert().IsNot(default(int)); - - Arg.Any().Assert().IsNot(default(string)); - Arg.NotNull().Assert().IsNot(default(string)); - Arg.Where(null).Assert().IsNot(default(string)); - } - - [Fact] - internal static void Arg_OutRefDefault() - { - Arg.AnyRef().Var.Assert().Is(default(int)); - Arg.WhereRef(null).Var.Assert().Is(default(int)); - - Arg.AnyRef().Var.Assert().Is(default(string)); - Arg.WhereRef(null).Var.Assert().Is(default(string)); - } - - [Theory, RandomData] - internal static void LambdaAny_MatchesValues(int value, string name) - { - Arg.LambdaAny().Matches(value).Assert().Is(true); - Arg.LambdaAny().Matches(name).Assert().Is(true); - } - - [Fact] - internal static void LambdaAny_NullsMatch() - { - Arg.LambdaAny().Matches(null).Assert().Is(true); - Arg.LambdaAny().Matches(null).Assert().Is(true); - } - - [Theory, RandomData] - internal static void LambdaAny_Mismatches(string name, int value) - { - Arg.LambdaAny().Matches(name).Assert().Is(false); - Arg.LambdaAny().Matches(value).Assert().Is(false); - } - - [Theory, RandomData] - internal static void LambdaAnyRef_MatchesValues(OutRef nameRef, OutRef valueRef) - { - Arg.LambdaAnyRef().Matches(valueRef).Assert().Is(true); - Arg.LambdaAnyRef().Matches(nameRef).Assert().Is(true); - } - - [Theory, RandomData] - internal static void LambdaNotNull_MatchesValues(string name) - { - Arg.LambdaNotNull().Matches(name).Assert().Is(true); - } - - [Fact] - internal static void LambdaNotNull_NullsInvalid() - { - Arg.LambdaNotNull().Matches(null).Assert().Is(false); - } - - [Theory, RandomData] - internal static void LambdaWhere_MatchesCondition(string name) - { - Arg.LambdaWhere(null).Matches(name).Assert().Is(true); - Arg.LambdaWhere(s => true).Matches(name).Assert().Is(true); - Arg.LambdaWhere(s => false).Matches(name).Assert().Is(false); - } - - [Theory, RandomData] - internal static void LambdaWhereRef_MatchesCondition(OutRef nameRef) - { - Arg.LambdaWhereRef(null).Matches(nameRef).Assert().Is(true); - Arg.LambdaWhereRef(s => true).Matches(nameRef).Assert().Is(true); - Arg.LambdaWhereRef(s => false).Matches(nameRef).Assert().Is(false); - } - - [Theory, RandomData] - internal static void Arg_Cloneable(string value) - { - Arg origin = Arg.LambdaWhere(d => d == value); - Arg copy = origin.CreateDeepClone(); - - copy.Assert().Is(origin); - copy.Matches(value).Assert().Is(true); - copy.Matches(value.CreateVariant()).Assert().Is(false); - } -} +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class ArgTests : AutoTester +{ + [Fact] + internal static void Arg_PairsWithLambda() + { + string[] methods = + [ + .. typeof(Arg) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .Select(m => m.Name), + ]; + + methods + .Where(m => !m.StartsWith("Lambda", StringComparison.Ordinal)) + .Where(m => !methods.Contains("Lambda" + m)) + .Assert() + .IsEmpty("Methods should have a lambda version to convert to."); + } + + [Fact] + internal static void Arg_Random() + { + Arg.Any().Assert().IsNot(default(int)); + Arg.Where(null).Assert().IsNot(default(int)); + + Arg.Any().Assert().IsNot(default(string)); + Arg.NotNull().Assert().IsNot(default(string)); + Arg.Where(null).Assert().IsNot(default(string)); + } + + [Fact] + internal static void Arg_OutRefDefault() + { + Arg.AnyRef().Var.Assert().Is(default(int)); + Arg.WhereRef(null).Var.Assert().Is(default(int)); + + Arg.AnyRef().Var.Assert().Is(default(string)); + Arg.WhereRef(null).Var.Assert().Is(default(string)); + } + + [Theory, RandomData] + internal static void LambdaAny_MatchesValues(int value, string name) + { + Arg.LambdaAny().Matches(value).Assert().Is(true); + Arg.LambdaAny().Matches(name).Assert().Is(true); + } + + [Fact] + internal static void LambdaAny_NullsMatch() + { + Arg.LambdaAny().Matches(null).Assert().Is(true); + Arg.LambdaAny().Matches(null).Assert().Is(true); + } + + [Theory, RandomData] + internal static void LambdaAny_Mismatches(string name, int value) + { + Arg.LambdaAny().Matches(name).Assert().Is(false); + Arg.LambdaAny().Matches(value).Assert().Is(false); + } + + [Theory, RandomData] + internal static void LambdaAnyRef_MatchesValues(OutRef nameRef, OutRef valueRef) + { + Arg.LambdaAnyRef().Matches(valueRef).Assert().Is(true); + Arg.LambdaAnyRef().Matches(nameRef).Assert().Is(true); + } + + [Theory, RandomData] + internal static void LambdaNotNull_MatchesValues(string name) + { + Arg.LambdaNotNull().Matches(name).Assert().Is(true); + } + + [Fact] + internal static void LambdaNotNull_NullsInvalid() + { + Arg.LambdaNotNull().Matches(null).Assert().Is(false); + } + + [Theory, RandomData] + internal static void LambdaWhere_MatchesCondition(string name) + { + Arg.LambdaWhere(null).Matches(name).Assert().Is(true); + Arg.LambdaWhere(_ => true).Matches(name).Assert().Is(true); + Arg.LambdaWhere(_ => false).Matches(name).Assert().Is(false); + } + + [Theory, RandomData] + internal static void LambdaWhereRef_MatchesCondition(OutRef nameRef) + { + Arg.LambdaWhereRef(null).Matches(nameRef).Assert().Is(true); + Arg.LambdaWhereRef(_ => true).Matches(nameRef).Assert().Is(true); + Arg.LambdaWhereRef(_ => false).Matches(nameRef).Assert().Is(false); + } + + [Theory, RandomData] + internal static void Arg_Cloneable(string value) + { + Arg origin = Arg.LambdaWhere(d => d == value); + Arg copy = origin.Tools().Copy(); + + copy.Assert().Is(origin); + copy.Matches(value).Assert().Is(true); + copy.Matches(value.Tools().Variant()).Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/BehaviorTests.cs b/tests/Toolbox.Tests/FakerTool/BehaviorTests.cs new file mode 100644 index 00000000..6c6ffe31 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/BehaviorTests.cs @@ -0,0 +1,142 @@ +using System.Collections.Frozen; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class BehaviorTests() : AutoTester(typeof(Behavior)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + MethodsToIgnore = FrozenSet.ToFrozenSet(["Throw"]), + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(ArgumentNullException), + typeof(NotImplementedException), + typeof(TargetParameterCountException), + ], + }; + + [Fact] + internal static void Call_BehaviorWorks() + { + foreach ( + MethodInfo info in typeof(Behavior) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .Where(m => m.Name == nameof(Behavior.Call)) + ) + { + Type type = info.GetParameters()[0].ParameterType; + + Type[] generics = + GenericConverter + .AsGenericBase(type) + ?.GetGenericArguments() + .Select(_ => typeof(string)) + .ToArray() + ?? Type.EmptyTypes; + + MethodInfo caller = (generics.Length != 0) ? info.MakeGenericMethod(generics) : info; + + Type setupType = caller.GetParameters()[0].ParameterType; + + Type[] args = type.Name.StartsWith("Func", StringComparison.Ordinal) + ? [.. generics.Skip(1)] + : generics; + + Behavior noTimes = (Behavior) + caller.Invoke(null, [Tools.Randomizer.Create(setupType), null]); + + noTimes.HasExpectedCalls().Assert().Is(false); + noTimes.Invoke([.. args.Select(a => Tools.Randomizer.Create(a))]); + noTimes.HasExpectedCalls().Assert().Is(true); + + Behavior withTimes = (Behavior) + caller.Invoke(null, [Tools.Randomizer.Create(setupType), Times.Never]); + + withTimes.HasExpectedCalls().Assert().Is(true); + withTimes.Invoke([.. args.Select(a => Tools.Randomizer.Create(a))]); + withTimes.HasExpectedCalls().Assert().Is(false); + } + } + + [Fact] + internal static void None_BehaviorWorks() + { + Behavior.None().Invoke([]).Assert().Is(default); + } + + [Fact] + internal static void Throw_DefaultBehaviorWorks() + { + Behavior.Throw().Assert(x => x.Invoke([])).Throws(); + } + + [Fact] + internal static void Null_BehaviorWorks() + { + Behavior.Null().Invoke([]).Assert().IsNull(); + } + + [Fact] + internal static void Default_BehaviorWorks() + { + Behavior.Default().Invoke([]).Assert().Is(default(int)); + } + + [Fact] + internal static void Throw_BehaviorWorks() + { + Behavior + .Throw() + .Assert(x => x.Invoke([])) + .Throws(); + } + + [Theory, RandomData] + internal static void Returns_BehaviorWorks(int value) + { + Behavior.Returns(value).Invoke([]).Assert().Is(value); + } + + [Fact] + internal static void Series_BehaviorWorks() + { + Behavior behavior = Behavior.Series(true, false, true); + behavior.Invoke([]).Assert().Is(true); + behavior.Invoke([]).Assert().Is(false); + behavior.Invoke([]).Assert().Is(true); + behavior.Invoke([]).Assert().Is(false); + behavior.Invoke([]).Assert().Is(false); + } + + [Theory, RandomData] + internal static void Series_NullCountsAsNone(string value) + { + Behavior behavior = Behavior.Series(value, null); + behavior.Invoke([]).Assert().Is(value); + behavior.Invoke([]).Assert().IsNull(); + behavior.Invoke([]).Assert().IsNull(); + } + + [Theory, RandomData] + internal static void ToExpectedCalls_MatchesTimes(Times times) + { + Behavior.None().ToExpectedCalls().Assert().Is(Times.AtLeast(1).ToString()); + Behavior.None(times).ToExpectedCalls().Assert().Is(times.ToString()); + } + + [Fact] + internal static void Invoke_ThrowsWithWrongArgs() + { + Behavior + .Call((int _) => { }) + .Assert(x => x.Invoke([])) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Behavior{T}Tests.cs b/tests/Toolbox.Tests/FakerTool/Behavior{T}Tests.cs new file mode 100644 index 00000000..8868d07e --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Behavior{T}Tests.cs @@ -0,0 +1,36 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class Behavior_T_Tests() : AutoTester(typeof(Behavior<>)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + MethodsToIgnore = ["Throw"], + IgnorableExceptions = + [ + typeof(MemberAccessException), + typeof(InvalidOperationException), + typeof(NotImplementedException), + typeof(BehaviorDefaultThrowException), + ], + }; + + [Fact] + internal static void Throw_DefaultBehaviorWorks() + { + Behavior.Throw().Assert(x => x.Invoke([])).Throws(); + } + + [Fact] + internal static void Throw_BehaviorWorks() + { + Behavior + .Throw() + .Assert(x => x.Invoke([])) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Engine/FakeHintResultTests.cs b/tests/Toolbox.Tests/FakerTool/Engine/FakeHintResultTests.cs new file mode 100644 index 00000000..dc317524 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Engine/FakeHintResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.FakerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Engine; + +public sealed class FakeHintResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + FakeHintResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Engine/FakePriorityTests.cs b/tests/Toolbox.Tests/FakerTool/Engine/FakePriorityTests.cs new file mode 100644 index 00000000..048642b3 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Engine/FakePriorityTests.cs @@ -0,0 +1,52 @@ +using Werecodent.CreateAndFake.FakerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Engine; + +public sealed class FakePriorityTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(FormatException)], + }; + + [Fact] + internal static void Disabled_SetToMin() + { + ((int)FakePriority.Disabled).Assert().Is(int.MinValue); + } + + [Fact] + internal static void None_DefaultAtZero() + { + ((int)FakePriority.None).Assert().Is(0); + } + + [Fact] + internal static void Highest_AtCap() + { + ((int)FakePriority.Highest).Assert().Is(Enum.GetValues(typeof(FakePriority)).Length - 2); + } + + [Fact] + internal static void Values_AllPositive() + { + Enum.GetValues(typeof(FakePriority)) + .Cast() + .Except([(int)FakePriority.Disabled]) + .Where(v => v < 0) + .Assert() + .IsEmpty(); + } + + [Fact] + internal static void Values_Unique() + { + Enum.GetValues(typeof(FakePriority)) + .Cast() + .ToHashSet() + .Assert() + .HasCount(Enum.GetValues(typeof(FakePriority)).Length); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Engine/FakerChainerTests.cs b/tests/Toolbox.Tests/FakerTool/Engine/FakerChainerTests.cs new file mode 100644 index 00000000..333e123d --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Engine/FakerChainerTests.cs @@ -0,0 +1,22 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Engine; + +public sealed class FakerChainerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(InvalidOperationException), + typeof(ArgumentOutOfRangeException), + typeof(TargetInvocationException), + typeof(ToolException), + ], + }; +} diff --git a/tests/Toolbox.Tests/FakerTool/Engine/FakerEngineTests.cs b/tests/Toolbox.Tests/FakerTool/Engine/FakerEngineTests.cs new file mode 100644 index 00000000..5eb8378d --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Engine/FakerEngineTests.cs @@ -0,0 +1,116 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Engine; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Engine; + +public sealed class FakerEngineTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + MethodsToIgnore = + [ + nameof(FakerEngine.InjectStubs), + nameof(FakerEngine.InjectMocks), + ], + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(InvalidOperationException), + typeof(ToolException), + ], + }; + + [Fact] + internal static void Inject_HandlesValues() + { + Injected sample = Tools.Faker.InjectMocks(); + sample.Dummy.Value1.Assert().Is(0); + sample.Dummy.Value2.Assert().IsNull(); + } + + [Fact] + internal static void Inject_ConstructorRequired() + { + Tools + .Faker.Assert(x => x.InjectStubs()) + .Throws(); + } + + [Theory, RandomData] + internal static void Inject_UsesValues(int num, string text) + { + Injected sample = Tools.Faker.InjectMocks([ + null, + Tools.Faker.Stub(), + num, + text, + ]); + + sample.Dummy.Sample1.Text.Assert().IsNull(); + sample.Dummy.Sample2.Assert(x => x.Calc()).Throws(); + sample.Dummy.Value1.Assert().Is(num); + sample.Dummy.Value2.Assert().Is(text); + } + + [Theory, RandomData] + internal void Mock_NoHintsUnsupported(Type type) + { + TestInstance + .Assert(x => x.Mock(type, [], CreateHintChainer(null))) + .Throws(); + } + + [Theory, RandomData] + internal void Mock_NullFakeResultSafe([Stub] IFakeHint hint, Type type) + { + TestInstance + .Assert(x => x.Mock(type, [], CreateHintChainer(hint))) + .Throws(); + } + + [Theory, RandomData] + internal void Mock_NullSetupResultSafe([Stub] IFakeHint hint, Type type, IFaked data) + { + hint.TryToFake(type, [], Arg.Any()).SetupReturn(new FakeHintResult(data)); + + TestInstance.Mock(type, [], CreateHintChainer(hint)).Dummy.Assert().Is(data); + } + + [Theory, RandomData] + internal void Stub_WrapsFakeError([Stub] IFakeHint hint, Type data) + { + hint.TryToFake(data, [], Arg.Any()) + .SetupReturn(Behavior.Throw()); + + TestInstance.Assert(x => x.Stub(data, [], CreateHintChainer(hint))).Throws(); + } + + [Theory, RandomData] + internal void Stub_WrapsSetupError([Stub] IFakeHint hint, Type data, IFaked result) + { + hint.TryToFake(data, [], Arg.Any()).SetupReturn(new FakeHintResult(result)); + hint.TryToSetup(result, Arg.Any()) + .SetupReturn(Behavior.Throw()); + + TestInstance.Assert(x => x.Stub(data, [], CreateHintChainer(hint))).Throws(); + } + + private static FakerChainer CreateHintChainer(IFakeHint hint) + { + return new FakerChainer( + Tools.Faker.Options with + { + IncludeFoundHints = false, + IncludeFrameworkHints = false, + Hints = hint != null ? [hint] : [], + }, + new FakerEngine() + ); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Engine/SetupHintResultTests.cs b/tests/Toolbox.Tests/FakerTool/Engine/SetupHintResultTests.cs new file mode 100644 index 00000000..ec6c1921 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Engine/SetupHintResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.FakerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Engine; + +public sealed class SetupHintResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + SetupHintResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/FakeExtensionsTests.cs b/tests/Toolbox.Tests/FakerTool/FakeExtensionsTests.cs new file mode 100644 index 00000000..ae77d0b0 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/FakeExtensionsTests.cs @@ -0,0 +1,9 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class FakeExtensionsTests() : AutoTester(typeof(FakeExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(InvalidCastException)] }; +} diff --git a/tests/Toolbox.Tests/FakerTool/FakeTests.cs b/tests/Toolbox.Tests/FakerTool/FakeTests.cs new file mode 100644 index 00000000..49794d8e --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/FakeTests.cs @@ -0,0 +1,34 @@ +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class FakeTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { DisableParameterMutationTests = true }; + + [Fact] + internal static void Verify_NoTotalValid() + { + Tools.Faker.Mock().Verify(); + } + + [Fact] + internal static void Setup_WorksProtectedMethods() + { + MethodInfo method = typeof(ProtectedSample).GetMethod( + "ChildMethod", + BindingFlags.Instance | BindingFlags.NonPublic + ); + object[] args = []; + + Fake fake = Tools.Faker.Mock(); + fake.Setup(method.Name, args, Behavior.None()); + fake.Verify(Times.Never, method.Name, args); + + method.Invoke(fake.Dummy, []); + fake.Verify(Times.Once, method.Name, args); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/FakerOptionsTests.cs b/tests/Toolbox.Tests/FakerTool/FakerOptionsTests.cs new file mode 100644 index 00000000..7bc5b448 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/FakerOptionsTests.cs @@ -0,0 +1,18 @@ +global using FakerMod = System.Func< + Werecodent.CreateAndFake.FakerTool.FakerOptions, + Werecodent.CreateAndFake.FakerTool.FakerOptions +>; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class FakerOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void FakerOptions_ModFormRandomizable() + { + typeof(FakerMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/FakerTests.cs b/tests/Toolbox.Tests/FakerTool/FakerTests.cs new file mode 100644 index 00000000..74f7003e --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/FakerTests.cs @@ -0,0 +1,111 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class FakerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(InvalidOperationException), + typeof(ArgumentOutOfRangeException), + typeof(TargetInvocationException), + typeof(ToolException), + ], + }; + + [Fact] + internal static void New_NullValuerValid() + { + new Faker(Tools.Faker.Options with { Valuer = null }).Assert().Pass(); + } + + [Fact] + internal static void Mock_SampleWorks() + { + Fake sample = Tools.Faker.Mock(); + sample.ThrowByDefault.Assert().Is(true); + sample.Dummy.Assert(x => x.HasNested(sample.Dummy.NestedValue)).Throws(); + } + + [Fact] + internal static void Mock_OverridesWork() + { + Tools.Faker.Mock().Assert().IsNotNull(); + Tools.Faker.Mock([]).Assert().IsNotNull(); + Tools.Faker.Mock([], null).Assert().IsNotNull(); + Tools.Faker.Mock(typeof(DataHolderSample)).Assert().IsNotNull(); + Tools.Faker.Mock(typeof(DataHolderSample), []).Assert().IsNotNull(); + Tools.Faker.Mock(typeof(DataHolderSample), [], null).Assert().IsNotNull(); + } + + [Fact] + internal static void Stub_SampleWorks() + { + Fake sample = Tools.Faker.Stub(); + sample.ThrowByDefault.Assert().Is(false); + sample.Dummy.HasNested(null).Assert().Is(false); + } + + [Fact] + internal static void Stub_OverridesWork() + { + Tools.Faker.Stub().Assert().IsNotNull(); + Tools.Faker.Stub([]).Assert().IsNotNull(); + Tools.Faker.Stub([], null).Assert().IsNotNull(); + Tools.Faker.Stub(typeof(DataHolderSample)).Assert().IsNotNull(); + Tools.Faker.Stub(typeof(DataHolderSample), []).Assert().IsNotNull(); + Tools.Faker.Stub(typeof(DataHolderSample), [], null).Assert().IsNotNull(); + } + + [Fact] + internal static void Supports_InvalidTypesFalse() + { + Tools.Faker.Supports().Assert().Is(false); + Tools.Faker.Supports().Assert().Is(false); + Tools.Faker.Supports().Assert().Is(false); + Tools.Faker.Supports(typeof(void*)).Assert().Is(false); + Tools.Faker.Supports(typeof(ConstraintSample<,>)).Assert().Is(false); + } + + [Fact] + internal static void InjectMocks_AreMocks() + { + Injected sample = Tools.Faker.InjectMocks(); + + sample.Dummy.Sample1.Assert(x => x.Calc()).Throws(); + sample.Dummy.Sample2.Assert(x => x.Text).Throws(); + } + + [Fact] + internal static void InjectMocks_OverridesWork() + { + Tools.Faker.InjectMocks().Assert().IsNotNull(); + Tools.Faker.InjectMocks([]).Assert().IsNotNull(); + } + + [Fact] + internal static void InjectStubs_AreStubs() + { + Injected sample = Tools.Faker.InjectStubs(); + + sample.Dummy.Sample1.Calc().Assert().Is(0); + sample.Dummy.Sample2.Text.Assert().IsNull(); + } + + [Fact] + internal static void InjectStubs_OverridesWork() + { + Tools.Faker.InjectStubs().Assert().IsNotNull(); + Tools.Faker.InjectStubs([]).Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Fake{T}Tests.cs b/tests/Toolbox.Tests/FakerTool/Fake{T}Tests.cs new file mode 100644 index 00000000..de903c37 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Fake{T}Tests.cs @@ -0,0 +1,255 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; +using Werecodent.CreateAndFake.Tests.TestSamples; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +#pragma warning disable RCS1021 // Expression-bodied lambda creates incorrect type. + +public static class Fake_T_Tests +{ + [Fact] + internal static void Fake_T_GuardsNulls() + { + ((IFaked)null).Assert(x => new Fake(x)).Throws(); + ((Fake)null).Assert(x => new Fake(x)).Throws(); + } + + [Fact] + internal static void Setup_GuardsNulls() + { + Tools + .Faker.Stub() + .Assert(x => x.Setup(null, Behavior.None())) + .Throws(); + } + + [Fact] + internal static void Fake_InterfacesWork() + { + FakeTester(); + } + + [Fact] + internal static void Fake_ClassesWork() + { + FakeTester(); + FakeTester(); + } + + [Theory, RandomData] + internal static void Fake_ScopeBehavior(string name) + { + Fake fake = Tools.Faker.Mock(); + fake.Dummy.Assert(x => x.PublicProp).Throws(); + fake.Dummy.Assert(x => x.PublicProp = name).Throws(); + fake.Dummy.Assert(x => x.PublicMethod()).Throws(); + + fake.Dummy.Assert(x => x.CallProtectProp()).Throws(); + fake.Dummy.Assert(x => x.SetProtectProp(name)).Throws(); + fake.Dummy.Assert(x => x.CallProtectGet()).Throws(); + fake.Dummy.Assert(x => x.SetProtectSet(name)).Throws(); + fake.Dummy.Assert(x => x.CallProtectMethod()).Throws(); + + fake.Dummy.Assert(x => x.ProIntProp).Throws(); + fake.Dummy.Assert(x => x.ProIntProp = name).Throws(); + fake.Dummy.Assert(x => x.ProIntGet).Throws(); + fake.Dummy.Assert(x => x.ProIntSet = name).Throws(); + fake.Dummy.Assert(x => x.ProIntMethod()).Throws(); + + fake.Dummy.InternalProp = name; + fake.Dummy.InternalProp.Assert().Is(name); + fake.Dummy.InternalMethod().Assert().IsNotNull(); + + fake.Dummy.Assert(x => x.InternalGet = name).Throws(); + fake.Dummy.InternalGet.Assert().IsNull(); + fake.Dummy.InternalSet = name; + fake.Dummy.Assert(x => x.InternalSet).Throws(); + } + + [Theory, RandomData] + internal static void Fake_HandlesOut(string data) + { + Fake fake = Tools.Faker.Mock(); + fake.Setup( + d => d.ReturnVoid(out Arg.AnyRef().Var), + Behavior.Call( + (OutRef d) => + { + d.Var = data; + }, + Times.Once + ) + ); + + fake.Dummy.ReturnVoid(out string value); + + value.Assert().Is(data); + fake.Verify(Times.Once); + } + + [Theory, RandomData] + internal static void Fake_HandlesOutValue(int plain, int data) + { + Fake fake = Tools.Faker.Mock(); + fake.Setup( + d => d.ReturnValue(out Arg.AnyRef().Var), + Behavior.Call( + (OutRef d) => + { + d.Var = data; + return plain; + }, + Times.Once + ) + ); + + fake.Dummy.ReturnValue(out int value).Assert().Is(plain); + + value.Assert().Is(data); + fake.Verify(Times.Once); + } + + [Theory, RandomData] + internal static void Fake_HandlesRef(string data, string start) + { + Fake fake = Tools.Faker.Mock(); + fake.Setup( + d => d.ReturnVoid(ref Arg.WhereRef(v => v == start).Var), + Behavior.Call( + (OutRef d) => + { + d.Var = data; + }, + Times.Once + ) + ); + + string value = start; + fake.Dummy.ReturnVoid(ref value); + + value.Assert().Is(data); + fake.Verify(Times.Once); + } + + [Theory, RandomData] + internal static void Fake_GenericsWork(string text, DataSample sample) + { + Fake> fake = Tools.Faker.Mock>(); + + fake.Setup(m => m.Run(text, sample), Behavior.Returns(true, Times.Once)); + fake.Setup(m => m.Run(text, sample), Behavior.Returns(5, Times.Once)); + + fake.Dummy.Run(text, sample).Assert().Is(true); + fake.Dummy.Run(text, sample).Assert().Is(5); + + fake.Verify(Times.Exactly(2)); + fake.Dummy.Assert(x => x.Run(text, sample)).Throws(); + } + + [Fact] + internal static void Setup_InvalidExpressionThrows() + { + Tools + .Faker.Mock() + .Assert(x => x.Setup(_ => new object(), Behavior.Returns(new object()))) + .Throws(); + } + + [Theory, RandomData] + internal static void ConvertArg_ConvertExpression([Stub] IValuer valuer, string[] data) + { + valuer.Tools().ToFake().Setup(m => m.Equals(true, true), Behavior.Returns(true)); + valuer + .Tools() + .ToFake() + .Setup( + m => m.Compare(true, Arg.Any(), null), + Behavior.Call( + (object o1, object o2) => + { + return (!o1.Equals(o2)) + ? Tools.Randomizer.Create>() + : []; + } + ) + ); + + Asserter tester = new(Tools.Asserter.Options with { Valuer = valuer }); + tester.IsNotEmpty(data); + tester.Assert(x => x.IsNotEmpty(null)).Throws(); + tester.Assert(x => x.IsNotEmpty(Array.Empty())).Throws(); + } + + private static void FakeTester() + where T : IFakeSample + { + Fake fake = Tools.Faker.Mock(typeof(IClashingFakeSample)); + + Behavior hintBehavior = Behavior.Returns("Hint"); + fake.Setup(m => m.Hint, hintBehavior); + fake.Verify(Times.Never, m => m.Hint); + fake.Dummy.Hint.Assert().Is("Hint"); + fake.Verify(Times.Once, m => m.Hint); + fake.Dummy.Hint.Assert().Is("Hint"); + fake.Verify(Times.Exactly(2), m => m.Hint); + + Fake fake2 = fake.ToFake(); + fake2.SetupSet(m => m.Text, Arg.LambdaAny(), Behavior.None()); + fake2.VerifySet(Times.Never, m => m.Text, Arg.LambdaAny()); + fake2.Dummy.Text = "What"; + fake2.VerifySet(Times.Once, m => m.Text, Arg.LambdaAny()); + + fake2.SetupSet(m => m.Text, "Hinter", Behavior.Call((string _) => { })); + fake2.VerifySet(Times.Never, m => m.Text, "Hinter"); + fake2.Dummy.Text = "Hinter"; + fake2.VerifySet(Times.Once, m => m.Text, "Hinter"); + fake2.VerifySet(Times.Exactly(2), m => m.Text, Arg.LambdaAny()); + + fake.Setup(m => m.Read(), Behavior.Call(() => "Test")); + fake.Verify(Times.Never, m => m.Read()); + fake.Dummy.Read().Assert().Is("Test"); + fake.Verify(Times.Once, m => m.Read()); + + fake.Setup(m => m.Calc(), Behavior.Returns(5)); + fake.Verify(Times.Never, m => m.Calc()); + fake.Dummy.Calc().Assert().Is(5); + fake.Verify(Times.Once, m => m.Calc()); + + fake.Setup(m => m.Read("Hey"), Behavior.Returns("Test2")); + fake.Verify(Times.Never, m => m.Read("Hey")); + fake.Dummy.Read("Hey").Assert().Is("Test2"); + fake.Verify(Times.Once, m => m.Read("Hey")); + + fake.Setup(m => m.Calc(3), Behavior.Returns(4)); + fake.Dummy.Calc(3).Assert().Is(4); + + fake.Dummy.Read().Assert().Is("Test"); + fake.Dummy.Calc().Assert().Is(5); + fake.Dummy.Read("Hey").Assert().Is("Test2"); + + fake.Setup(m => m.Calc(Arg.Where(i => i > 8)), Behavior.Returns(1)); + fake.Verify(Times.Never, m => m.Calc(Arg.Where(i => i > 8))); + fake.Dummy.Calc(9); + fake.Verify(Times.Once, m => m.Calc(Arg.Where(i => i > 8))); + + fake.Setup(m => m.Calc(Arg.Any()), Behavior.Returns(7)); + fake.Dummy.Calc(0).Assert().Is(7); + + fake.Setup(m => m.Read(Arg.Any()), Behavior.Returns("Wow!")); + fake.Dummy.Read("Okay?").Assert().Is("Wow!"); + + fake.Setup(m => m.Combo(2, "Finally"), Behavior.Call((int _, string __) => { })); + fake.Verify(Times.Never, m => m.Combo(2, "Finally")); + fake.Dummy.Combo(2, "Finally"); + fake.Verify(Times.Once, m => m.Combo(2, "Finally")); + + hintBehavior.Calls.Assert().Is(2); + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/FakerTool/Hints/AsyncDisposableFakeHintTests.cs b/tests/Toolbox.Tests/FakerTool/Hints/AsyncDisposableFakeHintTests.cs new file mode 100644 index 00000000..d68d8838 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Hints/AsyncDisposableFakeHintTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.FakerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Hints; + +public sealed class AsyncDisposableFakeHintTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(NotSupportedException)], + }; +} diff --git a/tests/Toolbox.Tests/FakerTool/Hints/DisposableFakeHintTests.cs b/tests/Toolbox.Tests/FakerTool/Hints/DisposableFakeHintTests.cs new file mode 100644 index 00000000..d9b1babb --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Hints/DisposableFakeHintTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.FakerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Hints; + +public sealed class DisposableFakeHintTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(NotSupportedException)], + }; +} diff --git a/tests/Toolbox.Tests/FakerTool/Hints/ObjectFakeHintTests.cs b/tests/Toolbox.Tests/FakerTool/Hints/ObjectFakeHintTests.cs new file mode 100644 index 00000000..c63134c7 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Hints/ObjectFakeHintTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.FakerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Hints; + +public sealed class ObjectFakeHintTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(NotSupportedException)], + }; +} diff --git a/tests/Toolbox.Tests/FakerTool/InjectedTests.cs b/tests/Toolbox.Tests/FakerTool/InjectedTests.cs new file mode 100644 index 00000000..58ca927d --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/InjectedTests.cs @@ -0,0 +1,26 @@ +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class InjectedTests : AutoTester> +{ + protected override Injected TestInstance => + Tools.Randomizer.Create>(); + + protected override TesterMod OptionConfiguration => + opt => + opt with + { + InjectionValues = [TestInstance.Fakes], + IgnorableExceptions = [typeof(InvalidOperationException)], + }; + + [Theory, RandomData] + internal static void Fake_CanFindByDummy(Injected sample) + { + sample.Fake(sample.Dummy.Sample1).Assert().Is(sample.Fake()); + sample.Fake(sample.Dummy.Sample2).Assert().Is(sample.Fake()); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/OutRefTests.cs b/tests/Toolbox.Tests/FakerTool/OutRefTests.cs new file mode 100644 index 00000000..710a9a07 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/OutRefTests.cs @@ -0,0 +1,9 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class OutRefTests() : AutoTester(typeof(OutRef<>)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(MemberAccessException)] }; +} diff --git a/tests/Toolbox.Tests/FakerTool/Proxy/CallDataTests.cs b/tests/Toolbox.Tests/FakerTool/Proxy/CallDataTests.cs new file mode 100644 index 00000000..cea419c3 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Proxy/CallDataTests.cs @@ -0,0 +1,71 @@ +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Proxy; + +public sealed class CallDataTests() : AutoTester(typeof(CallData)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { DisableParameterMutationTests = true }; + + [Theory, RandomData] + internal static void MatchesCall_MethodNameMismatch( + DataHolderSample[] data, + Type[] generics, + string name + ) + { + new CallData(name, generics, data, Tools.Faker.Options) + .MatchesCall(new CallData(name.Tools().Variant(), generics, data, null)) + .Assert() + .Is(false); + } + + [Theory, RandomData] + internal static void MatchesCall_GenericsMismatch(DataHolderSample[] data, string name) + { + Type[] generics1 = [.. Tools.Randomizer.Create().Except([typeof(AnyGeneric)])]; + Type[] generics2 = Tools.Mutator.Variant(generics1); + + new CallData(name, generics1, data, Tools.Faker.Options) + .MatchesCall(new CallData(name, generics2, data, null)) + .Assert() + .Is(false); + } + + [Theory, RandomData] + internal static void MatchesCall_AnyGenericMatchesAll( + DataHolderSample[] data, + string name, + Type[] generics1 + ) + { + Type[] generics2 = [.. generics1.Select(_ => typeof(AnyGeneric))]; + + new CallData(name, generics2, data, Tools.Faker.Options) + .MatchesCall(new CallData(name, generics1, data, null)) + .Assert() + .Is(true); + } + + [Theory, RandomData] + internal static void MatchesCall_DataMatchBehavior( + string name, + Type[] generics, + DataHolderSample[] data1 + ) + { + DataHolderSample[] data2 = [.. data1.Select(d => d.Tools().Copy())]; + + new CallData(name, generics, data1, Tools.Faker.Options) + .MatchesCall(new CallData(name, generics, data2, null)) + .Assert() + .Is(true); + + new CallData(name, generics, data1, null) + .MatchesCall(new CallData(name, generics, data2, null)) + .Assert() + .Is(false); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Proxy/EmitterTests.cs b/tests/Toolbox.Tests/FakerTool/Proxy/EmitterTests.cs new file mode 100644 index 00000000..c4f7b78d --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Proxy/EmitterTests.cs @@ -0,0 +1,9 @@ +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Proxy; + +public sealed class EmitterTests() : AutoTester(typeof(Emitter)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { DisableParameterMutationTests = true }; +} diff --git a/tests/Toolbox.Tests/FakerTool/Proxy/FakeCallExceptionTests.cs b/tests/Toolbox.Tests/FakerTool/Proxy/FakeCallExceptionTests.cs new file mode 100644 index 00000000..1bd69907 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Proxy/FakeCallExceptionTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Proxy; + +public sealed class FakeCallExceptionTests : ExceptionTestBase +{ + [Fact] + internal static void FakeCallException_MultiNullsOkay() + { + new FakeCallException(null, null).Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Proxy/FakeMetaProviderTests.cs b/tests/Toolbox.Tests/FakerTool/Proxy/FakeMetaProviderTests.cs new file mode 100644 index 00000000..46ee52fe --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Proxy/FakeMetaProviderTests.cs @@ -0,0 +1,133 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Proxy; + +public sealed class FakeMetaProviderTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(FakeCallException), + typeof(ToolException), + typeof(FakeVerifyException), + typeof(InvalidOperationException), + ], + }; + + [Theory, RandomData] + internal static void Verify_PresetOutOfRangeThrows( + MethodInfo method, + [Unique] MethodInfo otherMethod + ) + { + FakeMetaProvider provider = new(0, Tools.Faker.Options) { ThrowByDefault = false }; + + CallData data = new(method.Name, Type.EmptyTypes, [], Tools.Faker.Options); + + provider.SetCallBehavior(data, Behavior.None(Times.Once)); + provider.Assert(x => x.Verify()).Throws(); + + provider.CallVoid(null, otherMethod, Type.EmptyTypes, []); + provider.Assert(x => x.Verify()).Throws(); + + provider.CallVoid(null, method, Type.EmptyTypes, []); + provider.Verify(); + + provider.CallVoid(null, method, Type.EmptyTypes, []); + provider.Assert(x => x.Verify()).Throws(); + } + + [Theory, RandomData] + internal static void Verify_CustomOutOfRangeThrows( + MethodInfo method, + [Unique] MethodInfo otherMethod + ) + { + FakeMetaProvider provider = new(0, Tools.Faker.Options) { ThrowByDefault = false }; + + CallData data = new(method.Name, Type.EmptyTypes, [], Tools.Faker.Options); + + provider.Verify(0, data); + provider.Assert(x => x.Verify(1, data)).Throws(); + + provider.CallVoid(null, otherMethod, Type.EmptyTypes, []); + provider.Verify(0, data); + provider.Assert(x => x.Verify(1, data)).Throws(); + + provider.CallVoid(null, method, Type.EmptyTypes, []); + provider.Assert(x => x.Verify(0, data)).Throws(); + provider.Verify(1, data); + + provider.CallVoid(null, method, Type.EmptyTypes, []); + provider.Assert(x => x.Verify(1, data)).Throws(); + provider.Verify(2, data); + } + + [Theory, RandomData] + internal static void VerifyTotalCalls_OutOfRangeThrows( + MethodInfo method, + [Unique] MethodInfo otherMethod + ) + { + FakeMetaProvider provider = new(0, Tools.Faker.Options) { ThrowByDefault = false }; + + provider.VerifyTotalCalls(0); + provider.Assert(x => x.VerifyTotalCalls(1)).Throws(); + + provider.CallVoid(null, method, Type.EmptyTypes, []); + provider.Assert(x => x.VerifyTotalCalls(0)).Throws(); + provider.VerifyTotalCalls(1); + + provider.CallVoid(null, otherMethod, Type.EmptyTypes, []); + provider.Assert(x => x.VerifyTotalCalls(1)).Throws(); + provider.VerifyTotalCalls(2); + } + + [Theory, RandomData] + internal static void CallVoid_ReturnValueThrows(MethodInfo method) + { + FakeMetaProvider provider = new(0, Tools.Faker.Options); + + CallData data = new(method.Name, Type.EmptyTypes, [], Tools.Faker.Options); + provider.SetCallBehavior(data, Behavior.Returns("")); + + provider + .Assert(x => x.CallVoid(null, method, Type.EmptyTypes, [])) + .Throws(); + } + + [Theory, RandomData] + internal static void SetLastCallBehavior_RequiresPreviousCall(Behavior behavior) + { + behavior + .Assert(x => + { + FakeMetaProvider.SetLastCallBehavior(x); + FakeMetaProvider.SetLastCallBehavior(x); + }) + .Throws(); + } + + [Theory, RandomData] + internal static void CallVoid_MissingBaseThrows([Stub] MethodInfo method, string name) + { + CallData call = new(name, [], [], null); + method.Name.SetupReturn(name); + method.IsGenericMethod.SetupReturn(false); + method.GetParameters().SetupReturn([]); + method.DeclaringType.SetupReturn(null); + + FakeMetaProvider provider = new(0, Tools.Faker.Options); + provider.SetCallBehavior(call, Behavior.Base()); + + provider + .Assert(p => p.CallVoid(new object(), method, [], [])) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/FakerTool/Proxy/FakeVerifyExceptionTests.cs b/tests/Toolbox.Tests/FakerTool/Proxy/FakeVerifyExceptionTests.cs new file mode 100644 index 00000000..1189dadb --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Proxy/FakeVerifyExceptionTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Proxy; + +public sealed class FakeVerifyExceptionTests : ExceptionTestBase; diff --git a/tests/Toolbox.Tests/FakerTool/Proxy/SubclasserTests.cs b/tests/Toolbox.Tests/FakerTool/Proxy/SubclasserTests.cs new file mode 100644 index 00000000..ace09d9d --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/Proxy/SubclasserTests.cs @@ -0,0 +1,154 @@ +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.FakerTool.Proxy; + +public sealed class SubclasserTests() : AutoTester(typeof(Subclasser)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ArgumentException)] }; + + [Fact] + internal static void Create_InterfacesWork() + { + Subclasser.Create(Tools.Faker.Options).Assert().IsNotNull(); + Subclasser + .Create(Tools.Faker.Options, typeof(IClashingFakeSample)) + .Assert() + .IsNotNull(); + } + + [Fact] + internal static void Create_ClassesWork() + { + Subclasser.Create(Tools.Faker.Options).Assert().IsNotNull(); + Subclasser.Create(Tools.Faker.Options).Assert().IsNotNull(); + } + + [Fact] + internal static void Create_BothWork() + { + Subclasser + .Create(Tools.Faker.Options, typeof(IFakeSample)) + .Assert() + .IsNotNull(); + Subclasser + .Create( + Tools.Faker.Options, + typeof(IFakeSample), + typeof(IClashingFakeSample) + ) + .Assert() + .IsNotNull(); + } + + [Fact] + internal static void Create_IFakedDefault() + { + Subclasser.Create(Tools.Faker.Options).Assert().Inherits(); + Subclasser.Create(null, Tools.Faker.Options, null).Assert().IsNotNull(); + } + + [Fact] + internal static void Create_IFakedFunctional() + { + Subclasser.Create(Tools.Faker.Options).FakeMeta.Assert().IsNotNull(); + } + + [Fact] + internal static void Create_OnlyMultipleInterfaces() + { + typeof(object) + .Assert(x => Subclasser.Create(Tools.Faker.Options, x)) + .Throws(); + } + + [Fact] + internal static void Create_SealedTypesThrow() + { + typeof(string) + .Assert(x => Subclasser.Create(x, Tools.Faker.Options)) + .Throws(); + } + + [Fact] + internal static void CreateInfo_NoDuplicatesCreated() + { + Subclasser + .CreateInfo(typeof(IFakeSample), typeof(IClashingFakeSample)) + .Assert() + .ReferenceEqual( + Subclasser.CreateInfo(typeof(IClashingFakeSample), typeof(IFakeSample)) + ); + } + + [Fact] + internal static void CreateInfo_IgnoreDupeInterfaces() + { + Subclasser + .CreateInfo(typeof(IFakeSample)) + .Assert() + .ReferenceEqual(Subclasser.CreateInfo(typeof(IFakeSample), typeof(IFakeSample))); + } + + [Fact] + internal static void Create_DefinedGenericsWork() + { + Subclasser + .Create>(Tools.Faker.Options) + .Assert() + .IsNotNull(); + Subclasser + .Create>(Tools.Faker.Options) + .Assert() + .IsNotNull(); + } + + [Fact] + internal static void Create_UndefinedGenericsThrow() + { + typeof(ConstraintSample<,>) + .Assert(x => Subclasser.Create(x, Tools.Faker.Options)) + .Throws(); + } + + [Fact] + internal static void Create_PointersThrow() + { + typeof(void*) + .Assert(x => Subclasser.Create(x, Tools.Faker.Options)) + .Throws(); + } + + [Fact] + internal static void Create_InternalTypesThrow() + { + typeof(InternalSample) + .Assert(x => Subclasser.Create(x, Tools.Faker.Options)) + .Throws(); + } + + [Fact] + internal static void Supports_FalseWithWithNonVisibleTypes() + { + const TypeAttributes invisibleAttributes = TypeAttributes.NotPublic; + + Type type = Tools.Faker.Stub().Dummy; + + type.Tools() + .ToFake() + .Setup("GetAttributeFlagsImpl", [], Behavior.Returns(invisibleAttributes)); + type.Tools().ToFake().Setup("HasElementTypeImpl", [], Behavior.Returns(false)); + type.Tools().ToFake().Setup("IsPointerImpl", [], Behavior.Returns(false)); + type.Assembly.SetupReturn(typeof(object).Assembly); + type.Name.SetupReturn("TestInvisibleType"); + + type.Assert(x => Subclasser.Create(x, Tools.Faker.Options)) + .Throws() + .With(e => e.Message) + .Contains("InternalsVisibleTo"); + } +} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/AbstractFakeSample.cs b/tests/Toolbox.Tests/FakerTool/TestSamples/AbstractFakeSample.cs similarity index 83% rename from tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/AbstractFakeSample.cs rename to tests/Toolbox.Tests/FakerTool/TestSamples/AbstractFakeSample.cs index 698f74ce..d1fef583 100644 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/AbstractFakeSample.cs +++ b/tests/Toolbox.Tests/FakerTool/TestSamples/AbstractFakeSample.cs @@ -1,22 +1,22 @@ -namespace CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -public abstract class AbstractFakeSample : IFakeSample -{ - public abstract int Num { get; } - - public abstract string Hint { get; } - - public abstract int Count { get; set; } - - public abstract string Text { get; set; } - - public abstract int Calc(); - - public abstract int Calc(int data); - - public abstract void Combo(int num, string text); - - public abstract string Read(); - - public abstract string Read(string data); -} +namespace Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +public abstract class AbstractFakeSample : IFakeSample +{ + public abstract int Num { get; } + + public abstract string Hint { get; } + + public abstract int Count { get; set; } + + public abstract string Text { get; set; } + + public abstract int Calc(); + + public abstract int Calc(int data); + + public abstract void Combo(int num, string text); + + public abstract string Read(); + + public abstract string Read(string data); +} diff --git a/tests/Toolbox.Tests/FakerTool/TestSamples/FakeHolderSample.cs b/tests/Toolbox.Tests/FakerTool/TestSamples/FakeHolderSample.cs new file mode 100644 index 00000000..25c56226 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/TestSamples/FakeHolderSample.cs @@ -0,0 +1,17 @@ +namespace Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +public sealed class FakeHolderSample( + IFakeSample sample1, + AbstractFakeSample sample2, + int value1, + string value2 +) +{ + public IFakeSample Sample1 { get; } = sample1; + + public AbstractFakeSample Sample2 { get; } = sample2; + + public int Value1 { get; } = value1; + + public string Value2 { get; } = value2; +} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/IClashingFakeSample.cs b/tests/Toolbox.Tests/FakerTool/TestSamples/IClashingFakeSample.cs similarity index 76% rename from tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/IClashingFakeSample.cs rename to tests/Toolbox.Tests/FakerTool/TestSamples/IClashingFakeSample.cs index 79668ab7..a00bf034 100644 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/IClashingFakeSample.cs +++ b/tests/Toolbox.Tests/FakerTool/TestSamples/IClashingFakeSample.cs @@ -1,22 +1,22 @@ -namespace CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -public interface IClashingFakeSample -{ - int Num { get; } - - string Hint { get; } - - int Count { get; set; } - - string Text { get; set; } - - int Calc(); - - int Calc(int data); - - string Read(); - - string Read(string data); - - void Combo(int num, string text); -} +namespace Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +public interface IClashingFakeSample +{ + int Num { get; } + + string Hint { get; } + + int Count { get; set; } + + string Text { get; set; } + + int Calc(); + + int Calc(int data); + + string Read(); + + string Read(string data); + + void Combo(int num, string text); +} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/IFakeSample.cs b/tests/Toolbox.Tests/FakerTool/TestSamples/IFakeSample.cs similarity index 76% rename from tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/IFakeSample.cs rename to tests/Toolbox.Tests/FakerTool/TestSamples/IFakeSample.cs index dfa3b3d5..10453729 100644 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/IFakeSample.cs +++ b/tests/Toolbox.Tests/FakerTool/TestSamples/IFakeSample.cs @@ -1,22 +1,22 @@ -namespace CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -public interface IFakeSample -{ - int Num { get; } - - string Hint { get; } - - int Count { get; set; } - - string Text { get; set; } - - int Calc(); - - int Calc(int data); - - string Read(); - - string Read(string data); - - void Combo(int num, string text); -} +namespace Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +public interface IFakeSample +{ + int Num { get; } + + string Hint { get; } + + int Count { get; set; } + + string Text { get; set; } + + int Calc(); + + int Calc(int data); + + string Read(); + + string Read(string data); + + void Combo(int num, string text); +} diff --git a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/VirtualFakeSample.cs b/tests/Toolbox.Tests/FakerTool/TestSamples/VirtualFakeSample.cs similarity index 76% rename from tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/VirtualFakeSample.cs rename to tests/Toolbox.Tests/FakerTool/TestSamples/VirtualFakeSample.cs index 37465ff4..33d59166 100644 --- a/tests/CreateAndFakeTests/Toolbox/FakerTool/TestSamples/VirtualFakeSample.cs +++ b/tests/Toolbox.Tests/FakerTool/TestSamples/VirtualFakeSample.cs @@ -1,50 +1,49 @@ -using System.Diagnostics.CodeAnalysis; - -namespace CreateAndFakeTests.Toolbox.FakerTool.TestSamples; - -[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", - Justification = "For testing.")] -[ExcludeFromCodeCoverage] -public class VirtualFakeSample : AbstractFakeSample -{ - public override int Num => throw new NotImplementedException(); - - public override string Hint => throw new NotImplementedException(); - - public override int Count - { - get => throw new NotImplementedException(); - set => throw new NotImplementedException(); - } - - public override string Text - { - get => throw new NotImplementedException(); - set => throw new NotImplementedException(); - } - - public override int Calc() - { - throw new NotImplementedException(); - } - - public override int Calc(int data) - { - throw new NotImplementedException(); - } - - public override void Combo(int num, string text) - { - throw new NotImplementedException(); - } - - public override string Read() - { - throw new NotImplementedException(); - } - - public override string Read(string data) - { - throw new NotImplementedException(); - } -} +namespace Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +#pragma warning disable CA1065, MA0025 // For testing. + +public class VirtualFakeSample : AbstractFakeSample +{ + public override int Num => throw new NotImplementedException(); + + public override string Hint => throw new NotImplementedException(); + + public override int Count + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } + + public override string Text + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } + + public override int Calc() + { + throw new NotImplementedException(); + } + + public override int Calc(int data) + { + throw new NotImplementedException(); + } + + public override void Combo(int num, string text) + { + throw new NotImplementedException(); + } + + public override string Read() + { + throw new NotImplementedException(); + } + + public override string Read(string data) + { + throw new NotImplementedException(); + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/FakerTool/TimesTests.cs b/tests/Toolbox.Tests/FakerTool/TimesTests.cs new file mode 100644 index 00000000..0e67dde0 --- /dev/null +++ b/tests/Toolbox.Tests/FakerTool/TimesTests.cs @@ -0,0 +1,106 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.FakerTool; + +public sealed class TimesTests : AutoTester +{ + [Fact] + internal static void Never_Works() + { + Times.Never.IsInRange(0).Assert().Is(true); + Times.Never.IsInRange(1).Assert().Is(false); + Times.Never.IsInRange(2).Assert().Is(false); + } + + [Fact] + internal static void Once_Works() + { + Times.Once.IsInRange(0).Assert().Is(false); + Times.Once.IsInRange(1).Assert().Is(true); + Times.Once.IsInRange(2).Assert().Is(false); + } + + [Theory, RandomData] + internal static void Exactly_Works(int value) + { + Times.Exactly(value).IsInRange(value - 1).Assert().Is(false); + Times.Exactly(value).IsInRange(value).Assert().Is(true); + Times.Exactly(value).IsInRange(value + 1).Assert().Is(false); + } + + [Fact] + internal static void Between_Works() + { + int min, + max; + do + { + min = Tools.Randomizer.Create(); + max = Tools.Randomizer.Create(); + } while (min >= max); + + Times.Between(min, max).IsInRange(min - 1).Assert().Is(false); + Times.Between(min, max).IsInRange(min).Assert().Is(true); + Times.Between(min, max).IsInRange(min + 1).Assert().Is(true); + + Times.Between(min, max).IsInRange(max - 1).Assert().Is(true); + Times.Between(min, max).IsInRange(max).Assert().Is(true); + Times.Between(min, max).IsInRange(max + 1).Assert().Is(false); + } + + [Theory, RandomData] + internal static void AtLeast_Works(int value) + { + Times.AtLeast(value).IsInRange(value - 1).Assert().Is(false); + Times.AtLeast(value).IsInRange(value).Assert().Is(true); + Times.AtLeast(value).IsInRange(value + 1).Assert().Is(true); + } + + [Fact] + internal static void AtMost_Works() + { + int value; + do + { + value = Tools.Randomizer.Create(); + } while (value <= 0); + + Times.AtMost(value).IsInRange(value - 1).Assert().Is(true); + Times.AtMost(value).IsInRange(value).Assert().Is(true); + Times.AtMost(value).IsInRange(value + 1).Assert().Is(false); + } + + [Fact] + internal static void ToString_Terse() + { + Times.Never.ToString().Assert().Is("0"); + Times.Once.ToString().Assert().Is("1"); + Times.Exactly(2).ToString().Assert().Is("2"); + Times.AtMost(1).ToString().Assert().Is("[0-1]"); + Times.AtLeast(1).ToString().Assert().Is("[1-*]"); + Times.Between(1, 2).ToString().Assert().Is("[1-2]"); + } + + [Fact] + internal static void Equals_MatchesValue() + { + int min, + max; + do + { + min = Tools.Randomizer.Create(); + max = Tools.Randomizer.Create(); + } while (min >= max); + + Times.Once.Equals(null).Assert().Is(false); + Times.Exactly(min).Equals(Times.Between(min, min)).Assert().Is(true); + Times.Exactly(max).Equals((object)Times.Between(max, max)).Assert().Is(true); + Times.Exactly(min).Equals(Times.Between(min, max)).Assert().Is(false); + Times.Exactly(max).Equals((object)Times.Between(min, max)).Assert().Is(false); + + Times.Between(min, min).GetHashCode().Assert().Is(Times.Exactly(min).GetHashCode()); + Times.Between(max, max).GetHashCode().Assert().Is(Times.Exactly(max).GetHashCode()); + Times.Between(min, max).GetHashCode().Assert().IsNot(Times.Exactly(min).GetHashCode()); + Times.Between(min, max).GetHashCode().Assert().IsNot(Times.Exactly(max).GetHashCode()); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertAsyncEnumerableTests.cs b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertAsyncEnumerableTests.cs new file mode 100644 index 00000000..4782b1a9 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertAsyncEnumerableTests.cs @@ -0,0 +1,443 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertAsyncCalls; + +public sealed class AssertAsyncEnumerableTests : AutoTester> +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = [typeof(AssertException), typeof(ToolException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertAsyncEnumerableTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal async Task AssertAsyncEnumerable_CallsAndChains( + Injected> instance + ) + { + string[] allowedResults = + [ + "AssertChainer opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != "AssertAsyncEnumerable") + .OrderBy(r => r.Method.Name) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal static Task AssertAsyncEnumerable_ObjectExtensionsWork( + IAsyncEnumerable sampleA, + IAsyncEnumerable sampleB + ) + { + sampleA.Assert().Is(sampleA); + return sampleA.Assert().IsNotAsync(sampleB, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal async Task IsEmptyAsync_Forwarded( + [Size(0)] IAsyncEnumerable valid, + [Size(1)] IAsyncEnumerable invalid + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await valid.Assert().IsEmptyAsync(canceler); + await valid.Assert().IsEmptyAsync(canceler, _mod); + await invalid + .Assert() + .IsEmptyAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await invalid + .Assert() + .IsEmptyAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .Assert() + .IsEmptyAsync(source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsNotEmptyAsync_Forwarded( + [Size(1)] IAsyncEnumerable valid, + [Size(0)] IAsyncEnumerable invalid + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await valid.Assert().IsNotEmptyAsync(canceler); + await valid.Assert().IsNotEmptyAsync(canceler, _mod); + await invalid + .Assert() + .IsNotEmptyAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await invalid + .Assert() + .IsNotEmptyAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + await valid + .Assert() + .IsNotEmptyAsync(new CancellationToken(true)) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().HasCountAsync(1, canceler); + await data.Assert().HasCountAsync(1, canceler, _mod); + await data.Assert() + .HasCountAsync(0, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .HasCountAsync(2, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .Assert() + .HasCountAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountLessThanAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().HasCountLessThanAsync(2, canceler); + await data.Assert().HasCountLessThanAsync(2, canceler, _mod); + await data.Assert() + .HasCountLessThanAsync(1, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .HasCountLessThanAsync(0, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .Assert() + .HasCountLessThanAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountLessOrExactlyAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().HasCountLessOrExactlyAsync(2, canceler); + await data.Assert().HasCountLessOrExactlyAsync(1, canceler, _mod); + await data.Assert() + .HasCountLessOrExactlyAsync(0, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .HasCountLessOrExactlyAsync(0, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .Assert() + .HasCountLessOrExactlyAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountMoreThanAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().HasCountMoreThanAsync(0, canceler); + await data.Assert().HasCountMoreThanAsync(0, canceler, _mod); + await data.Assert() + .HasCountMoreThanAsync(1, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .HasCountMoreThanAsync(2, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .Assert() + .HasCountMoreThanAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountMoreOrExactlyAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().HasCountMoreOrExactlyAsync(0, canceler); + await data.Assert().HasCountMoreOrExactlyAsync(1, canceler, _mod); + await data.Assert() + .HasCountMoreOrExactlyAsync(2, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .HasCountMoreOrExactlyAsync(2, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .Assert() + .HasCountMoreOrExactlyAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsAsync_Forwarded(int valid, int invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IAsyncEnumerable data = AsyncSeriesHelper.CreateFromAsync([valid], 1); + + await data.Assert().ContainsAsync(valid, canceler); + await data.Assert().ContainsAsync(valid, canceler, _mod); + await data.Assert() + .ContainsAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ContainsAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .Assert() + .ContainsAsync(valid, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsNotAsync_Forwarded(int valid, int invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IAsyncEnumerable data = AsyncSeriesHelper.CreateFromAsync([invalid], 1); + + await data.Assert().ContainsNotAsync(valid, canceler); + await data.Assert().ContainsNotAsync(valid, canceler, _mod); + await data.Assert() + .ContainsNotAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ContainsNotAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await AsyncSeriesHelper + .CreateCancelingIterationAsync(source) + .Assert() + .ContainsNotAsync(valid, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task FailAsync_Forwarded(IAsyncEnumerable data, [Fake] IAsserter asserter) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet silentFailSet = MakeSet(asserter); + + await data.Assert(silentFailSet).FailAsync(canceler); + await data.Assert(silentFailSet).FailAsync(canceler, _mod); + await data.Assert().FailAsync(canceler).Assert().ThrowsAsync(canceler); + await data.Assert() + .FailAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal async Task DebugAsync_Forwarded(IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet debugPassSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = false }) + ); + ToolSet debugFailSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = true }) + ); + + await data.Assert(debugPassSet).DebugAsync(canceler); + await data.Assert(debugPassSet).DebugAsync(canceler, _mod); + await data.Assert(debugFailSet) + .DebugAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert(debugFailSet) + .DebugAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsAsync_Forwarded(IAsyncEnumerable data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async IAsyncEnumerable thrower() + { + yield return 1; + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await thrower().Assert().ThrowsAsync(canceler); + await thrower().Assert().ThrowsAsync(canceler, _mod); + await data.Assert() + .ThrowsAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ThrowsAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsExceptionAsync_Forwarded(IAsyncEnumerable data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async IAsyncEnumerable thrower() + { + yield return 1; + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await thrower().Assert().ThrowsExceptionAsync(canceler); + await thrower().Assert().ThrowsExceptionAsync(canceler, _mod); + await data.Assert() + .ThrowsExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ThrowsExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + private static ToolSet MakeSet(IAsserter asserter) + { + return new( + Tools.Gen, + Tools.Valuer, + Tools.Faker, + Tools.Randomizer, + Tools.Extractor, + Tools.Mutator, + asserter, + Tools.Duplicator, + Tools.Runner, + Tools.Tester + ); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertAsyncObjectTests.cs b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertAsyncObjectTests.cs new file mode 100644 index 00000000..c4d9643d --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertAsyncObjectTests.cs @@ -0,0 +1,179 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertAsyncCalls; + +public sealed class AssertAsyncObjectTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = [typeof(AssertException), typeof(ToolException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertAsyncObjectTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal async Task AssertAsyncObject_CallsAndChains(Injected instance) + { + string[] allowedResults = + [ + "AssertChainer opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != nameof(AssertAsyncObject)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal async Task IsAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().IsAsync(clone, canceler); + await data.Assert().IsAsync(clone, canceler, _mod); + await data.Assert() + .IsAsync(variant, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .IsAsync(variant, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsNotAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().IsNotAsync(variant, canceler); + await data.Assert().IsNotAsync(variant, canceler, _mod); + await data.Assert() + .IsNotAsync(clone, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .IsNotAsync(clone, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ValuesEqualAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().ValuesEqualAsync(clone, canceler); + await data.Assert().ValuesEqualAsync(clone, canceler, _mod); + await data.Assert() + .ValuesEqualAsync(variant, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ValuesEqualAsync(variant, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ValuesNotEqualAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().ValuesNotEqualAsync(variant, canceler); + await data.Assert().ValuesNotEqualAsync(variant, canceler, _mod); + await data.Assert() + .ValuesNotEqualAsync(clone, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ValuesNotEqualAsync(clone, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task UniqueFromAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + [Unique] AsyncDataSample unique + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await data.Assert().UniqueFromAsync(unique, canceler); + await data.Assert().UniqueFromAsync(unique, canceler, _mod); + await data.Assert() + .UniqueFromAsync(clone, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .UniqueFromAsync(clone, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertGenericTaskTests.cs b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertGenericTaskTests.cs new file mode 100644 index 00000000..f7660fc0 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertGenericTaskTests.cs @@ -0,0 +1,124 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Extensions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertAsyncCalls; + +public sealed class AssertGenericTaskTests : AutoTester> +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(ArgumentException), + typeof(ValueTaskRepeatedAccessException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertGenericTaskTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal async Task AssertGenericTask_CallsAndChains( + Injected> instance + ) + { + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken + ); + results + .RawResults.Where(r => r.Result != null) + .Where(r => r.Result is not AssertChainer>) + .Where(r => r.Result is not AlsoChainer) + .Where(r => r.Result is not ResultChainer) + .Where(r => r.Result.GetType().Inherits(typeof(ExceptionChainer<>))) + .Where(r => r.Result as string != "AssertGenericTask") + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal async Task HasResultAsync_WithMatchForwarded(string value, string variant) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task getValue() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + return value; + } + + await getValue().Assert().HasResultAsync(value, canceler); + await getValue().Assert().HasResultAsync(value, canceler, _mod); + await getValue() + .Assert() + .HasResultAsync(variant, canceler) + .Assert() + .ThrowsAsync(canceler); + await getValue() + .Assert() + .HasResultAsync(variant, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasResultAsync_Forwarded( + Task dataA, + Task dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await dataA.Assert().HasResultAsync(canceler); + await dataB.Assert().HasResultAsync(canceler, _mod); + await thrower() + .Assert() + .HasResultAsync(canceler) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + await thrower() + .Assert() + .HasResultAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertGenericValueTaskTests.cs b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertGenericValueTaskTests.cs new file mode 100644 index 00000000..c0610a24 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertGenericValueTaskTests.cs @@ -0,0 +1,248 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Extensions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertAsyncCalls; + +public sealed class AssertGenericValueTaskTests : AutoTester> +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(ArgumentException), + typeof(ValueTaskRepeatedAccessException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertGenericValueTaskTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static async Task AssertGenericValueTask_CallsAndChains( + Injected> instance + ) + { + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken, + opt => opt with { IncludeBaseObjectMethods = false } + ); + results + .RawResults.Where(r => r.Result != null) + .Where(r => r.Result is not AssertChainer>) + .Where(r => r.Result is not AlsoChainer) + .Where(r => r.Result.GetType().Inherits(typeof(ExceptionChainer<>))) + .Where(r => r.Result as string != "AssertGenericValueTask") + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal async Task HasResultAsync_WithMatchForwarded(string value, string variant) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask getValue() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + return value; + } + + await getValue().Assert().HasResultAsync(value, canceler); + await getValue().Assert().HasResultAsync(value, canceler, _mod); + await getValue() + .Assert() + .HasResultAsync(variant, canceler) + .Assert() + .ThrowsAsync(canceler); + await getValue() + .Assert() + .HasResultAsync(variant, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasResultAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await dataA.Assert().HasResultAsync(canceler); + await dataB.Assert().HasResultAsync(canceler, _mod); + await thrower() + .Assert() + .HasResultAsync(canceler) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + await thrower() + .Assert() + .HasResultAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await thrower().Assert().ThrowsAsync(canceler); + await thrower().Assert().ThrowsAsync(canceler, _mod); + await dataA + .Assert() + .ThrowsAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await dataB + .Assert() + .ThrowsAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsExceptionAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await thrower().Assert().ThrowsExceptionAsync(canceler); + await thrower().Assert().ThrowsExceptionAsync(canceler, _mod); + await dataA + .Assert() + .ThrowsExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await dataB + .Assert() + .ThrowsExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await dataA.Assert().ThrowsNoAsync(canceler); + await dataB.Assert().ThrowsNoAsync(canceler, _mod); + await thrower() + .Assert() + .ThrowsNoAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await thrower() + .Assert() + .ThrowsNoAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoExceptionAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await dataA.Assert().ThrowsNoExceptionAsync(canceler); + await dataB.Assert().ThrowsNoExceptionAsync(canceler, _mod); + await thrower() + .Assert() + .ThrowsNoExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await thrower() + .Assert() + .ThrowsNoExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertTaskTests.cs b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertTaskTests.cs new file mode 100644 index 00000000..901d83ed --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertTaskTests.cs @@ -0,0 +1,162 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Extensions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertAsyncCalls; + +public sealed class AssertTaskTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(ArgumentException), + typeof(ValueTaskRepeatedAccessException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertTaskTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal async Task AssertTask_CallsAndChains(Injected instance) + { + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken + ); + results + .RawResults.Where(r => r.Result != null) + .Where(r => r.Result is not AssertChainer) + .Where(r => r.Result is not AlsoChainer) + .Where(r => r.Result.GetType().Inherits(typeof(ExceptionChainer<>))) + .Where(r => r.Result as string != nameof(AssertTask)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal async Task ThrowsAsync_Forwarded(Task data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await thrower().Assert().ThrowsAsync(canceler); + await thrower().Assert().ThrowsAsync(canceler, _mod); + await data.Assert() + .ThrowsAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ThrowsAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsExceptionAsync_Forwarded(Task data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await thrower().Assert().ThrowsExceptionAsync(canceler); + await thrower().Assert().ThrowsExceptionAsync(canceler, _mod); + await data.Assert() + .ThrowsExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ThrowsExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoAsync_Forwarded(Task data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await data.Assert().ThrowsNoAsync(canceler); + await data.Assert().ThrowsNoAsync(canceler, _mod); + await thrower() + .Assert() + .ThrowsNoAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await thrower() + .Assert() + .ThrowsNoAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoExceptionAsync_Forwarded(Task data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await data.Assert().ThrowsNoExceptionAsync(canceler); + await data.Assert().ThrowsNoExceptionAsync(canceler, _mod); + await thrower() + .Assert() + .ThrowsNoExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await thrower() + .Assert() + .ThrowsNoExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertValueTaskTests.cs b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertValueTaskTests.cs new file mode 100644 index 00000000..317250cf --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertAsyncCalls/AssertValueTaskTests.cs @@ -0,0 +1,188 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertAsyncCalls; + +public sealed class AssertValueTaskTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(ArgumentException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertValueTaskTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal async Task AssertValueTask_CallsAndChains(Injected instance) + { + string[] allowedResults = + [ + "AssertChainer", + "ExceptionChainer<", + nameof(AlsoChainer), + "ResultChainer<", + nameof(VoidType), + ]; + + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken, + opt => opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != nameof(AssertValueTask)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal async Task ThrowsAsync_Forwarded(ValueTask dataA, ValueTask dataB, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await thrower().Assert().ThrowsAsync(canceler); + await thrower().Assert().ThrowsAsync(canceler, _mod); + await dataA + .Assert() + .ThrowsAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await dataB + .Assert() + .ThrowsAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsExceptionAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await thrower().Assert().ThrowsExceptionAsync(canceler); + await thrower().Assert().ThrowsExceptionAsync(canceler, _mod); + await dataA + .Assert() + .ThrowsExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await dataB + .Assert() + .ThrowsExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoAsync_Forwarded(ValueTask dataA, ValueTask dataB, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await dataA.Assert().ThrowsNoAsync(canceler); + await dataB.Assert().ThrowsNoAsync(canceler, _mod); + await thrower() + .Assert() + .ThrowsNoAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await thrower() + .Assert() + .ThrowsNoAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoExceptionAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await dataA.Assert().ThrowsNoExceptionAsync(canceler); + await dataB.Assert().ThrowsNoExceptionAsync(canceler, _mod); + await thrower() + .Assert() + .ThrowsNoExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await thrower() + .Assert() + .ThrowsNoExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertCalls/AssertActionTests.cs b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertActionTests.cs new file mode 100644 index 00000000..ecab73ff --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertActionTests.cs @@ -0,0 +1,123 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertCalls; + +public sealed class AssertActionTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(ArgumentException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertActionTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static async Task AssertAction_CallsAndChains(Injected instance) + { + string[] allowedResults = + [ + "AssertChainer", + "ExceptionChainer<", + nameof(AlsoChainer), + "ResultChainer<", + nameof(VoidType), + ]; + + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken, + opt => opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != nameof(AssertAction)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal void Throws_Forwarded(Action behavior, Exception error) + { + Action thrower = () => throw error; + + thrower.Assert().Throws(); + thrower.Assert().Throws(_mod); + behavior.Assert(x => x.Assert().Throws()).Throws(); + behavior.Assert(x => x.Assert().Throws(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ThrowsException_Forwarded(Action behavior, Exception error) + { + Action thrower = () => throw error; + + thrower.Assert().ThrowsException(); + thrower.Assert().ThrowsException(_mod); + behavior.Assert(x => x.Assert().ThrowsException()).Throws(); + behavior.Assert(x => x.Assert().ThrowsException(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ThrowsNo_Forwarded(Action behavior, Exception error) + { + Action thrower = () => throw error; + + behavior.Assert().ThrowsNo(); + behavior.Assert().ThrowsNo(_mod); + thrower.Assert(x => x.Assert().ThrowsNo()).Throws(); + thrower.Assert(x => x.Assert().ThrowsNo(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ThrowsNoException_Forwarded(Action behavior, Exception error) + { + Action thrower = () => throw error; + + behavior.Assert().ThrowsNoException(); + behavior.Assert().ThrowsNoException(_mod); + thrower.Assert(x => x.Assert().ThrowsNoException()).Throws(); + thrower.Assert(x => x.Assert().ThrowsNoException(_mod)).Throws(); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertCalls/AssertComparableTests.cs b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertComparableTests.cs new file mode 100644 index 00000000..9398a2e3 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertComparableTests.cs @@ -0,0 +1,180 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertCalls; + +public sealed class AssertComparableTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(ArgumentException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertComparableTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static async Task AssertComparable_CallsAndChains(Injected instance) + { + string[] allowedResults = + [ + "AssertChainer", + "ResultChainer<", + nameof(VoidType), + ]; + + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken, + opt => opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != nameof(AssertComparable)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal void GreaterThan_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + data.Assert().GreaterThan(less); + data.Assert().GreaterThan(less, _mod); + data.Assert(d => d.Assert().GreaterThan(same)).Throws(); + data.Assert(d => d.Assert().GreaterThan(more, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void GreaterThanOrEqualTo_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + data.Assert().GreaterThanOrEqualTo(less); + data.Assert().GreaterThanOrEqualTo(same, _mod); + data.Assert(d => d.Assert().GreaterThanOrEqualTo(more)).Throws(); + data.Assert(d => d.Assert().GreaterThanOrEqualTo(more, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void GreaterThanOrIs_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + data.Assert().GreaterThanOrIs(less); + data.Assert().GreaterThanOrIs(same, _mod); + data.Assert(d => d.Assert().GreaterThanOrIs(more)).Throws(); + data.Assert(d => d.Assert().GreaterThanOrIs(more, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void LessThan_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + data.Assert().LessThan(more); + data.Assert().LessThan(more, _mod); + data.Assert(d => d.Assert().LessThan(same)).Throws(); + data.Assert(d => d.Assert().LessThan(less, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void LessThanOrEqualTo_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + data.Assert().LessThanOrEqualTo(more); + data.Assert().LessThanOrEqualTo(same, _mod); + data.Assert(d => d.Assert().LessThanOrEqualTo(less)).Throws(); + data.Assert(d => d.Assert().LessThanOrEqualTo(less, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void LessThanOrIs_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + data.Assert().LessThanOrIs(more); + data.Assert().LessThanOrIs(same, _mod); + data.Assert(d => d.Assert().LessThanOrIs(less)).Throws(); + data.Assert(d => d.Assert().LessThanOrIs(less, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void InRange_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + data.Assert().InRange(less, same); + data.Assert().InRange(same, more, _mod); + data.Assert(d => d.Assert().InRange(less, less)).Throws(); + data.Assert(d => d.Assert().InRange(more, more, _mod)).Throws(); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertCalls/AssertDelegateTests.cs b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertDelegateTests.cs new file mode 100644 index 00000000..9602ddfe --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertDelegateTests.cs @@ -0,0 +1,271 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertCalls; + +public sealed class AssertDelegateTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = [typeof(AssertException), typeof(ToolException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertDelegateTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static void Throws_ReturnsException(Exception error) + { + error.Assert(x => false ? "" : throw x).Throws().That().Is(error); + } + + [Theory, RandomData] + internal static void Throws_CatchesExpected(ArgumentNullException error) + { + error.Assert(x => false ? "" : throw x).Throws().That().Is(error); + } + + [Theory, RandomData] + internal static void Throws_UnwrapsAggregate(InvalidOperationException error) + { + error + .Assert(x => false ? "" : throw new AggregateException(x)) + .Throws() + .That() + .Is(error); + } + + [Theory, RandomData] + internal static void Throws_ActionNoException(Action behavior) + { + behavior.Assert(x => x.Assert().Throws()).Throws(); + } + + [Theory, RandomData] + internal static void Throws_FuncNoException(Func behavior) + { + behavior.Assert(x => x.Assert().Throws()).Throws(); + } + + [Theory, RandomData] + internal static void Throws_WrongException(ArgumentNullException error) + { + error + .Assert(x => x.Assert(ex => throw ex).Throws()) + .Throws(); + } + + [Theory, RandomData] + internal static void Throws_OptionsOkay(ArgumentNullException error) + { + error + .Assert(x => x.Assert(ex => throw ex).Throws(opt => opt)) + .ThrowsNo(); + } + + [Theory, RandomData] + internal static void Throws_WrongAggregate(InvalidOperationException error) + { + error + .Assert(x => + x.Assert(ex => throw new AggregateException(ex)).Throws() + ) + .Throws(); + } + + [Theory, RandomData] + internal static void Throws_TooManyAggregate( + ArgumentNullException error, + InvalidOperationException error2 + ) + { + error + .Assert(x => + error2 + .Assert(ex => throw new AggregateException(x, ex)) + .Throws() + ) + .Throws(); + } + + [Theory, RandomData] + internal static void ThrowsNo_NoopAction(Action behavior) + { + behavior.Assert().ThrowsNo(); + } + + [Theory, RandomData] + internal static void ThrowsNo_NoopFunc(Func behavior) + { + behavior.Assert().ThrowsNo(); + } + + [Theory, RandomData] + internal static void ThrowsNo_Error(Exception error) + { + error.Assert(x => x.Assert(ex => throw ex).ThrowsNo()).Throws(); + } + + [Theory, RandomData] + internal static void ThrowsNo_DifferentExceptionIgnored(TimeoutException error) + { + error + .Assert(x => x.Assert(ex => throw ex).ThrowsNo()) + .ThrowsNo(); + } + + [Theory, RandomData] + internal static async Task AssertDelegate_CallsAndChains(Injected instance) + { + string[] allowedResults = + [ + "AssertChainer", + "ExceptionChainer<", + nameof(AlsoChainer), + "ResultChainer<", + nameof(VoidType), + ]; + + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken, + opt => opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != nameof(AssertDelegate)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal void HasResult_ForwardedPlain(string data) + { + Delegate behavior = () => data; + + behavior.Assert().HasResult(); + behavior.Assert().HasResult(_mod); + + behavior.Assert(x => x.Assert().HasResult()).Throws(); + behavior.Assert(x => x.Assert().HasResult(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void HasResult_Forwarded(string valid, string invalid) + { + Delegate behavior = () => valid; + + behavior.Assert().HasResult(valid); + behavior.Assert().HasResult(valid, _mod); + + behavior.Assert(x => x.Assert().HasResult(invalid)).Throws(); + behavior.Assert(x => x.Assert().HasResult(invalid, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasResultAsync_Forwarded(string valid, string invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Delegate behavior = () => valid; + + await behavior.Assert().HasResultAsync(valid, canceler); + await behavior.Assert().HasResultAsync(valid, canceler, _mod); + + await behavior + .Assert() + .HasResultAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await behavior + .Assert() + .HasResultAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void Throws_Forwarded(Delegate behavior, Exception error) + { + Delegate thrower = (Action)(() => throw error); + + thrower.Assert().Throws(); + thrower.Assert().Throws(_mod); + + behavior.Assert(x => x.Assert().Throws()).Throws(); + behavior.Assert(x => x.Assert().Throws(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ThrowsException_Forwarded(Func behavior, Exception error) + { + Func thrower = () => throw error; + + thrower.Assert().ThrowsException(); + thrower.Assert().ThrowsException(_mod); + + behavior.Assert(x => x.Assert().ThrowsException()).Throws(); + behavior.Assert(x => x.Assert().ThrowsException(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ThrowsNo_Forwarded(Delegate behavior, Exception error) + { + Delegate thrower = (Action)(() => throw error); + + behavior.Assert().ThrowsNo(); + behavior.Assert().ThrowsNo(_mod); + thrower.Assert(x => x.Assert().ThrowsNo()).Throws(); + thrower.Assert(x => x.Assert().ThrowsNo(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ThrowsNoException_Forwarded(Func behavior, Exception error) + { + Func thrower = () => throw error; + + behavior.Assert().ThrowsNoException(); + behavior.Assert().ThrowsNoException(_mod); + thrower.Assert(x => x.Assert().ThrowsNoException()).Throws(); + thrower.Assert(x => x.Assert().ThrowsNoException(_mod)).Throws(); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertCalls/AssertEnumerableTests.cs b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertEnumerableTests.cs new file mode 100644 index 00000000..673d1be7 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertEnumerableTests.cs @@ -0,0 +1,270 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertCalls; + +public sealed class AssertEnumerableTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(UnsupportedException), + typeof(ArgumentException), + typeof(TargetException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertEnumerableTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static async Task AssertEnumerable_CallsAndChains(Injected instance) + { + string[] allowedResults = + [ + "AssertChainer", + "ResultChainer<", + nameof(VoidType), + ]; + + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken, + opt => opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != nameof(AssertEnumerable)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal void IsEmpty_Forwarded( + [Size(0)] IEnumerable valid, + [Size(1)] IEnumerable invalid + ) + { + valid.Assert().IsEmpty(); + valid.Assert().IsEmpty(_mod); + invalid.Assert(x => x.Assert().IsEmpty()).Throws(); + invalid.Assert(x => x.Assert().IsEmpty(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void IsNotEmpty_Forwarded( + [Size(1)] IEnumerable valid, + [Size(0)] IEnumerable invalid + ) + { + valid.Assert().IsNotEmpty(); + valid.Assert().IsNotEmpty(_mod); + invalid.Assert(x => x.Assert().IsNotEmpty()).Throws(); + invalid.Assert(x => x.Assert().IsNotEmpty(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void HasCount_Forwarded([Size(1)] IEnumerable data) + { + data.Assert().HasCount(1); + data.Assert().HasCount(1, _mod); + data.Assert(x => x.Assert().HasCount(0)).Throws(); + data.Assert(x => x.Assert().HasCount(2, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void HasCountLessThan_Forwarded([Size(1)] IEnumerable data) + { + data.Assert().HasCountLessThan(2); + data.Assert().HasCountLessThan(2, _mod); + data.Assert(x => x.Assert().HasCountLessThan(1)).Throws(); + data.Assert(x => x.Assert().HasCountLessThan(0, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void HasCountLessOrExactly_Forwarded([Size(1)] IEnumerable data) + { + data.Assert().HasCountLessOrExactly(2); + data.Assert().HasCountLessOrExactly(1, _mod); + data.Assert(x => x.Assert().HasCountLessOrExactly(0)).Throws(); + data.Assert(x => x.Assert().HasCountLessOrExactly(0, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void HasCountMoreThan_Forwarded([Size(1)] IEnumerable data) + { + data.Assert().HasCountMoreThan(0); + data.Assert().HasCountMoreThan(0, _mod); + data.Assert(x => x.Assert().HasCountMoreThan(1)).Throws(); + data.Assert(x => x.Assert().HasCountMoreThan(2, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void HasCountMoreOrExactly_Forwarded([Size(1)] IEnumerable data) + { + data.Assert().HasCountMoreOrExactly(0); + data.Assert().HasCountMoreOrExactly(1, _mod); + data.Assert(x => x.Assert().HasCountMoreOrExactly(2)).Throws(); + data.Assert(x => x.Assert().HasCountMoreOrExactly(2, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void Contains_Forwarded(int valid, int invalid) + { + IEnumerable data = [valid]; + + data.Assert().Contains(valid); + data.Assert().Contains(valid, _mod); + data.Assert(x => x.Assert().Contains(invalid)).Throws(); + data.Assert(x => x.Assert().Contains(invalid, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsAsync_Forwarded(AsyncDataSample valid, AsyncDataSample invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IEnumerable data = [valid]; + + await data.Assert().ContainsAsync(valid, canceler); + await data.Assert().ContainsAsync(valid, canceler, _mod); + await data.Assert() + .ContainsAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ContainsAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ContainsNot_Forwarded(int valid, int invalid) + { + IEnumerable data = [invalid]; + + data.Assert().ContainsNot(valid); + data.Assert().ContainsNot(valid, _mod); + data.Assert(x => x.Assert().ContainsNot(invalid)).Throws(); + data.Assert(x => x.Assert().ContainsNot(invalid, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsNotAsync_Forwarded(AsyncDataSample valid, AsyncDataSample invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IEnumerable data = [invalid]; + + await data.Assert().ContainsNotAsync(valid, canceler); + await data.Assert().ContainsNotAsync(valid, canceler, _mod); + await data.Assert() + .ContainsNotAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await data.Assert() + .ContainsNotAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void Fail_Forwarded(IEnumerable data, [Fake] IAsserter asserter) + { + ToolSet silentFailSet = MakeSet(asserter); + + data.Assert(silentFailSet).Fail(); + data.Assert(silentFailSet).Fail(_mod); + data.Assert(x => x.Assert().Fail()).Throws(); + data.Assert(x => x.Assert().Fail(_mod)).Throws(); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal void Debug_Forwarded(IEnumerable data) + { + ToolSet debugPassSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = false }) + ); + ToolSet debugFailSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = true }) + ); + + data.Assert(debugPassSet).Debug(); + data.Assert(debugPassSet).Debug(_mod); + data.Assert(x => x.Assert(debugFailSet).Debug()).Throws(); + data.Assert(x => x.Assert(debugFailSet).Debug(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + private static ToolSet MakeSet(IAsserter asserter) + { + return new( + Tools.Gen, + Tools.Valuer, + Tools.Faker, + Tools.Randomizer, + Tools.Extractor, + Tools.Mutator, + asserter, + Tools.Duplicator, + Tools.Runner, + Tools.Tester + ); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertCalls/AssertErrorTests.cs b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertErrorTests.cs new file mode 100644 index 00000000..b7025cec --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertErrorTests.cs @@ -0,0 +1,129 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertCalls; + +public sealed class AssertErrorTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertErrorTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static async Task AssertError_CallsAndChains(Injected instance) + { + string[] allowedResults = + [ + "AssertChainer", + "ExceptionChainer<", + nameof(VoidType), + ]; + + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken, + opt => opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != nameof(AssertError)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal void Inherits_Forwarded(AggregateException error) + { + error.Assert().Inherits(); + error.Assert().Inherits(_mod); + error + .Assert(x => x.Assert().Inherits()) + .Throws(); + error + .Assert(x => x.Assert().Inherits(_mod)) + .Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void Fail_Forwarded(Exception data, [Fake] IAsserter asserter) + { + ToolSet silentFailSet = MakeSet(asserter); + + data.Assert(silentFailSet).Fail(); + data.Assert(silentFailSet).Fail(_mod); + data.Assert(x => x.Assert().Fail()).Throws(); + data.Assert(x => x.Assert().Fail(_mod)).Throws(); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal void Debug_Forwarded(Exception data) + { + ToolSet debugPassSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = false }) + ); + ToolSet debugFailSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = true }) + ); + + data.Assert(debugPassSet).Debug(); + data.Assert(debugPassSet).Debug(_mod); + data.Assert(x => x.Assert(debugFailSet).Debug()).Throws(); + data.Assert(x => x.Assert(debugFailSet).Debug(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + private static ToolSet MakeSet(IAsserter asserter) + { + return new( + Tools.Gen, + Tools.Valuer, + Tools.Faker, + Tools.Randomizer, + Tools.Extractor, + Tools.Mutator, + asserter, + Tools.Duplicator, + Tools.Runner, + Tools.Tester + ); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertCalls/AssertFuncTests.cs b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertFuncTests.cs new file mode 100644 index 00000000..7f1893ba --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertFuncTests.cs @@ -0,0 +1,85 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertCalls; + +public sealed class AssertFuncTests : AutoTester> +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(ArgumentException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertFuncTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static async Task AssertFunc_CallsAndChains(Injected> instance) + { + string[] allowedResults = + [ + "AssertChainer opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != "AssertFunc") + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal void HasResult_Forwarded(Func behavior, Exception error) + { + Func thrower = () => throw error; + + behavior.Assert().HasResult(); + behavior.Assert().HasResult(_mod); + + thrower.Assert(x => x.Assert().HasResult()).Throws(); + thrower.Assert(x => x.Assert().HasResult(_mod)).Throws(); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertCalls/AssertObjectTests.cs b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertObjectTests.cs new file mode 100644 index 00000000..fd6915b7 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertObjectTests.cs @@ -0,0 +1,251 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertCalls; + +public sealed class AssertObjectTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(FakeVerifyException), + typeof(InvalidCastException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertObjectTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static async Task AssertObject_CallsAndChains(Injected instance) + { + string[] allowedResults = ["AssertChainer", nameof(VoidType)]; + + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken, + opt => opt with { MethodsToIgnore = [nameof(AssertObjectBase<>.IsA)] } + ); + results + .RawResults.Where(r => + !allowedResults.Any(x => + GenericConverter + .ExpandName(r.Result?.GetType()) + .Contains(x, StringComparison.Ordinal) + ) + ) + .Where(r => r.Result as string != nameof(AssertObject)) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal void Is_Forwarded(DataSample data, [Copy] DataSample clone, DataSample variant) + { + data.Assert().Is(clone); + data.Assert().Is(clone, _mod); + data.Assert(d => d.Assert().Is(variant)).Throws(); + data.Assert(d => d.Assert().Is(variant, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void IsNull_Forwarded(DataSample data) + { + ((object)null).Assert().IsNull(); + ((object)null).Assert().IsNull(_mod); + data.Assert(d => d.Assert().IsNull()).Throws(); + data.Assert(d => d.Assert().IsNull(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void IsNot_Forwarded(DataSample data, [Copy] DataSample clone, DataSample variant) + { + data.Assert().IsNot(variant); + data.Assert().IsNot(variant, _mod); + data.Assert(d => d.Assert().IsNot(clone)).Throws(); + data.Assert(d => d.Assert().IsNot(clone, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void IsNotNull_Forwarded(DataSample data) + { + data.Assert().IsNotNull(); + data.Assert().IsNotNull(_mod); + ((object)null).Assert(d => d.Assert().IsNotNull()).Throws(); + ((object)null).Assert(d => d.Assert().IsNotNull(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ReferenceEqual_Forwarded(DataSample data, [Copy] DataSample clone) + { + data.Assert().ReferenceEqual(data); + data.Assert().ReferenceEqual(data, _mod); + data.Assert(d => d.Assert().ReferenceEqual(clone)).Throws(); + data.Assert(d => d.Assert().ReferenceEqual(clone, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ReferenceNotEqual_Forwarded(DataSample data, [Copy] DataSample clone) + { + data.Assert().ReferenceNotEqual(clone); + data.Assert().ReferenceNotEqual(clone, _mod); + data.Assert(d => d.Assert().ReferenceNotEqual(data)).Throws(); + data.Assert(d => d.Assert().ReferenceNotEqual(data, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ValuesEqual_Forwarded( + DataSample data, + [Copy] DataSample clone, + DataSample variant + ) + { + data.Assert().ValuesEqual(clone); + data.Assert().ValuesEqual(clone, _mod); + data.Assert(d => d.Assert().ValuesEqual(variant)).Throws(); + data.Assert(d => d.Assert().ValuesEqual(variant, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void ValuesNotEqual_Forwarded( + DataSample data, + [Copy] DataSample clone, + DataSample variant + ) + { + data.Assert().ValuesNotEqual(variant); + data.Assert().ValuesNotEqual(variant, _mod); + data.Assert(d => d.Assert().ValuesNotEqual(clone)).Throws(); + data.Assert(d => d.Assert().ValuesNotEqual(clone, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void UniqueFrom_Forwarded( + DataSample data, + [Copy] DataSample clone, + [Unique] DataSample unique + ) + { + data.Assert().UniqueFrom(unique); + data.Assert().UniqueFrom(unique, _mod); + data.Assert(d => d.Assert().UniqueFrom(clone)).Throws(); + data.Assert(d => d.Assert().UniqueFrom(clone, _mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void Fail_Forwarded(DataSample data, [Fake] IAsserter asserter) + { + ToolSet silentFailSet = MakeSet(asserter); + + data.Assert(silentFailSet).Fail(); + data.Assert(silentFailSet).Fail(_mod); + data.Assert(d => d.Assert().Fail()).Throws(); + data.Assert(d => d.Assert().Fail(_mod)).Throws(); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal void Debug_Forwarded(DataSample data) + { + ToolSet debugPassSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = false }) + ); + ToolSet debugFailSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = true }) + ); + + data.Assert(debugPassSet).Debug(); + data.Assert(debugPassSet).Debug(_mod); + data.Assert(d => d.Assert(debugFailSet).Debug()).Throws(); + data.Assert(d => d.Assert(debugFailSet).Debug(_mod)).Throws(); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal void Pass_Forwarded(DataSample data) + { + data.Assert().Pass(); + data.Assert().Pass(_mod); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal void Called_Forwarded([Fake] DataSample data, DataSample nonFake) + { + data.ToString(); + + data.Assert().Called(); + data.Assert().Called(_mod); + + data.Equals(Arg.Any()).SetupReturn(Behavior.Throw()); + + data.Assert(d => d.Assert().Called()).Throws(); + data.Assert(d => d.Assert().Called(_mod)).Throws(); + + nonFake.Assert(d => d.Assert().Called()).Throws(); + nonFake.Assert(d => d.Assert().Called(_mod)).Throws(); + + _modCount.Assert().Is(0); + } + + private static ToolSet MakeSet(IAsserter asserter) + { + return new( + Tools.Gen, + Tools.Valuer, + Tools.Faker, + Tools.Randomizer, + Tools.Extractor, + Tools.Mutator, + asserter, + Tools.Duplicator, + Tools.Runner, + Tools.Tester + ); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertCalls/AssertStringTests.cs b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertStringTests.cs new file mode 100644 index 00000000..bdcc37b5 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertCalls/AssertStringTests.cs @@ -0,0 +1,194 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent.AssertCalls; + +public sealed class AssertStringTests : AutoTester +{ + private static readonly char[] _Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); + + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ToolException), + typeof(InvalidCastException), + typeof(UnsupportedException), + typeof(TargetException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public AssertStringTests() + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Theory, RandomData] + internal static void AssertString_SupportSizeTests([Size(5)] string original) + { + original + .Assert() + .HasCount(5) + .And() + .HasCountLessOrExactly(5) + .And() + .HasCountLessOrExactly(6) + .And() + .HasCountLessThan(6) + .And() + .HasCountMoreOrExactly(5) + .And() + .HasCountMoreOrExactly(4) + .And() + .HasCountMoreThan(4); + } + + [Theory, RandomData] + internal static async Task AssertString_CallsAndChains(Injected instance) + { + RunResults results = await Tools.Runner.CallMethodsOnAsync( + instance.Dummy, + TestContext.Current.CancellationToken + ); + results + .RawResults.Where(r => r.Result != null) + .Where(r => + r.Result + is not AssertChainer + and Task> + ) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal void Contains_Forwarded(string data) + { + char someChar = Tools.Gen.NextItem(data); + char uniqueChar = Tools.Gen.NextItem(_Letters.Except(data)); + + data.Assert().Contains(someChar); + data.Assert().Contains(someChar, _mod); + data.Assert().Contains(someChar.ToString()); + data.Assert().Contains(someChar.ToString(), _mod); + data.Assert(d => d.Assert().Contains(uniqueChar)).Throws(); + data.Assert(d => d.Assert().Contains(uniqueChar, _mod)).Throws(); + data.Assert(d => d.Assert().Contains(uniqueChar.ToString())).Throws(); + data.Assert(d => d.Assert().Contains(uniqueChar.ToString(), _mod)) + .Throws(); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal void ContainsNot_Forwarded(string data) + { + char someChar = Tools.Gen.NextItem(data); + char uniqueChar = Tools.Gen.NextItem(_Letters.Except(data)); + + data.Assert().ContainsNot(uniqueChar); + data.Assert().ContainsNot(uniqueChar, _mod); + data.Assert().ContainsNot(uniqueChar.ToString()); + data.Assert().ContainsNot(uniqueChar.ToString(), _mod); + data.Assert(d => d.Assert().ContainsNot(someChar)).Throws(); + data.Assert(d => d.Assert().ContainsNot(someChar, _mod)).Throws(); + data.Assert(d => d.Assert().ContainsNot(someChar.ToString())).Throws(); + data.Assert(d => d.Assert().ContainsNot(someChar.ToString(), _mod)) + .Throws(); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal void StartsWith_Forwarded(string data) + { + char firstChar = data[0]; + char otherChar = firstChar.Tools().Variant(); + + data.Assert().StartsWith(firstChar); + data.Assert().StartsWith(firstChar, _mod); + data.Assert().StartsWith(firstChar.ToString()); + data.Assert().StartsWith(firstChar.ToString(), _mod); + data.Assert(d => d.Assert().StartsWith(otherChar)).Throws(); + data.Assert(d => d.Assert().StartsWith(otherChar, _mod)).Throws(); + data.Assert(d => d.Assert().StartsWith(otherChar.ToString())).Throws(); + data.Assert(d => d.Assert().StartsWith(otherChar.ToString(), _mod)) + .Throws(); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal void StartsNotWith_Forwarded(string data) + { + char firstChar = data[0]; + char otherChar = firstChar.Tools().Variant(); + + data.Assert().StartsNotWith(otherChar); + data.Assert().StartsNotWith(otherChar, _mod); + data.Assert().StartsNotWith(otherChar.ToString()); + data.Assert().StartsNotWith(otherChar.ToString(), _mod); + data.Assert(d => d.Assert().StartsNotWith(firstChar)).Throws(); + data.Assert(d => d.Assert().StartsNotWith(firstChar, _mod)).Throws(); + data.Assert(d => d.Assert().StartsNotWith(firstChar.ToString())).Throws(); + data.Assert(d => d.Assert().StartsNotWith(firstChar.ToString(), _mod)) + .Throws(); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal void EndsWith_Forwarded([Size(3)] string data) + { + char lastChar = data[2]; + char otherChar = lastChar.Tools().Variant(); + + data.Assert().EndsWith(lastChar); + data.Assert().EndsWith(lastChar, _mod); + data.Assert().EndsWith(lastChar.ToString()); + data.Assert().EndsWith(lastChar.ToString(), _mod); + data.Assert(d => d.Assert().EndsWith(otherChar)).Throws(); + data.Assert(d => d.Assert().EndsWith(otherChar, _mod)).Throws(); + data.Assert(d => d.Assert().EndsWith(otherChar.ToString())).Throws(); + data.Assert(d => d.Assert().EndsWith(otherChar.ToString(), _mod)).Throws(); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal void EndsNotWith_Forwarded([Size(3)] string data) + { + char lastChar = data[2]; + char otherChar = lastChar.Tools().Variant(); + + data.Assert().EndsNotWith(otherChar); + data.Assert().EndsNotWith(otherChar, _mod); + data.Assert().EndsNotWith(otherChar.ToString()); + data.Assert().EndsNotWith(otherChar.ToString(), _mod); + data.Assert(d => d.Assert().EndsNotWith(lastChar)).Throws(); + data.Assert(d => d.Assert().EndsNotWith(lastChar, _mod)).Throws(); + data.Assert(d => d.Assert().EndsNotWith(lastChar.ToString())).Throws(); + data.Assert(d => d.Assert().EndsNotWith(lastChar.ToString(), _mod)) + .Throws(); + + _modCount.Assert().Is(4); + } +} diff --git a/tests/Toolbox.Tests/Fluent/AssertExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/AssertExtensionsTests.cs new file mode 100644 index 00000000..f37954b0 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/AssertExtensionsTests.cs @@ -0,0 +1,37 @@ +namespace Werecodent.CreateAndFake.Tests.Fluent; + +public sealed class AssertExtensionsTests() : AutoTester(typeof(AssertExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { DisableParameterMutationTests = true }; + + [Theory, RandomData] + internal static void Assert_ObjectIsFluent(int data) + { + data.Assert().Is(data).And().IsNotNull(); + } + + [Theory, RandomData] + internal static void Assert_StringIsFluent(string data) + { + data.Assert().Is(data).And().Contains(data).And().HasCount(data.Length); + } + + [Theory, RandomData] + internal static void Assert_CollectionIsFluent(ICollection data) + { + data.Assert().IsNotEmpty().And().Contains(data.First()); + } + + [Theory, RandomData] + internal static void Assert_ReadOnlyCollectionIsFluent(IReadOnlyCollection data) + { + data.Assert().IsNotEmpty().And().Contains(data.First()); + } + + [Theory, RandomData] + public static void Assert_ComparableIsFluent(int data) + { + data.Assert().GreaterThanOrEqualTo(int.MinValue).And().LessThanOrEqualTo(int.MaxValue); + } +} diff --git a/tests/Toolbox.Tests/Fluent/Chaining/AlsoChainerTests.cs b/tests/Toolbox.Tests/Fluent/Chaining/AlsoChainerTests.cs new file mode 100644 index 00000000..7742323c --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/Chaining/AlsoChainerTests.cs @@ -0,0 +1,161 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.Chaining; + +public sealed class AlsoChainerTests : AutoTester +{ + [Theory, RandomData] + internal static void Also_HandlesCompiledAction(AlsoChainer chainer, string data) + { + chainer.Also(() => data.Assert().Fail()).GetType().Assert().Is(typeof(AssertAction)); + } + + [Theory, RandomData] + internal static void Also_HandlesCompiledFunc(AlsoChainer chainer, string data) + { + chainer.Also(() => data.Length).GetType().Assert().Inherits(typeof(AssertFunc)); + } + + [Theory, RandomData] + internal static void Also_SupportsIAsyncEnumerable( + AlsoChainer chainer, + IAsyncEnumerable data + ) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertAsyncEnumerable)); + } + + [Theory, RandomData] + internal static void Also_SupportsSpecificIAsyncEnumerable( + AlsoChainer chainer, + AsyncList data + ) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertAsyncEnumerable)); + } + + [Theory, RandomData] + internal static void Also_SupportsObject(AlsoChainer chainer, object data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertAsyncObject)); + } + + [Theory, RandomData] + internal static void Also_SupportsUnknownObject(AlsoChainer chainer, DataSample data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertAsyncObject)); + } + + [Theory, RandomData] + internal static void Also_SupportsGenericTask(AlsoChainer chainer, Task data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertGenericTask)); + } + + [Theory, RandomData] + internal static void Also_SupportsGenericValueTask(AlsoChainer chainer, ValueTask data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertGenericValueTask)); + } + + [Theory, RandomData] + internal static void Also_SupportsNullableGenericValueTask( + AlsoChainer chainer, + ValueTask? data + ) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertGenericValueTask)); + } + + [Theory, RandomData] + internal static void Also_SupportsTask(AlsoChainer chainer, Task data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertTask)); + } + + [Theory, RandomData] + internal static void Also_SupportsValueTask(AlsoChainer chainer, ValueTask data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertValueTask)); + } + + [Theory, RandomData] + internal static void Also_SupportsNullableValueTask(AlsoChainer chainer, ValueTask? data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertValueTask)); + } + + [Theory, RandomData] + internal static void Also_SupportsAction(AlsoChainer chainer, Action data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertAction)); + } + + [Theory, RandomData] + internal static void Also_SupportsIComparable(AlsoChainer chainer, IComparable data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void Also_SupportsInt(AlsoChainer chainer, int data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void Also_SupportsGenericIEnumerable( + AlsoChainer chainer, + IEnumerable data + ) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void Also_SupportsList(AlsoChainer chainer, List data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void Also_SupportsArray(AlsoChainer chainer, DataSample[] data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void Also_SupportsIEnumerable(AlsoChainer chainer, IEnumerable data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void Also_SupportsException(AlsoChainer chainer, Exception data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void Also_SupportsSpecificException(AlsoChainer chainer, ArgumentException data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void Also_SupportsFunc(AlsoChainer chainer, Func data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertFunc)); + } + + [Theory, RandomData] + internal static void Also_SupportsString(AlsoChainer chainer, string data) + { + chainer.Also(data).GetType().Assert().Is(typeof(AssertString)); + } +} diff --git a/tests/Toolbox.Tests/Fluent/Chaining/AssertChainerTests.cs b/tests/Toolbox.Tests/Fluent/Chaining/AssertChainerTests.cs new file mode 100644 index 00000000..24e9e15a --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/Chaining/AssertChainerTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Tests.Fluent.Chaining; + +public sealed class AssertChainerTests : AutoTester> +{ + [Theory, RandomData] + internal static void And_ReturnsInput(object data) + { + new AssertChainer(data, Tools.Asserter).And().Assert().Is(data); + } +} diff --git a/tests/Toolbox.Tests/Fluent/Chaining/ExceptionChainerTests.cs b/tests/Toolbox.Tests/Fluent/Chaining/ExceptionChainerTests.cs new file mode 100644 index 00000000..59ecb0ff --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/Chaining/ExceptionChainerTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Tests.Fluent.Chaining; + +public sealed class ExceptionChainerTests() : AutoTester(typeof(ExceptionChainer<>)) +{ + [Theory, RandomData] + internal static void That_SupportsArgumentException(ExceptionChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } +} diff --git a/tests/Toolbox.Tests/Fluent/Chaining/ResultChainerExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/Chaining/ResultChainerExtensionsTests.cs new file mode 100644 index 00000000..d5b3e058 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/Chaining/ResultChainerExtensionsTests.cs @@ -0,0 +1,698 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Collections.Specialized; +using System.Numerics; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.Chaining; + +public sealed class ResultChainerExtensionsTests() : AutoTester(typeof(ResultChainerExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + [Theory, RandomData] + internal static void That_SupportsIAsyncEnumerable(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertAsyncEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsAsyncList(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertAsyncEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsIAsyncSet(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertAsyncEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsAsyncHashSet( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertAsyncEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsObject(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertAsyncObject)); + } + + [Theory, RandomData] + internal static void That_SupportsUnknownObject(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertAsyncObject)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericTask(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertGenericTask)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericValueTask(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertGenericValueTask)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableGenericValueTask( + ResultChainer?> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertGenericValueTask)); + } + + [Theory, RandomData] + internal static void That_SupportsTask(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertTask)); + } + + [Theory, RandomData] + internal static void That_SupportsValueTask(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertValueTask)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableValueTask(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertValueTask)); + } + + [Theory, RandomData] + internal static void That_SupportsAction(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertAction)); + } + + [Theory, RandomData] + internal static void That_SupportsIComparable(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsDelegate(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertDelegate)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericIEnumerable(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericArray(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericICollection(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericIReadOnlyCollection( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericIList(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericList(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericQueue(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericStack(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericISet(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericHashSet(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericLinkedList( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericConcurrentQueue( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericConcurrentStack( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericFrozenSet(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableList( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableQueue( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableStack( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableHashSet( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableSortedSet( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericIDictionary( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericDictionary( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericConcurrentDictionary( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericFrozenDictionary( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableDictionary( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableSortedDictionary( + ResultChainer> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsIEnumerable(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsICollection(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsIDictionary(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsHashtable(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsSortedList(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsListDictionary(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsHybridDictionary(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsStringDictionary(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsOrderedDictionary(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsNameValueCollection( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsArray(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsStack(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsQueue(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsArrayList(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsBitArray(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsStringCollection(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void That_SupportsException(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsAggregateException(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsArgumentException(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsNotSupportedException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsInvalidOperationException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsAssertException(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsSystemException(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsTaskCanceledException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsOperationCanceledException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsFormatException(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsArgumentNullException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsNullReferenceException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsIndexOutOfRangeException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsInvalidCastException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsArgumentOutOfRangeException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsIOException(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsFileNotFoundException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsKeyNotFoundException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsNotImplementedException( + ResultChainer chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void That_SupportsFunc(ResultChainer> chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertFunc)); + } + + [Theory, RandomData] + internal static void That_SupportsString(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertString)); + } + + [Theory, RandomData] + internal static void That_SupportsBool(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableBool(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsFloat(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableFloat(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsDouble(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableDouble(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsDecimal(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableDecimal(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsTimeSpan(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableTimeSpan(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsDateTime(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableDateTime(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsBigInteger(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableBigInteger(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsDateTimeOffset(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableDateTimeOffset(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsChar(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableChar(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsInt(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableInt(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsLong(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableLong(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsShort(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableShort(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsByte(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableByte(ResultChainer chainer) + { + chainer.That().GetType().Assert().Is(typeof(AssertComparable)); + } +} diff --git a/tests/Toolbox.Tests/Fluent/Chaining/ResultChainerTests.cs b/tests/Toolbox.Tests/Fluent/Chaining/ResultChainerTests.cs new file mode 100644 index 00000000..e6e20eb1 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/Chaining/ResultChainerTests.cs @@ -0,0 +1,164 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.Chaining; + +public sealed class ResultChainerTests() : AutoTester(typeof(ResultChainer<>)) +{ + [Theory, RandomData] + internal static void With_HandlesCompiledAction(ResultChainer chainer, string data) + { + chainer.With(_ => data.Assert().Fail()).GetType().Assert().Is(typeof(AssertAction)); + } + + [Theory, RandomData] + internal static void With_SupportsIAsyncEnumerable( + ResultChainer chainer, + IAsyncEnumerable data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertAsyncEnumerable)); + } + + [Theory, RandomData] + internal static void With_SupportsSpecificIAsyncEnumerable( + ResultChainer chainer, + AsyncList data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertAsyncEnumerable)); + } + + [Theory, RandomData] + internal static void With_SupportsObject(ResultChainer chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(AssertAsyncObject)); + } + + [Theory, RandomData] + internal static void With_SupportsUnknownObject(ResultChainer chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(AssertAsyncObject)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericTask(ResultChainer chainer, Task data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertGenericTask)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericValueTask( + ResultChainer chainer, + ValueTask data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertGenericValueTask)); + } + + [Theory, RandomData] + internal static void With_SupportsNullableGenericValueTask( + ResultChainer chainer, + ValueTask? data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertGenericValueTask)); + } + + [Theory, RandomData] + internal static void With_SupportsTask(ResultChainer chainer, Task data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertTask)); + } + + [Theory, RandomData] + internal static void With_SupportsValueTask(ResultChainer chainer, ValueTask data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertValueTask)); + } + + [Theory, RandomData] + internal static void With_SupportsNullableValueTask( + ResultChainer chainer, + ValueTask? data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertValueTask)); + } + + [Theory, RandomData] + internal static void With_SupportsAction(ResultChainer chainer, Action data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertAction)); + } + + [Theory, RandomData] + internal static void With_SupportsIComparable(ResultChainer chainer, IComparable data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void With_SupportsDelegate(ResultChainer chainer, Delegate data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertDelegate)); + } + + [Theory, RandomData] + internal static void With_SupportsInt(ResultChainer chainer) + { + chainer.With(x => x.NumberValue).GetType().Assert().Is(typeof(AssertComparable)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericIEnumerable(ResultChainer chainer) + { + chainer.With(x => x.CollectionValue).GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void With_SupportsList(ResultChainer> chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void With_SupportsArray(ResultChainer chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void With_SupportsIEnumerable(ResultChainer chainer, IEnumerable data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertEnumerable)); + } + + [Theory, RandomData] + internal static void With_SupportsException(ResultChainer chainer) + { + chainer.With(x => x.InnerException).GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void With_SupportsSpecificException(ResultChainer chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(AssertError)); + } + + [Theory, RandomData] + internal static void With_SupportsFunc(ResultChainer chainer, Func data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(AssertFunc)); + } + + [Theory, RandomData] + internal static void With_SupportsString(ResultChainer chainer) + { + chainer.With(x => x.ToString()).GetType().Assert().Is(typeof(AssertString)); + } +} diff --git a/tests/Toolbox.Tests/Fluent/FakedExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/FakedExtensionsTests.cs new file mode 100644 index 00000000..75f7fcfd --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/FakedExtensionsTests.cs @@ -0,0 +1,39 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.Fluent; + +#pragma warning disable RCS1021 // Expression-bodied lambda creates incorrect type. + +public sealed class FakedExtensionsTests() : AutoTester(typeof(FakedExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = + [ + typeof(InvalidOperationException), + typeof(InvalidCastException), + ], + }; + + [Theory, RandomData] + internal static void SetupReturn_WorksForVoidMethods([Fake] IDisposable disposable) + { + bool called = false; + + disposable.SetupReturn( + x => x.Dispose(), + Behavior.Call(() => + { + called = true; + }) + ); + + disposable.Dispose(); + called.Assert().Is(true); + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncEnumerableExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncEnumerableExtensionsTests.cs new file mode 100644 index 00000000..849b3f38 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncEnumerableExtensionsTests.cs @@ -0,0 +1,378 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertAsyncUnwrapping; + +public sealed class TaskAssertAsyncEnumerableExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertAsyncEnumerableExtensionsTests() + : base(typeof(TaskAssertAsyncEnumerableExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertAsyncEnumerableExtensions_MatchesEveryMethod() + { + typeof(AssertAsyncEnumerableBase<,>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Where(x => x != nameof(AssertAsyncEnumerableBase<,>.ThrowsAsync)) + .Assert() + .Is( + typeof(TaskAssertAsyncEnumerableExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task TaskAssertAsyncEnumerableExtensions_ObjectExtensionsWork( + IAsyncEnumerable sampleA, + IAsyncEnumerable sampleB + ) + { + await Task.FromResult(sampleA.Assert()).Is(sampleA); + await Task.FromResult(sampleA.Assert()) + .IsNotAsync(sampleB, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal async Task IsEmptyAsync_Forwarded( + [Size(0)] IAsyncEnumerable valid, + [Size(1)] IAsyncEnumerable invalid + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(valid.Assert()).IsEmptyAsync(canceler); + await Task.FromResult(valid.Assert()).IsEmptyAsync(canceler, _mod); + await Task.FromResult(invalid.Assert()) + .IsEmptyAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(invalid.Assert()) + .IsEmptyAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await Task.FromResult(AsyncSeriesHelper.CreateCancelingIterationAsync(source).Assert()) + .IsEmptyAsync(source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsNotEmptyAsync_Forwarded( + [Size(1)] IAsyncEnumerable valid, + [Size(0)] IAsyncEnumerable invalid + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(valid.Assert()).IsNotEmptyAsync(canceler); + await Task.FromResult(valid.Assert()).IsNotEmptyAsync(canceler, _mod); + await Task.FromResult(invalid.Assert()) + .IsNotEmptyAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(invalid.Assert()) + .IsNotEmptyAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + await Task.FromResult(valid.Assert()) + .IsNotEmptyAsync(new CancellationToken(true)) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountAsync(1, canceler); + await Task.FromResult(data.Assert()).HasCountAsync(1, canceler, _mod); + await Task.FromResult(data.Assert()) + .HasCountAsync(0, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountAsync(2, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await Task.FromResult(AsyncSeriesHelper.CreateCancelingIterationAsync(source).Assert()) + .HasCountAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountLessThanAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountLessThanAsync(2, canceler); + await Task.FromResult(data.Assert()).HasCountLessThanAsync(2, canceler, _mod); + await Task.FromResult(data.Assert()) + .HasCountLessThanAsync(1, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountLessThanAsync(0, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await Task.FromResult(AsyncSeriesHelper.CreateCancelingIterationAsync(source).Assert()) + .HasCountLessThanAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountLessOrExactlyAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountLessOrExactlyAsync(2, canceler); + await Task.FromResult(data.Assert()).HasCountLessOrExactlyAsync(1, canceler, _mod); + await Task.FromResult(data.Assert()) + .HasCountLessOrExactlyAsync(0, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountLessOrExactlyAsync(0, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await Task.FromResult(AsyncSeriesHelper.CreateCancelingIterationAsync(source).Assert()) + .HasCountLessOrExactlyAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountMoreThanAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountMoreThanAsync(0, canceler); + await Task.FromResult(data.Assert()).HasCountMoreThanAsync(0, canceler, _mod); + await Task.FromResult(data.Assert()) + .HasCountMoreThanAsync(1, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountMoreThanAsync(2, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await Task.FromResult(AsyncSeriesHelper.CreateCancelingIterationAsync(source).Assert()) + .HasCountMoreThanAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountMoreOrExactlyAsync_Forwarded([Size(1)] IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountMoreOrExactlyAsync(0, canceler); + await Task.FromResult(data.Assert()).HasCountMoreOrExactlyAsync(1, canceler, _mod); + await Task.FromResult(data.Assert()) + .HasCountMoreOrExactlyAsync(2, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountMoreOrExactlyAsync(2, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await Task.FromResult(AsyncSeriesHelper.CreateCancelingIterationAsync(source).Assert()) + .HasCountMoreOrExactlyAsync(0, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsAsync_Forwarded(int valid, int invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IAsyncEnumerable data = AsyncSeriesHelper.CreateFromAsync([valid], 1); + + await Task.FromResult(data.Assert()).ContainsAsync(valid, canceler); + await Task.FromResult(data.Assert()).ContainsAsync(valid, canceler, _mod); + await Task.FromResult(data.Assert()) + .ContainsAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ContainsAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await Task.FromResult(AsyncSeriesHelper.CreateCancelingIterationAsync(source).Assert()) + .ContainsAsync(valid, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsNotAsync_Forwarded(int valid, int invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IAsyncEnumerable data = AsyncSeriesHelper.CreateFromAsync([invalid], 1); + + await Task.FromResult(data.Assert()).ContainsNotAsync(valid, canceler); + await Task.FromResult(data.Assert()).ContainsNotAsync(valid, canceler, _mod); + await Task.FromResult(data.Assert()) + .ContainsNotAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ContainsNotAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + using CancellationTokenSource source = new(); + await Task.FromResult(AsyncSeriesHelper.CreateCancelingIterationAsync(source).Assert()) + .ContainsNotAsync(valid, source.Token) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task FailAsync_Forwarded(IAsyncEnumerable data, [Fake] IAsserter asserter) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet silentFailSet = MakeSet(asserter); + + await Task.FromResult(data.Assert(silentFailSet)).FailAsync(canceler); + await Task.FromResult(data.Assert(silentFailSet)).FailAsync(canceler, _mod); + await Task.FromResult(data.Assert()) + .FailAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .FailAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal async Task DebugAsync_Forwarded(IAsyncEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet debugPassSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = false }) + ); + ToolSet debugFailSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = true }) + ); + + await Task.FromResult(data.Assert(debugPassSet)).DebugAsync(canceler); + await Task.FromResult(data.Assert(debugPassSet)).DebugAsync(canceler, _mod); + await Task.FromResult(data.Assert(debugFailSet)) + .DebugAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert(debugFailSet)) + .DebugAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsExceptionAsync_Forwarded(IAsyncEnumerable data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async IAsyncEnumerable thrower() + { + yield return 1; + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(thrower().Assert()).ThrowsExceptionAsync(canceler); + await Task.FromResult(thrower().Assert()).ThrowsExceptionAsync(canceler, _mod); + await Task.FromResult(data.Assert()) + .ThrowsExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ThrowsExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + private static ToolSet MakeSet(IAsserter asserter) + { + return new( + Tools.Gen, + Tools.Valuer, + Tools.Faker, + Tools.Randomizer, + Tools.Extractor, + Tools.Mutator, + asserter, + Tools.Duplicator, + Tools.Runner, + Tools.Tester + ); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncObjectExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncObjectExtensionsTests.cs new file mode 100644 index 00000000..d5f9359d --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertAsyncObjectExtensionsTests.cs @@ -0,0 +1,226 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertAsyncUnwrapping; + +public sealed class TaskAssertAsyncObjectExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = [typeof(AssertException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertAsyncObjectExtensionsTests() + : base(typeof(TaskAssertAsyncObjectExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertAsyncObjectExtensions_MatchesEveryMethod() + { + typeof(AssertAsyncObjectBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertAsyncObjectExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Where(m => m != nameof(AssertObjectBase<>.IsA)) + .Where(m => m != nameof(AssertObjectBase<>.Inherits)) + .Where(m => m != nameof(AssertObjectBase<>.InheritedBy)) + ); + } + + [Theory, RandomData] + internal async Task IsAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).IsAsync(clone, canceler); + await Task.FromResult(data.Assert()).IsAsync(clone, canceler, _mod); + await Task.FromResult(data.Assert()) + .IsAsync(variant, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .IsAsync(variant, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsNotAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).IsNotAsync(variant, canceler); + await Task.FromResult(data.Assert()).IsNotAsync(variant, canceler, _mod); + await Task.FromResult(data.Assert()) + .IsNotAsync(clone, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .IsNotAsync(clone, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ValuesEqualAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).ValuesEqualAsync(clone, canceler); + await Task.FromResult(data.Assert()).ValuesEqualAsync(clone, canceler, _mod); + await Task.FromResult(data.Assert()) + .ValuesEqualAsync(variant, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ValuesEqualAsync(variant, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ValuesNotEqualAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + AsyncDataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).ValuesNotEqualAsync(variant, canceler); + await Task.FromResult(data.Assert()).ValuesNotEqualAsync(variant, canceler, _mod); + await Task.FromResult(data.Assert()) + .ValuesNotEqualAsync(clone, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ValuesNotEqualAsync(clone, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task UniqueFromAsync_Forwarded( + AsyncDataSample data, + [Copy] AsyncDataSample clone, + [Unique] AsyncDataSample unique + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).UniqueFromAsync(unique, canceler); + await Task.FromResult(data.Assert()).UniqueFromAsync(unique, canceler, _mod); + await Task.FromResult(data.Assert()) + .UniqueFromAsync(clone, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .UniqueFromAsync(clone, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsA_Forwarded([Fake] IParentType parent, [Fake] IChildType child) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(child.Assert()).IsA(); + await Task.FromResult(child.Assert()).IsA(_mod); + await Task.FromResult(parent.Assert()) + .IsA() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(parent.Assert()) + .IsA(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task Inherits_Forwarded([Fake] IParentType parent, [Fake] IChildType child) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(child.Assert()).Inherits(); + await Task.FromResult(child.Assert()).Inherits(_mod); + await Task.FromResult(parent.Assert()) + .Inherits() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(parent.Assert()) + .Inherits(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task InheritedBy_Forwarded([Fake] IChildType child) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + Type parentType = typeof(IParentType); + + await Task.FromResult(parentType.Assert()).InheritedBy(); + await Task.FromResult(parentType.Assert()).InheritedBy(_mod); + await Task.FromResult(child.Assert()) + .InheritedBy() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(child.Assert()) + .InheritedBy(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericTaskExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericTaskExtensionsTests.cs new file mode 100644 index 00000000..5ed4c008 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericTaskExtensionsTests.cs @@ -0,0 +1,101 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertAsyncUnwrapping; + +public sealed class TaskAssertGenericTaskExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertGenericTaskExtensionsTests() + : base(typeof(TaskAssertGenericTaskExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertGenericTaskExtensions_MatchesEveryMethod() + { + typeof(AssertGenericTaskBase<,>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertGenericTaskExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task HasResultAsync_WithMatchForwarded(string value, string variant) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task getValue() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + return value; + } + + await Task.FromResult(getValue().Assert()).HasResultAsync(value, canceler); + await Task.FromResult(getValue().Assert()).HasResultAsync(value, canceler, _mod); + await Task.FromResult(getValue().Assert()) + .HasResultAsync(variant, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(getValue().Assert()) + .HasResultAsync(variant, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasResultAsync_Forwarded( + Task dataA, + Task dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(dataA.Assert()).HasResultAsync(canceler); + await Task.FromResult(dataB.Assert()).HasResultAsync(canceler, _mod); + await Task.FromResult(thrower().Assert()) + .HasResultAsync(canceler) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + await Task.FromResult(thrower().Assert()) + .HasResultAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericValueTaskExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericValueTaskExtensionsTests.cs new file mode 100644 index 00000000..d120a51e --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertGenericValueTaskExtensionsTests.cs @@ -0,0 +1,170 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertAsyncUnwrapping; + +public sealed class TaskAssertGenericValueTaskExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(AssertException), + typeof(ValueTaskRepeatedAccessException), + ], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertGenericValueTaskExtensionsTests() + : base(typeof(TaskAssertGenericValueTaskExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertGenericValueTaskExtensions_MatchesEveryMethod() + { + typeof(AssertGenericValueTaskBase<,>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Where(m => m != nameof(AssertGenericTaskBase<,>.ThrowsAsync)) + .Where(m => m != nameof(AssertGenericTaskBase<,>.ThrowsNoAsync)) + .Assert() + .Is( + typeof(TaskAssertGenericValueTaskExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task HasResultAsync_WithMatchForwarded(string value, string variant) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask getValue() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + return value; + } + + await Task.FromResult(getValue().Assert()).HasResultAsync(value, canceler); + await Task.FromResult(getValue().Assert()).HasResultAsync(value, canceler, _mod); + await Task.FromResult(getValue().Assert()) + .HasResultAsync(variant, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(getValue().Assert()) + .HasResultAsync(variant, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasResultAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(dataA.Assert()).HasResultAsync(canceler); + await Task.FromResult(dataB.Assert()).HasResultAsync(canceler, _mod); + await Task.FromResult(thrower().Assert()) + .HasResultAsync(canceler) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + await Task.FromResult(thrower().Assert()) + .HasResultAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler) + .That() + .Is(error); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsExceptionAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(thrower().Assert()).ThrowsExceptionAsync(canceler); + await Task.FromResult(thrower().Assert()).ThrowsExceptionAsync(canceler, _mod); + await Task.FromResult(dataA.Assert()) + .ThrowsExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(dataB.Assert()) + .ThrowsExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoExceptionAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(dataA.Assert()).ThrowsNoExceptionAsync(canceler); + await Task.FromResult(dataB.Assert()).ThrowsNoExceptionAsync(canceler, _mod); + await Task.FromResult(thrower().Assert()) + .ThrowsNoExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower().Assert()) + .ThrowsNoExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertTaskExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertTaskExtensionsTests.cs new file mode 100644 index 00000000..32061536 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertTaskExtensionsTests.cs @@ -0,0 +1,142 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertAsyncUnwrapping; + +public sealed class TaskAssertTaskExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertTaskExtensionsTests() + : base(typeof(TaskAssertTaskExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertTaskExtensions_MatchesEveryMethod() + { + typeof(AssertTaskBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertTaskExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task ThrowsAsync_Forwarded(Task data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(thrower().Assert()).ThrowsAsync(canceler); + await Task.FromResult(thrower().Assert()).ThrowsAsync(canceler, _mod); + await Task.FromResult(data.Assert()) + .ThrowsAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ThrowsAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsExceptionAsync_Forwarded(Task data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(thrower().Assert()).ThrowsExceptionAsync(canceler); + await Task.FromResult(thrower().Assert()).ThrowsExceptionAsync(canceler, _mod); + await Task.FromResult(data.Assert()) + .ThrowsExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ThrowsExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoAsync_Forwarded(Task data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(data.Assert()).ThrowsNoAsync(canceler); + await Task.FromResult(data.Assert()).ThrowsNoAsync(canceler, _mod); + await Task.FromResult(thrower().Assert()) + .ThrowsNoAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower().Assert()) + .ThrowsNoAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoExceptionAsync_Forwarded(Task data, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async Task thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(data.Assert()).ThrowsNoExceptionAsync(canceler); + await Task.FromResult(data.Assert()).ThrowsNoExceptionAsync(canceler, _mod); + await Task.FromResult(thrower().Assert()) + .ThrowsNoExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower().Assert()) + .ThrowsNoExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertValueTaskExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertValueTaskExtensionsTests.cs new file mode 100644 index 00000000..c29741eb --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertAsyncUnwrapping/TaskAssertValueTaskExtensionsTests.cs @@ -0,0 +1,150 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertAsyncUnwrapping; + +public sealed class TaskAssertValueTaskExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertValueTaskExtensionsTests() + : base(typeof(TaskAssertValueTaskExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertValueTaskExtensions_MatchesEveryMethod() + { + typeof(AssertValueTaskBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertValueTaskExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task ThrowsAsync_Forwarded(ValueTask dataA, ValueTask dataB, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(thrower().Assert()).ThrowsAsync(canceler); + await Task.FromResult(thrower().Assert()).ThrowsAsync(canceler, _mod); + await Task.FromResult(dataA.Assert()) + .ThrowsAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(dataB.Assert()) + .ThrowsAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsExceptionAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(thrower().Assert()).ThrowsExceptionAsync(canceler); + await Task.FromResult(thrower().Assert()).ThrowsExceptionAsync(canceler, _mod); + await Task.FromResult(dataA.Assert()) + .ThrowsExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(dataB.Assert()) + .ThrowsExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoAsync_Forwarded(ValueTask dataA, ValueTask dataB, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(dataA.Assert()).ThrowsNoAsync(canceler); + await Task.FromResult(dataB.Assert()).ThrowsNoAsync(canceler, _mod); + await Task.FromResult(thrower().Assert()) + .ThrowsNoAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower().Assert()) + .ThrowsNoAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoExceptionAsync_Forwarded( + ValueTask dataA, + ValueTask dataB, + Exception error + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + async ValueTask thrower() + { + await Task.Delay(0, canceler).ConfigureAwait(false); + throw error; + } + + await Task.FromResult(dataA.Assert()).ThrowsNoExceptionAsync(canceler); + await Task.FromResult(dataB.Assert()).ThrowsNoExceptionAsync(canceler, _mod); + await Task.FromResult(thrower().Assert()) + .ThrowsNoExceptionAsync(canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower().Assert()) + .ThrowsNoExceptionAsync(canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertActionExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertActionExtensionsTests.cs new file mode 100644 index 00000000..f7b29b37 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertActionExtensionsTests.cs @@ -0,0 +1,128 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertUnwrapping; + +public sealed class TaskAssertActionExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(AssertException), typeof(ArgumentException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertActionExtensionsTests() + : base(typeof(TaskAssertActionExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertActionExtensions_MatchesEveryMethod() + { + typeof(AssertActionBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertActionExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task Throws_Forwarded(Action behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Action thrower = () => throw error; + + await Task.FromResult(thrower.Assert()).Throws(); + await Task.FromResult(thrower.Assert()).Throws(_mod); + + await Task.FromResult(behavior.Assert()) + .Throws() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(behavior.Assert()) + .Throws(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsException_Forwarded(Action behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Action thrower = () => throw error; + + await Task.FromResult(thrower.Assert()).ThrowsException(); + await Task.FromResult(thrower.Assert()).ThrowsException(_mod); + + await Task.FromResult(behavior.Assert()) + .ThrowsException() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(behavior.Assert()) + .ThrowsException(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNo_Forwarded(Action behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Action thrower = () => throw error; + + await Task.FromResult(behavior.Assert()).ThrowsNo(); + await Task.FromResult(behavior.Assert()).ThrowsNo(_mod); + await Task.FromResult(thrower.Assert()) + .ThrowsNo() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower.Assert()) + .ThrowsNo(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoException_Forwarded(Action behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Action thrower = () => throw error; + + await Task.FromResult(behavior.Assert()).ThrowsNoException(); + await Task.FromResult(behavior.Assert()).ThrowsNoException(_mod); + await Task.FromResult(thrower.Assert()) + .ThrowsNoException() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower.Assert()) + .ThrowsNoException(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertComparableExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertComparableExtensionsTests.cs new file mode 100644 index 00000000..1814df70 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertComparableExtensionsTests.cs @@ -0,0 +1,214 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertUnwrapping; + +public sealed class TaskAssertComparableExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(AssertException), typeof(ArgumentException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertComparableExtensionsTests() + : base(typeof(TaskAssertComparableExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertComparableExtensions_MatchesEveryMethod() + { + typeof(AssertComparableBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertComparableExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task GreaterThan_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).GreaterThan(less); + await Task.FromResult(data.Assert()).GreaterThan(less, _mod); + await Task.FromResult(data.Assert()) + .GreaterThan(same) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .GreaterThan(more, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task GreaterThanOrEqualTo_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).GreaterThanOrEqualTo(less); + await Task.FromResult(data.Assert()).GreaterThanOrEqualTo(same, _mod); + await Task.FromResult(data.Assert()) + .GreaterThanOrEqualTo(more) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .GreaterThanOrEqualTo(more, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task GreaterThanOrIs_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).GreaterThanOrIs(less); + await Task.FromResult(data.Assert()).GreaterThanOrIs(same, _mod); + await Task.FromResult(data.Assert()) + .GreaterThanOrIs(more) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .GreaterThanOrIs(more, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task LessThan_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).LessThan(more); + await Task.FromResult(data.Assert()).LessThan(more, _mod); + await Task.FromResult(data.Assert()) + .LessThan(same) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .LessThan(less, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task LessThanOrEqualTo_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).LessThanOrEqualTo(more); + await Task.FromResult(data.Assert()).LessThanOrEqualTo(same, _mod); + await Task.FromResult(data.Assert()) + .LessThanOrEqualTo(less) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .LessThanOrEqualTo(less, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task LessThanOrIs_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).LessThanOrIs(more); + await Task.FromResult(data.Assert()).LessThanOrIs(same, _mod); + await Task.FromResult(data.Assert()) + .LessThanOrIs(less) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .LessThanOrIs(less, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task InRange_Forwarded( + [Cap(3, 5)] int data, + [Copy] int same, + [Cap(6, 8)] int more, + [Cap(0, 2)] int less + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).InRange(less, same); + await Task.FromResult(data.Assert()).InRange(same, more, _mod); + await Task.FromResult(data.Assert()) + .InRange(less, less) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .InRange(more, more, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertDelegateExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertDelegateExtensionsTests.cs new file mode 100644 index 00000000..a125266a --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertDelegateExtensionsTests.cs @@ -0,0 +1,191 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertUnwrapping; + +public sealed class TaskAssertDelegateExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(AssertException), typeof(ArgumentException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertDelegateExtensionsTests() + : base(typeof(TaskAssertDelegateExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertDelegateExtensions_MatchesEveryMethod() + { + typeof(AssertDelegateBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertDelegateExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task HasResult_ForwardedPlain(string data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Delegate behavior = () => data; + + await Task.FromResult(behavior.Assert()).HasResult(); + await Task.FromResult(behavior.Assert()).HasResult(_mod); + + await Task.FromResult(behavior.Assert()) + .HasResult() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(behavior.Assert()) + .HasResult(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasResult_Forwarded(string valid, string invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Delegate behavior = () => valid; + + await Task.FromResult(behavior.Assert()).HasResult(valid); + await Task.FromResult(behavior.Assert()).HasResult(valid, _mod); + + await Task.FromResult(behavior.Assert()) + .HasResult(invalid) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(behavior.Assert()) + .HasResult(invalid, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasResultAsync_Forwarded(string valid, string invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Delegate behavior = () => valid; + + await Task.FromResult(behavior.Assert()).HasResultAsync(valid, canceler); + await Task.FromResult(behavior.Assert()).HasResultAsync(valid, canceler, _mod); + + await Task.FromResult(behavior.Assert()) + .HasResultAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(behavior.Assert()) + .HasResultAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task Throws_Forwarded(Delegate behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Delegate thrower = (Action)(() => throw error); + + await Task.FromResult(thrower.Assert()).Throws(); + await Task.FromResult(thrower.Assert()).Throws(_mod); + + await Task.FromResult(behavior.Assert()) + .Throws() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(behavior.Assert()) + .Throws(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsException_Forwarded(Func behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Func thrower = () => throw error; + + await Task.FromResult(thrower.Assert()).ThrowsException(); + await Task.FromResult(thrower.Assert()).ThrowsException(_mod); + + await Task.FromResult(behavior.Assert()) + .ThrowsException() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(behavior.Assert()) + .ThrowsException(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNo_Forwarded(Delegate behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Delegate thrower = (Action)(() => throw error); + + await Task.FromResult(behavior.Assert()).ThrowsNo(); + await Task.FromResult(behavior.Assert()).ThrowsNo(_mod); + await Task.FromResult(thrower.Assert()) + .ThrowsNo() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower.Assert()) + .ThrowsNo(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ThrowsNoException_Forwarded(Func behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Func thrower = () => throw error; + + await Task.FromResult(behavior.Assert()).ThrowsNoException(); + await Task.FromResult(behavior.Assert()).ThrowsNoException(_mod); + await Task.FromResult(thrower.Assert()) + .ThrowsNoException() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower.Assert()) + .ThrowsNoException(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertEnumerableExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertEnumerableExtensionsTests.cs new file mode 100644 index 00000000..01cfda97 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertEnumerableExtensionsTests.cs @@ -0,0 +1,337 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertUnwrapping; + +public sealed class TaskAssertEnumerableExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertEnumerableExtensionsTests() + : base(typeof(TaskAssertEnumerableExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertEnumerableExtensions_MatchesEveryMethod() + { + typeof(AssertEnumerableBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertEnumerableExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task TaskAssertEnumerableExtensions_ObjectExtensionsWork( + IEnumerable sampleA, + IEnumerable sampleB + ) + { + await Task.FromResult(sampleA.Assert()).Is(sampleA); + await Task.FromResult(sampleA.Assert()) + .IsNotAsync(sampleB, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal async Task IsEmpty_Forwarded( + [Size(0)] IEnumerable valid, + [Size(1)] IEnumerable invalid + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(valid.Assert()).IsEmpty(); + await Task.FromResult(valid.Assert()).IsEmpty(_mod); + await Task.FromResult(invalid.Assert()) + .IsEmpty() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(invalid.Assert()) + .IsEmpty(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsNotEmpty_Forwarded( + [Size(1)] IEnumerable valid, + [Size(0)] IEnumerable invalid + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(valid.Assert()).IsNotEmpty(); + await Task.FromResult(valid.Assert()).IsNotEmpty(_mod); + await Task.FromResult(invalid.Assert()) + .IsNotEmpty() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(invalid.Assert()) + .IsNotEmpty(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCount_Forwarded([Size(1)] IEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCount(1); + await Task.FromResult(data.Assert()).HasCount(1, _mod); + await Task.FromResult(data.Assert()) + .HasCount(0) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCount(2, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountLessThan_Forwarded([Size(1)] IEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountLessThan(2); + await Task.FromResult(data.Assert()).HasCountLessThan(2, _mod); + await Task.FromResult(data.Assert()) + .HasCountLessThan(1) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountLessThan(0, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountLessOrExactly_Forwarded([Size(1)] IEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountLessOrExactly(2); + await Task.FromResult(data.Assert()).HasCountLessOrExactly(1, _mod); + await Task.FromResult(data.Assert()) + .HasCountLessOrExactly(0) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountLessOrExactly(0, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountMoreThan_Forwarded([Size(1)] IEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountMoreThan(0); + await Task.FromResult(data.Assert()).HasCountMoreThan(0, _mod); + await Task.FromResult(data.Assert()) + .HasCountMoreThan(1) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountMoreThan(2, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task HasCountMoreOrExactly_Forwarded([Size(1)] IEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).HasCountMoreOrExactly(0); + await Task.FromResult(data.Assert()).HasCountMoreOrExactly(1, _mod); + await Task.FromResult(data.Assert()) + .HasCountMoreOrExactly(2) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .HasCountMoreOrExactly(2, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task Contains_Forwarded(int valid, int invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IEnumerable data = [valid]; + + await Task.FromResult(data.Assert()).Contains(valid); + await Task.FromResult(data.Assert()).Contains(valid, _mod); + await Task.FromResult(data.Assert()) + .Contains(invalid) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Contains(invalid, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsAsync_Forwarded(AsyncDataSample valid, AsyncDataSample invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IEnumerable data = [valid]; + + await Task.FromResult(data.Assert()).ContainsAsync(valid, canceler); + await Task.FromResult(data.Assert()).ContainsAsync(valid, canceler, _mod); + await Task.FromResult(data.Assert()) + .ContainsAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ContainsAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsNot_Forwarded(int valid, int invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IEnumerable data = [invalid]; + + await Task.FromResult(data.Assert()).ContainsNot(valid); + await Task.FromResult(data.Assert()).ContainsNot(valid, _mod); + await Task.FromResult(data.Assert()) + .ContainsNot(invalid) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ContainsNot(invalid, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ContainsNotAsync_Forwarded(AsyncDataSample valid, AsyncDataSample invalid) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + IEnumerable data = [invalid]; + + await Task.FromResult(data.Assert()).ContainsNotAsync(valid, canceler); + await Task.FromResult(data.Assert()).ContainsNotAsync(valid, canceler, _mod); + await Task.FromResult(data.Assert()) + .ContainsNotAsync(invalid, canceler) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ContainsNotAsync(invalid, canceler, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task Fail_Forwarded(IEnumerable data, [Fake] IAsserter asserter) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet silentFailSet = MakeSet(asserter); + + await Task.FromResult(data.Assert(silentFailSet)).Fail(); + await Task.FromResult(data.Assert(silentFailSet)).Fail(_mod); + await Task.FromResult(data.Assert()).Fail().Assert().ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Fail(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal async Task Debug_Forwarded(IEnumerable data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet debugPassSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = false }) + ); + ToolSet debugFailSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = true }) + ); + + await Task.FromResult(data.Assert(debugPassSet)).Debug(); + await Task.FromResult(data.Assert(debugPassSet)).Debug(_mod); + await Task.FromResult(data.Assert(debugFailSet)) + .Debug() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert(debugFailSet)) + .Debug(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + private static ToolSet MakeSet(IAsserter asserter) + { + return new( + Tools.Gen, + Tools.Valuer, + Tools.Faker, + Tools.Randomizer, + Tools.Extractor, + Tools.Mutator, + asserter, + Tools.Duplicator, + Tools.Runner, + Tools.Tester + ); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertErrorExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertErrorExtensionsTests.cs new file mode 100644 index 00000000..5903b512 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertErrorExtensionsTests.cs @@ -0,0 +1,122 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertUnwrapping; + +public sealed class TaskAssertErrorExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertErrorExtensionsTests() + : base(typeof(TaskAssertErrorExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertErrorExtensions_MatchesEveryMethod() + { + typeof(AssertErrorBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertErrorExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Where(m => m != nameof(AssertObjectBase<>.Inherits)) + ); + } + + [Theory, RandomData] + internal async Task Inherits_Forwarded(AggregateException error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(error.Assert()).Inherits(); + await Task.FromResult(error.Assert()).Inherits(_mod); + await Task.FromResult(error.Assert()) + .Inherits() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(error.Assert()) + .Inherits(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task Fail_Forwarded(Exception data, [Fake] IAsserter asserter) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet silentFailSet = MakeSet(asserter); + + await Task.FromResult(data.Assert(silentFailSet)).Fail(); + await Task.FromResult(data.Assert(silentFailSet)).Fail(_mod); + await Task.FromResult(data.Assert()).Fail().Assert().ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Fail(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal async Task Debug_Forwarded(Exception data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet debugPassSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = false }) + ); + ToolSet debugFailSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = true }) + ); + + await Task.FromResult(data.Assert(debugPassSet)).Debug(); + await Task.FromResult(data.Assert(debugPassSet)).Debug(_mod); + await Task.FromResult(data.Assert(debugFailSet)) + .Debug() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert(debugFailSet)) + .Debug(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + private static ToolSet MakeSet(IAsserter asserter) + { + return new( + Tools.Gen, + Tools.Valuer, + Tools.Faker, + Tools.Randomizer, + Tools.Extractor, + Tools.Mutator, + asserter, + Tools.Duplicator, + Tools.Runner, + Tools.Tester + ); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertFuncExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertFuncExtensionsTests.cs new file mode 100644 index 00000000..d4cc22fc --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertFuncExtensionsTests.cs @@ -0,0 +1,67 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertUnwrapping; + +public sealed class TaskAssertFuncExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(AssertException), typeof(ArgumentException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertFuncExtensionsTests() + : base(typeof(TaskAssertFuncExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertFuncExtensions_MatchesEveryMethod() + { + typeof(AssertFuncBase<,>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertFuncExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task HasResult_Forwarded(Func behavior, Exception error) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + Func thrower = () => throw error; + + await Task.FromResult(behavior.Assert()).HasResult(); + await Task.FromResult(behavior.Assert()).HasResult(_mod); + + await Task.FromResult(thrower.Assert()) + .HasResult() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(thrower.Assert()) + .HasResult(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertObjectExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertObjectExtensionsTests.cs new file mode 100644 index 00000000..5852638b --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertObjectExtensionsTests.cs @@ -0,0 +1,420 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertUnwrapping; + +public sealed class TaskAssertObjectExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = [typeof(AssertException), typeof(ToolException)], + }; + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertObjectExtensionsTests() + : base(typeof(TaskAssertObjectExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertObjectExtensions_MatchesEveryMethod() + { + typeof(AssertObjectBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Where(x => x != nameof(ToString)) + .Distinct() + .Assert() + .Is( + typeof(TaskAssertObjectExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Distinct() + ); + } + + [Theory, RandomData] + internal async Task Is_Forwarded(DataSample data, [Copy] DataSample clone, DataSample variant) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).Is(clone); + await Task.FromResult(data.Assert()).Is(clone, _mod); + await Task.FromResult(data.Assert()) + .Is(variant) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Is(variant, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsNull_Forwarded(DataSample data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(((object)null).Assert()).IsNull(); + await Task.FromResult(((object)null).Assert()).IsNull(_mod); + await Task.FromResult(data.Assert()) + .IsNull() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .IsNull(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsNot_Forwarded( + DataSample data, + [Copy] DataSample clone, + DataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).IsNot(variant); + await Task.FromResult(data.Assert()).IsNot(variant, _mod); + await Task.FromResult(data.Assert()) + .IsNot(clone) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .IsNot(clone, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsNotNull_Forwarded(DataSample data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).IsNotNull(); + await Task.FromResult(data.Assert()).IsNotNull(_mod); + await Task.FromResult(((object)null).Assert()) + .IsNotNull() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(((object)null).Assert()) + .IsNotNull(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ReferenceEqual_Forwarded(DataSample data, [Copy] DataSample clone) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).ReferenceEqual(data); + await Task.FromResult(data.Assert()).ReferenceEqual(data, _mod); + await Task.FromResult(data.Assert()) + .ReferenceEqual(clone) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ReferenceEqual(clone, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ReferenceNotEqual_Forwarded(DataSample data, [Copy] DataSample clone) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).ReferenceNotEqual(clone); + await Task.FromResult(data.Assert()).ReferenceNotEqual(clone, _mod); + await Task.FromResult(data.Assert()) + .ReferenceNotEqual(data) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ReferenceNotEqual(data, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ValuesEqual_Forwarded( + DataSample data, + [Copy] DataSample clone, + DataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).ValuesEqual(clone); + await Task.FromResult(data.Assert()).ValuesEqual(clone, _mod); + await Task.FromResult(data.Assert()) + .ValuesEqual(variant) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ValuesEqual(variant, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task ValuesNotEqual_Forwarded( + DataSample data, + [Copy] DataSample clone, + DataSample variant + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).ValuesNotEqual(variant); + await Task.FromResult(data.Assert()).ValuesNotEqual(variant, _mod); + await Task.FromResult(data.Assert()) + .ValuesNotEqual(clone) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ValuesNotEqual(clone, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task UniqueFrom_Forwarded( + DataSample data, + [Copy] DataSample clone, + [Unique] DataSample unique + ) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(data.Assert()).UniqueFrom(unique); + await Task.FromResult(data.Assert()).UniqueFrom(unique, _mod); + await Task.FromResult(data.Assert()) + .UniqueFrom(clone) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .UniqueFrom(clone, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task IsA_Forwarded([Fake] IParentType parent, [Fake] IChildType child) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(new AssertObject(Tools.Asserter, child)).IsA(); + await Task.FromResult(new AssertObject(Tools.Asserter, child)).IsA(_mod); + await Task.FromResult(new AssertObject(Tools.Asserter, parent)) + .IsA() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(new AssertObject(Tools.Asserter, parent)) + .IsA(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task Inherits_Forwarded([Fake] IParentType parent, [Fake] IChildType child) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + await Task.FromResult(child.Assert()).Inherits(typeof(IParentType)); + await Task.FromResult(child.Assert()).Inherits(typeof(IParentType), _mod); + await Task.FromResult(parent.Assert()) + .Inherits(typeof(IChildType)) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(parent.Assert()) + .Inherits(typeof(IChildType), _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task InheritedBy_Forwarded([Fake] IChildType child) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + Type parentType = typeof(IParentType); + + await Task.FromResult(parentType.Assert()).InheritedBy(typeof(IChildType)); + await Task.FromResult(parentType.Assert()).InheritedBy(typeof(IChildType), _mod); + await Task.FromResult(child.Assert()) + .InheritedBy(typeof(IParentType)) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(child.Assert()) + .InheritedBy(typeof(IParentType), _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task Fail_Forwarded(DataSample data, [Fake] IAsserter asserter) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet silentFailSet = MakeSet(asserter); + + await Task.FromResult(data.Assert(silentFailSet)).Fail(); + await Task.FromResult(data.Assert(silentFailSet)).Fail(_mod); + await Task.FromResult(data.Assert()).Fail().Assert().ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Fail(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal async Task Debug_Forwarded(DataSample data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + ToolSet debugPassSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = false }) + ); + ToolSet debugFailSet = MakeSet( + Tools.Asserter.WithOptions(opt => opt with { TriggerFailureForDebugAsserts = true }) + ); + + await Task.FromResult(data.Assert(debugPassSet)).Debug(); + await Task.FromResult(data.Assert(debugPassSet)).Debug(_mod); + await Task.FromResult(data.Assert(debugFailSet)) + .Debug() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert(debugFailSet)) + .Debug(_mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(2); + } + + [Theory, RandomData] + internal async Task Pass_Forwarded(DataSample data) + { + await Task.FromResult(data.Assert()).Pass(); + await Task.FromResult(data.Assert()).Pass(_mod); + + _modCount.Assert().Is(1); + } + + [Theory, RandomData] + internal async Task Called_Forwarded([Fake] DataSample data, DataSample nonFake) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + data.ToString(); + + await Task.FromResult(data.Assert()).Called(); + await Task.FromResult(data.Assert()).Called(_mod); + await Task.FromResult(data.Assert()).Called(Times.Once); + await Task.FromResult(data.Assert()).Called(Times.Once, _mod); + + data.Equals(Arg.Any()).SetupReturn(Behavior.Throw()); + + await Task.FromResult(data.Assert()) + .Called() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Called(_mod) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Called(Times.Never) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Called(Times.Never, _mod) + .Assert() + .ThrowsAsync(canceler); + + await Task.FromResult(nonFake.Assert()) + .Called() + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(nonFake.Assert()) + .Called(_mod) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(nonFake.Assert()) + .Called(Times.Any) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(nonFake.Assert()) + .Called(Times.Any, _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(0); + } + + private static ToolSet MakeSet(IAsserter asserter) + { + return new( + Tools.Gen, + Tools.Valuer, + Tools.Faker, + Tools.Randomizer, + Tools.Extractor, + Tools.Mutator, + asserter, + Tools.Duplicator, + Tools.Runner, + Tools.Tester + ); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertStringExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertStringExtensionsTests.cs new file mode 100644 index 00000000..5a3c24bb --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskAssertUnwrapping/TaskAssertStringExtensionsTests.cs @@ -0,0 +1,236 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskAssertUnwrapping; + +public sealed class TaskAssertStringExtensionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + private static readonly char[] _Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); + + private int _modCount; + + private readonly AsserterMod _mod; + + public TaskAssertStringExtensionsTests() + : base(typeof(TaskAssertStringExtensions)) + { + _modCount = 0; + _mod = opt => + { + _modCount++; + return opt; + }; + } + + [Fact] + internal static void TaskAssertStringExtensions_MatchesEveryMethod() + { + typeof(AssertStringBase<>) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .OrderBy(m => m.Name) + .Select(m => m.Name) + .Assert() + .Is( + typeof(TaskAssertStringExtensions) + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .OrderBy(m => m.Name) + .Select(m => m.Name) + ); + } + + [Theory, RandomData] + internal async Task Contains_Forwarded(string data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + char someChar = Tools.Gen.NextItem(data); + char uniqueChar = Tools.Gen.NextItem(_Letters.Except(data)); + + await Task.FromResult(data.Assert()).Contains(someChar); + await Task.FromResult(data.Assert()).Contains(someChar, _mod); + await Task.FromResult(data.Assert()).Contains(someChar.ToString()); + await Task.FromResult(data.Assert()).Contains(someChar.ToString(), _mod); + await Task.FromResult(data.Assert()) + .Contains(uniqueChar) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Contains(uniqueChar, _mod) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Contains(uniqueChar.ToString()) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .Contains(uniqueChar.ToString(), _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal async Task ContainsNot_Forwarded(string data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + char someChar = Tools.Gen.NextItem(data); + char uniqueChar = Tools.Gen.NextItem(_Letters.Except(data)); + + await Task.FromResult(data.Assert()).ContainsNot(uniqueChar); + await Task.FromResult(data.Assert()).ContainsNot(uniqueChar, _mod); + await Task.FromResult(data.Assert()).ContainsNot(uniqueChar.ToString()); + await Task.FromResult(data.Assert()).ContainsNot(uniqueChar.ToString(), _mod); + await Task.FromResult(data.Assert()) + .ContainsNot(someChar) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ContainsNot(someChar, _mod) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ContainsNot(someChar.ToString()) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .ContainsNot(someChar.ToString(), _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal async Task StartsWith_Forwarded(string data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + char firstChar = data[0]; + char otherChar = firstChar.Tools().Variant(); + + await Task.FromResult(data.Assert()).StartsWith(firstChar); + await Task.FromResult(data.Assert()).StartsWith(firstChar, _mod); + await Task.FromResult(data.Assert()).StartsWith(firstChar.ToString()); + await Task.FromResult(data.Assert()).StartsWith(firstChar.ToString(), _mod); + await Task.FromResult(data.Assert()) + .StartsWith(otherChar) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .StartsWith(otherChar, _mod) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .StartsWith(otherChar.ToString()) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .StartsWith(otherChar.ToString(), _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal async Task StartsNotWith_Forwarded(string data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + char firstChar = data[0]; + char otherChar = firstChar.Tools().Variant(); + + await Task.FromResult(data.Assert()).StartsNotWith(otherChar); + await Task.FromResult(data.Assert()).StartsNotWith(otherChar, _mod); + await Task.FromResult(data.Assert()).StartsNotWith(otherChar.ToString()); + await Task.FromResult(data.Assert()).StartsNotWith(otherChar.ToString(), _mod); + await Task.FromResult(data.Assert()) + .StartsNotWith(firstChar) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .StartsNotWith(firstChar, _mod) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .StartsNotWith(firstChar.ToString()) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .StartsNotWith(firstChar.ToString(), _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal async Task EndsWith_Forwarded([Size(3)] string data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + char lastChar = data[2]; + char otherChar = lastChar.Tools().Variant(); + + await Task.FromResult(data.Assert()).EndsWith(lastChar); + await Task.FromResult(data.Assert()).EndsWith(lastChar, _mod); + await Task.FromResult(data.Assert()).EndsWith(lastChar.ToString()); + await Task.FromResult(data.Assert()).EndsWith(lastChar.ToString(), _mod); + await Task.FromResult(data.Assert()) + .EndsWith(otherChar) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .EndsWith(otherChar, _mod) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .EndsWith(otherChar.ToString()) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .EndsWith(otherChar.ToString(), _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(4); + } + + [Theory, RandomData] + internal async Task EndsNotWith_Forwarded([Size(3)] string data) + { + CancellationToken canceler = TestContext.Current.CancellationToken; + + char lastChar = data[2]; + char otherChar = lastChar.Tools().Variant(); + + await Task.FromResult(data.Assert()).EndsNotWith(otherChar); + await Task.FromResult(data.Assert()).EndsNotWith(otherChar, _mod); + await Task.FromResult(data.Assert()).EndsNotWith(otherChar.ToString()); + await Task.FromResult(data.Assert()).EndsNotWith(otherChar.ToString(), _mod); + await Task.FromResult(data.Assert()) + .EndsNotWith(lastChar) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .EndsNotWith(lastChar, _mod) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .EndsNotWith(lastChar.ToString()) + .Assert() + .ThrowsAsync(canceler); + await Task.FromResult(data.Assert()) + .EndsNotWith(lastChar.ToString(), _mod) + .Assert() + .ThrowsAsync(canceler); + + _modCount.Assert().Is(4); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskAlsoChainerExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskAlsoChainerExtensionsTests.cs new file mode 100644 index 00000000..f67da87b --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskAlsoChainerExtensionsTests.cs @@ -0,0 +1,167 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskChainingUnwrapping; + +public sealed class TaskAlsoChainerExtensionsTests() : AutoTester(typeof(TaskAlsoChainerExtensions)) +{ + [Theory, RandomData] + internal static void Also_HandlesCompiledAction(Task chainer, string data) + { + chainer.Also(() => data.Assert().Fail()).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_HandlesCompiledFunc(Task chainer, string data) + { + chainer.Also(() => data.Length).GetType().Assert().Inherits(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsIAsyncEnumerable( + Task chainer, + IAsyncEnumerable data + ) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void Also_SupportsSpecificIAsyncEnumerable( + Task chainer, + AsyncList data + ) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void Also_SupportsObject(Task chainer, object data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsUnknownObject(Task chainer, DataSample data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsGenericTask(Task chainer, Task data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void Also_SupportsGenericValueTask( + Task chainer, + ValueTask data + ) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void Also_SupportsNullableGenericValueTask( + Task chainer, + ValueTask? data + ) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void Also_SupportsTask(Task chainer, Task data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsValueTask(Task chainer, ValueTask data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsNullableValueTask(Task chainer, ValueTask? data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsAction(Task chainer, Action data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsIComparable(Task chainer, IComparable data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsInt(Task chainer, int data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsGenericIEnumerable( + Task chainer, + IEnumerable data + ) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsList(Task chainer, List data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsArray(Task chainer, string[] data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsIEnumerable(Task chainer, IEnumerable data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsException(Task chainer, Exception data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsSpecificException( + Task chainer, + ArgumentException data + ) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void Also_SupportsFunc(Task chainer, Func data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void Also_SupportsString(Task chainer, string data) + { + chainer.Also(() => data).GetType().Assert().Is(typeof(Task)); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskAssertChainerExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskAssertChainerExtensionsTests.cs new file mode 100644 index 00000000..61a3ed04 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskAssertChainerExtensionsTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskChainingUnwrapping; + +public sealed class TaskAssertChainerExtensionsTests() + : AutoTester(typeof(TaskAssertChainerExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + [Theory, RandomData] + internal static Task And_Chains(Task> chainer) + { + return chainer.And().Pass(); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskExceptionChainerExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskExceptionChainerExtensionsTests.cs new file mode 100644 index 00000000..4cff878c --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskExceptionChainerExtensionsTests.cs @@ -0,0 +1,195 @@ +using System.Collections; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskChainingUnwrapping; + +public sealed class TaskExceptionChainerExtensionsTests() + : AutoTester(typeof(TaskExceptionChainerExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + [Theory, RandomData] + internal static void With_HandlesCompiledAction( + Task> chainer, + string data + ) + { + chainer.With(_ => data.Assert().Fail()).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsIAsyncEnumerable( + Task> chainer, + IAsyncEnumerable data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsSpecificIAsyncEnumerable( + Task> chainer, + AsyncList data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsObject(Task> chainer, object data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsUnknownObject( + Task> chainer, + DataSample data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericTask( + Task> chainer, + Task data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericValueTask( + Task> chainer, + ValueTask data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsNullableGenericValueTask( + Task> chainer, + ValueTask? data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsTask(Task> chainer, Task data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsValueTask( + Task> chainer, + ValueTask data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsNullableValueTask( + Task> chainer, + ValueTask? data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsAction(Task> chainer, Action data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsIComparable( + Task> chainer, + IComparable data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsInt(Task> chainer, int data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericIEnumerable( + Task> chainer, + IEnumerable data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsList( + Task> chainer, + List data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsArray( + Task> chainer, + DataSample[] data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsIEnumerable( + Task> chainer, + IEnumerable data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsException(Task> chainer) + { + chainer.With(x => x.InnerException).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsSpecificException( + Task> chainer + ) + { + chainer.With(x => x).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsFunc( + Task> chainer, + Func data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsString(Task> chainer) + { + chainer.With(x => x.ToString()).GetType().Assert().Is(typeof(Task)); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskResultChainerExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskResultChainerExtensionsTests.cs new file mode 100644 index 00000000..6cc76a23 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskResultChainerExtensionsTests.cs @@ -0,0 +1,721 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Collections.Specialized; +using System.Numerics; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskChainingUnwrapping; + +public sealed class TaskResultChainerExtensionsTests() + : AutoTester(typeof(TaskResultChainerExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + [Theory, RandomData] + internal static void That_SupportsIAsyncEnumerable( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void That_SupportsAsyncList(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void That_SupportsIAsyncSet(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void That_SupportsAsyncHashSet( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void That_SupportsObject(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsUnknownObject(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericTask(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericValueTask(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableGenericValueTask( + Task?>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void That_SupportsTask(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsValueTask(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableValueTask(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsAction(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsIComparable(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsDelegate(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericIEnumerable( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericArray(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericICollection( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericIReadOnlyCollection( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericIList(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericList(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericQueue(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericStack(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericISet(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericHashSet(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericLinkedList( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericConcurrentQueue( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericConcurrentStack( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericFrozenSet( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableList( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableQueue( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableStack( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableHashSet( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableSortedSet( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericIDictionary( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericDictionary( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericConcurrentDictionary( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericFrozenDictionary( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableDictionary( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsGenericImmutableSortedDictionary( + Task>> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsIEnumerable(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsICollection(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsIDictionary(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsHashtable(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsSortedList(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsListDictionary(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsHybridDictionary( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsStringDictionary( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsOrderedDictionary( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNameValueCollection( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsArray(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsStack(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsQueue(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsArrayList(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsBitArray(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsStringCollection( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsException(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsAggregateException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsArgumentException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNotSupportedException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsInvalidOperationException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsAssertException(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsSystemException(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsTaskCanceledException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsOperationCanceledException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsFormatException(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsArgumentNullException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullReferenceException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsIndexOutOfRangeException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsInvalidCastException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsArgumentOutOfRangeException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsIOException(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsFileNotFoundException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsKeyNotFoundException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNotImplementedException( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsFunc(Task>> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void That_SupportsString(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsBool(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableBool(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsFloat(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableFloat(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsDouble(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableDouble(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsDecimal(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableDecimal(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsTimeSpan(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableTimeSpan(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsDateTime(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableDateTime(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsBigInteger(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableBigInteger(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsDateTimeOffset(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableDateTimeOffset( + Task> chainer + ) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsChar(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableChar(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsInt(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableInt(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsLong(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableLong(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsShort(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableShort(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsByte(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void That_SupportsNullableByte(Task> chainer) + { + chainer.That().GetType().Assert().Is(typeof(Task)); + } +} diff --git a/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskWithChainerExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskWithChainerExtensionsTests.cs new file mode 100644 index 00000000..1c88b41d --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/TaskChainingUnwrapping/TaskWithChainerExtensionsTests.cs @@ -0,0 +1,182 @@ +using System.Collections; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.AssertCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.Fluent.TaskChainingUnwrapping; + +public sealed class TaskWithChainerExtensionsTests() : AutoTester(typeof(TaskWithChainerExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + [Theory, RandomData] + internal static void With_HandlesCompiledAction( + Task> chainer, + string data + ) + { + chainer.With(_ => data.Assert().Fail()).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsIAsyncEnumerable( + Task> chainer, + IAsyncEnumerable data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsSpecificIAsyncEnumerable( + Task> chainer, + AsyncList data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsObject(Task> chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsUnknownObject(Task> chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericTask( + Task> chainer, + Task data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericValueTask( + Task> chainer, + ValueTask data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsNullableGenericValueTask( + Task> chainer, + ValueTask? data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsTask(Task> chainer, Task data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsValueTask(Task> chainer, ValueTask data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsNullableValueTask( + Task> chainer, + ValueTask? data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsAction(Task> chainer, Action data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsIComparable( + Task> chainer, + IComparable data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsDelegate(Task> chainer, Delegate data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsInt(Task> chainer) + { + chainer.With(x => x.NumberValue).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsGenericIEnumerable(Task> chainer) + { + chainer.With(x => x.CollectionValue).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsList(Task>> chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsArray(Task> chainer) + { + chainer.With(x => x).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsIEnumerable( + Task> chainer, + IEnumerable data + ) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsException(Task> chainer) + { + chainer.With(x => x.InnerException).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsSpecificException( + Task> chainer + ) + { + chainer.With(x => x.InnerException).GetType().Assert().Is(typeof(Task)); + } + + [Theory, RandomData] + internal static void With_SupportsFunc(Task> chainer, Func data) + { + chainer.With(_ => data).GetType().Assert().Is(typeof(Task>)); + } + + [Theory, RandomData] + internal static void With_SupportsString(Task> chainer) + { + chainer.With(x => x.ToString()).GetType().Assert().Is(typeof(Task)); + } +} diff --git a/tests/Toolbox.Tests/Fluent/Tooling/AsyncObjectToolsTests.cs b/tests/Toolbox.Tests/Fluent/Tooling/AsyncObjectToolsTests.cs new file mode 100644 index 00000000..c2416be2 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/Tooling/AsyncObjectToolsTests.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent.Tooling; + +namespace Werecodent.CreateAndFake.Tests.Fluent.Tooling; + +public sealed class AsyncObjectToolsTests() : AutoTester> +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ToolException)] }; + + public override Task Tester_ValueEqualityOverrideCheck() + { + return Task.CompletedTask; + } +} diff --git a/tests/Toolbox.Tests/Fluent/Tooling/ObjectToolsTests.cs b/tests/Toolbox.Tests/Fluent/Tooling/ObjectToolsTests.cs new file mode 100644 index 00000000..1b905c34 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/Tooling/ObjectToolsTests.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Fluent.Tooling; + +namespace Werecodent.CreateAndFake.Tests.Fluent.Tooling; + +public sealed class ObjectToolsTests : AutoTester> +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ToolException)] }; + + public override Task Tester_ValueEqualityOverrideCheck() + { + return Task.CompletedTask; + } +} diff --git a/tests/Toolbox.Tests/Fluent/Tooling/TypeToolsTests.cs b/tests/Toolbox.Tests/Fluent/Tooling/TypeToolsTests.cs new file mode 100644 index 00000000..06307410 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/Tooling/TypeToolsTests.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Fluent.Tooling; + +namespace Werecodent.CreateAndFake.Tests.Fluent.Tooling; + +public sealed class TypeToolsTests : AutoTester +{ + protected override TypeTools TestInstance { get; } = typeof(object).Tools(); + + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + MethodsToIgnore = [nameof(TypeTools.CallMethodsAsync)], + InjectionValues = [Tools.Gen.Next(5, 8)], + IgnorableExceptions = [typeof(ToolException), typeof(InvalidCastException)], + }; + + public override Task Tester_ValueEqualityOverrideCheck() + { + return Task.CompletedTask; + } +} diff --git a/tests/Toolbox.Tests/Fluent/ToolingExtensionsTests.cs b/tests/Toolbox.Tests/Fluent/ToolingExtensionsTests.cs new file mode 100644 index 00000000..c6a96900 --- /dev/null +++ b/tests/Toolbox.Tests/Fluent/ToolingExtensionsTests.cs @@ -0,0 +1,14 @@ +using Werecodent.CreateAndFake.Design.Exceptions; + +namespace Werecodent.CreateAndFake.Tests.Fluent; + +public sealed class ToolingExtensionsTests() : AutoTester(typeof(ToolingExtensions)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + IgnorableExceptions = [typeof(ToolException)], + }; +} diff --git a/tests/Toolbox.Tests/IssueReplication/.editorconfig b/tests/Toolbox.Tests/IssueReplication/.editorconfig new file mode 100644 index 00000000..23c1a341 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# Default severity for all analyzer diagnostics +dotnet_analyzer_diagnostic.severity = None diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue001Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue001Tests.cs new file mode 100644 index 00000000..032df264 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue001Tests.cs @@ -0,0 +1,26 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue001Tests +{ + internal sealed class Sample + { + public int Value { get; set; } + + public string Name { get; set; } + } + + [Theory, RandomData] + internal static void Issue001_CanCreateUniques(Sample original) + { + Sample unique = original.Tools().Unique(); + unique.Name.Assert().IsNot(original.Name); + unique.Value.Assert().IsNot(original.Value); + unique.Assert().UniqueFrom(original); + } + + [Theory, RandomData] + internal static void Issue001_CanCreateUniqueValues(int original) + { + original.Tools().Unique().Assert().IsNot(original); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue002Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue002Tests.cs new file mode 100644 index 00000000..a10e25ee --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue002Tests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue002Tests +{ + [Fact] + internal static void Issue002_CallDataEncapsulated() + { + typeof(CallData).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue003Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue003Tests.cs new file mode 100644 index 00000000..ea7af7bb --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue003Tests.cs @@ -0,0 +1,52 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue003Tests +{ + public abstract class RefHolder + { + public abstract int TestMethodA(out int value); + + public abstract int TestMethodB(ref int value); + } + + [Theory, RandomData] + internal static void Issue003_FakeHandlesOut(Fake sample, int testValue, int result) + { + sample.Setup( + d => d.TestMethodA(out Arg.AnyRef().Var), + Behavior.Call( + (OutRef v) => + { + v.Var = testValue; + return result; + } + ) + ); + + sample.Dummy.TestMethodA(out int newValue).Assert().Is(result); + sample.Verify(); + newValue.Assert().Is(testValue); + } + + [Theory, RandomData] + internal static void Issue003_FakeHandlesRef(Fake sample, int result) + { + int testValue = 0; + sample.Setup( + d => d.TestMethodB(ref Arg.AnyRef().Var), + Behavior.Call( + (OutRef v) => + { + v.Var -= 5; + return result; + } + ) + ); + + sample.Dummy.TestMethodB(ref testValue).Assert().Is(result); + sample.Verify(); + testValue.Assert().Is(-5); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue004Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue004Tests.cs new file mode 100644 index 00000000..f0f71e2c --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue004Tests.cs @@ -0,0 +1,114 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue004Tests +{ + public interface IBaseHolder + { + void GetValueUnset(); + } + + public abstract class BaseHolder + { + internal static readonly int _TestValue = Tools.Randomizer.Create(); + + public int ValueHolder { get; set; } + + public virtual int GetValueA() + { + return _TestValue; + } + + public virtual int GetValueB(int input) + { + return input; + } + + public virtual void GetValueC() + { + ValueHolder = _TestValue; + } + + public virtual void GetValueD(int input) + { + ValueHolder = input; + } + + public virtual T GetValueE(T input) + { + return input; + } + + public virtual void ThrowError(Exception e) + { + throw e; + } + + public abstract void GetValueUnset(); + } + + [Theory, RandomData] + internal static void Issue004_MockCanCallBaseA(Fake sample) + { + sample.Setup(d => d.GetValueA(), Behavior.Base()); + sample.Dummy.GetValueA().Assert().Is(BaseHolder._TestValue); + sample.Verify(); + } + + [Theory, RandomData] + internal static void Issue004_MockCanCallBaseB(Fake sample, int value) + { + sample.Setup(d => d.GetValueB(value), Behavior.Base()); + sample.Dummy.GetValueB(value).Assert().Is(value); + sample.Verify(); + } + + [Theory, RandomData] + internal static void Issue004_MockCanCallBaseC(Fake sample) + { + sample.Setup(d => d.GetValueC(), Behavior.Base()); + sample.Dummy.GetValueC(); + sample.Dummy.ValueHolder.Assert().Is(BaseHolder._TestValue); + sample.Verify(); + } + + [Theory, RandomData] + internal static void Issue004_MockCanCallBaseD(Fake sample, int value) + { + sample.Setup(d => d.GetValueD(value), Behavior.Base()); + sample.Dummy.GetValueD(value); + sample.Dummy.ValueHolder.Assert().Is(value); + sample.Verify(); + } + + [Theory, RandomData] + internal static void Issue004_MockCanCallBaseE(Fake sample, int value) + { + sample.Setup(d => d.GetValueE(value), Behavior.Base()); + sample.Dummy.GetValueE(value).Assert().Is(value); + sample.Verify(); + } + + [Theory, RandomData] + internal static void Issue004_MockCanCallBaseThrow(Fake sample, Exception e) + { + sample.Setup(d => d.ThrowError(e), Behavior.Base()); + sample.Dummy.Assert(x => x.ThrowError(e)).Throws().That().Is(e); + sample.Verify(); + } + + [Theory, RandomData] + internal static void Issue004_MockCallBaseAbstractInvalid(Fake sample) + { + sample.Setup(d => d.GetValueUnset(), Behavior.Base()); + sample.Dummy.Assert(x => x.GetValueUnset()).Throws(); + } + + [Theory, RandomData] + internal static void Issue004_MockCallBaseWrongTypeInvalid(Fake sample) + { + sample.Setup(d => d.GetValueUnset(), Behavior.Base()); + sample.Dummy.Assert(x => x.GetValueUnset()).Throws(); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue009Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue009Tests.cs new file mode 100644 index 00000000..887a4ba2 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue009Tests.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.Design.Data; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue009Tests +{ + internal sealed class Sample(string lastName) + { + public string FirstName { get; set; } + + public string _middleName = null; + + public string LastName { get; } = lastName; + } + + [Theory, RandomData] + internal static void Issue009_SmartDataIsUsed(Sample sample) + { + NameData.Values.Assert().Contains(sample.FirstName); + NameData.Values.Assert().Contains(sample._middleName); + NameData.Values.Assert().Contains(sample.LastName); + } + + [Theory, RandomData] + internal static void Issue009_SmartDataIsUsedForRandomData(string firstName) + { + NameData.Values.Assert().Contains(firstName); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue012Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue012Tests.cs new file mode 100644 index 00000000..57212022 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue012Tests.cs @@ -0,0 +1,23 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue012Tests +{ + public abstract class Sample + { + public abstract int Value(); + } + + [Theory, RandomData] + internal static void Issue012_RandomizedFake(Fake sample) + { + sample.Dummy.Value().Assert().IsNot(0); + } + + [Theory, RandomData] + internal static void Issue012_FakeImmutableResult(Fake sample) + { + sample.Tools().Copy().Dummy.Value().Assert().Is(sample.Dummy.Value()); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue015Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue015Tests.cs new file mode 100644 index 00000000..c4dcb0e6 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue015Tests.cs @@ -0,0 +1,35 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue015Tests +{ + internal static class Sample + { + public static void Bad(int[] value) + { + ArgumentGuard.ThrowIfNull(value, nameof(value)); + + value[0] = value[0].Tools().Variant(); + } + } + + [Fact] + internal static Task Issue015_GuardsParameterMutation() + { + return Tools + .Tester.PreventsParameterMutationAsync( + typeof(Sample), + TestContext.Current.CancellationToken, + opt => + opt with + { + DisableParameterMutationTests = false, + IncludeStaticMethods = true, + } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue016Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue016Tests.cs new file mode 100644 index 00000000..a863744d --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue016Tests.cs @@ -0,0 +1,25 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue016Tests +{ + internal sealed class Sample + { + public static int ValueA = 0; + + public int ValueB = 0; + + public static int ValueC { get; set; } = 0; + } + + [Theory, RandomData] + internal static void Issue016_StaticFieldsNotRandomized(Sample sample) + { + sample.ValueB.Assert().IsNot(0).Also(Sample.ValueA).Is(0); + } + + [Theory, RandomData] + internal static void Issue016_StaticPropertiesNotRandomized(Sample sample) + { + sample.ValueB.Assert().IsNot(0).Also(Sample.ValueC).Is(0); + } +} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue018Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue018Tests.cs similarity index 81% rename from tests/CreateAndFakeTests/IssueReplication/000-050/Issue018Tests.cs rename to tests/Toolbox.Tests/IssueReplication/000-050/Issue018Tests.cs index 36adb14e..965aca2c 100644 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue018Tests.cs +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue018Tests.cs @@ -1,22 +1,22 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue018Tests -{ - internal sealed class Sample(IInternalSample internalSample) - { - public IInternalSample InternalSample { get; } = internalSample; - } - - public interface IInternalSample - { - string Value { get; } - } - - [Theory, RandomData] - internal static void Issue018_RandomizerInjects(Injected sample) - { - sample.Dummy.InternalSample.Assert().Is(sample.Fake().Dummy); - } -} \ No newline at end of file +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue018Tests +{ + internal sealed class Sample(IInternalSample internalSample) + { + public IInternalSample InternalSample { get; } = internalSample; + } + + public interface IInternalSample + { + string Value { get; } + } + + [Theory, RandomData] + internal static void Issue018_RandomizerInjects(Injected sample) + { + sample.Dummy.InternalSample.Assert().Is(sample.Fake().Dummy); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue021Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue021Tests.cs new file mode 100644 index 00000000..11fe5211 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue021Tests.cs @@ -0,0 +1,33 @@ +using Werecodent.CreateAndFake.Design.Data; +using Werecodent.CreateAndFake.Design.Reiteration; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue021Tests +{ + internal sealed class Sample + { + public string FirstName { get; set; } + } + + [Theory, RandomData] + internal static void Issue021_MutatorMutates(Sample sample) + { + string original = sample.FirstName; + Tools.Mutator.Modify(sample); + sample.FirstName.Assert().IsNot(original); + } + + [Theory, RandomData] + internal static void Issue021_MutatorUsesSmartData(Sample sample) + { + Limiter.Few.Retry( + "Retry if completely random name is used due to random smart name match.", + () => + { + Tools.Mutator.Modify(sample).Assert().Is(true); + NameData.Values.Assert().Contains(sample.FirstName); + } + ); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue028Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue028Tests.cs new file mode 100644 index 00000000..536f6ef7 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue028Tests.cs @@ -0,0 +1,26 @@ +using Werecodent.CreateAndFake.Design.Reiteration; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue028Tests +{ + internal sealed class Sample + { + public int Value { get; set; } + } + + [Fact] + internal static void Issue028_ConditionalCreation() + { + Tools + .Randomizer.Create(opt => + opt with + { + FinalConditionAttemptLimit = Limiter.Hundred, + FinalCondition = r => r is Sample s && s.Value > 0, + } + ) + .Value.Assert() + .GreaterThan(0); + } +} diff --git a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue030Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue030Tests.cs similarity index 89% rename from tests/CreateAndFakeTests/IssueReplication/000-050/Issue030Tests.cs rename to tests/Toolbox.Tests/IssueReplication/000-050/Issue030Tests.cs index 013e5bfa..2dea5502 100644 --- a/tests/CreateAndFakeTests/IssueReplication/000-050/Issue030Tests.cs +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue030Tests.cs @@ -1,25 +1,25 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue030Tests -{ - [Fact] - internal static void Issue030_SupportsGuid() - { - TestSample(); - } - - private static void TestSample() - { - for (int i = 0; i < 50; i++) - { - T sample = Tools.Randomizer.Create(); - Tools.Asserter.IsNot(null, sample); - Tools.Asserter.IsNot(sample, Tools.Mutator.Variant(sample)); - - T dupe = Tools.Duplicator.Copy(sample); - - Tools.Asserter.Is(sample, dupe); - Tools.Asserter.Is(Tools.Valuer.GetHashCode(sample), Tools.Valuer.GetHashCode(dupe)); - } - } -} +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue030Tests +{ + [Fact] + internal static void Issue030_SupportsGuid() + { + TestSample(); + } + + private static void TestSample() + { + for (int i = 0; i < 50; i++) + { + T sample = Tools.Randomizer.Create(); + Tools.Asserter.IsNot(null, sample); + Tools.Asserter.IsNot(sample, Tools.Mutator.Variant(sample)); + + T dupe = Tools.Duplicator.Copy(sample); + + Tools.Asserter.Is(sample, dupe); + Tools.Asserter.Is(Tools.Valuer.GetHashCode(sample), Tools.Valuer.GetHashCode(dupe)); + } + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue038Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue038Tests.cs new file mode 100644 index 00000000..88eb1e38 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue038Tests.cs @@ -0,0 +1,91 @@ +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue038Tests +{ + public interface ISample + { + string Value { get; set; } + + int Check(InnerSample value); + + int Check(string item1, string item2); + } + + public class InnerSample + { + public string Value { get; set; } + } + + [Theory, RandomData] + internal static void Issue038_FluentStubSetup([Stub] ISample sample, string value) + { + sample.Value.Assert().IsNull(); + sample.Value.SetupReturn(value); + sample.Value.Assert().Is(value); + sample.Assert().Called(); + } + + [Theory, RandomData] + internal static void Issue038_FluentFakeSetup([Fake] ISample sample, string value) + { + sample.Value.Assert().IsNotNull(); + sample.Value.SetupReturn(value); + sample.Value.Assert().Is(value); + sample.Assert().Called(); + } + + [Theory, RandomData] + internal static void Issue038_FluentArgsByValue( + [Stub] ISample sample, + InnerSample item, + int result + ) + { + sample.Check(item).SetupReturn(result); + sample.Check(Tools.Duplicator.Copy(item)).Assert().Is(result); + sample.Assert().Called(); + } + + [Theory, RandomData] + internal static void Issue038_FluentArgWorks( + [Stub] ISample sample, + string item1, + string item2, + int result + ) + { + sample.Check(Arg.Any(), Arg.Where(s => s == item2)).SetupReturn(result); + sample.Check(item2, item1).Assert().Is(0); + sample.Check(item1, item2).Assert().Is(result); + sample.Assert().Called(); + } + + [Theory, RandomData] + internal static void Issue038_FluentTimesCorrect([Stub] ISample sample, string value) + { + sample.Value.SetupReturn(value, Times.Exactly(2)); + sample.Value.Assert().Is(value); + sample.Assert(x => x.Assert().Called()).Throws(); + sample.Value.Assert().Is(value); + sample.Assert().Called(); + } + + [Theory, RandomData] + internal static void Issue038_FluentFakeCastWorks( + [Stub] ISample sample, + string value, + string identity + ) + { + sample.Tools().ToFake().Setup(d => d.Value, Behavior.Returns(value)); + sample.Tools().ToFake().Setup(d => d.ToString(), Behavior.Returns(identity)); + + sample.Value.Assert().Is(value); + sample.ToString().Assert().Is(identity); + + sample.Tools().ToFake().ToFake().Verify(); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/000-050/Issue043Tests.cs b/tests/Toolbox.Tests/IssueReplication/000-050/Issue043Tests.cs new file mode 100644 index 00000000..48d4970e --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/000-050/Issue043Tests.cs @@ -0,0 +1,36 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue043Tests +{ + [Fact] + internal static Task Issue043_SupportsTask() + { + return TestSample(); + } + + [Fact] + internal static Task Issue043_SupportsGenericTask() + { + return TestSample>(); + } + + private static async Task TestSample() + { + CancellationToken ct = TestContext.Current.CancellationToken; + for (int i = 0; i < 50; i++) + { + T sample = Tools.Randomizer.Create(); + await Tools.Asserter.IsNotAsync(null, sample, ct); + await Tools.Asserter.IsNotAsync(sample, Tools.Mutator.Variant(sample), ct); + + T dupe = Tools.Duplicator.Copy(sample); + + await Tools.Asserter.IsAsync(sample, dupe, ct); + await Tools.Asserter.IsAsync( + Tools.Valuer.GetHashCodeAsync(sample, ct), + Tools.Valuer.GetHashCodeAsync(dupe, ct), + ct + ); + } + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue052Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue052Tests.cs new file mode 100644 index 00000000..69e8eae7 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue052Tests.cs @@ -0,0 +1,83 @@ +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.DuplicatorTool.Engine; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue052Tests +{ + internal sealed class Data + { + public string Item { get; set; } + } + + [Theory, RandomData] + internal static void Issue052_RandomizerPostCustomizable(Fake hint) + { + Randomizer randomizer = new( + Tools.Randomizer.Options with + { + IncludeFrameworkHints = false, + } + ); + Data testItem = new() { Item = "Sample" }; + + hint.Setup( + d => d.TryToCreate(typeof(Data), Arg.Any()), + Behavior.Returns(new CreateHintResult(testItem), Times.Once) + ); + + randomizer + .Create(opt => opt with { Hints = [hint.Dummy] }) + .Assert() + .ReferenceEqual(testItem); + hint.Verify(); + } + + [Theory, RandomData] + internal static void Issue052_DuplicatorPostCustomizable(Fake hint, Data item) + { + Duplicator duplicator = new( + Tools.Duplicator.Options with + { + IncludeFrameworkHints = false, + } + ); + + hint.Setup( + d => d.TryCopy(item, Arg.Any()), + Behavior.Returns(new CopyHintResult(item), Times.Once) + ); + + duplicator + .Copy(item, opt => opt with { Hints = [hint.Dummy] }) + .Assert() + .ReferenceEqual(item); + hint.Verify(); + } + + [Theory, RandomData] + internal static void Issue052_ValuerPostCustomizable( + [Stub] ICompareHint hint, + Data item1, + Data item2 + ) + { + Valuer valuer = new( + Tools.Valuer.Options with + { + IncludeFrameworkHints = false, + IncludeValueHashInComparison = false, + } + ); + + hint.TryToCompare(item1, item2, Arg.Any()).SetupReturn(new([]), Times.Once); + + valuer.Equals(item1, item2, opt => opt with { Hints = [hint] }).Assert().Is(true); + hint.Assert().Called(); + } +} diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue055Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue055Tests.cs similarity index 81% rename from tests/CreateAndFakeTests/IssueReplication/050-100/Issue055Tests.cs rename to tests/Toolbox.Tests/IssueReplication/050-100/Issue055Tests.cs index 91101959..23ae494f 100644 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue055Tests.cs +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue055Tests.cs @@ -1,57 +1,61 @@ -using CreateAndFake.Toolbox.FakerTool; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue055Tests -{ - public class User - { - public string Street { get; set; } - - public int ZipCode { get; set; } - - public string MailingAddress => Street + ZipCode; - } - - public class Details - { - public string Name { get; set; } - public string Year { get; set; } - - public IEnumerable Directors { get; set; } - } - - public interface IStorage - { - IEnumerable
Find(string name); - } - - internal sealed class Endpoint(IStorage db) - { - private readonly IStorage _db = db; - - public IEnumerable GetDirectors(string name, string year) - { - return _db.Find(name).FirstOrDefault(m => m.Year == year).Directors; - } - } - - [Theory, RandomData] - internal static void Issue055_TestGetMovieDirectors([Fake] IStorage db, Endpoint api, [Size(2)] Details[] movies) - { - db.Find(movies[0].Name).SetupReturn(movies, Times.Once); - api.GetDirectors(movies[0].Name, movies[0].Year).Assert().Is(movies[0].Directors); - db.VerifyAllCalls(); - } - - [Fact] - internal static void Issue055_TestMailingAddressUpdates() - { - User details = Tools.Randomizer.Create(); - User copy = Tools.Duplicator.Copy(details); - - details.ZipCode = Tools.Mutator.Variant(details.ZipCode); - - Tools.Asserter.IsNot(copy.MailingAddress, details.MailingAddress); - } -} +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue055Tests +{ + public class User + { + public string Street { get; set; } + + public int ZipCode { get; set; } + + public string MailingAddress => Street + ZipCode; + } + + public class Details + { + public string Name { get; set; } + public string Year { get; set; } + + public IEnumerable Directors { get; set; } + } + + public interface IStorage + { + IEnumerable
Find(string name); + } + + internal sealed class Endpoint(IStorage db) + { + private readonly IStorage _db = db; + + public IEnumerable GetDirectors(string name, string year) + { + return _db.Find(name).FirstOrDefault(m => m.Year == year).Directors; + } + } + + [Theory, RandomData] + internal static void Issue055_TestGetMovieDirectors( + [Fake] IStorage db, + [Inject] Endpoint api, + [Size(2)] Details[] movies + ) + { + db.Find(movies[0].Name).SetupReturn(movies, Times.Once); + api.GetDirectors(movies[0].Name, movies[0].Year).Assert().Is(movies[0].Directors); + db.Assert().Called(); + } + + [Fact] + internal static void Issue055_TestMailingAddressUpdates() + { + User details = Tools.Randomizer.Create(); + User copy = Tools.Duplicator.Copy(details); + + details.ZipCode = Tools.Mutator.Variant(details.ZipCode); + + Tools.Asserter.IsNot(copy.MailingAddress, details.MailingAddress); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue065Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue065Tests.cs new file mode 100644 index 00000000..fd0ebfbf --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue065Tests.cs @@ -0,0 +1,47 @@ +using Werecodent.CreateAndFake.Design.Types; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue065Tests +{ + internal sealed class InfiniteA + { + public int Id { get; set; } + + public ICollection Start { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } + } + + internal sealed class InfiniteB + { + public InfiniteC Nested { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } + } + + internal sealed class InfiniteC + { + public InfiniteA Back { get; set; } + + public override string ToString() + { + return GenericConverter.ExpandName(GetType()); + } + } + + [Fact] + internal static Task Issue065_HandlesInfiniteChains() + { + return Tools.Tester.VerifyToolSetSupportAsync( + [typeof(InfiniteA), typeof(InfiniteB), typeof(InfiniteC)], + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue067Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue067Tests.cs similarity index 90% rename from tests/CreateAndFakeTests/IssueReplication/050-100/Issue067Tests.cs rename to tests/Toolbox.Tests/IssueReplication/050-100/Issue067Tests.cs index aaca1a01..6476dad2 100644 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue067Tests.cs +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue067Tests.cs @@ -1,31 +1,31 @@ -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue067Tests -{ - [Fact] - internal static void Issue067_SupportsUri() - { - TestSample(); - } - - [Fact] - internal static void Issue067_SupportsDateTimeOffset() - { - TestSample(); - } - - private static void TestSample() - { - for (int i = 0; i < 50; i++) - { - T sample = Tools.Randomizer.Create(); - Tools.Asserter.IsNot(null, sample); - Tools.Asserter.IsNot(sample, Tools.Mutator.Variant(sample)); - - T dupe = Tools.Duplicator.Copy(sample); - - Tools.Asserter.Is(sample, dupe); - Tools.Asserter.Is(Tools.Valuer.GetHashCode(sample), Tools.Valuer.GetHashCode(dupe)); - } - } -} +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue067Tests +{ + [Fact] + internal static void Issue067_SupportsUri() + { + TestSample(); + } + + [Fact] + internal static void Issue067_SupportsDateTimeOffset() + { + TestSample(); + } + + private static void TestSample() + { + for (int i = 0; i < 50; i++) + { + T sample = Tools.Randomizer.Create(); + Tools.Asserter.IsNot(null, sample); + Tools.Asserter.IsNot(sample, Tools.Mutator.Variant(sample)); + + T dupe = Tools.Duplicator.Copy(sample); + + Tools.Asserter.Is(sample, dupe); + Tools.Asserter.Is(Tools.Valuer.GetHashCode(sample), Tools.Valuer.GetHashCode(dupe)); + } + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue078Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue078Tests.cs new file mode 100644 index 00000000..1fa36f42 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue078Tests.cs @@ -0,0 +1,16 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue078Tests +{ + [Theory, RandomData] + internal static void Issue078_CanChainObjects(int[] valueA, bool valueB) + { + valueA.Assert().IsNotEmpty().Also(valueB).IsNotNull(); + } + + [Theory, RandomData] + internal static void Issue078_CanChainCollections(bool valueA, int[] valueB) + { + valueA.Assert().IsNotNull().Also(valueB).IsNotEmpty(); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue081Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue081Tests.cs new file mode 100644 index 00000000..0b651a57 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue081Tests.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue081Tests +{ + [Fact] + internal static void Issue081_RandomizationIsSeeded() + { + Tools.Gen.InitialSeed.Assert().IsNotNull(); + } + + [Fact] + internal static void Issue081_AssertionsContainSeed() + { + Tools + .Asserter.Assert(x => x.Fail()) + .Throws() + .With(e => e.Message) + .Contains($"{Tools.Gen.InitialSeed}"); + } +} diff --git a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue086Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue086Tests.cs similarity index 87% rename from tests/CreateAndFakeTests/IssueReplication/050-100/Issue086Tests.cs rename to tests/Toolbox.Tests/IssueReplication/050-100/Issue086Tests.cs index 50e419df..e78010c1 100644 --- a/tests/CreateAndFakeTests/IssueReplication/050-100/Issue086Tests.cs +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue086Tests.cs @@ -1,24 +1,24 @@ -using System.Collections; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue086Tests -{ - [Theory, RandomData] - internal static void Issue086_SizeWorks([Size(5)] string[] items) - { - items.Assert().HasCount(5); - } - - [Theory, RandomData] - internal static void Issue086_EmptyCollection([Size(0)] List items) - { - items.Assert().IsEmpty(); - } - - [Theory, RandomData] - internal static void Issue086_LegacyCollection([Size(3)] Hashtable items) - { - items.Keys.Assert().HasCount(3); - } -} \ No newline at end of file +using System.Collections; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue086Tests +{ + [Theory, RandomData] + internal static void Issue086_SizeWorks([Size(5)] string[] items) + { + items.Assert().HasCount(5); + } + + [Theory, RandomData] + internal static void Issue086_EmptyCollection([Size(0)] List items) + { + items.Assert().IsEmpty(); + } + + [Theory, RandomData] + internal static void Issue086_LegacyCollection([Size(3)] Hashtable items) + { + items.Keys.Assert().HasCount(3); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue089Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue089Tests.cs new file mode 100644 index 00000000..a41f8c33 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue089Tests.cs @@ -0,0 +1,100 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue089Tests +{ + [Theory, RandomData] + internal static void Issue089_StringAssertions(string text) + { + text.Assert().Is(Tools.Duplicator.Copy(text)); + text.Assert().HasCount(text.Length); + + string startSample = text.Substring(0, 2); + string endSample = text.Substring(text.Length - 2, 2); + + text.Assert().Contains(text.Substring(2, 2)); + text.Assert().ContainsNot(Tools.Mutator.Variant(text)); + text.Assert().StartsWith(startSample); + text.Assert().StartsNotWith(Tools.Mutator.Variant(startSample)); + text.Assert().EndsWith(endSample); + text.Assert().EndsNotWith(Tools.Mutator.Variant(endSample)); + } + + [Theory, RandomData] + internal static void Issue089_InvalidStringAssertions(string text) + { + text.Assert(x => x.Assert().IsNot(Tools.Duplicator.Copy(text))).Throws(); + text.Assert(x => x.Assert().HasCount(text.Length + 1)).Throws(); + + string startSample = text.Substring(0, 2); + string endSample = text.Substring(text.Length - 2, 2); + + text.Assert(x => x.Assert().Contains(Tools.Mutator.Variant(text))) + .Throws(); + text.Assert(x => x.Assert().ContainsNot(text.Substring(2, 2))).Throws(); + text.Assert(x => x.Assert().StartsWith(Tools.Mutator.Variant(startSample))) + .Throws(); + text.Assert(x => x.Assert().StartsNotWith(startSample)).Throws(); + text.Assert(x => x.Assert().EndsWith(Tools.Mutator.Variant(endSample))) + .Throws(); + text.Assert(x => x.Assert().EndsNotWith(endSample)).Throws(); + } + + [Theory, RandomData] + internal static void Issue089_DelegateAssertions(InvalidOperationException error, object item) + { + Action action = () => throw error; + action.Assert().Throws().That().Is(error); + + Func func = () => throw error; + func.Assert().Throws().That().Is(error); + + item.Assert(_ => false ? "" : throw error) + .Throws() + .That() + .Is(error); + + item.Assert(x => x.Assert().Fail()).Throws().That().IsNot(error); + } + + [Theory, RandomData] + internal static void Issue089_ComparableAssertions(int value) + { + value.Assert().GreaterThan(value - 1); + value.Assert().GreaterThanOrEqualTo(value - 1); + value.Assert().GreaterThanOrEqualTo(value); + value.Assert().LessThanOrEqualTo(value); + value.Assert().LessThanOrEqualTo(value + 1); + value.Assert().LessThan(value + 1); + + value.Assert().InRange(value - 1, value + 1); + value.Assert().InRange(value, value); + + value.Assert().GreaterThanOrIs(value - 1); + value.Assert().GreaterThanOrIs(value); + value.Assert().LessThanOrIs(value); + value.Assert().LessThanOrIs(value + 1); + + ((int?)null).Assert().GreaterThanOrIs(null); + ((int?)null).Assert().LessThanOrIs(null); + } + + [Theory, RandomData] + internal static void Issue089_InvalidComparableAssertions(int value) + { + value.Assert(x => x.Assert().GreaterThan(value + 1)).Throws(); + value.Assert(x => x.Assert().GreaterThanOrEqualTo(value + 1)).Throws(); + value.Assert(x => x.Assert().LessThanOrEqualTo(value - 1)).Throws(); + value.Assert(x => x.Assert().LessThan(value - 1)).Throws(); + + value.Assert(x => x.Assert().InRange(value + 1, value)).Throws(); + value.Assert(x => x.Assert().InRange(value, value - 1)).Throws(); + + value.Assert(x => x.Assert().GreaterThan(null)).Throws(); + value.Assert(x => x.Assert().InRange(null, value)).Throws(); + value.Assert(x => x.Assert().InRange(value, null)).Throws(); + ((int?)null).Assert(x => x.Assert().InRange(value, value)).Throws(); + ((int?)null).Assert(x => x.Assert().GreaterThan(value)).Throws(); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue091Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue091Tests.cs new file mode 100644 index 00000000..cec901ac --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue091Tests.cs @@ -0,0 +1,96 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue091Tests +{ + internal sealed class Api(ILayer layer) + { + public Item FindItem(int key) + { + return layer.GetItem(key); + } + + public Item FindItem(Guid id) + { + return layer.GetItem(id); + } + + public Item FindItem(object key) + { + return layer.GetItem(key); + } + } + + public interface ILayer + { + Item GetItem(int key); + + Item GetItem(Guid id); + + Item GetItem(object key); + } + + public class Item + { + public Guid Id { get; set; } + } + + [Theory, RandomData] + internal static void Issue091_FluentArgMatchesInt( + [Fake] ILayer layer, + [Inject] Api api, + Item sample, + int key + ) + { + layer.GetItem(Arg.Any()).SetupReturn(sample, Times.Once); + + api.FindItem(key).Assert().Is(sample); + + layer.Assert().Called(); + } + + [Theory, RandomData] + internal static void Issue091_FluentArgMatchesGuid( + [Fake] ILayer layer, + [Inject] Api api, + Item sample + ) + { + layer.GetItem(Arg.Any()).SetupReturn(sample, Times.Once); + + api.FindItem(sample.Id).Assert().Is(sample); + + layer.Assert().Called(); + } + + [Theory, RandomData] + internal static void Issue091_FluentArgMatchesObject( + [Fake] ILayer layer, + [Inject] Api api, + Item sample, + object key + ) + { + layer.GetItem(Arg.Any()).SetupReturn(sample, Times.Once); + + api.FindItem(key).Assert().Is(sample); + + layer.Assert().Called(); + } + + [Theory, RandomData] + internal static void Issue091_FluentArgMatchesNull( + [Fake] ILayer layer, + [Inject] Api api, + Item sample + ) + { + layer.GetItem(null).SetupReturn(sample, Times.Once); + + api.FindItem(null).Assert().Is(sample); + + layer.Assert().Called(); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue093Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue093Tests.cs new file mode 100644 index 00000000..4cb6072d --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue093Tests.cs @@ -0,0 +1,73 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue093Tests +{ + public interface IProvider + { + string Value { get; set; } + } + + public abstract class AbstractProvider : IProvider + { + public string Value { get; set; } + } + + public class UnsealedProvider : IProvider + { + public string Value { get; set; } + } + + public sealed class Api + { + private readonly IProvider _provider; + + public Api(IProvider provider) + { + _provider = provider; + } + + public string Value => _provider.Value; + } + + [Theory, RandomData] + internal static void Issue093_AssertInterfaceFakeCallIntegration( + [Fake] IProvider faked, + [Inject] Api sample, + string value + ) + { + TestFakeCallIntegration(faked, sample, value); + } + + [Theory, RandomData] + internal static void Issue093_AssertAbstractFakeCallIntegration( + [Fake] AbstractProvider faked, + [Inject] Api sample, + string value + ) + { + TestFakeCallIntegration(faked, sample, value); + } + + [Theory, RandomData] + internal static void Issue093_AssertUnsealedFakeCallIntegration( + [Fake] UnsealedProvider faked, + [Inject] Api sample, + string value + ) + { + TestFakeCallIntegration(faked, sample, value); + } + + private static void TestFakeCallIntegration(IProvider faked, Api sample, string value) + { + faked.Value.SetupReturn(value); + Tools.Asserter.Throws(() => faked.Assert().Called()); + + sample.Value.Assert().Is(value).Also(faked).Called(); + Tools.Asserter.Throws(() => sample.Value.Assert().Is("")); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue094Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue094Tests.cs new file mode 100644 index 00000000..caee5033 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue094Tests.cs @@ -0,0 +1,254 @@ +using System.Collections.Specialized; +using System.Globalization; +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Tooling; +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue094Tests +{ + public sealed class Wrapped(IEnumerable data) + { + public IEnumerable Data { get; } = [.. data]; + } + + [Theory, RandomData] + internal static void Issue094_StringSizeModifiedBySizeAttribute([Size(20)] string data) + { + data.Assert().HasCount(20); + } + + [Theory, RandomData] + internal static void Issue094_SizeAttributeOnlyTopCollection( + [Size(20)] IEnumerable data + ) + { + data.Assert().HasCount(20); + data.First().Length.Assert().IsNot(20); + } + + [Fact] + internal static async Task Issue094_AsserterOptionsWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_DuplicatorOptionsWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_FakerOptionsWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_MutatorOptionsWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_ExtractorOptionsWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_RandomizerOptionsWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_TesterOptionsWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_ValuerOptionsWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_AsserterWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_DuplicatorWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_FakerWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_MutatorWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_ExtractorWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_RandomizerWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_TesterWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_ValuerWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static Task Issue094_IntPtrWorks() + { + return TestToolBehavior(); + } + + [Fact] + internal static Task Issue094_RuntimeArrayWorks() + { + return TestToolBehavior(); + } + + [Fact] + internal static async Task Issue094_MemberInfoWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + await TestToolBehavior(); + await TestToolBehavior(); + await TestToolBehavior(); + await TestToolBehavior(); + await TestToolBehavior(); + } + + [Fact] + internal static Task Issue094_SpanWorks() + { + return TestToolBehavior(typeof(Span<>)); + } + + [Fact] + internal static Task Issue094_ValueTupleWorks() + { + return TestToolBehavior(typeof(ValueTuple<,>)); + } + + [Fact] + internal static async Task Issue094_FormatProviderWorks() + { + await TestToolBehavior(); + await TestToolBehavior(); + await TestToolBehavior(); + await TestToolBehavior(); + + foreach (IFormatProvider provider in CultureInfo.GetCultures(CultureTypes.AllCultures)) + { + provider.Tools().Copy().Assert().Is(provider); + } + } + + [Fact] + internal static async Task Issue094_FakedWorks() + { + await TestToolBehavior(typeof(IFaked)); + await TestToolBehavior(typeof(Fake)); + } + + [Fact] + internal static Task Issue094_MethodCallWrapperWorks() + { + return TestToolBehavior(typeof(MethodCallWrapper)); + } + + [Theory, RandomData] + internal static Task Issue094_MethodCallWrapperWithFakesWorks( + MethodBase method, + Fake fake + ) + { + OrderedDictionary dict = new OrderedDictionary(); + dict.Add("test", fake); + + MethodCallWrapper wrapper = new MethodCallWrapper(method, dict); + return wrapper + .Assert() + .IsAsync(wrapper.Tools().Copy(), TestContext.Current.CancellationToken); + } + + private static Task TestToolBehavior() + { + return TestToolBehavior(typeof(T)); + } + + private static async Task TestToolBehavior(Type type) + { + for (int i = 0; i < 3; i++) + { + object sample = Tools.Randomizer.Create(type); + await Tools.Asserter.IsNotAsync(null, sample, TestContext.Current.CancellationToken); + await Tools.Asserter.IsNotAsync( + sample, + Tools.Mutator.Variant(sample), + TestContext.Current.CancellationToken + ); + + object dupe = Tools.Duplicator.Copy(sample); + + await Tools.Asserter.IsAsync(sample, dupe, TestContext.Current.CancellationToken); + await Tools.Asserter.IsAsync(sample, dupe, TestContext.Current.CancellationToken); + } + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue096Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue096Tests.cs new file mode 100644 index 00000000..a256daaa --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue096Tests.cs @@ -0,0 +1,49 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue096Tests +{ + [Fact] + internal static async Task Issue096_SupportsIAsyncEnumerable() + { + await TestSample>(); + await TestSample>(); + await TestSample>(); + } + + [Theory, RandomData] + internal static async Task Issue096_SupportsSizedAsyncEnumerable( + [Size(5)] IAsyncEnumerable items + ) + { + int count = 0; + await foreach (int item in items) + { + count++; + } + count.Assert().Is(5); + } + + private static async Task TestSample() + { + var ct = TestContext.Current.CancellationToken; + for (int i = 0; i < 50; i++) + { + T sample = Tools.Randomizer.Create(); + await Tools.Asserter.IsNotAsync(null, sample, ct); + await Tools.Asserter.IsNotAsync( + sample, + await Tools.Mutator.VariantAsync(sample, ct), + ct + ); + + T dupe = Tools.Duplicator.Copy(sample); + + await Tools.Asserter.IsAsync(sample, dupe, ct); + await Tools.Asserter.IsAsync( + await Tools.Valuer.GetHashCodeAsync(sample, ct), + await Tools.Valuer.GetHashCodeAsync(dupe, ct), + ct + ); + } + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/050-100/Issue099Tests.cs b/tests/Toolbox.Tests/IssueReplication/050-100/Issue099Tests.cs new file mode 100644 index 00000000..44aae1af --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/050-100/Issue099Tests.cs @@ -0,0 +1,40 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue099Tests +{ + public static int ExtendedCall(this ITester sample, object item) + { + return sample?.GetValue(item) ?? 0; + } + + public interface ITester + { + int GetValue(object item); + } + + [Theory, RandomData] + internal static void Issue099_FakingThrowsWithExtensionMethod( + Fake sample, + object item, + int result + ) + { + Tools.Asserter.Throws(() => + sample.Setup(f => f.ExtendedCall(item), Behavior.Returns(result)) + ); + } + + [Theory, RandomData] + internal static void Issue099_FluentPassthroughWithExtensionMethod( + [Stub] ITester sample, + object item, + int result + ) + { + sample.ExtendedCall(item).SetupReturn(result); + sample.ExtendedCall(item).Assert().Is(result); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue101Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue101Tests.cs new file mode 100644 index 00000000..e076d158 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue101Tests.cs @@ -0,0 +1,16 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue101Tests +{ + [Theory, RandomData] + internal static void Issue101_EasyCloneValues(int value) + { + value.Tools().Copy().Assert().Is(value); + } + + [Theory, RandomData] + internal static void Issue101_EasyCloneObjects(string value) + { + value.Tools().Copy().Assert().Is(value); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue103Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue103Tests.cs new file mode 100644 index 00000000..18774836 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue103Tests.cs @@ -0,0 +1,28 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue103Tests +{ + [Theory, RandomData] + internal static void Issue103_AssertFailIncludesTestValue(string text) + { + string alt = Tools.Mutator.Variant(text); + Tools + .Asserter.Throws(() => text.Assert().Contains(alt)) + .Message.Assert() + .Contains(alt); + } + + [Theory, RandomData] + internal static void Issue103_AssertFailIncludesTestValueAndDetails(string text, string details) + { + string alt = Tools.Mutator.Variant(text); + Tools + .Asserter.Throws(() => text.Assert().Contains(alt, details)) + .Message.Assert() + .Contains(alt) + .And() + .Contains(details); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue104Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue104Tests.cs new file mode 100644 index 00000000..86f0b1ba --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue104Tests.cs @@ -0,0 +1,16 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue104Tests +{ + [Theory, RandomData] + internal static void Issue104_EasyVariantValues(int value) + { + value.Tools().Variant().Assert().IsNot(value); + } + + [Theory, RandomData] + internal static void Issue104_EasyVariantObjects(string value) + { + value.Tools().Variant().Assert().IsNot(value); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue106Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue106Tests.cs new file mode 100644 index 00000000..51c35d36 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue106Tests.cs @@ -0,0 +1,40 @@ +using Werecodent.CreateAndFake.AsserterTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue106Tests +{ + internal sealed class RandomNameContainer + { + public T Content { get; set; } + } + + public sealed class RandomNameItem + { + public string Message { get; set; } + } + + [Theory, RandomData] + internal static void Issue106_AssertIncludesGenericName( + RandomNameContainer generic + ) + { + generic + .Assert(x => x.Assert().Is(generic.Tools().Variant())) + .Throws() + .With(e => e.Message) + .Contains(nameof(RandomNameItem)); + } + + [Theory, RandomData] + internal static void Issue106_AssertIncludesGenericNameCollections( + List> generic + ) + { + generic + .Assert(x => x.Assert().Is(generic.Tools().Variant())) + .Throws() + .With(e => e.Message) + .Contains(nameof(RandomNameItem)); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue107Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue107Tests.cs new file mode 100644 index 00000000..6cc375b4 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue107Tests.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Tooling; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue107Tests +{ + internal abstract class SelfReferenceContainer + where T : SelfReferenceContainer { } + + [Fact] + internal static void Issue107_SelfReferenceGenericMustHaveSubclass() + { + typeof(SelfReferenceContainer<>) + .Assert(x => x.Tools().CreateRandomInstance()) + .Throws(); + + typeof(SelfReferenceContainer<>) + .Assert(x => Tools.Randomizer.Inject(typeof(SelfReferenceContainer<>), [])) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue108Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue108Tests.cs new file mode 100644 index 00000000..6847a5c7 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue108Tests.cs @@ -0,0 +1,55 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue108Tests +{ + public abstract class InnerStuff + where T : InnerStuff + { + public string Message { get; set; } + } + + public sealed class Wrapper : InnerStuff + { + public int Value { get; set; } + } + + public class Container + where T : InnerStuff + { + public T Content { get; set; } + } + + public sealed class WrapperContainer : Container { } + + [Fact] + internal static void Issue108_SupportsSelfReference() + { + typeof(InnerStuff<>).Tools().CreateRandomInstance().Assert().IsNotNull(); + } + + [Theory, RandomData] + internal static void Issue108_SupportsWrappingSelfReference(Wrapper instance) + { + instance.Assert().IsNotNull(); + } + + [Fact] + internal static void Issue108_SupportsContainerWithSelfReferenceContent() + { + typeof(Container<>).Tools().CreateRandomInstance().Assert().IsNotNull(); + } + + [Theory, RandomData] + internal static void Issue108_SupportsContainerWithWrappedSelfReference( + Container instance + ) + { + instance.Assert().IsNotNull(); + } + + [Theory, RandomData] + internal static void Issue108_SupportsWrappedContainer(WrapperContainer instance) + { + instance.Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue109Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue109Tests.cs new file mode 100644 index 00000000..7498ff2e --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue109Tests.cs @@ -0,0 +1,63 @@ +using Werecodent.CreateAndFake.DuplicatorTool; +using Werecodent.CreateAndFake.DuplicatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +#pragma warning disable CA2227 // For testing. + +public static class Issue109Tests +{ + public interface IDetails + { + string Name { get; set; } + } + + [Serializable] + public sealed class Details : IDetails + { + public string Name { get; set; } + public int Year { get; set; } + + public Details() { } + } + + public interface IContainer + { + IDetails Item { get; set; } + } + + [Serializable] + public sealed class Container : IContainer + { + public IDetails Item { get; set; } + + private List Values { get; set; } + + public Dictionary> Map { get; set; } + + public Container() { } + + public override string ToString() + { + return Values?.ToString() + Map?.ToString(); + } + } + + [Theory, RandomData] + internal static void Issue109_BinarySerializationRemovedDateTime(DateTime date) + { + date.Tools().Copy().Assert().Is(date); + } + + [Theory, RandomData] + internal static void Issue109_BinarySerializationRemovedSample(IContainer sample) + { + sample.Tools().Copy().Assert().Is(sample); + new Duplicator(Tools.Duplicator.Options with { Hints = [new SerializableCopyHint()] }) + .Copy(sample) + .Assert() + .Is(sample); + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue114Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue114Tests.cs new file mode 100644 index 00000000..4237042f --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue114Tests.cs @@ -0,0 +1,36 @@ +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue114Tests +{ + [Theory, RandomData] + internal static void Issue114_IntArraySequencesEqualRegardlessOfType(int[] sample) + { + sample.Assert().Is(sample.Tools().Copy().ToList()); + } + + [Theory, RandomData] + internal static void Issue114_ObjectArraySequencesEqualRegardlessOfType(object[] sample) + { + sample.Assert().Is(sample.Tools().Copy().ToList()); + } + + [Theory, RandomData] + internal static void Issue114_StringListSequencesEqualRegardlessOfType(IList sample) + { + sample.Assert().Is(sample.Tools().Copy().ToList()); + } + + [Theory, RandomData] + internal static void Issue114_ObjectListSequencesEqualRegardlessOfType(IList sample) + { + sample.Assert().Is(sample.Tools().Copy().ToList()); + } + + [Theory, RandomData] + internal static void Issue114_StringSequencesEqualRegardlessOfType( + IDictionary sample + ) + { + sample.Assert().Is(sample.Tools().Copy().ToDictionary(e => e.Key, e => e.Value)); + } +} diff --git a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue117Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue117Tests.cs similarity index 78% rename from tests/CreateAndFakeTests/IssueReplication/100-150/Issue117Tests.cs rename to tests/Toolbox.Tests/IssueReplication/100-150/Issue117Tests.cs index 90872981..fa138eb3 100644 --- a/tests/CreateAndFakeTests/IssueReplication/100-150/Issue117Tests.cs +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue117Tests.cs @@ -1,18 +1,18 @@ -using CreateAndFakeTests.TestSamples; - -namespace CreateAndFakeTests.IssueReplication; - -public static class Issue117Tests -{ - [Fact] - internal static void Issue117_AddsTypeAssertions() - { - typeof(string).Assert().Inherits().Also(typeof(int)).Inherits(); - } - - [Theory, RandomData] - internal static void Issue117_AddsContainsAssertions(IList sample) - { - sample.Assert().Contains(Tools.Gen.NextItem(sample)); - } -} +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue117Tests +{ + [Fact] + internal static void Issue117_AddsTypeAssertions() + { + typeof(string).Assert().Inherits().Also(typeof(int)).Inherits(); + } + + [Theory, RandomData] + internal static void Issue117_AddsContainsAssertions(IList sample) + { + sample.Assert().Contains(Tools.Gen.NextItem(sample)); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue118Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue118Tests.cs new file mode 100644 index 00000000..86f08432 --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue118Tests.cs @@ -0,0 +1,24 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue118Tests +{ + [Fact] + internal static void Issue118_AddsPass() + { + typeof(object).Assert().Pass(); + } + + [Theory, RandomData] + internal static void Issue118_FixesFakeTypeRandomData(Fake type) + { + type.Assert().IsNotNull(); + } + + [Theory, RandomData] + internal static void Issue118_FixesStubTypeRandomData([Stub] Type type) + { + type.Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/IssueReplication/100-150/Issue123Tests.cs b/tests/Toolbox.Tests/IssueReplication/100-150/Issue123Tests.cs new file mode 100644 index 00000000..a7fe38ef --- /dev/null +++ b/tests/Toolbox.Tests/IssueReplication/100-150/Issue123Tests.cs @@ -0,0 +1,26 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; + +namespace Werecodent.CreateAndFake.Tests.IssueReplication; + +public static class Issue123Tests +{ + [Theory, RandomData] + internal static void Issue123_ImmutablesSupported(ImmutableArray data) + { + data.Assert().Is(data.Tools().Copy()); + } + + [Theory, RandomData] + internal static void Issue123_FrozenDictionarySupported(FrozenDictionary data) + { + data.Assert().Is(data.Tools().Copy()); + } + + [Fact] + internal static void Issue123_FrozenSetSupported() + { + FrozenSet data = Tools.Randomizer.Create>(); + data.Assert().Is(data.Tools().Copy()); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Engine/MutateHintResultTests.cs b/tests/Toolbox.Tests/MutatorTool/Engine/MutateHintResultTests.cs new file mode 100644 index 00000000..a7c5505a --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Engine/MutateHintResultTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Engine; + +public sealed class MutateHintResultTests : AutoTester; diff --git a/tests/Toolbox.Tests/MutatorTool/Engine/MutatePriorityTests.cs b/tests/Toolbox.Tests/MutatorTool/Engine/MutatePriorityTests.cs new file mode 100644 index 00000000..00abc3d5 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Engine/MutatePriorityTests.cs @@ -0,0 +1,54 @@ +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Engine; + +public sealed class MutatePriorityTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(FormatException)], + }; + + [Fact] + internal static void Disabled_SetToMin() + { + ((int)MutatePriority.Disabled).Assert().Is(int.MinValue); + } + + [Fact] + internal static void None_DefaultAtZero() + { + ((int)MutatePriority.None).Assert().Is(0); + } + + [Fact] + internal static void Highest_AtCap() + { + ((int)MutatePriority.Highest) + .Assert() + .Is(Enum.GetValues(typeof(MutatePriority)).Length - 2); + } + + [Fact] + internal static void Values_AllPositive() + { + Enum.GetValues(typeof(MutatePriority)) + .Cast() + .Except([(int)MutatePriority.Disabled]) + .Where(v => v < 0) + .Assert() + .IsEmpty(); + } + + [Fact] + internal static void Values_Unique() + { + Enum.GetValues(typeof(MutatePriority)) + .Cast() + .ToHashSet() + .Assert() + .HasCount(Enum.GetValues(typeof(MutatePriority)).Length); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Engine/MutatorChainerTests.cs b/tests/Toolbox.Tests/MutatorTool/Engine/MutatorChainerTests.cs new file mode 100644 index 00000000..699afc44 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Engine/MutatorChainerTests.cs @@ -0,0 +1,64 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Engine; + +public sealed class MutatorChainerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(InvalidCastException), typeof(ToolException)], + DisableParameterMutationTests = true, + }; + + [Theory, RandomData] + internal static void MutatorChainer_RecursionLimited([Stub] IMutatorEngine engine, string data) + { + engine + .Modify(Arg.Any(), Arg.Any()) + .SetupReturn( + Behavior.Call( + (_, chainer) => chainer.Modify(Tools.Randomizer.Create()) + ) + ); + + new MutatorChainer( + Tools.Mutator.Options with + { + Valuer = Tools.Valuer.WithOptions(o => + o with + { + Design = o.Design with { IterationLimit = 2 }, + } + ), + }, + engine + ) + .Assert(x => x.Modify(data)) + .Throws(); + } + + [Theory, RandomData] + internal static void Modify_HandlesRecursionLoop([Stub] IMutatorEngine engine, object data) + { + engine + .Modify(data, Arg.Any()) + .SetupReturn( + Behavior.Call((d, chainer) => chainer.Modify(d)) + ); + + new MutatorChainer(Tools.Mutator.Options, engine).Modify(data).Assert().Is(false); + } + + [Theory, RandomData] + internal static void WithOptions_CreatesVariant( + MutatorChainer chainer, + MutatorMod optionConfiguration + ) + { + chainer.WithOptions(optionConfiguration).Assert().IsNot(chainer); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Engine/MutatorEngineTests.cs b/tests/Toolbox.Tests/MutatorTool/Engine/MutatorEngineTests.cs new file mode 100644 index 00000000..1cc535ff --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Engine/MutatorEngineTests.cs @@ -0,0 +1,495 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.ExtractorTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Engine; + +public sealed class MutatorEngineTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { DisableParameterMutationTests = true }; + + [Theory, RandomData] + internal static void Variant_AcceptsNull(string value) + { + new Mutator(Tools.Mutator.Options).Variant(null).Assert().IsNotNull(); + + new Mutator(Tools.Mutator.Options) + .Variant(value, null) + .Assert() + .IsNot(value) + .And() + .IsNotNull(); + } + + [Fact] + internal static void VariantOf_ThrowsIfImpossible() + { + Tools.Mutator.Assert(x => x.VariantOf([true, false])).Throws(); + } + + [Theory, RandomData] + internal static void VariantOf_ManyValuesWorks([Size(3000)] int[] data) + { + IValuer valuer = Tools.Valuer.WithOptions(opt => + opt with + { + Design = opt.Design with { IterationLimit = data.Length + 1 }, + } + ); + + int result = Tools.Mutator.VariantOf(data, opt => opt with { Valuer = valuer }); + data.Assert().ContainsNot(result, opt => opt with { Valuer = valuer }); + } + + [Theory, RandomData] + internal static void Variant_TimesOut([Fake] IValuer fakeValuer, DataSample sample) + { + fakeValuer.Options.SetupReturn(Tools.Valuer.Options); + fakeValuer + .Equals(Arg.Any(), Arg.Any(), Arg.Any()) + .SetupReturn(true); + + new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForVariants = new Limiter(3), + } + ) + .Assert(x => x.Variant(sample)) + .Throws(); + + fakeValuer.Assert().Called(); + } + + [Theory, RandomData] + internal static void Variant_RepeatsUntilUnequal([Fake] IValuer fakeValuer, DataSample sample) + { + fakeValuer.Options.SetupReturn(Tools.Valuer.Options); + fakeValuer + .Equals(Arg.Any(), Arg.Any(), Arg.Any()) + .SetupReturn(Behavior.Series(true, true, true, false)); + + new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForVariants = new Limiter(5), + } + ) + .Variant(sample) + .Assert() + .IsNotNull(); + + fakeValuer.Assert().Called(); + } + + [Theory, RandomData] + internal static void Variant_RepeatsUntilBothUnequal( + [Fake] IValuer fakeValuer, + DataSample sample1, + DataSample sample2 + ) + { + fakeValuer.Options.SetupReturn(Tools.Valuer.Options); + fakeValuer + .Equals(Arg.Any(), Arg.Any(), Arg.Any()) + .SetupReturn(Behavior.Series(false, true, true, false, true, true, false, false)); + + new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForVariants = new Limiter(5), + } + ) + .VariantOf([sample1, sample2]) + .Assert() + .IsNotNull(); + + fakeValuer.Assert().Called(); + } + + [Theory, RandomData] + internal static async Task VariantAsync_AcceptsNull(string value) + { + await new Mutator(Tools.Mutator.Options) + .VariantAsync(null, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNotNull(); + + await new Mutator(Tools.Mutator.Options) + .VariantAsync(value, TestContext.Current.CancellationToken, null) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNot(value); + } + + [Fact] + internal static Task VariantOfAsync_ThrowsIfImpossible() + { + return Tools + .Mutator.VariantOfAsync([true, false], TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task VariantOfAsync_ManyValuesWorks([Size(3000)] int[] data) + { + IValuer valuer = Tools.Valuer.WithOptions(opt => + opt with + { + Design = opt.Design with { IterationLimit = data.Length + 1 }, + } + ); + + int result = await Tools.Mutator.VariantOfAsync( + data, + TestContext.Current.CancellationToken, + opt => opt with { Valuer = valuer } + ); + await data.Assert() + .ContainsNotAsync( + result, + TestContext.Current.CancellationToken, + opt => opt with { Valuer = valuer } + ); + } + + [Theory, RandomData] + internal static async Task VariantAsync_TimesOut([Fake] IValuer fakeValuer, DataSample sample) + { + fakeValuer + .EqualsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .SetupReturn(Task.FromResult(true)); + + await new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForVariants = new Limiter(3), + } + ) + .VariantAsync(sample, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + fakeValuer.Assert().Called(); + } + + [Theory, RandomData] + internal static async Task VariantAsync_RepeatsUntilUnequal( + [Fake] IValuer fakeValuer, + DataSample sample + ) + { + fakeValuer + .EqualsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .SetupReturn( + Behavior.Series( + Task.FromResult(true), + Task.FromResult(true), + Task.FromResult(true), + Task.FromResult(false) + ) + ); + + await new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForVariants = new Limiter(5), + } + ) + .VariantAsync(sample, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNotNull(); + + fakeValuer.Assert().Called(); + } + + [Theory, RandomData] + internal static async Task VariantAsync_RepeatsUntilBothUnequal( + [Fake] IValuer fakeValuer, + DataSample sample1, + DataSample sample2 + ) + { + fakeValuer + .EqualsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .SetupReturn( + Behavior.Series( + Task.FromResult(false), + Task.FromResult(true), + Task.FromResult(true), + Task.FromResult(false), + Task.FromResult(true), + Task.FromResult(true), + Task.FromResult(false), + Task.FromResult(false) + ) + ); + + await new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForVariants = new Limiter(5), + } + ) + .VariantOfAsync([sample1, sample2], TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNotNull(); + + fakeValuer.Assert().Called(); + } + + [Theory, RandomData] + internal static void Unique_AcceptsNull(string value) + { + Tools.Mutator.Unique(null).Assert().IsNotNull(); + Tools.Mutator.UniqueOf(value, null).Assert().IsNot(value).And().IsNotNull(); + } + + [Theory, RandomData] + internal static void UniqueOf_ManyValuesWorks([Size(100)] int[] data) + { + int result = Tools.Mutator.UniqueOf(data); + data.Assert().ContainsNot(result); + } + + [Theory, RandomData] + internal static void Unique_TimesOut([Fake] IValuer fakeValuer, DataSample sample) + { + fakeValuer.Equals(Arg.Any(), Arg.Any()).SetupReturn(true); + fakeValuer.GetHashCode(Arg.Any()).SetupReturn(0); + + new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + Extractor = new Extractor(Tools.Extractor.Options with { Valuer = fakeValuer }), + } + ) + .Assert(x => x.Unique(sample)) + .Throws(); + } + + [Theory, RandomData] + internal static void Unique_RepeatsUntilUnequal([Fake] IValuer fakeValuer, string sample) + { + fakeValuer + .Equals(Arg.Any(), Arg.Any()) + .SetupReturn(Behavior.Series(true, true, true, false)); + fakeValuer.GetHashCode(Arg.Any()).SetupReturn(0); + + new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForUniques = new Limiter(5), + } + ) + .Unique(sample) + .Assert() + .IsNotNull(); + } + + [Theory, RandomData] + internal static void Unique_RepeatsUntilBothUnequal( + [Fake] IValuer fakeValuer, + string sample1, + string sample2 + ) + { + fakeValuer + .Equals(Arg.Any(), Arg.Any()) + .SetupReturn(Behavior.Series(false, true, true, false, true, true, false, false)); + fakeValuer.GetHashCode(Arg.Any()).SetupReturn(0); + + new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForUniques = new Limiter(5), + } + ) + .UniqueOf([sample1, sample2]) + .Assert() + .IsNotNull(); + } + + [Theory, RandomData] + internal static async Task UniqueAsync_AcceptsNull(string value) + { + await Tools + .Mutator.UniqueAsync(null, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNotNull(); + await Tools + .Mutator.UniqueOfAsync([value, null], TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNot(value) + .And() + .IsNotNull(); + } + + [Theory, RandomData] + internal static async Task UniqueOfAsync_ManyValuesWorks([Size(100)] int[] data) + { + int result = await Tools.Mutator.UniqueOfAsync(data, TestContext.Current.CancellationToken); + await data.Assert().ContainsNotAsync(result, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task UniqueAsync_TimesOut([Fake] IValuer fakeValuer, DataSample sample) + { + fakeValuer + .EqualsAsync( + Arg.Any(), + Arg.Any(), + TestContext.Current.CancellationToken + ) + .SetupReturn(Task.FromResult(true)); + fakeValuer + .GetHashCodeAsync(Arg.Any(), TestContext.Current.CancellationToken) + .SetupReturn(Task.FromResult(0)); + + return new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + Extractor = new Extractor(Tools.Extractor.Options with { Valuer = fakeValuer }), + } + ) + .UniqueAsync(sample, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task UniqueAsync_RepeatsUntilUnequal([Fake] IValuer fakeValuer, string sample) + { + fakeValuer + .EqualsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .SetupReturn( + Behavior.Series( + Task.FromResult(true), + Task.FromResult(true), + Task.FromResult(true), + Task.FromResult(false) + ) + ); + fakeValuer + .GetHashCodeAsync(Arg.Any(), Arg.Any()) + .SetupReturn(Task.FromResult(0)); + + return new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForUniques = new Limiter(5), + } + ) + .UniqueAsync(sample, TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNotNull(); + } + + [Theory, RandomData] + internal static Task UniqueAsync_RepeatsUntilBothUnequal( + [Fake] IValuer fakeValuer, + string sample1, + string sample2 + ) + { + fakeValuer + .EqualsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .SetupReturn( + Behavior.Series( + Task.FromResult(false), + Task.FromResult(true), + Task.FromResult(true), + Task.FromResult(false), + Task.FromResult(true), + Task.FromResult(true), + Task.FromResult(false), + Task.FromResult(false) + ) + ); + fakeValuer + .GetHashCodeAsync(Arg.Any(), Arg.Any()) + .SetupReturn(Task.FromResult(0)); + + return new Mutator( + Tools.Mutator.Options with + { + Valuer = fakeValuer, + AttemptLimitForUniques = new Limiter(5), + } + ) + .UniqueOfAsync([sample1, sample2], TestContext.Current.CancellationToken) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .IsNotNull(); + } + + [Theory, RandomData] + internal void Modify_NoHintsUnsupported(object data) + { + TestInstance + .Assert(x => x.Modify(data, CreateHintChainer(null))) + .Throws(); + } + + [Theory, RandomData] + internal void Modify_NullResultSafe([Stub] IMutateHint hint, object data) + { + TestInstance + .Assert(x => x.Modify(data, CreateHintChainer(hint))) + .Throws(); + } + + [Theory, RandomData] + internal void Modify_WrapsError([Stub] IMutateHint hint, object data) + { + hint.TryToModify(data, Arg.Any()) + .SetupReturn(Behavior.Throw()); + + TestInstance.Assert(x => x.Modify(data, CreateHintChainer(hint))).Throws(); + } + + private static MutatorChainer CreateHintChainer(IMutateHint hint) + { + return new MutatorChainer( + Tools.Mutator.Options with + { + IncludeFoundHints = false, + IncludeFrameworkHints = false, + Hints = hint != null ? [hint] : [], + }, + new MutatorEngine() + ); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Handlers/CollectionInternalsMutateHandlerTests.cs b/tests/Toolbox.Tests/MutatorTool/Handlers/CollectionInternalsMutateHandlerTests.cs new file mode 100644 index 00000000..c46ad049 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Handlers/CollectionInternalsMutateHandlerTests.cs @@ -0,0 +1,27 @@ +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Handlers; + +public sealed class CollectionInternalsMutateHandlerTests() + : AutoTester(typeof(CollectionInternalsMutateHandler)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(InvalidCastException)], + DisableParameterMutationTests = true, + }; + + [Fact] + internal static void CollectionInternalsMutateHandler_InternalOnly() + { + typeof(CollectionInternalsMutateHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void SupportedType_SetAsInvalid() + { + new CollectionInternalsMutateHandler().SupportedType.Assert().IsNull(); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Handlers/FactoryMutateHandlerTests.cs b/tests/Toolbox.Tests/MutatorTool/Handlers/FactoryMutateHandlerTests.cs new file mode 100644 index 00000000..fc9b1f78 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Handlers/FactoryMutateHandlerTests.cs @@ -0,0 +1,20 @@ +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Handlers; + +public sealed class FactoryMutateHandlerTests() : AutoTester(typeof(FactoryMutateHandler<>)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(InvalidCastException)], + DisableParameterMutationTests = true, + }; + + [Fact] + internal static void FactoryMutateHandler_InternalOnly() + { + typeof(FactoryMutateHandler<>).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Handlers/NoMutateHandlerTests.cs b/tests/Toolbox.Tests/MutatorTool/Handlers/NoMutateHandlerTests.cs new file mode 100644 index 00000000..65c5d296 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Handlers/NoMutateHandlerTests.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Handlers; + +public sealed class NoMutateHandlerTests() : AutoTester(typeof(NoMutateHandler)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { DisableParameterMutationTests = true }; + + [Fact] + internal static void NoMutateHandler_InternalOnly() + { + typeof(NoMutateHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Handlers/ReflectionMutateHandlersTests.cs b/tests/Toolbox.Tests/MutatorTool/Handlers/ReflectionMutateHandlersTests.cs new file mode 100644 index 00000000..0d7bb3dc --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Handlers/ReflectionMutateHandlersTests.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Handlers; + +public sealed class ReflectionMutateHandlersTests() : AutoTester(typeof(ReflectionMutateHandlers)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { DisableParameterMutationTests = true }; + + [Fact] + internal static void ReflectionMutateHandlers_InternalOnly() + { + typeof(ReflectionMutateHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Handlers/StringDictionaryMutateHandlerTests.cs b/tests/Toolbox.Tests/MutatorTool/Handlers/StringDictionaryMutateHandlerTests.cs new file mode 100644 index 00000000..a62bfc08 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Handlers/StringDictionaryMutateHandlerTests.cs @@ -0,0 +1,32 @@ +using System.Collections.Specialized; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Handlers; + +public sealed class StringDictionaryMutateHandlerTests() + : AutoTester(typeof(StringDictionaryMutateHandler)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(InvalidCastException)], + DisableParameterMutationTests = true, + }; + + [Fact] + internal static void StringDictionaryMutateHandler_InternalOnly() + { + typeof(StringDictionaryMutateHandler).IsPublic.Assert().Is(false); + } + + [Theory, RandomData] + internal static void ModifySupported_EmptyWorks([Size(0)] StringDictionary data) + { + new StringDictionaryMutateHandler() + .ModifySupported(data, new MutatorChainer(Tools.Mutator.Options, new MutatorEngine())) + .Assert() + .Is(true); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/CollectionMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/CollectionMutateHintTests.cs new file mode 100644 index 00000000..4c94797f --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/CollectionMutateHintTests.cs @@ -0,0 +1,44 @@ +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class CollectionMutateHintTests : MutateHintTestBase +{ + [Fact] + public void Alter_ImmutableSamplesFalse() + { + RunModifyTest(false); + RunModifyTest(false, 0); + RunModifyTest(false, 0); + } + + [Fact] + public void Alter_MutableSamplesTrue() + { + RunModifyTest(true, 10); + RunModifyTest>(true); + RunModifyTest>(true, 0); + } + + [Theory, RandomData] + public void Alter_AddsToMutableCollection(List data) + { + List original = data.Tools().Copy(); + + TestInstance + .TryToModify(data, CreateChainer()) + .Assert() + .Is(new MutateHintResult(true)) + .Also(data) + .HasCount(original.Count + 1); + } + + [Fact] + public void Alter_CappedAttempts() + { + HashSet full = [true, false]; + full.Tools().Modify().Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/DictionaryMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/DictionaryMutateHintTests.cs new file mode 100644 index 00000000..795cb7e8 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/DictionaryMutateHintTests.cs @@ -0,0 +1,51 @@ +using System.Collections.Frozen; +using System.Collections.Specialized; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.MutatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class DictionaryMutateHintTests : MutateHintTestBase +{ + [Fact] + public void Modify_ImmutableSamplesFalse() + { + RunModifyTest>(false, 0); + RunModifyTest>(false); + } + + [Fact] + public void Modify_MutableSamplesTrue() + { + RunModifyTest>(true, 0); + RunModifyTest>(true); + RunModifyTest>(true, 0); + RunModifyTest>(true); + RunModifyTest(true, 0); + RunModifyTest(true); + RunModifyTest(true, 0); + RunModifyTest(true); + } + + [Theory, RandomData] + public void Modify_UsesInternalType(int key, DataSample value) + { + ListDictionary data = new() { { key.Tools().Variant(), null }, { key, value } }; + ListDictionary original = data.Tools().Copy(); + + Limiter.Score.StallUntil( + "Until added to.", + () => TestInstance.TryToModify(data, CreateChainer()), + () => data.Count > original.Count, + TestContext.Current.CancellationToken + ); + + data.Assert() + .IsNot(original) + .Also(data.Keys.OfType()) + .HasCount(3) + .Also(data.Values.OfType()) + .HasCountMoreThan(1); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/HandlerMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/HandlerMutateHintTests.cs new file mode 100644 index 00000000..9f2e8ce1 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/HandlerMutateHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.MutatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class HandlerMutateHintTests : MutateHintTestBase; diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/ImmutableEnumerableMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/ImmutableEnumerableMutateHintTests.cs new file mode 100644 index 00000000..9e3e121b --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/ImmutableEnumerableMutateHintTests.cs @@ -0,0 +1,23 @@ +using System.Collections.Immutable; +using Werecodent.CreateAndFake.MutatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class ImmutableEnumerableMutateHintTests + : MutateHintTestBase +{ + [Fact] + public void Modify_ImmutableSamplesFalse() + { + RunModifyTest>(false); + RunModifyTest>(false, 0); + RunModifyTest>(false, 0); + } + + [Fact] + public void Modify_MutableSamplesTrue() + { + RunModifyTest>(true, 10); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/LegacyCollectionMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/LegacyCollectionMutateHintTests.cs new file mode 100644 index 00000000..341b8a7a --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/LegacyCollectionMutateHintTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.MutatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class LegacyCollectionMutateHintTests : MutateHintTestBase +{ + [Fact] + public void Modify_DataCollectionMutable() + { + RunModifyTest(true, 10); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/ListMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/ListMutateHintTests.cs new file mode 100644 index 00000000..461f5e05 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/ListMutateHintTests.cs @@ -0,0 +1,45 @@ +using System.Collections; +using System.Collections.Immutable; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.MutatorTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class ListMutateHintTests : MutateHintTestBase +{ + [Fact] + public void Modify_ImmutableSamplesFalse() + { + RunModifyTest(false, 0); + RunModifyTest(false, 0); + RunModifyTest>(false, 0); + RunModifyTest(false, 0); + } + + [Fact] + public void Modify_ValueCollectionMutable() + { + RunModifyTest(true); + RunModifyTest(true); + RunModifyTest(true); + RunModifyTest(true, 0); + RunModifyTest(true, 10); + } + + [Theory, RandomData] + public void Modify_UsesInternalType(DataSample value) + { + ArrayList data = new() { { null }, { value } }; + ArrayList original = data.Tools().Copy(); + + Limiter.Score.StallUntil( + "Until added to.", + () => TestInstance.TryToModify(data, CreateChainer()), + () => data.Count > original.Count, + TestContext.Current.CancellationToken + ); + + data.Assert().IsNot(original).Also(data.OfType()).HasCountMoreThan(1); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/ObjectMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/ObjectMutateHintTests.cs new file mode 100644 index 00000000..db814c37 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/ObjectMutateHintTests.cs @@ -0,0 +1,116 @@ +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Hints; +using Werecodent.CreateAndFake.Samples.BasicData; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class ObjectMutateHintTests : MutateHintTestBase +{ + public ObjectMutateHintTests() + : base([typeof(DataHolderSample)], []) { } + + [Fact] + internal void SupportedTypes_SupportsObject() + { + TestInstance.SupportedTypes.Assert().Is(new Type[] { typeof(object) }); + } + + [Fact] + internal void Modify_StatelessImmutable() + { + RunModifyTest(false); + } + + [Fact] + internal void Modify_ComplexObjectsWork() + { + RunModifyTest(true); + RunModifyTest(true); + RunModifyTest(true); + RunModifyTest(true); + RunModifyTest(true); + } + + [Fact] + internal void Modify_IgnoresReadOnly() + { + TestInstance + .TryToModify(new AllInvalidsSample(), CreateChainer()) + .Assert() + .Is(new MutateHintResult(false)); + } + + [Fact] + internal void Modify_RandomizesProperty() + { + PropertyLoopSample original = Tools.Randomizer.Create(); + IMutatorChainer chainer = CreateChainer(); + MutateHintResult expectedResult = new(true); + + Limiter.Myriad.Repeat( + "Test smart randomization unequal.", + () => + { + PropertyLoopSample sample = new() { FirstName = original.FirstName }; + TestInstance.TryToModify(sample, chainer).Assert().Is(expectedResult); + sample.FirstName.Assert().IsNot(original.FirstName); + }, + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal void Modify_RandomizesField() + { + FieldLoopSample original = Tools.Randomizer.Create(); + IMutatorChainer chainer = CreateChainer(); + MutateHintResult expectedResult = new(true); + + Limiter.Myriad.Repeat( + "Test smart randomization unequal.", + () => + { + FieldLoopSample sample = new() { LastName = original.LastName }; + TestInstance.TryToModify(sample, chainer).Assert().Is(expectedResult); + sample.LastName.Assert().IsNot(original.LastName); + }, + TestContext.Current.CancellationToken + ); + } + + private sealed class PropertyLoopSample + { + public string FirstName { get; set; } + } + + private sealed class FieldLoopSample + { + public string LastName; + } + +#pragma warning disable IDE0052, S1144, S2325, S2376 // For testing. + private sealed class AllInvalidsSample + { + public const int ConstField = 0; + + public readonly string ReadOnlyField = "Value"; + + private string _hidden = ""; + + public string ReadOnlyProp { get; } = "Value"; + + public string SetOnlyProp + { + set => _hidden = value; + } + + public string BadProp + { + get => ""; + set => throw new NotSupportedException(); + } + } +#pragma warning restore S1144, IDE0052, S2376, S2325 +} diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/StreamMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/StreamMutateHintTests.cs new file mode 100644 index 00000000..ccca6a41 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/StreamMutateHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.MutatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class StreamMutateHintTests : MutateHintTestBase; diff --git a/tests/Toolbox.Tests/MutatorTool/Hints/UnmodifiableMutateHintTests.cs b/tests/Toolbox.Tests/MutatorTool/Hints/UnmodifiableMutateHintTests.cs new file mode 100644 index 00000000..33fa5682 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/Hints/UnmodifiableMutateHintTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.MutatorTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool.Hints; + +public sealed class UnmodifiableMutateHintTests : MutateHintTestBase +{ + [Theory, RandomData] + internal void TryToModify_EnumIncluded(Enum flags) + { + TestInstance.TryToModify(flags, CreateChainer()).Assert().Is(new MutateHintResult(false)); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/MutateHintTestBase.cs b/tests/Toolbox.Tests/MutatorTool/MutateHintTestBase.cs new file mode 100644 index 00000000..4ca640d2 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/MutateHintTestBase.cs @@ -0,0 +1,127 @@ +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.MutatorTool.Engine; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool; + +/// Handles testing s. +/// Hint to test. +/// +/// +public abstract class MutateHintTestBase( + IEnumerable validTypes = null, + IEnumerable invalidTypes = null +) : AutoTester + where T : IMutateHint, new() +{ + /// Types that are supported by the hint. + private readonly IEnumerable _validTypes = validTypes ?? new T().SupportedTypes; + + /// Types that aren't supported by the hint. + private readonly IEnumerable _invalidTypes = invalidTypes ?? [typeof(DataHolderSample)]; + + /// + public override Task Tester_NoParameterMutation() + { + return Task.CompletedTask; + } + + /// Ensure the hint supports all provided valid types. + [Fact] + public void TryToModify_ValidTypesSupported() + { + foreach (Type type in _validTypes) + { + object data = type.Tools().CreateRandomInstance(); + TestInstance + .TryToModify(data, CreateChainer()) + .HasData.Assert() + .Is( + true, + $"Hint '{GenericConverter.ExpandName()}' failed to modify type " + + $"'{GenericConverter.ExpandName(type)}'. " + + $"Actual type: '{GenericConverter.ExpandName(data)}'." + ); + } + } + + /// Ensure the hint does not support any invalid types. + [Fact] + public void TryToModify_InvalidTypesNotSupported() + { + foreach (Type type in _invalidTypes) + { + object data = type.Tools().CreateRandomInstance(); + TestInstance + .TryToModify(data, CreateChainer()) + .HasData.Assert() + .Is( + false, + $"Hint '{GenericConverter.ExpandName()}' modified type " + + $"'{GenericConverter.ExpandName(type)}'. " + + $"Actual type: '{GenericConverter.ExpandName(data)}'." + ); + } + } + + /// Ensure priority is within range. + [Fact] + public void EnginePriority_Constrained() + { + TestInstance + .EnginePriority.Assert() + .GreaterThan((int)MutatePriority.None) + .And() + .LessThan((int)MutatePriority.Highest); + } + + /// Ensure expanded type name is used. + [Fact] + public void ToString_Overridden() + { + TestInstance.ToString().Assert().Is(GenericConverter.ExpandName(TestInstance)); + } + + /// The to test. + /// + protected void RunModifyTest(bool shouldMutate, int? collectionSize = null) + { + RunModifyTest(typeof(TData), shouldMutate, collectionSize); + } + + /// Tests that attempted mutation works as intended. + /// The to test. + /// If the data should be mutated. + /// Exact collection size to use if set. + protected void RunModifyTest(Type type, bool shouldMutate, int? collectionSize = null) + { + object data = + (collectionSize == null) + ? type.Tools().CreateRandomInstance() + : type.Tools().CreateRandomSizedInstance(collectionSize.Value); + object original = data.Tools().Copy(); + + TestInstance + .TryToModify(data, CreateChainer()) + .Assert() + .Is(new MutateHintResult(shouldMutate)); + + if (shouldMutate) + { + data.Assert().IsNot(original); + } + else + { + data.Assert().Is(original); + } + } + + /// Create a chainer to use for testing. + /// The created chainer. + /// Options to pass via the chainer. + protected static IMutatorChainer CreateChainer(MutatorOptions options = null) + { + return new MutatorChainer(options ?? Tools.Mutator.Options, new MutatorEngine()); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/MutatorOptionsTests.cs b/tests/Toolbox.Tests/MutatorTool/MutatorOptionsTests.cs new file mode 100644 index 00000000..0b61006f --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/MutatorOptionsTests.cs @@ -0,0 +1,18 @@ +global using MutatorMod = System.Func< + Werecodent.CreateAndFake.MutatorTool.MutatorOptions, + Werecodent.CreateAndFake.MutatorTool.MutatorOptions +>; +using Werecodent.CreateAndFake.MutatorTool; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool; + +public sealed class MutatorOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void MutatorOptions_ModFormRandomizable() + { + typeof(MutatorMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/MutatorTool/MutatorTests.cs b/tests/Toolbox.Tests/MutatorTool/MutatorTests.cs new file mode 100644 index 00000000..82aa6544 --- /dev/null +++ b/tests/Toolbox.Tests/MutatorTool/MutatorTests.cs @@ -0,0 +1,77 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.MutatorTool; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Tests.MutatorTool; + +public sealed class MutatorTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ToolException)], + DisableParameterMutationTests = true, + }; + + [Fact] + internal static Task Mutator_PassthroughWithNoExceptions() + { + return Tools.Tester.PassthroughWithNoExceptionsAsync( + TestContext.Current.CancellationToken, + opt => opt with { IgnorableExceptions = [typeof(TargetInvocationException)] } + ); + } + + [Theory, RandomData] + internal static void Modify_UsesMaxAttemptsForModify([Fake] IValuer valuer, DataSample sample) + { + MutatorOptions mod(MutatorOptions opt) + { + return opt with + { + Valuer = valuer, + MaxAttemptsForModify = 2, + VerifyModifyViaValueHashes = true, + NestedOptions = opt, + }; + } + + Tools.Mutator.WithOptions(mod).Modify(sample).Assert().Is(true); + Tools.Mutator.Modify(sample, mod).Assert().Is(true); + + valuer.GetHashCode(sample, Arg.Any()).SetupReturn(0); + + Tools.Mutator.WithOptions(mod).Modify(sample).Assert().Is(false); + Tools.Mutator.Modify(sample, mod).Assert().Is(false); + + valuer.GetHashCode(sample, Arg.Any()).SetupReturn(Behavior.Series(0, 1, 0, 1)); + + Tools.Mutator.WithOptions(mod).Modify(sample).Assert().Is(true); + Tools.Mutator.Modify(sample, mod).Assert().Is(true); + } + + [Theory, RandomData] + internal static void Modify_CanDisableVerifyModifyViaValueHashes( + [Stub] IValuer valuer, + DataSample sample + ) + { + MutatorOptions mod(MutatorOptions opt) + { + return opt with + { + Valuer = valuer, + MaxAttemptsForModify = 2, + VerifyModifyViaValueHashes = false, + NestedOptions = opt, + }; + } + + Tools.Mutator.Modify(sample, mod).Assert().Is(true); + Tools.Mutator.WithOptions(mod).Modify(sample).Assert().Is(true); + } +} diff --git a/tests/Toolbox.Tests/Properties/AssemblyInfo.cs b/tests/Toolbox.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..4267720d --- /dev/null +++ b/tests/Toolbox.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1 @@ +[assembly: CaptureConsole] diff --git a/tests/Toolbox.Tests/Properties/ConfigTests.cs b/tests/Toolbox.Tests/Properties/ConfigTests.cs new file mode 100644 index 00000000..e537ff66 --- /dev/null +++ b/tests/Toolbox.Tests/Properties/ConfigTests.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using Microsoft.Extensions.Configuration; +using Werecodent.CreateAndFake.Properties; + +namespace Werecodent.CreateAndFake.Tests.Properties; + +public static class ConfigTests +{ + [Fact] + internal static Task Config_GuardsNulls() + { + return Tools.Tester.PreventsNullRefExceptionAsync( + typeof(Config), + TestContext.Current.CancellationToken, + opt => opt with { IgnorableExceptions = [typeof(TypeLoadException)] } + ); + } + + [Fact] + internal static Task Config_NoParameterMutation() + { + return Tools.Tester.PreventsParameterMutationAsync( + typeof(Config), + TestContext.Current.CancellationToken, + opt => + opt with + { + IgnorableExceptions = + [ + typeof(InvalidOperationException), + typeof(TypeLoadException), + ], + } + ); + } + + [Theory, RandomData] + internal static void GetArray_NullReturnsProperty( + [Stub] IConfigurationSection section, + ImmutableArray data + ) + { + Config.GetArray(section, data).Assert().Is(data); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/CreateHintTestBase.cs b/tests/Toolbox.Tests/RandomizerTool/CreateHintTestBase.cs new file mode 100644 index 00000000..5171bfd1 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/CreateHintTestBase.cs @@ -0,0 +1,99 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool; + +/// Handles testing create hints. +/// Create hint to test. +/// Types that can be created by the hint. +/// Types that can't be created by the hint. +public abstract class CreateHintTestBase( + IEnumerable validTypes = null, + IEnumerable invalidTypes = null +) : AutoTester + where T : CreateHint, new() +{ + /// + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = [CreateChainer()], + IgnorableExceptions = [typeof(InvalidOperationException)], + }; + + /// Types that can be created by the hint. + private readonly IEnumerable _validTypes = validTypes ?? new T().SupportedTypes; + + /// Types that can't be created by the hint. + private readonly IEnumerable _invalidTypes = + invalidTypes ?? [typeof(DataHolderSample), typeof(IEnumerable), typeof(IEnumerable<>)]; + + /// Verifies the hint supports the correct types. + [Fact] + public async Task TryToCreate_SupportsValidTypes() + { + foreach (Type type in _validTypes) + { + CreateHintResult result = TestInstance.TryToCreate(type, CreateChainer()); + try + { + result + .HasData.Assert() + .Is( + true, + "Hint '" + typeof(T).Name + "' did not support type '" + type.Name + "'." + ); + result + .Data.Assert() + .IsNotNull( + "Hint '" + typeof(T).Name + "' did not create valid '" + type.Name + "'." + ); + + if (result.Data is IEnumerable collection) + { + collection + .Assert() + .IsNotEmpty( + "Hint '" + + typeof(T).Name + + "' failed to create populated '" + + type + + "'." + ); + } + } + finally + { + await Disposer.CleanupAsync(result.Data); + } + } + } + + /// Verifies the hint doesn't support the wrong types. + [Fact] + public void TryToCreate_InvalidTypesFail() + { + foreach (Type type in _invalidTypes) + { + TestInstance + .TryToCreate(type, CreateChainer()) + .Assert() + .Is( + CreateHintResult.None, + "Hint '" + typeof(T).Name + "' should not support type '" + type.Name + "'." + ); + } + } + + /// Create a chainer to use for testing. + /// Chainer to use for testing. + /// Options to pass via the chainer. + protected static IRandomizerChainer CreateChainer(RandomizerOptions options = null) + { + return new RandomizerChainer(options ?? Tools.Randomizer.Options, new RandomizerEngine()); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Engine/CreateHintResultTests.cs b/tests/Toolbox.Tests/RandomizerTool/Engine/CreateHintResultTests.cs new file mode 100644 index 00000000..3a2d6afb --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Engine/CreateHintResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Engine; + +public sealed class CreateHintResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + CreateHintResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Engine/CreatePriorityTests.cs b/tests/Toolbox.Tests/RandomizerTool/Engine/CreatePriorityTests.cs new file mode 100644 index 00000000..2df128ed --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Engine/CreatePriorityTests.cs @@ -0,0 +1,54 @@ +using Werecodent.CreateAndFake.RandomizerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Engine; + +public sealed class CreatePriorityTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(FormatException)], + }; + + [Fact] + internal static void Disabled_SetToMin() + { + ((int)CreatePriority.Disabled).Assert().Is(int.MinValue); + } + + [Fact] + internal static void None_DefaultAtZero() + { + ((int)CreatePriority.None).Assert().Is(0); + } + + [Fact] + internal static void Highest_AtCap() + { + ((int)CreatePriority.Highest) + .Assert() + .Is(Enum.GetValues(typeof(CreatePriority)).Length - 2); + } + + [Fact] + internal static void Values_AllPositive() + { + Enum.GetValues(typeof(CreatePriority)) + .Cast() + .Except([(int)CreatePriority.Disabled]) + .Where(v => v < 0) + .Assert() + .IsEmpty(); + } + + [Fact] + internal static void Values_Unique() + { + Enum.GetValues(typeof(CreatePriority)) + .Cast() + .ToHashSet() + .Assert() + .HasCount(Enum.GetValues(typeof(CreatePriority)).Length); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Engine/RandomizerChainerTests.cs b/tests/Toolbox.Tests/RandomizerTool/Engine/RandomizerChainerTests.cs new file mode 100644 index 00000000..95653ee0 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Engine/RandomizerChainerTests.cs @@ -0,0 +1,125 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.Samples.ErrorCases; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Engine; + +public sealed class RandomizerChainerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = [Tools.Gen.Next(3, 5)], + MethodsToIgnore = + [ + nameof(RandomizerChainer.CreateInternal), + nameof(RandomizerChainer.Inject), + ], + IgnorableExceptions = + [ + typeof(ArgumentOutOfRangeException), + typeof(ArgumentException), + ], + }; + + [Fact] + internal static Task RandomizerChainer_PassthroughWithNoExceptions() + { + return Tools.Tester.PassthroughWithNoExceptionsAsync( + TestContext.Current.CancellationToken, + opt => opt with { IgnorableExceptions = [typeof(InvalidCastException)] } + ); + } + + [Theory, RandomData] + internal static void CreateSpecific_ThrowsWhenRecreatingSameType( + [Stub] IRandomizerEngine engine, + Type specificType, + Type parentType + ) + { + engine + .Create(specificType, Arg.Any()) + .SetupReturn( + Behavior.Call( + (_, chainer) => chainer.CreateSpecific(specificType, parentType) + ) + ); + + new RandomizerChainer(Tools.Randomizer.Options, engine) + .Assert(x => x.CreateSpecific(specificType, parentType)) + .Throws(); + } + + [Theory, RandomData] + internal static void CreateInternal_ThrowsWhenSameTypeRecreated( + [Stub] IRandomizerEngine engine, + object data + ) + { + Type type = Tools.Mutator.Variant(data.GetType()); + + engine + .Create(type, Arg.Any()) + .SetupReturn( + Behavior.Call( + (_, chainer) => chainer.CreateInternal(type, data) + ) + ); + + new RandomizerChainer(Tools.Randomizer.Options, engine) + .Assert(x => x.CreateInternal(type, data)) + .Throws(); + } + + [Theory, RandomData] + internal static void CreateInternal_CreatesParentLoop( + [Stub] IRandomizerEngine engine, + object parentData, + object childData + ) + { + Type type = Tools.Mutator.VariantOf([parentData.GetType(), childData.GetType()]); + + engine + .Create(type, Arg.Any()) + .SetupReturn( + Behavior.Call( + (_, chainer) => chainer.CreateInternal(parentData.GetType(), childData) + ) + ); + + new RandomizerChainer(Tools.Randomizer.Options, engine) + .CreateInternal(type, parentData) + .Assert() + .Is(parentData); + } + + [Theory, RandomData] + internal static void CreateInternal_CreatesSelfLoop( + [Stub] IRandomizerEngine engine, + object data + ) + { + new RandomizerChainer(Tools.Randomizer.Options, engine) + .CreateInternal(data.GetType(), data) + .Assert() + .Is(data); + } + + [Theory, RandomData] + internal static void Inject_InterfaceFakesInjected( + [Fake] IOnlyMockSample fake, + [Fake] IOnlyMockSample fake2 + ) + { + InjectMockSample holder = Tools.Randomizer.Inject([fake, fake2]); + fake.Tools().ToFake().Verify(Times.Never, f => f.FailIfNotMocked()); + fake2.Tools().ToFake().Verify(Times.Never, f => f.FailIfNotMocked()); + holder.TestIfMockedSeparately(); + fake.Tools().ToFake().Verify(Times.Once, f => f.FailIfNotMocked()); + fake2.Tools().ToFake().Verify(Times.Once, f => f.FailIfNotMocked()); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Engine/RandomizerEngineTests.cs b/tests/Toolbox.Tests/RandomizerTool/Engine/RandomizerEngineTests.cs new file mode 100644 index 00000000..7da40a06 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Engine/RandomizerEngineTests.cs @@ -0,0 +1,82 @@ +using System.Collections.Frozen; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Engine; + +public sealed class RandomizerEngineTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = [Tools.Randomizer.Options], + MethodsToIgnore = FrozenSet.ToFrozenSet(["Inject"]), + }; + + [Theory, RandomData] + internal void Create_NoHintsUnsupported(Type type) + { + TestInstance + .Assert(x => x.Create(type, CreateHintChainer(null))) + .Throws(); + } + + [Theory, RandomData] + internal void Create_NullResultSafe([Stub] ICreateHint hint, Type type) + { + TestInstance + .Assert(x => x.Create(type, CreateHintChainer(hint))) + .Throws(); + } + + [Theory, RandomData] + internal void Inject_NoHintsUnsupported(Type type) + { + TestInstance + .Assert(x => x.Inject(type, null, CreateHintChainer(null))) + .Throws(); + } + + [Theory, RandomData] + internal void Inject_NullResultSafe([Stub] ICreateHint hint, Type type) + { + TestInstance + .Assert(x => x.Inject(type, [], CreateHintChainer(hint))) + .Throws(); + } + + [Fact] + internal void Inject_LimitedIteration() + { + TestInstance + .Assert(x => + x.Inject( + typeof(GoodOrBadSampleHolder<>), + [], + new RandomizerChainer( + Tools.Randomizer.Options with + { + Design = Tools.Randomizer.Options.Design with { IterationLimit = 0 }, + }, + new RandomizerEngine() + ) + ) + ) + .Throws(); + } + + private static RandomizerChainer CreateHintChainer(ICreateHint hint) + { + return new RandomizerChainer( + Tools.Randomizer.Options with + { + IncludeFoundHints = false, + IncludeFrameworkHints = false, + Hints = hint != null ? [hint] : [], + }, + new RandomizerEngine() + ); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/GenericResolverTests.cs b/tests/Toolbox.Tests/RandomizerTool/GenericResolverTests.cs new file mode 100644 index 00000000..3ebec8e7 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/GenericResolverTests.cs @@ -0,0 +1,9 @@ +using Werecodent.CreateAndFake.RandomizerTool; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool; + +public sealed class GenericResolverTests() : AutoTester(typeof(GenericResolver)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ArgumentException)] }; +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/ConfigurationSectionCreateHandlerTests.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/ConfigurationSectionCreateHandlerTests.cs new file mode 100644 index 00000000..086953a9 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/ConfigurationSectionCreateHandlerTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class ConfigurationSectionCreateHandlerTests() + : AutoTester(typeof(ConfigurationSectionCreateHandler)) +{ + [Fact] + internal static void ConfigurationSectionCreateHandler_InternalOnly() + { + typeof(ConfigurationSectionCreateHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/ExceptionCreateHandlersTests.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/ExceptionCreateHandlersTests.cs new file mode 100644 index 00000000..eff60702 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/ExceptionCreateHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class ExceptionCreateHandlersTests() : AutoTester(typeof(ExceptionCreateHandlers)) +{ + [Fact] + internal static void ExceptionCreateHandlers_InternalOnly() + { + typeof(ExceptionCreateHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/FactoryCreateHandlerTests.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/FactoryCreateHandlerTests.cs new file mode 100644 index 00000000..afd9b502 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/FactoryCreateHandlerTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class FactoryCreateHandlerTests() : AutoTester(typeof(FactoryCreateHandler)); diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/FactoryCreateHandler{T}Tests.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/FactoryCreateHandler{T}Tests.cs new file mode 100644 index 00000000..451c9d32 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/FactoryCreateHandler{T}Tests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class FactoryCreateHandler_T_Tests() : AutoTester(typeof(FactoryCreateHandler<>)); diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/ReflectionCreateHandlersTest.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/ReflectionCreateHandlersTest.cs new file mode 100644 index 00000000..935a9f05 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/ReflectionCreateHandlersTest.cs @@ -0,0 +1,104 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Handlers; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class ReflectionCreateHandlersTests() : AutoTester(typeof(ReflectionCreateHandlers)) +{ + private const int _HealthyMin = 6; + + [Fact] + internal static void ReflectionCreateHandlers_InternalOnly() + { + typeof(ReflectionCreateHandlers).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void Handlers_HealthyRandomizationPools() + { + ReflectionCreateHandlers.PossibleTypes.Assert().HasCountMoreThan(_HealthyMin); + ReflectionCreateHandlers.PossibleConstructors.Assert().HasCountMoreThan(_HealthyMin); + ReflectionCreateHandlers.PossibleMethods.Assert().HasCountMoreThan(_HealthyMin); + ReflectionCreateHandlers.PossibleProperties.Assert().HasCountMoreThan(_HealthyMin); + ReflectionCreateHandlers.PossibleConstants.Assert().HasCountMoreThan(_HealthyMin); + ReflectionCreateHandlers.PossibleParameters.Assert().HasCountMoreThan(_HealthyMin); + ReflectionCreateHandlers + .PossibleFields.Where(f => f.GetType() == RuntimeDetails.RtFieldInfoType) + .Assert() + .HasCountMoreThan(_HealthyMin); + ReflectionCreateHandlers + .PossibleFields.Where(f => f.GetType() == RuntimeDetails.MdFieldInfoType) + .Assert() + .HasCountMoreThan(_HealthyMin); + } + + [Fact] + internal static async Task Handlers_AllMethodsSupported() + { + foreach ( + MethodBase method in Enumerable + .Empty() + .Concat(ReflectionCreateHandlers.PossibleMethods) + .Concat(ReflectionCreateHandlers.PossibleConstructors) + ) + { + object instance = null; + MethodCallWrapper syncWrapper = null; + MethodCallWrapper asyncWrapper = null; + RunResult result = null; + try + { + instance = method.ReflectedType.Tools().CreateRandomInstance(); + +#pragma warning disable CA1849, MA0042, S6966, VSTHRD103 // For testing. + syncWrapper = Tools.Runner.CreateFor(method, TestContext.Current.CancellationToken); +#pragma warning restore CA1849, MA0042, S6966, VSTHRD103 + + asyncWrapper = await Tools.Runner.CreateForAsync( + method, + TestContext.Current.CancellationToken + ); + await asyncWrapper + .Tools() + .Copy() + .Assert() + .IsAsync(asyncWrapper, TestContext.Current.CancellationToken); + + result = await Tools.Runner.RunAsync( + instance, + asyncWrapper, + TestContext.Current.CancellationToken + ); + } + catch (Exception e) + { + throw new ToolException( + $"Method '{method}' on '{method.DeclaringType}' encountered an issue.", + e + ); + } + finally + { + await Disposer.CleanupAsync( + instance, + syncWrapper?.Args, + asyncWrapper?.Args, + result?.Result + ); + } + } + } + + [Fact] + internal static Task PossibleTypes_AllSupported() + { + return Tools.Tester.VerifyToolSetSupportAsync( + ReflectionCreateHandlers.PossibleTypes, + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/SelfCreateHandlersTests.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/SelfCreateHandlersTests.cs new file mode 100644 index 00000000..80ac35be --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/SelfCreateHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class SelfCreateHandlersTests() : AutoTester(typeof(SelfCreateHandlers)) +{ + [Fact] + internal static void SelfCreateHandlers_InternalOnly() + { + typeof(SelfCreateHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/StringCreateHandlerTests.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/StringCreateHandlerTests.cs new file mode 100644 index 00000000..bb5fe9e3 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/StringCreateHandlerTests.cs @@ -0,0 +1,66 @@ +using System.Collections.Frozen; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class StringCreateHandlerTests() : AutoTester(typeof(StringCreateHandler)) +{ + [Fact] + internal static void StringCreateHandler_InternalOnly() + { + typeof(StringCreateHandler).IsPublic.Assert().Is(false); + } + + [Fact] + internal static void CreateSupported_SizeConstraintsWork() + { + RandomizerOptions options = Tools.Randomizer.Options with + { + StringMinSize = 2, + StringMaxSize = 5, + }; + StringCreateHandler hint = new(); + RandomizerChainer chainer = new(options, new RandomizerEngine()); + + for (int i = 0; i < 1000; i++) + { + string result = (string)hint.CreateSupported(chainer); + + result + .Length.Assert() + .GreaterThanOrEqualTo(options.StringMinSize, "Result was too small."); + result.Length.Assert().LessThanOrEqualTo(options.StringMaxSize, "Result was too big."); + } + } + + [Fact] + internal static void CreateSupported_UsesCharSet() + { + RandomizerOptions options = Tools.Randomizer.Options with + { + StringMinSize = 3, + StringMaxSize = 3, + StringCharacterSet = FrozenSet.ToFrozenSet("a"), + }; + StringCreateHandler hint = new(); + object value = "aaa"; + for (int i = 0; i < 100; i++) + { + hint.CreateSupported(new RandomizerChainer(options, new RandomizerEngine())) + .Assert() + .Is(value); + } + + RandomizerOptions options2 = options with + { + StringCharacterSet = FrozenSet.ToFrozenSet("ab"), + }; + RandomizerChainer chainer = new(options2, new RandomizerEngine()); + for (int i = 0; i < 100; i++) + { + ((string)hint.CreateSupported(chainer)).Trim('a', 'b').Length.Assert().Is(0); + } + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/SystemCreateHandlersTests.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/SystemCreateHandlersTests.cs new file mode 100644 index 00000000..2a403cb0 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/SystemCreateHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class SystemCreateHandlersTests() : AutoTester(typeof(SystemCreateHandlers)) +{ + [Fact] + internal static void SystemCreateHandlers_InternalOnly() + { + typeof(SystemCreateHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Handlers/ValueCreateHandlersTests.cs b/tests/Toolbox.Tests/RandomizerTool/Handlers/ValueCreateHandlersTests.cs new file mode 100644 index 00000000..622c97dd --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Handlers/ValueCreateHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.RandomizerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Handlers; + +public sealed class ValueCreateHandlersTests() : AutoTester(typeof(ValueCreateHandlers)) +{ + [Fact] + internal static void ValueCreateHandlers_InternalOnly() + { + typeof(ValueCreateHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/AsyncCollectionCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/AsyncCollectionCreateHintTests.cs new file mode 100644 index 00000000..df02d956 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/AsyncCollectionCreateHintTests.cs @@ -0,0 +1,142 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class AsyncCollectionCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(AsyncHashSet), + typeof(AsyncHashSet), + typeof(IAsyncSet), + typeof(IAsyncSet), + typeof(IAsyncEnumerable), + typeof(IAsyncEnumerable), + typeof(AsyncList), + typeof(AsyncList), + ]; + + public AsyncCollectionCreateHintTests() + : base(_ValidTypes) { } + + [Theory, RandomData] + internal static async Task TryToCreate_Empty([Size(0)] IAsyncSet items) + { + IAsyncEnumerator gen = items.GetAsyncEnumerator(TestContext.Current.CancellationToken); + await using (gen) + { + (await gen.MoveNextAsync()).Assert().Is(false); + } + } + + [Theory, RandomData] + internal static async Task TryToCreate_Repeatable(IAsyncSet items) + { + List first = []; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + first.Add(item); + } + + List second = []; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + second.Add(item); + } + + first.Assert().Is(second); + } + + [Theory, RandomData] + internal static async Task TryToCreate_Cancel(IAsyncSet items) + { + await items.GetAsyncEnumerator(TestContext.Current.CancellationToken).DisposeAsync(); + } + + [Theory, RandomData] + internal static async Task TryToCreate_Interrupt([Size(5)] IAsyncSet items) + { + await items.GetAsyncEnumerator(TestContext.Current.CancellationToken).DisposeAsync(); + + int count = 0; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + count++; + if (count == 3) + { + break; + } + } + + count = 0; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + count++; + } + count.Assert().Is(5); + } + + [Theory, RandomData] + internal static async Task TryToCreate_EmptyList([Size(0)] IAsyncEnumerable items) + { + IAsyncEnumerator gen = items.GetAsyncEnumerator(TestContext.Current.CancellationToken); + await using (gen) + { + (await gen.MoveNextAsync()).Assert().Is(false); + } + } + + [Theory, RandomData] + internal static async Task TryToCreate_RepeatableList(IAsyncEnumerable items) + { + List first = []; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + first.Add(item); + } + + List second = []; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + second.Add(item); + } + + first.Assert().Is(second); + } + + [Theory, RandomData] + internal static async Task TryToCreate_CancelList(IAsyncEnumerable items) + { + await items.GetAsyncEnumerator(TestContext.Current.CancellationToken).DisposeAsync(); + } + + [Theory, RandomData] + internal static async Task TryToCreate_InterruptList([Size(5)] IAsyncEnumerable items) + { + await items.GetAsyncEnumerator(TestContext.Current.CancellationToken).DisposeAsync(); + + int count = 0; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + count++; + if (count == 3) + { + break; + } + } + + count = 0; + await foreach (int item in items.WithCancellation(TestContext.Current.CancellationToken)) + { + count++; + } + count.Assert().Is(5); + } + + [Theory, RandomData] + internal static Task TryToCreate_LargeAsyncSetsValid([Size(100)] IAsyncSet items) + { + return items.Assert().HasCountAsync(100, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/CollectionCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/CollectionCreateHintTests.cs new file mode 100644 index 00000000..cdfda942 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/CollectionCreateHintTests.cs @@ -0,0 +1,76 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class CollectionCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ItemTypes = + [ + typeof(string), + typeof(IComparable), + typeof(int), + typeof(double), + typeof(KeyValuePair), + ]; + + private static readonly Type[] _ValidTypes = + [ + .. CollectionCreateHint + .PotentialCollections.Concat([ + typeof(IEnumerable<>), + typeof(IList<>), + typeof(ISet<>), + typeof(IDictionary<,>), + typeof(IReadOnlyCollection<>), + typeof(IReadOnlyList<>), + typeof(IReadOnlyDictionary<,>), + typeof(int[]), + typeof(string[]), + typeof(object[]), + typeof(IImmutableList<>), + typeof(IImmutableQueue<>), + typeof(IImmutableStack<>), + typeof(IImmutableDictionary<,>), + typeof(FrozenSet<>), + typeof(FrozenDictionary<,>), + ]) + .Select(MakeDefined), + ]; + + public CollectionCreateHintTests() + : base(_ValidTypes) { } + + [Fact] + public void TryToCreate_RetriesSetsWithDuplicates() + { + for (int i = 0; i < 20; i++) + { + TestInstance.TryToCreate(typeof(IDictionary), CreateChainer()); + } + } + + [Fact] + public void TryToCreate_CorrectSizeEvenWithDuplicates() + { + for (int i = 0; i < 20; i++) + { + Tools.Randomizer.CreateSized>(2).Assert().HasCount(2); + } + } + + private static Type MakeDefined(Type type) + { + if (type.IsGenericTypeDefinition) + { + return type.MakeGenericType([ + .. type.GetGenericArguments().Select(_ => Tools.Gen.NextItem(_ItemTypes)), + ]); + } + else + { + return type; + } + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/ComparerCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/ComparerCreateHintTests.cs new file mode 100644 index 00000000..9a85abd4 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/ComparerCreateHintTests.cs @@ -0,0 +1,18 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class ComparerCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(IAsyncEqualityComparer), + typeof(IAsyncEqualityComparer), + typeof(IEqualityComparer), + typeof(IEqualityComparer), + ]; + + public ComparerCreateHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/DelegateCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/DelegateCreateHintTests.cs new file mode 100644 index 00000000..76d827a6 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/DelegateCreateHintTests.cs @@ -0,0 +1,91 @@ +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class DelegateCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ActionTypes = + [ + typeof(Action), + typeof(Action<>), + typeof(Action<,>), + typeof(Action<,,>), + typeof(Action<,,,>), + typeof(Action<,,,,>), + typeof(Action<,,,,,>), + typeof(Action<,,,,,,>), + typeof(Action<,,,,,,,>), + typeof(Action<,,,,,,,,>), + typeof(Action<,,,,,,,,,>), + typeof(Action<,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,,,,>), + ]; + + private static readonly Type[] _FuncTypes = + [ + typeof(Func<>), + typeof(Func<,>), + typeof(Func<,,>), + typeof(Func<,,,>), + typeof(Func<,,,,>), + typeof(Func<,,,,,>), + typeof(Func<,,,,,,>), + typeof(Func<,,,,,,,>), + typeof(Func<,,,,,,,,>), + typeof(Func<,,,,,,,,,>), + typeof(Func<,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,,,,>), + ]; + + private static readonly Type[] _ValidTypes = + [ + typeof(Action), + typeof(Func), + typeof(Delegate), + typeof(Action), + ]; + + public DelegateCreateHintTests() + : base(_ValidTypes) { } + + [Fact] + internal static void Create_HandlesAllDelegates() + { + foreach (Type type in _ActionTypes.Concat(_FuncTypes)) + { + Tools.Randomizer.Create(type).Assert().IsNotNull(); + } + } + + [Fact] + internal void Create_HandlesOutRef() + { + CreateHintResult result = TestInstance.TryToCreate( + typeof(Action), + CreateChainer() + ); + result.HasData.Assert().Is(true); + + Action action = (Action)result.Data; + + OutRef sampleInt = new(); + action.Invoke(sampleInt); + sampleInt.Var.Assert().IsNot(default(int)); + + OutRef sampleString = new(); + action.Invoke(sampleString); + sampleString.Var.Assert().IsNot(default(string)); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/EnumCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/EnumCreateHintTests.cs new file mode 100644 index 00000000..f8a4beab --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/EnumCreateHintTests.cs @@ -0,0 +1,12 @@ +using System.Reflection; +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class EnumCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(BindingFlags)]; + + public EnumCreateHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/FakeCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/FakeCreateHintTests.cs new file mode 100644 index 00000000..aaea8e59 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/FakeCreateHintTests.cs @@ -0,0 +1,31 @@ +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Samples.SingleValue; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class FakeCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(Fake), + typeof(Fake), + typeof(Fake>), + ]; + + public FakeCreateHintTests() + : base(_ValidTypes) { } + + [Theory, RandomData] + internal static void TryToCreate_VoidCovered([Fake] Holder sample, string data) + { + sample.Assert(x => x.WriteValue(data)).ThrowsNoException(); + } + + [Theory, RandomData] + internal static void TryToCreate_GenericsCovered([Fake] GenericSample sample) + { + sample.Run("").Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/GenericCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/GenericCreateHintTests.cs new file mode 100644 index 00000000..2611c915 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/GenericCreateHintTests.cs @@ -0,0 +1,25 @@ +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class GenericCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(IList<>), + typeof(KeyValuePair<,>), + typeof(GenericSample<>), + typeof(ConstraintSample<,>), + ]; + + private static readonly Type[] _InvalidTypes = + [ + typeof(DataHolderSample), + typeof(IList), + typeof(KeyValuePair), + ]; + + public GenericCreateHintTests() + : base(_ValidTypes, _InvalidTypes) { } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/HandlerCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/HandlerCreateHintTests.cs new file mode 100644 index 00000000..53307ba7 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/HandlerCreateHintTests.cs @@ -0,0 +1,38 @@ +using System.Collections; +using System.Reflection; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class HandlerCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _InvalidTypes = + [ + typeof(IEnumerable), + typeof(IEnumerable<>), + typeof(IEnumerable), + ]; + + public HandlerCreateHintTests() + : base(null, _InvalidTypes) { } + + [Fact] + internal void Debug_HandlerCreateHint_SupportedTypes() + { + TestInstance + .SupportedTypes.OrderBy(t => t.Name) + .Select(GenericConverter.ExpandName) + .Assert() + .Debug(); + } + + [Fact] + internal void TryToCreate_ContinuesUntilMemberFound() + { + for (int i = 0; i < 50; i++) + { + _ = TestInstance.TryToCreate(typeof(FieldInfo), CreateChainer()); + } + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/InjectedCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/InjectedCreateHintTests.cs new file mode 100644 index 00000000..b28d96dc --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/InjectedCreateHintTests.cs @@ -0,0 +1,63 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.Tests.FakerTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class InjectedCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(Injected), + typeof(Injected), + typeof(Injected), + typeof(Injected), + typeof(Injected), + ]; + + private static readonly Type[] _InvalidTypes = + [ + typeof(DataHolderSample), + typeof(IUnimplementedSample), + ]; + + public InjectedCreateHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + [Theory, RandomData] + internal void Create_ValidInjections(Injected sample) + { + sample.Fake().Assert().IsNotNull(); + sample + .Fake(1) + .Assert() + .IsNotNull() + .And() + .IsNot(sample.Fake()); + + sample + .Fake() + .Setup(m => m.FailIfNotMocked(), Behavior.Returns(false, Times.Once)); + sample.Dummy.TestIfMockedSeparately(); + sample.Fake().Verify(Times.Once); + sample.Verify(); + } + + [Fact] + internal void Create_NoConstructorThrows() + { + Tools + .Randomizer.Assert(x => x.Create>()) + .Throws(); + } + + [Theory, RandomData] + internal void Create_ValuesRandom(Injected sample) + { + sample.Dummy.Value1.Assert().IsNot(0); + sample.Dummy.Value2.Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/LegacyCollectionCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/LegacyCollectionCreateHintTests.cs new file mode 100644 index 00000000..2e4661bf --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/LegacyCollectionCreateHintTests.cs @@ -0,0 +1,21 @@ +using System.Collections; +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class LegacyCollectionCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + .. LegacyCollectionCreateHint.PotentialCollections, + typeof(IEnumerable), + typeof(IList), + typeof(IDictionary), + ]; + + private static readonly Type[] _InvalidTypes = [typeof(DataHolderSample)]; + + public LegacyCollectionCreateHintTests() + : base(_ValidTypes, _InvalidTypes) { } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/NullableCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/NullableCreateHintTests.cs new file mode 100644 index 00000000..5987798b --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/NullableCreateHintTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class NullableCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(ValueTask?)]; + + public NullableCreateHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/ObjectCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/ObjectCreateHintTests.cs new file mode 100644 index 00000000..17bd4286 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/ObjectCreateHintTests.cs @@ -0,0 +1,35 @@ +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class ObjectCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(DataHolderSample), + typeof(Arg), + typeof(DataHolderSample), + typeof(IUnimplementedSample), + typeof(FieldSample), + typeof(FactoryAlterSample), + typeof(object), + ]; + + private static readonly Type[] _InvalidTypes = [typeof(PrivateCreateSample)]; + + public ObjectCreateHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + [Theory, RandomData] + public void ObjectCreateHint_CanHandleInfinites( + InfiniteSample sample1, + ParentLoopSample sample2 + ) + { + sample1.Assert().IsNotNull(); + sample2.Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/SpanCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/SpanCreateHintTests.cs new file mode 100644 index 00000000..80c12b50 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/SpanCreateHintTests.cs @@ -0,0 +1,38 @@ +using Werecodent.CreateAndFake.RandomizerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class SpanCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ItemTypes = + [ + typeof(string), + typeof(object), + typeof(int), + typeof(double), + typeof(KeyValuePair), + ]; + + private static readonly Type[] _ValidTypes = + [ + MakeDefined(typeof(Span<>)), + MakeDefined(typeof(ReadOnlySpan<>)), + ]; + + public SpanCreateHintTests() + : base(_ValidTypes) { } + + private static Type MakeDefined(Type type) + { + if (type.IsGenericTypeDefinition) + { + return type.MakeGenericType([ + .. type.GetGenericArguments().Select(_ => Tools.Gen.NextItem(_ItemTypes)), + ]); + } + else + { + return type; + } + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/SubclassCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/SubclassCreateHintTests.cs new file mode 100644 index 00000000..ab05d409 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/SubclassCreateHintTests.cs @@ -0,0 +1,62 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class SubclassCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(IIsGoodOrBadSample)]; + + private static readonly Type[] _InvalidTypes = [typeof(VoidType)]; + + public SubclassCreateHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + [Fact] + internal void TryToCreate_CanNotPreferLocalSubclasses() + { + TestInstance + .TryToCreate( + typeof(IIsGoodOrBadSample), + CreateChainer(Tools.Randomizer.Options with { PreferLocalSubclasses = false }) + ) + .HasData.Assert() + .Is(true); + } + + [Theory, RandomData] + internal void TryToCreate_ContinuesAfterExceptions( + [Stub] IRandomizerChainer randomizer, + IsGoodSample sample + ) + { + randomizer.AlreadyCreated(Arg.Any()).SetupReturn(false); + randomizer.Options.SetupReturn(Tools.Randomizer.Options); + randomizer + .CreateSpecific( + typeof(IsBadSample), + typeof(IIsGoodOrBadSample), + Arg.Any() + ) + .SetupReturn(Behavior.Throw()); + randomizer + .CreateSpecific( + typeof(IsGoodSample), + typeof(IIsGoodOrBadSample), + Arg.Any() + ) + .SetupReturn(sample); + + for (int i = 0; i < 10; i++) + { + TestInstance + .TryToCreate(typeof(IIsGoodOrBadSample), randomizer) + .Assert() + .Is(new CreateHintResult(sample)); + } + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/TaskCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/TaskCreateHintTests.cs new file mode 100644 index 00000000..6fc12b20 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/TaskCreateHintTests.cs @@ -0,0 +1,27 @@ +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class TaskCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(Task), + typeof(Task), + typeof(Task), + typeof(Task), + typeof(Task), + typeof(TaskCompletionSource), + typeof(Task), + ]; + + public TaskCreateHintTests() + : base(_ValidTypes) { } + + [Fact] + internal static void TryToCreate_TaskTypingCorrect() + { + Tools.Randomizer.Create>().GetType().Assert().Is(typeof(Task)); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/Hints/ValueTaskCreateHintTests.cs b/tests/Toolbox.Tests/RandomizerTool/Hints/ValueTaskCreateHintTests.cs new file mode 100644 index 00000000..9670e179 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/Hints/ValueTaskCreateHintTests.cs @@ -0,0 +1,21 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.RandomizerTool.Hints; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool.Hints; + +public sealed class ValueTaskCreateHintTests : CreateHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(ValueTask), + typeof(ValueTask), + typeof(ValueTask), + typeof(ValueTask), + typeof(ValueTask), + typeof(SingleCallValueTaskSource), + ]; + + public ValueTaskCreateHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/RandomizerOptionsTests.cs b/tests/Toolbox.Tests/RandomizerTool/RandomizerOptionsTests.cs new file mode 100644 index 00000000..9bb476f6 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/RandomizerOptionsTests.cs @@ -0,0 +1,47 @@ +global using RandomizerMod = System.Func< + Werecodent.CreateAndFake.RandomizerTool.RandomizerOptions, + Werecodent.CreateAndFake.RandomizerTool.RandomizerOptions +>; +using Werecodent.CreateAndFake.RandomizerTool; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool; + +public sealed class RandomizerOptionsTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ArgumentNullException)] }; + + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void RandomizerOptions_ModFormRandomizable() + { + typeof(RandomizerMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } + + [Fact] + internal static void NextStringSize_PreventsOverflow() + { + ( + Tools.Randomizer.Options with + { + StringMinSize = int.MaxValue, + StringMaxSize = int.MaxValue, + } + ) + .NextStringSize() + .Assert() + .Is(int.MaxValue); + } + + [Fact] + internal static void NextStringSize_InvertsSizeWhenFlipped() + { + (Tools.Randomizer.Options with { StringMinSize = 1, StringMaxSize = 0 }) + .NextStringSize() + .Assert() + .GreaterThanOrEqualTo(0) + .And() + .LessThanOrEqualTo(1); + } +} diff --git a/tests/Toolbox.Tests/RandomizerTool/RandomizerTests.cs b/tests/Toolbox.Tests/RandomizerTool/RandomizerTests.cs new file mode 100644 index 00000000..22e6e5c1 --- /dev/null +++ b/tests/Toolbox.Tests/RandomizerTool/RandomizerTests.cs @@ -0,0 +1,200 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.RandomizerTool.Engine; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RandomizerTool; + +public sealed class RandomizerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(ArgumentOutOfRangeException), + ], + InjectionValues = [GetGeneratableMethod(), Tools.Gen.Next(5, 8)], + MethodsToIgnore = [nameof(Randomizer.Inject)], + }; + + private static MethodInfo GetGeneratableMethod() + { + return Tools.Randomizer.Create(opt => + opt with + { + FinalCondition = m => + m is MethodInfo info + && !info.IsGenericMethod + && !info.IsGenericMethodDefinition, + } + ); + } + + [Fact] + internal static void Create_NoRulesThrows() + { + new Randomizer(Tools.Randomizer.Options with { IncludeFrameworkHints = false }) + .Assert(x => x.Create()) + .Throws(); + } + + [Theory, RandomData] + internal static void Create_MissingMatchThrows([Stub] CreateHint hint, string data) + { + hint.Tools().ToFake().ThrowByDefault = true; + hint.Tools() + .ToFake() + .Setup( + m => m.TryToCreate(data.GetType(), Arg.Any()), + Behavior.Returns(CreateHintResult.None, Times.Once) + ); + + new Randomizer( + Tools.Randomizer.Options with + { + IncludeFrameworkHints = false, + Hints = [hint], + } + ) + .Assert(x => x.Create()) + .Throws(); + + hint.Assert().Called(); + } + + [Theory, RandomData] + internal static void Create_ValidHintWorks([Stub] CreateHint hint, string data) + { + hint.Tools().ToFake().ThrowByDefault = true; + hint.Tools() + .ToFake() + .Setup( + m => m.TryToCreate(data.GetType(), Arg.Any()), + Behavior.Returns(new CreateHintResult(data), Times.Once) + ); + + new Randomizer( + Tools.Randomizer.Options with + { + IncludeFrameworkHints = false, + Hints = [hint], + } + ) + .Create() + .Assert() + .Is(data); + + hint.Assert().Called(); + } + + [Theory, RandomData] + internal static void Create_InfiniteLoopDetails(Type type, [Fake] CreateHint hint) + { + hint.Tools() + .ToFake() + .Setup( + m => m.TryToCreate(type, Arg.Any()), + Behavior.Throw(Times.Once) + ); + + new Randomizer( + Tools.Randomizer.Options with + { + IncludeFrameworkHints = false, + Hints = [hint], + } + ) + .Assert(x => x.Create(type)) + .Throws() + .With(e => e.Message) + .Contains(GenericConverter.ExpandName(type)); + } + + [Fact] + internal static void Create_ConditionMatchReturned() + { + Tools + .Randomizer.Create(opt => + opt with + { + FinalConditionAttemptLimit = Limiter.Hundred, + FinalCondition = r => r is int v && v < 0, + } + ) + .Assert() + .LessThan(0); + } + + [Fact] + internal static void Create_ConditionTimesOut() + { + Tools + .Randomizer.Assert(x => + x.Create(opt => + opt with + { + FinalCondition = r => r is DateTime d && d < DateTime.MinValue, + } + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal static void Inject_SingleFakeInjected(Fake fake) + { + InjectSample holder = Tools.Randomizer.Inject([fake]); + holder.Data.Assert().ReferenceEqual(fake.Dummy); + holder.Data2.Assert().ReferenceNotEqual(fake.Dummy); + } + + [Theory, RandomData] + internal static void Inject_DoubleFakeInjected( + Fake fake, + [Fake] DataSample fake2, + [Inject] InjectSample holder + ) + { + holder.Data2.Assert().ReferenceEqual(fake.Dummy); + holder.Data.Assert().ReferenceEqual(fake2); + } + + [Theory, RandomData] + internal static void Inject_InterfaceFakesInjected( + Fake fake, + Fake fake2, + [Inject] InjectMockSample holder + ) + { + fake.Verify(Times.Never, f => f.FailIfNotMocked()); + fake2.Verify(Times.Never, f => f.FailIfNotMocked()); + holder.TestIfMockedSeparately(); + fake.Verify(Times.Once, f => f.FailIfNotMocked()); + fake2.Verify(Times.Once, f => f.FailIfNotMocked()); + } + + [Fact] + internal static void Inject_ThrowsHandled() + { + Tools.Randomizer.Assert(x => x.Inject(null)).Throws(); + + Tools + .Randomizer.Assert(x => x.Inject(typeof(PrivateCreateSample), null)) + .Throws(); + } + + [Fact] + internal static void Create_HandlesInfinites() + { + Tools.Randomizer.Create().Assert().IsNotNull(); + Tools.Randomizer.Create().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/RunnerTool/Attributes/BaseCapAttributeTests.cs b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseCapAttributeTests.cs new file mode 100644 index 00000000..8f79f11b --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseCapAttributeTests.cs @@ -0,0 +1,86 @@ +using System.Reflection; +using Microsoft.CSharp.RuntimeBinder; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.RunnerTool.Attributes; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool.Attributes; + +public sealed class BaseCapAttributeTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableToolSetSupportTests = true, + IgnorableExceptions = + [ + typeof(ArgumentException), + typeof(InvalidCastException), + typeof(ToolException), + typeof(TesterFailureException), + typeof(ArgumentOutOfRangeException), + typeof(RuntimeBinderException), + ], + }; + + [Fact] + internal static Task CreateParameterValue_PreventsMismatchedMinValue() + { + return Tools + .Runner.CreateForAsync( + typeof(BaseCapAttributeTests).GetMethod( + nameof(BadMinValueMatch), + BindingFlags.Static | BindingFlags.NonPublic + ), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task CreateParameterValue_PreventsMismatchedMaxValue() + { + return Tools + .Runner.CreateForAsync( + typeof(BaseCapAttributeTests).GetMethod( + nameof(BadMaxValueMatch), + BindingFlags.Static | BindingFlags.NonPublic + ), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task CreateParameterValue_PreventsNonValue() + { + return Tools + .Runner.CreateForAsync( + typeof(BaseCapAttributeTests).GetMethod( + nameof(BadTypeValueMatch), + BindingFlags.Static | BindingFlags.NonPublic + ), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + private static int BadMinValueMatch([Cap(2.3, 5)] int size) + { + return size; + } + + private static int BadMaxValueMatch([Cap(3, 4u)] int size) + { + return size; + } + + private static DataSample BadTypeValueMatch([Cap(3, 4)] DataSample sample) + { + return sample; + } +} diff --git a/tests/Toolbox.Tests/RunnerTool/Attributes/BaseCopyAttributeTests.cs b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseCopyAttributeTests.cs new file mode 100644 index 00000000..04f9fc01 --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseCopyAttributeTests.cs @@ -0,0 +1,37 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.RunnerTool.Attributes; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool.Attributes; + +public sealed class BaseCopyAttributeTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableToolSetSupportTests = true, + IgnorableExceptions = [typeof(ToolException)], + }; + + [Fact] + internal static Task CreateParameterValue_PreventsNonValue() + { + return Tools + .Runner.CreateForAsync( + typeof(BaseCopyAttributeTests).GetMethod( + nameof(BadNothingToCopy), + BindingFlags.Static | BindingFlags.NonPublic + ), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + private static DataSample BadNothingToCopy([Copy] DataSample sample) + { + return sample; + } +} diff --git a/tests/Toolbox.Tests/RunnerTool/Attributes/BaseFakeAttributeTests.cs b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseFakeAttributeTests.cs new file mode 100644 index 00000000..9c4e1987 --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseFakeAttributeTests.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool.Attributes; + +public sealed class BaseFakeAttributeTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableToolSetSupportTests = true, + IgnorableExceptions = [typeof(ToolException), typeof(ArgumentException)], + }; +} diff --git a/tests/Toolbox.Tests/RunnerTool/Attributes/BaseInjectAttributeTests.cs b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseInjectAttributeTests.cs new file mode 100644 index 00000000..0960e2f7 --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseInjectAttributeTests.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool.Attributes; + +public sealed class BaseInjectAttributeTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableToolSetSupportTests = true, + IgnorableExceptions = [typeof(ToolException)], + }; +} diff --git a/tests/Toolbox.Tests/RunnerTool/Attributes/BaseUniqueAttributeTests.cs b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseUniqueAttributeTests.cs new file mode 100644 index 00000000..e1f85c4e --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/Attributes/BaseUniqueAttributeTests.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.RunnerTool.Attributes; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool.Attributes; + +public sealed class BaseUniqueAttributeTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableToolSetSupportTests = true, + IgnorableExceptions = [typeof(ToolException)], + }; +} diff --git a/tests/Toolbox.Tests/RunnerTool/MethodCallWrapperTests.cs b/tests/Toolbox.Tests/RunnerTool/MethodCallWrapperTests.cs new file mode 100644 index 00000000..59a46428 --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/MethodCallWrapperTests.cs @@ -0,0 +1,124 @@ +using System.Collections.Frozen; +using System.Collections.Specialized; +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool; + +public sealed class MethodCallWrapperTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(KeyNotFoundException), + typeof(ArgumentOutOfRangeException), + ], + MethodsToIgnore = opt + .MethodsToIgnore.Concat([nameof(MethodCallWrapper.InvokeOn)]) + .ToFrozenSet(), + DisableParameterMutationTests = true, + }; + + [Fact] + internal static void MethodCallWrapper_CanRandomize() + { + Tools.Randomizer.Create().Assert().IsNotNull(); + } + + [Theory, RandomData] + internal static void MethodCallWrapper_WorksInFake( + [Stub] IRunner runner, + MethodCallWrapper wrapper, + MethodBase method + ) + { + runner.CreateFor(Arg.Any(), Arg.Any()).SetupReturn(wrapper); + runner.CreateFor(method, TestContext.Current.CancellationToken).Assert().Is(wrapper); + } + + [Theory, RandomData] + internal static void ModifyArg_ThrowsWithUnknownParameter( + MethodCallWrapper method, + string parameter, + object value + ) + { + method.Assert(x => x.ModifyArg(parameter, value)).Throws(); + } + + [Theory, RandomData] + internal static void ModifyArg_CanMutate(DataSample sample) + { + MethodCallWrapper wrapper = Tools.Runner.CreateFor( + typeof(DataHolderSample).GetMethod(nameof(DataHolderSample.HasNested)), + TestContext.Current.CancellationToken + ); + + wrapper.ModifyArg("value", sample); + wrapper.Args.Assert().Contains(sample); + } + + [Theory, RandomData] + internal static void InvokeOn_UsesArgs(DataSample sample) + { + MethodCallWrapper wrapper = Tools.Runner.CreateFor( + typeof(DataSample).GetMethod(nameof(Equals)), + TestContext.Current.CancellationToken + ); + + wrapper.InvokeOn(sample).Assert().Is(false); + wrapper.ModifyArg("obj", sample); + wrapper.InvokeOn(sample).Assert().Is(true); + } + + [Theory, RandomData] + internal static Task CompareAsync_NoDifferencesWithCopy( + MethodBase originalMethod, + [Copy] MethodBase cloneMethod, + OrderedDictionary originalArgs, + [Copy] OrderedDictionary cloneArgs + ) + { + MethodCallWrapper original = new(originalMethod, originalArgs); + MethodCallWrapper clone = new(cloneMethod, cloneArgs); + + return original + .CompareAsync(clone, Tools.Valuer, TestContext.Current.CancellationToken) + .Assert() + .HasCountAsync(0, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task CompareAsync_DifferencesWithVariant( + MethodBase originalMethod, + MethodBase variantMethod, + OrderedDictionary originalArgs, + OrderedDictionary variantArgs + ) + { + MethodCallWrapper original = new(originalMethod, originalArgs); + MethodCallWrapper variant = new(variantMethod, variantArgs); + + return original + .CompareAsync(variant, Tools.Valuer, TestContext.Current.CancellationToken) + .Assert() + .HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task CompareAsync_DifferenceWithDifferentType( + MethodCallWrapper wrapper, + DataSample sample + ) + { + return wrapper + .CompareAsync(sample, Tools.Valuer, TestContext.Current.CancellationToken) + .Assert() + .HasCountAsync(1, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/RunnerTool/RunResultTests.cs b/tests/Toolbox.Tests/RunnerTool/RunResultTests.cs new file mode 100644 index 00000000..6ae7316a --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/RunResultTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool; + +public sealed class RunResultTests : AutoTester; diff --git a/tests/Toolbox.Tests/RunnerTool/RunResultsTests.cs b/tests/Toolbox.Tests/RunnerTool/RunResultsTests.cs new file mode 100644 index 00000000..bd096fa9 --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/RunResultsTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool; + +public sealed class RunResultsTests : AutoTester; diff --git a/tests/Toolbox.Tests/RunnerTool/RunnerOptionsTests.cs b/tests/Toolbox.Tests/RunnerTool/RunnerOptionsTests.cs new file mode 100644 index 00000000..61ba380a --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/RunnerOptionsTests.cs @@ -0,0 +1,18 @@ +global using RunnerMod = System.Func< + Werecodent.CreateAndFake.RunnerTool.RunnerOptions, + Werecodent.CreateAndFake.RunnerTool.RunnerOptions +>; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool; + +public sealed class RunnerOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void RunnerOptions_ModFormRandomizable() + { + typeof(RunnerMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/RunnerTool/RunnerTests.cs b/tests/Toolbox.Tests/RunnerTool/RunnerTests.cs new file mode 100644 index 00000000..8300506c --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/RunnerTests.cs @@ -0,0 +1,147 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool; + +public sealed class RunnerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = [GetGeneratableMethod()], + IgnorableExceptions = + [ + typeof(ArgumentOutOfRangeException), + typeof(ToolException), + typeof(UnsupportedException), + ], + }; + + private static MethodInfo GetGeneratableMethod() + { + return Tools.Randomizer.Create(opt => + opt with + { + FinalCondition = m => + m is MethodInfo info + && !info.IsGenericMethod + && !info.IsGenericMethodDefinition, + } + ); + } + + [Theory, RandomData] + internal static async Task RunAsync_DefaultTimeoutWhenNegative(AsyncDataSample sample) + { + await Tools + .Runner.CallMethodsOnAsync(sample, TestContext.Current.CancellationToken, opt => + opt with + { + RunTimeout = TimeSpan.Zero, + IncludeBaseObjectMethods = true, + } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + await Tools + .Runner.CallMethodsOnAsync(sample, TestContext.Current.CancellationToken, opt => + opt with + { + RunTimeout = TimeSpan.FromMilliseconds(-1), + IncludeBaseObjectMethods = true, + } + ) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static void CreateFor_InterfaceFakesInjected( + Fake fake, + Fake fake2 + ) + { + Tools + .Runner.CreateFor( + TypeDescriber.For().Constructors.OnlyPublic.Single(), + TestContext.Current.CancellationToken, + opt => opt with { InjectionValues = [fake, fake2.Dummy] } + ) + .Args.ToArray() + .Assert() + .Is(new object[] { fake.Dummy, fake2.Dummy }); + } + + [Theory, RandomData] + internal static void CreateFor_InjectedWorks(Injected injected) + { + injected.Dummy.TestIfMockedSeparately(); + } + + [Theory, RandomData] + internal static void CreateFor_InjectedNotManuallyInjected( + Fake inner1, + Fake inner2, + InjectMockSample sample, + Injected injected + ) + { + injected.Dummy.Assert().IsNot(sample); + injected.Fakes.Contains(inner1).Assert().Is(false); + injected.Fakes.Contains(inner2).Assert().Is(false); + + injected.Dummy.TestIfMockedSeparately(); + } + + [Fact] + internal static void CreateFor_ThrowsWithUnspecifiedGenerics() + { + Tools + .Runner.Assert(x => + x.CreateFor( + typeof(Enumerable).GetMethod(nameof(Enumerable.Empty)), + TestContext.Current.CancellationToken + ) + ) + .Throws(); + } + + [Fact] + internal static Task CreateForAsync_ThrowsWithUnspecifiedGenerics() + { + return Tools + .Runner.CreateForAsync( + typeof(Enumerable).GetMethod(nameof(Enumerable.Empty)), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task CreateForAsync_ThrowsWithMultipleHints() + { + return Tools + .Runner.CreateForAsync( + typeof(RunnerTests).GetMethod( + nameof(BadMultipleHints), + BindingFlags.Static | BindingFlags.NonPublic + ), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + private static DataSample BadMultipleHints([Fake] [Stub] DataSample sample) + { + return sample; + } +} diff --git a/tests/Toolbox.Tests/RunnerTool/UnwrapperTests.cs b/tests/Toolbox.Tests/RunnerTool/UnwrapperTests.cs new file mode 100644 index 00000000..c11e641b --- /dev/null +++ b/tests/Toolbox.Tests/RunnerTool/UnwrapperTests.cs @@ -0,0 +1,229 @@ +using System.Collections; +using Werecodent.CreateAndFake.Fluent.AssertAsyncCalls; +using Werecodent.CreateAndFake.Fluent.Chaining; +using Werecodent.CreateAndFake.RunnerTool; + +namespace Werecodent.CreateAndFake.Tests.RunnerTool; + +#pragma warning disable IDE0059 + +public sealed class UnwrapperTests() : AutoTester(typeof(Unwrapper)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(ArgumentException)] }; + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsTaskAndIntAsyncEnumerable( + IAsyncEnumerable data + ) + { + return UnwrapsTaskAndAsyncEnumerableAsync(data); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsTaskAndStringAsyncEnumerable( + IAsyncEnumerable data + ) + { + return UnwrapsTaskAndAsyncEnumerableAsync(data); + } + + private static async Task UnwrapsTaskAndAsyncEnumerableAsync(IAsyncEnumerable data) + { + bool iterated = false; + + async IAsyncEnumerable iterateAsync() + { + await foreach (T item in data.WithCancellation(TestContext.Current.CancellationToken)) + { + yield return item; + } + iterated = true; + } + + IAsyncEnumerable series = iterateAsync(); + iterated.Assert().Is(false); + + object result = await Unwrapper.UnwrapResultAsync( + series, + typeof(IAsyncEnumerable), + Tools.Runner.Options, + TestContext.Current.CancellationToken + ); + + await iterated + .Assert() + .Is(true) + .Also(result) + .IsAsync(data, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsTaskAndIntEnumerable(IEnumerable data) + { + return UnwrapsTaskAndEnumerableAsync(data); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsTaskAndStringEnumerable(IEnumerable data) + { + return UnwrapsTaskAndEnumerableAsync(data); + } + + private static async Task UnwrapsTaskAndEnumerableAsync(IEnumerable data) + { + bool iterated = false; + + IEnumerable iterate() + { + foreach (T item in data) + { + yield return item; + } + iterated = true; + } + + IEnumerable series = iterate(); + iterated.Assert().Is(false); + + object result = await Unwrapper.UnwrapResultAsync( + series, + typeof(IEnumerable), + Tools.Runner.Options, + TestContext.Current.CancellationToken + ); + + await iterated + .Assert() + .Is(true) + .Also(result) + .IsAsync(data, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsIntTask(Task data) + { + return TestUnwrapAsync(() => data, data); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsStringTask(Task data) + { + return TestUnwrapAsync(() => data, data); + } + + [Fact] + internal static Task UnwrapResultAsync_UnwrapsNullTask() + { + Task run = Task.Run(() => (object)null, TestContext.Current.CancellationToken); + return TestUnwrapAsync(() => run, run); + } + + [Fact] + internal static Task UnwrapResultAsync_UnwrapsTask() + { + return TestUnwrapAsync(() => Task.CompletedTask, Task.CompletedTask); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsIntValueTask(int data) + { + ValueTask run = new(data); + return TestUnwrapAsync(() => run, Task.FromResult(data)); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsStringValueTask(string data) + { + ValueTask run = new(Task.FromResult(data)); + return TestUnwrapAsync(() => run, Task.FromResult(data)); + } + + [Fact] + internal static Task UnwrapResultAsync_UnwrapsNullValueTask() + { + ValueTask run = new(Task.FromResult(null)); + return TestUnwrapAsync(() => run, Task.FromResult((object)null)); + } + + [Fact] + internal static Task UnwrapResultAsync_UnwrapsNullValueTaskWithType() + { + ValueTask run = new(Task.FromResult(null)); + return TestUnwrapAsync(() => run, Task.FromResult((string)null)); + } + + [Fact] + internal static Task UnwrapResultAsync_UnwrapsValueTask() + { + return TestUnwrapAsync(() => new ValueTask(Task.CompletedTask), Task.CompletedTask); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsString(string data) + { + return TestUnwrapAsync(() => data, data); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsInt(int data) + { + return TestUnwrapAsync(() => data, data); + } + + [Fact] + internal static Task UnwrapResultAsync_UnwrapsNull() + { + return TestUnwrapAsync(() => null, null); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsListInt(List data) + { + return TestUnwrapAsync(() => data, data); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsListString(List data) + { + return TestUnwrapAsync(() => data, data); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsArrayInt(int[] data) + { + return TestUnwrapAsync(() => data, data); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsArrayString(string[] data) + { + return TestUnwrapAsync(() => data, data); + } + + [Theory, RandomData] + internal static Task UnwrapResultAsync_UnwrapsCollection(ICollection data) + { + return TestUnwrapAsync(() => data, data); + } + + private static Task> TestUnwrapAsync( + Func call, + object expectedResult + ) + { + return Unwrapper + .UnwrapResultAsync( + call(), + typeof(T), + Tools.Runner.Options, + TestContext.Current.CancellationToken + ) + .Assert() + .HasResultAsync(TestContext.Current.CancellationToken) + .That() + .Is(expectedResult); + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/TestSamples/.editorconfig b/tests/Toolbox.Tests/TestSamples/.editorconfig new file mode 100644 index 00000000..6ccdf8ce --- /dev/null +++ b/tests/Toolbox.Tests/TestSamples/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# Samples intended to be of broken designs in order to test the framework. +dotnet_analyzer_diagnostic.severity = None diff --git a/tests/Toolbox.Tests/TestSamples/InternalScopeSample.cs b/tests/Toolbox.Tests/TestSamples/InternalScopeSample.cs new file mode 100644 index 00000000..26099321 --- /dev/null +++ b/tests/Toolbox.Tests/TestSamples/InternalScopeSample.cs @@ -0,0 +1,75 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Werecodent.CreateAndFake.Tests.TestSamples; + +public class InternalScopeSample +{ + public virtual string PublicProp { get; set; } + + internal virtual string InternalProp { get; set; } + + protected internal virtual string ProIntProp { get; set; } + + protected virtual string ProtectProp { get; set; } + + public virtual string InternalGet { internal get; set; } + + public virtual string ProIntGet { protected internal get; set; } + + public virtual string ProtectGet { protected get; set; } + + public virtual string PrivateGet { private get; set; } + + public virtual string InternalSet { get; internal set; } + + public virtual string ProIntSet { get; protected internal set; } + + public virtual string ProtectSet { get; protected set; } + + public virtual string PrivateSet { get; private set; } + + public virtual string PublicMethod() + { + return "Value"; + } + + internal virtual string InternalMethod() + { + return "Value"; + } + + protected internal virtual string ProIntMethod() + { + return "Value"; + } + + protected virtual string ProtectMethod() + { + return "Value"; + } + + public string CallProtectProp() + { + return ProtectProp; + } + + public void SetProtectProp(string data) + { + ProtectProp = data; + } + + public string CallProtectGet() + { + return ProtectGet; + } + + public void SetProtectSet(string data) + { + ProtectSet = data; + } + + public string CallProtectMethod() + { + return ProtectMethod(); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/BaseAutoTesterTests.cs b/tests/Toolbox.Tests/TesterTool/BaseAutoTesterTests.cs new file mode 100644 index 00000000..b8ece0a2 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/BaseAutoTesterTests.cs @@ -0,0 +1,53 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Tests.TesterTool; + +public static class BaseAutoTesterTests +{ + private sealed class InjectedAutoTester(IToolSet tools) + : AutoTester(typeof(ValueEquatableSample)) + { + protected override IToolSet AutoTools { get; } = tools; + } + + [Theory, RandomData] + internal static async Task BaseAutoTester_WrapsExceptions([Stub] IToolSet tools) + { + ITester tester = Tools.Faker.Stub().Dummy; + IAsserter asserter = Tools.Faker.Mock().Dummy; + IRandomizer randomizer = Tools.Faker.Mock().Dummy; + + tester.Options.SetupReturn(Tools.Tester.Options); + tester.Tools().ToFake().ThrowByDefault = true; + + tools.Tester.SetupReturn(tester); + tools.Asserter.SetupReturn(asserter); + tools.Randomizer.SetupReturn(randomizer); + + InjectedAutoTester testInstance = new(tools); + await testInstance + .Tester_GuardsNulls() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + await testInstance + .Tester_NoParameterMutation() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + await testInstance + .Tester_ValueEqualityOverrideCheck() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + await testInstance + .Tester_ToolSupport() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + await testInstance + .Tester_Debug_ToString() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/BaseAutoTester{T}Tests.cs b/tests/Toolbox.Tests/TesterTool/BaseAutoTester{T}Tests.cs new file mode 100644 index 00000000..23a15bf5 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/BaseAutoTester{T}Tests.cs @@ -0,0 +1,79 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RandomizerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Tests.TesterTool; + +public static class BaseAutoTester_T_Tests +{ + private sealed class NullInstanceTester(IToolSet tools) : AutoTester + { + protected override IToolSet AutoTools { get; } = tools; + + protected override ValueEquatableSample TestInstance { get; } = null; + } + + [Theory, RandomData] + internal static async Task BaseAutoTester_T_WrapsExceptions([Stub] IToolSet tools) + { + ITester tester = Tools.Faker.Stub().Dummy; + IAsserter asserter = Tools.Faker.Mock().Dummy; + IRandomizer randomizer = Tools.Faker.Mock().Dummy; + + tester.Options.SetupReturn(Tools.Tester.Options); + tester.Tools().ToFake().ThrowByDefault = true; + + tools.Tester.SetupReturn(tester); + tools.Asserter.SetupReturn(asserter); + tools.Randomizer.SetupReturn(randomizer); + + NullInstanceTester testInstance = new(tools); + await testInstance + .Tester_GuardsNulls() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + await testInstance + .Tester_NoParameterMutation() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + await testInstance + .Tester_ValueEqualityOverrideCheck() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + await testInstance + .Tester_Debug_ToString() + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task TestInstance_AltersBehaviorWhenNull( + [Stub] IToolSet tools, + [Stub] ITester tester + ) + { + tools.Tester.SetupReturn(tester); + tester + .PreventsNullRefExceptionAsync( + Arg.Any(), + Arg.Any() + ) + .SetupReturn(Task.CompletedTask); + tester + .PreventsParameterMutationAsync( + Arg.Any(), + Arg.Any() + ) + .SetupReturn(Task.CompletedTask); + tester.Tools().ToFake().ThrowByDefault = true; + + NullInstanceTester testInstance = new(tools); + await testInstance.Tester_GuardsNulls(); + await testInstance.Tester_NoParameterMutation(); + + tester.Assert().Called(); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/GenericFixerTests.cs b/tests/Toolbox.Tests/TesterTool/GenericFixerTests.cs new file mode 100644 index 00000000..5d652130 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/GenericFixerTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Tests.TesterTool; + +public sealed class GenericFixerTests() : AutoTester(typeof(GenericFixer)); diff --git a/tests/Toolbox.Tests/TesterTool/Guarders/ExceptionGuarderTests.cs b/tests/Toolbox.Tests/TesterTool/Guarders/ExceptionGuarderTests.cs new file mode 100644 index 00000000..0f5c968a --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/Guarders/ExceptionGuarderTests.cs @@ -0,0 +1,74 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.TesterTool.Guarders; +using Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.Guarders; + +public static class ExceptionGuarderTests +{ + [Fact] + internal static Task CallAllMethodsAsync_SuccessfulNoException() + { + return Tools.Tester.PassthroughWithNoExceptionsAsync( + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static async Task CallAllMethodsAsync_FailsWithException() + { + await Tools + .Tester.PassthroughWithNoExceptionsAsync( + TestContext.Current.CancellationToken, + opt => opt with { DisablePassthroughTests = false } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + + await Tools + .Tester.PassthroughWithNoExceptionsAsync( + Tools.Randomizer.Create(), + TestContext.Current.CancellationToken, + opt => opt with { DisablePassthroughTests = false } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static async Task HandleCheckException_UsesAsserterFail([Fake] IAsserter asserter) + { + asserter + .Tools() + .ToFake() + .Setup(d => d.Fail(Arg.Any(), Arg.Any()), Behavior.None(Times.Once)); + + await new ExceptionGuarder( + Tools.Tester.Options with + { + Asserter = asserter, + } + ).CallAllMethodsAsync(new MethodThrowsSample(), TestContext.Current.CancellationToken); + + asserter.Assert().Called(); + } + + [Theory, RandomData] + internal static async Task PassthroughWithNoExceptionsAsync_CanBeDisabled( + MethodThrowsSample sample + ) + { + await Tools.Tester.PassthroughWithNoExceptionsAsync( + sample, + TestContext.Current.CancellationToken, + opt => opt with { DisablePassthroughTests = true } + ); + + await Tools.Tester.PassthroughWithNoExceptionsAsync( + TestContext.Current.CancellationToken, + opt => opt with { DisablePassthroughTests = true } + ); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/Guarders/MutationGuarderTests.cs b/tests/Toolbox.Tests/TesterTool/Guarders/MutationGuarderTests.cs new file mode 100644 index 00000000..c210dd32 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/Guarders/MutationGuarderTests.cs @@ -0,0 +1,156 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool.Guarders; +using Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.Guarders; + +public static class MutationGuarderTests +{ + private static readonly MutationGuarder _LongTestInstance = new( + Tools.Tester.Options with + { + Runner = new Runner(Tools.Runner.Options with { RunTimeout = new TimeSpan(0, 0, 10) }), + } + ); + + [Fact] + internal static Task PreventsMutationOnStaticsAsync_UsesStatics() + { + return Tools + .Tester.PreventsParameterMutationAsync( + typeof(StaticMutationSample), + TestContext.Current.CancellationToken, + opt => + opt with + { + DisableParameterMutationTests = false, + IncludeStaticMethods = true, + } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task PreventsMutationAsync_StatelessFine() + { + return Tools.Tester.PreventsParameterMutationAsync( + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static Task PreventsMutationOnMethodsAsync_InjectsMultipleValues( + Fake fake1, + Fake fake2 + ) + { + return Tools.Tester.PreventsParameterMutationAsync( + TestContext.Current.CancellationToken, + opt => opt with { InjectionValues = [fake1, fake2] } + ); + } + + [Theory, RandomData] + internal static Task PreventsMutationOnMethodsAsync_InjectsWithMethods( + Fake fake + ) + { + return Tools.Tester.PreventsParameterMutationAsync( + TestContext.Current.CancellationToken, + opt => opt with { InjectionValues = [fake] } + ); + } + + [Fact] + internal static async Task PreventsMutationOnConstructorsAsync_Disposes() + { + await MockDisposableSample._Lock.WaitAsync(TestContext.Current.CancellationToken); + try + { + MockDisposableSample._ClassDisposes = 0; + MockDisposableSample._FinalizerDisposes = 0; + MockDisposableSample._Fake = Tools.Faker.Stub(); + + await _LongTestInstance.PreventsMutationOnConstructorsAsync( + typeof(MockDisposableSample), + true, + TestContext.Current.CancellationToken + ); + Tools.Asserter.Is(1, MockDisposableSample._ClassDisposes); + Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); + MockDisposableSample._Fake.Verify(Times.Once, d => d.Dispose()); + } + finally + { + MockDisposableSample._Lock.Release(); + } + } + + [Fact] + internal static async Task PreventsMutationOnMethodsAsync_Disposes() + { + await MockDisposableSample._Lock.WaitAsync(TestContext.Current.CancellationToken); + try + { + MockDisposableSample._ClassDisposes = 0; + MockDisposableSample._FinalizerDisposes = 0; + MockDisposableSample._Fake = Tools.Faker.Stub(); + + using MockDisposableSample sample = new(null); + await _LongTestInstance.PreventsMutationOnMethodsAsync( + sample, + TestContext.Current.CancellationToken + ); + Tools.Asserter.Is(0, MockDisposableSample._ClassDisposes); + Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); + MockDisposableSample._Fake.Verify(Times.Once, d => d.Dispose()); + } + finally + { + MockDisposableSample._Lock.Release(); + } + } + + [Fact] + internal static Task PreventsParameterMutationAsync_InstanceMethodsCanBeIgnored() + { + return Tools.Tester.PreventsParameterMutationAsync( + typeof(StructSample), + TestContext.Current.CancellationToken, + opt => opt with { IncludeInstanceMethods = false } + ); + } + + [Fact] + internal static Task PreventsParameterMutationAsync_StaticMethodsCanBeIgnored() + { + return Tools.Tester.PreventsParameterMutationAsync( + typeof(StaticMutationSample), + TestContext.Current.CancellationToken, + opt => opt with { IncludeStaticMethods = false } + ); + } + + [Theory, RandomData] + internal static async Task PreventsParameterMutationAsync_CanBeDisabled( + MockMethodPassOnly sample + ) + { + await Tools.Tester.PreventsParameterMutationAsync( + sample, + TestContext.Current.CancellationToken, + opt => opt with { DisableParameterMutationTests = true } + ); + + await Tools.Tester.PreventsParameterMutationAsync( + typeof(StaticMutationSample), + TestContext.Current.CancellationToken, + opt => opt with { DisableParameterMutationTests = true } + ); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/Guarders/NullGuarderTests.cs b/tests/Toolbox.Tests/TesterTool/Guarders/NullGuarderTests.cs new file mode 100644 index 00000000..e761c39d --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/Guarders/NullGuarderTests.cs @@ -0,0 +1,191 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool.Guarders; +using Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.Guarders; + +public static class NullGuarderTests +{ + private static readonly TesterMod _Config = opt => + opt with + { + IgnoreAllExceptions = true, + IncludeInternals = false, + }; + + private static readonly NullGuarder _ShortTestInstance = new( + Tools.Tester.Options with + { + Runner = new Runner( + Tools.Runner.Options with + { + RunTimeout = new TimeSpan(0, 0, 0, 2, 0), + } + ), + } + ); + + private static readonly NullGuarder _LongTestInstance = new( + Tools.Tester.Options with + { + Runner = new Runner(Tools.Runner.Options with { RunTimeout = new TimeSpan(0, 0, 15) }), + } + ); + + [Fact] + internal static Task NullGuarder_GuardsNulls() + { + return Tools.Tester.PreventsNullRefExceptionAsync( + _ShortTestInstance, + TestContext.Current.CancellationToken, + _Config + ); + } + + [Fact] + internal static Task NullGuarder_NoParameterMutation() + { + return Tools.Tester.PreventsParameterMutationAsync( + _ShortTestInstance, + TestContext.Current.CancellationToken, + _Config + ); + } + + [Fact] + internal static Task PreventsNullRefExceptionAsync_NullReferenceThrows() + { + return _ShortTestInstance + .PreventsNullRefExceptionOnConstructorsAsync( + typeof(NullReferenceSample), + true, + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal static Task PreventsNullRefExceptionAsync_InjectsMultipleValues( + Fake fake1, + Fake fake2 + ) + { + return Tools.Tester.PreventsNullRefExceptionAsync( + TestContext.Current.CancellationToken, + opt => opt with { InjectionValues = [fake1, fake2] } + ); + } + + [Theory, RandomData] + internal static Task PreventsNullRefExceptionAsync_InjectsWithMethods( + Fake fake + ) + { + return Tools.Tester.PreventsNullRefExceptionAsync( + TestContext.Current.CancellationToken, + opt => opt with { InjectionValues = [fake] } + ); + } + + [Fact] + internal static Task PreventsNullRefExceptionAsync_OnStatics() + { + return Tools + .Tester.PreventsNullRefExceptionAsync( + typeof(StaticMutationSample), + TestContext.Current.CancellationToken, + opt => + opt with + { + DisableNullRefExceptionTests = false, + IncludeStaticMethods = true, + } + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static Task PreventsNullRefExceptionAsync_StatelessFine() + { + return Tools.Tester.PreventsNullRefExceptionAsync( + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static async Task PreventsNullRefExceptionOnConstructorsAsync_Disposes( + [Stub] IDisposable disposable + ) + { + await MockDisposableSample._Lock.WaitAsync(TestContext.Current.CancellationToken); + try + { + MockDisposableSample._ClassDisposes = 0; + MockDisposableSample._FinalizerDisposes = 0; + MockDisposableSample._Fake = disposable.Tools().ToFake(); + + await _LongTestInstance.PreventsNullRefExceptionOnConstructorsAsync( + typeof(MockDisposableSample), + true, + TestContext.Current.CancellationToken + ); + Tools.Asserter.Is(1, MockDisposableSample._ClassDisposes); + Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); + MockDisposableSample._Fake.Verify(Times.Once, d => d.Dispose()); + } + finally + { + MockDisposableSample._Lock.Release(); + } + } + + [Theory, RandomData] + internal static async Task PreventsNullRefExceptionOnMethodsAsync_Disposes( + [Stub] IDisposable disposable + ) + { + await MockDisposableSample._Lock.WaitAsync(TestContext.Current.CancellationToken); + try + { + MockDisposableSample._ClassDisposes = 0; + MockDisposableSample._FinalizerDisposes = 0; + MockDisposableSample._Fake = disposable.Tools().ToFake(); + + using MockDisposableSample sample = new(null); + await _LongTestInstance.PreventsNullRefExceptionOnMethodsAsync( + sample, + TestContext.Current.CancellationToken + ); + Tools.Asserter.Is(0, MockDisposableSample._ClassDisposes); + Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); + MockDisposableSample._Fake.Verify(Times.Once, d => d.Dispose()); + } + finally + { + MockDisposableSample._Lock.Release(); + } + } + + [Theory, RandomData] + internal static async Task PreventsNullRefExceptionAsync_CanBeDisabled( + NullReferenceSample sample + ) + { + await Tools.Tester.PreventsNullRefExceptionAsync( + TestContext.Current.CancellationToken, + opt => opt with { DisableNullRefExceptionTests = true } + ); + + await Tools.Tester.PreventsNullRefExceptionAsync( + sample, + TestContext.Current.CancellationToken, + opt => opt with { DisableNullRefExceptionTests = true } + ); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/TestSamples/LongMethodSample.cs b/tests/Toolbox.Tests/TesterTool/TestSamples/LongMethodSample.cs new file mode 100644 index 00000000..9fe67e67 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/TestSamples/LongMethodSample.cs @@ -0,0 +1,15 @@ +namespace Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +public static class LongMethodSample +{ + public static void BeSlow(string data, out T output) + where T : new() + { + Thread.Sleep(new TimeSpan(0, 0, 3)); + Thread.Sleep(new TimeSpan(0, 0, 2)); + Thread.Sleep(new TimeSpan(0, 0, 1)); + + output = new T(); + throw new InvalidOperationException($"{nameof(BeSlow)} finished with data: {data}."); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/TestSamples/MethodThrowsSample.cs b/tests/Toolbox.Tests/TesterTool/TestSamples/MethodThrowsSample.cs new file mode 100644 index 00000000..587cbc80 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/TestSamples/MethodThrowsSample.cs @@ -0,0 +1,9 @@ +namespace Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +public sealed class MethodThrowsSample +{ + public void ThrowSomething() + { + throw new InvalidOperationException(GetType().Name); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/TestSamples/MockDisposableSample.cs b/tests/Toolbox.Tests/TesterTool/TestSamples/MockDisposableSample.cs new file mode 100644 index 00000000..3b057694 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/TestSamples/MockDisposableSample.cs @@ -0,0 +1,38 @@ +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +#pragma warning disable // For testing. + +public sealed class MockDisposableSample(object value) : IDisposable +{ + internal static readonly SemaphoreSlim _Lock = new(1); + + internal static Fake _Fake = Tools.Faker.Stub(); + + internal static int _ClassDisposes = 0; + + internal static int _FinalizerDisposes = 0; + + ~MockDisposableSample() + { + try + { + _FinalizerDisposes++; + } + catch { } + } + + public void Dispose() + { + GC.SuppressFinalize(this); + _ClassDisposes++; + } + + public IDisposable DisposePass(object value) + { + return _Fake.Dummy; + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/TesterTool/TestSamples/MockMethodPassOnly.cs b/tests/Toolbox.Tests/TesterTool/TestSamples/MockMethodPassOnly.cs new file mode 100644 index 00000000..37bdd55b --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/TestSamples/MockMethodPassOnly.cs @@ -0,0 +1,16 @@ +using Werecodent.CreateAndFake.Samples.ErrorCases; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +#pragma warning disable // For testing. + +public sealed class MockMethodPassOnly +{ + public bool MockPassOnly(IOnlyMockSample sample) + { + sample?.FailIfNotMocked(); + return true; + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/TesterTool/TestSamples/NullReferenceSample.cs b/tests/Toolbox.Tests/TesterTool/TestSamples/NullReferenceSample.cs new file mode 100644 index 00000000..c6330f11 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/TestSamples/NullReferenceSample.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Design.Comparisons; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +public sealed class NullReferenceSample(IValueEquatable data) +{ + private readonly IValueEquatable _data = data; + + public override string ToString() + { + return _data.ToString(); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/TestSamples/StaticMutationSample.cs b/tests/Toolbox.Tests/TesterTool/TestSamples/StaticMutationSample.cs new file mode 100644 index 00000000..f25a6e39 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/TestSamples/StaticMutationSample.cs @@ -0,0 +1,11 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +internal static class StaticMutationSample +{ + public static void Mutate(DataHolderSample data) + { + data.NestedValue = null; + } +} diff --git a/tests/Toolbox.Tests/TesterTool/TesterOptionsTests.cs b/tests/Toolbox.Tests/TesterTool/TesterOptionsTests.cs new file mode 100644 index 00000000..fc058383 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/TesterOptionsTests.cs @@ -0,0 +1,18 @@ +global using TesterMod = System.Func< + Werecodent.CreateAndFake.TesterTool.TesterOptions, + Werecodent.CreateAndFake.TesterTool.TesterOptions +>; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.Tests.TesterTool; + +public sealed class TesterOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void TesterOptions_ModFormRandomizable() + { + typeof(TesterMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/TesterTests.cs b/tests/Toolbox.Tests/TesterTool/TesterTests.cs new file mode 100644 index 00000000..afb6f557 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/TesterTests.cs @@ -0,0 +1,132 @@ +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.RunnerTool; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool; +using Werecodent.CreateAndFake.Tests.TesterTool.TestSamples; + +namespace Werecodent.CreateAndFake.Tests.TesterTool; + +public static class TesterTests +{ + private static readonly Tester _ShortTestInstance = new( + Tools.Tester.Options with + { + Runner = new Runner( + Tools.Runner.Options with + { + RunTimeout = new TimeSpan(0, 0, 0, 0, 100), + } + ), + } + ); + + private static readonly Tester _LongTestInstance = new( + Tools.Tester.Options with + { + Runner = new Runner(Tools.Runner.Options with { RunTimeout = new TimeSpan(0, 0, 10) }), + } + ); + + [Fact] + internal static void Tester_AllMethodsVirtual() + { + Tools.Asserter.IsEmpty( + typeof(Tester) + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) + .Where(m => !m.IsVirtual) + .Select(m => m.Name) + .Where(n => n != $"get_{nameof(Tester.Options)}") + ); + } + + [Fact] + internal static async Task Tester_GuardsNulls() + { + 1.Assert(_ => new Tester(null)).Throws(); + + Type nullType = null; + await _ShortTestInstance + .PreventsNullRefExceptionAsync(nullType, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + await _ShortTestInstance + .PreventsParameterMutationAsync(nullType, TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Fact] + internal static async Task PreventsNullRefExceptionAsync_Disposes() + { + await MockDisposableSample._Lock.WaitAsync(TestContext.Current.CancellationToken); + try + { + MockDisposableSample._ClassDisposes = 0; + MockDisposableSample._FinalizerDisposes = 0; + MockDisposableSample._Fake = Tools.Faker.Stub(); + + await _LongTestInstance.PreventsNullRefExceptionAsync( + TestContext.Current.CancellationToken, + opt => + opt with + { + DisableNullRefExceptionTests = false, + IncludeConstructors = true, + IncludeInstanceMethods = true, + } + ); + Tools.Asserter.Is(2, MockDisposableSample._ClassDisposes); + Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); + MockDisposableSample._Fake.Verify(Times.Exactly(2), d => d.Dispose()); + } + finally + { + MockDisposableSample._Lock.Release(); + } + } + + [Fact] + internal static async Task PreventsParameterMutationAsync_Disposes() + { + await MockDisposableSample._Lock.WaitAsync(TestContext.Current.CancellationToken); + try + { + MockDisposableSample._ClassDisposes = 0; + MockDisposableSample._FinalizerDisposes = 0; + MockDisposableSample._Fake = Tools.Faker.Stub(); + + await _LongTestInstance.PreventsParameterMutationAsync( + TestContext.Current.CancellationToken, + opt => + opt with + { + DisableParameterMutationTests = false, + IncludeConstructors = true, + IncludeInstanceMethods = true, + } + ); + Tools.Asserter.Is(2, MockDisposableSample._ClassDisposes); + Tools.Asserter.Is(0, MockDisposableSample._FinalizerDisposes); + MockDisposableSample._Fake.Verify(Times.Exactly(2), d => d.Dispose()); + } + finally + { + MockDisposableSample._Lock.Release(); + } + } + + [Fact] + internal static Task VerifyValueEqualityAsync_GenericWorks() + { + return Tools.Tester.VerifyValueEqualityAsync( + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static void WithOptions_CreatesAnotherInstance(TesterMod mod) + { + Tools.Tester.WithOptions(mod).Assert().IsNotNull().And().IsNot(Tools.Tester); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/Validators/CancelValidatorTests.cs b/tests/Toolbox.Tests/TesterTool/Validators/CancelValidatorTests.cs new file mode 100644 index 00000000..b8612c56 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/Validators/CancelValidatorTests.cs @@ -0,0 +1,41 @@ +using System.Runtime.CompilerServices; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.TesterTool.Validators; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.Validators; + +#pragma warning disable MA0079 // For testing. + +public sealed class CancelValidatorTests() : AutoTester(typeof(CancelValidator)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + [Fact] + internal static Task VerifySupportsCancellationAsync_CanIgnoreCancelWithEmptySeries() + { + static async IAsyncEnumerable iterate( + IAsyncEnumerable series, + [EnumeratorCancellation] CancellationToken canceler = default + ) + { + await foreach (string item in series) + { + canceler.ThrowIfCancellationRequested(); + yield return item; + } + } + + return Tools + .Tester.VerifySupportsCancellationAsync( + (size, canceler) => + iterate(Tools.Randomizer.CreateSized>(size), canceler), + TestContext.Current.CancellationToken, + opt => opt with { ThrowsUponCancelWithEmptySeries = false } + ) + .Assert() + .ThrowsNoExceptionAsync(TestContext.Current.CancellationToken); + } +} + +#pragma warning restore diff --git a/tests/Toolbox.Tests/TesterTool/Validators/EqualityValidatorTests.cs b/tests/Toolbox.Tests/TesterTool/Validators/EqualityValidatorTests.cs new file mode 100644 index 00000000..573946f6 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/Validators/EqualityValidatorTests.cs @@ -0,0 +1,43 @@ +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.TesterTool.Validators; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.Validators; + +public sealed class EqualityValidatorTests() : AutoTester(typeof(EqualityValidator)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(AssertException)] }; + + [Theory, RandomData] + internal static Task VerifyEqualsMatchesHashCodesAsync_ValidatesIValuerEquatable( + IValuerEquatable sample + ) + { + return Tools.Tester.VerifyEqualsMatchesHashCodesAsync( + sample.GetType(), + TestContext.Current.CancellationToken + ); + } + + [Theory, RandomData] + internal static Task VerifyEqualsMatchesHashCodesAsync_ValidatesIValueEquatable( + IValueEquatable sample + ) + { + return Tools.Tester.VerifyEqualsMatchesHashCodesAsync( + sample.GetType(), + TestContext.Current.CancellationToken + ); + } + + [Fact] + internal static Task VerifyEqualsMatchesHashCodesAsync_ValidatesObjects() + { + return Tools.Tester.VerifyEqualsMatchesHashCodesAsync( + TestContext.Current.CancellationToken + ); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/Validators/SerializationValidatorTests.cs b/tests/Toolbox.Tests/TesterTool/Validators/SerializationValidatorTests.cs new file mode 100644 index 00000000..81ef4f87 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/Validators/SerializationValidatorTests.cs @@ -0,0 +1,45 @@ +using System.Runtime.Serialization; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.TesterTool.Validators; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.Validators; + +public sealed class SerializationValidatorTests() : AutoTester(typeof(SerializationValidator)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(AssertException), + typeof(SerializationException), + typeof(ArgumentOutOfRangeException), + typeof(InvalidCastException), + ], + }; + + [Theory, RandomData] + internal static void VerifyJsonSerialization_Functional(string sample) + { + Tools.Tester.VerifyJsonSerialization(); + Tools.Tester.VerifyJsonSerialization(sample); + } + + [Theory, RandomData] + internal static void VerifyXmlSerialization_Functional(string sample) + { + Tools.Tester.VerifyXmlSerialization(); + Tools.Tester.VerifyXmlSerialization(sample); + } + + [Fact] + internal static void VerifyXmlSerialization_ExceptionsWrapped() + { + Tools + .Tester.Assert(x => x.VerifyXmlSerialization()) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/Validators/SupportValidatorTests.cs b/tests/Toolbox.Tests/TesterTool/Validators/SupportValidatorTests.cs new file mode 100644 index 00000000..66bbbb35 --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/Validators/SupportValidatorTests.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.TesterTool.Validators; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.Validators; + +public sealed class SupportValidatorTests() : AutoTester(typeof(SupportValidator)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + DisableNullRefExceptionTests = true, + DisableParameterMutationTests = true, + DisableToolSetSupportTests = true, + }; + + [Fact] + internal static void New_NullOptionsGuarded() + { + 1.Assert(_ => new SupportValidator(null)).Throws(); + } + + [Fact] + internal static void VerifyToolSetSupportAsync_FailsWithoutCoverage() + { + Tools + .Tester.Assert(x => + x.ProvidesTestClassCoverage( + Assembly.GetAssembly(typeof(ToolSet)), + Assembly.GetAssembly(typeof(ToolSet)) + ) + ) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/TesterTool/Validators/TestValidatorTests.cs b/tests/Toolbox.Tests/TesterTool/Validators/TestValidatorTests.cs new file mode 100644 index 00000000..19a87c4f --- /dev/null +++ b/tests/Toolbox.Tests/TesterTool/Validators/TestValidatorTests.cs @@ -0,0 +1,52 @@ +using System.Reflection; +using Werecodent.CreateAndFake.AsserterTool; +using Werecodent.CreateAndFake.TesterTool.Validators; + +namespace Werecodent.CreateAndFake.Tests.TesterTool.Validators; + +public sealed class TestValidatorTests() : AutoTester(typeof(TestValidator)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(AssertException)], + DisableParameterMutationTests = true, + }; + + [Theory, RandomData] + internal static void VerifyTestMethodNaming_MatchesTargetOptions( + [Stub] Assembly codeAssembly, + [Stub] Assembly testAssembly, + AssemblyName name + ) + { + codeAssembly.GetTypes().SetupReturn([]); + codeAssembly.GetName().SetupReturn(name); + + testAssembly.GetName().SetupReturn(name); + testAssembly.GetTypes().SetupReturn([typeof(TestMethodProvider)]); + + new TestValidator( + Tools.Tester.Options with + { + RequirePrefixInTestName = false, + } + ).VerifyTestMethodNaming([typeof(ObsoleteAttribute)], codeAssembly, testAssembly); + + new TestValidator(Tools.Tester.Options with { RequirePrefixInTestName = true }) + .Assert(x => + x.VerifyTestMethodNaming([typeof(ObsoleteAttribute)], codeAssembly, testAssembly) + ) + .Throws(); + } + + internal static class TestMethodProvider + { + [Obsolete("To mark for testing.")] + internal static void NameWithoutTarget() + { + // Name coverage test. + } + } +} diff --git a/tests/Toolbox.Tests/ToolSetTests.cs b/tests/Toolbox.Tests/ToolSetTests.cs new file mode 100644 index 00000000..cf7df4bc --- /dev/null +++ b/tests/Toolbox.Tests/ToolSetTests.cs @@ -0,0 +1,13 @@ +namespace Werecodent.CreateAndFake.Tests; + +public sealed class ToolSetTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(FileNotFoundException)] }; + + [Fact] + internal static void ToolSet_Creatable() + { + ToolSet.CreateViaSeed(0).Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/ToolboxTests.cs b/tests/Toolbox.Tests/ToolboxTests.cs new file mode 100644 index 00000000..7dd2a59e --- /dev/null +++ b/tests/Toolbox.Tests/ToolboxTests.cs @@ -0,0 +1,20 @@ +using System.Reflection; + +namespace Werecodent.CreateAndFake.Tests; + +public sealed class ToolboxTests : AssemblyTester +{ + protected override Assembly CodeAssembly { get; } = Assembly.GetAssembly(typeof(ToolSet)); + + [Fact] + internal static async Task CreateAndFake_TestIndividual() + { + for (int i = 0; i < 100; i++) + { + await Tools.Tester.VerifyToolSetSupportAsync( + [typeof(FieldInfo)], + TestContext.Current.CancellationToken + ); + } + } +} diff --git a/tests/Toolbox.Tests/ToolsTests.cs b/tests/Toolbox.Tests/ToolsTests.cs new file mode 100644 index 00000000..5ff66c36 --- /dev/null +++ b/tests/Toolbox.Tests/ToolsTests.cs @@ -0,0 +1,35 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.Samples.ErrorCases; +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.Tests; + +public static class ToolsTests +{ + [Theory, RandomData] + internal static void Tools_IntegrationWorks( + DataHolderSample original, + [Fake] DataHolderSample faked + ) + { + DataHolderSample dupe = original.Tools().Copy(); + + original.Assert().Is(dupe).And().IsNot(original.Tools().Variant()); + + faked.HasNested(dupe).SetupReturn(true, Times.Once); + faked.HasNested(original).Assert().Is(true, "Value equality did not work for args."); + faked.Assert().Called(); + } + + [Theory, RandomData] + internal static void Tools_HandlesInfinites(InfiniteSample sample) + { + Tools.Mutator.Assert(x => x.Variant(sample)).Throws(); + + InfiniteSample dupe = Tools.Duplicator.Copy(sample); + + dupe.Assert().Is(sample); + Tools.Valuer.GetHashCode(dupe).Assert().Is(Tools.Valuer.GetHashCode(sample)); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/CompareHintTestBase.cs b/tests/Toolbox.Tests/ValuerTool/CompareHintTestBase.cs new file mode 100644 index 00000000..11ea5582 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/CompareHintTestBase.cs @@ -0,0 +1,639 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool.Proxy; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool; + +/// Handles testing compare hints. +/// Compare hint to test. +/// Types that can be compared by the hint. +/// Types that can't be compared by the hint. +public abstract class CompareHintTestBase( + IEnumerable validTypes = null, + IEnumerable invalidTypes = null +) : AutoTester + where T : CompareHint, new() +{ + /// + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(InvalidCastException), + typeof(UnsupportedException), + typeof(ToolException), + typeof(EngineException), + typeof(TargetException), + typeof(InvalidOperationException), + typeof(TargetParameterCountException), + typeof(ArgumentException), + typeof(FakeCallException), + typeof(TimeoutException), + typeof(KeyNotFoundException), + ], + }; + + /// Types that can be compared by the hint. + private readonly IEnumerable _validTypes = validTypes ?? new T().SupportedTypes; + + /// Types that can't be compared by the hint. + private readonly IEnumerable _invalidTypes = invalidTypes ?? [typeof(DataHolderSample)]; + + /// If sync calls are not supported for the hint. + protected virtual bool RequiresAsync { get; } = false; + + /// Verifies the hint supports the correct types. + [Fact] + public async Task TryToAsyncCompare_SupportsSameValidTypes() + { + foreach (Type type in _validTypes) + { + object data = Tools.Randomizer.Create(type); + try + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data, + data, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + await result + .Data.Assert() + .IsEmptyAsync( + TestContext.Current.CancellationToken, + $"Hint '{typeof(T).Name}' found differences with same '{type.Name}' of '{data.GetType()}'." + ); + } + finally + { + await Disposer.CleanupAsync(data); + } + } + } + + /// Verifies the hint supports the correct types. + [Fact] + public virtual async Task TryToAsyncCompare_SupportsDifferentValidTypes() + { + foreach (Type type in _validTypes) + { + object one = null, + two = null; + try + { + one = Tools.Randomizer.Create(type); + await Limiter.Hundred.StallUntilAsync( + $"Variant of same type: {GenericConverter.ExpandName(type)}, " + + $"Existing type: {GenericConverter.ExpandName(one)}.", + () => two = Tools.Mutator.Variant(type, one), + () => two.GetType() == one.GetType(), + TestContext.Current.CancellationToken + ); + + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + one, + two, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + await result + .Data.Assert() + .HasCountMoreThanAsync( + 0, + TestContext.Current.CancellationToken, + $"Hint '{typeof(T).Name}' didn't find differences with two random '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(one, two); + } + } + } + + /// Verifies the hint doesn't support the wrong types. + [Fact] + public async Task TryToAsyncCompare_InvalidTypesFail() + { + foreach (Type type in _invalidTypes) + { + object one = null, + two = null; + try + { + one = Tools.Randomizer.Create(type); + two = Tools.Randomizer.Create( + GenericConverter.AsMatchedGeneric(type, one.GetType()) ?? type + ); + + await TestInstance + .TryToAsyncCompare( + one, + two, + CreateChainer(), + TestContext.Current.CancellationToken + ) + .Assert() + .IsAsync( + DifferenceHintAsyncResult.None, + TestContext.Current.CancellationToken, + $"Hint '{typeof(T).Name}' should not support type '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(one, two); + } + } + } + + /// Verifies the hint supports the correct types. + [Fact] + public async Task TryToCompare_SupportsSameValidTypes() + { + if (RequiresAsync) + { + return; + } + + foreach (Type type in _validTypes) + { + object data = Tools.Randomizer.Create(type); + try + { + DifferenceHintResult result = TestInstance.TryToCompare( + data, + data, + CreateChainer() + ); + + result + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + result + .Data.Assert() + .IsEmpty( + $"Hint '{typeof(T).Name}' found differences with same '{type.Name}' of '{data.GetType()}'." + ); + } + finally + { + await Disposer.CleanupAsync(data); + } + } + } + + /// Verifies the hint supports the correct types. + [Fact] + public virtual async Task TryToCompare_SupportsDifferentValidTypes() + { + if (RequiresAsync) + { + return; + } + + foreach (Type type in _validTypes) + { + object one = null, + two = null; + try + { + one = Tools.Randomizer.Create(type); + await Limiter.Hundred.StallUntilAsync( + $"Variant of same type: {GenericConverter.ExpandName(type)}, " + + $"Existing type: {GenericConverter.ExpandName(one)}.", + () => two = Tools.Mutator.Variant(type, one), + () => two.GetType() == one.GetType(), + TestContext.Current.CancellationToken + ); + + DifferenceHintResult result = TestInstance.TryToCompare(one, two, CreateChainer()); + + result + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + result + .Data.Assert() + .HasCountMoreThan( + 0, + $"Hint '{typeof(T).Name}' didn't find differences with two random '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(one, two); + } + } + } + + /// Verifies the hint doesn't support the wrong types. + [Fact] + public async Task TryToCompare_InvalidTypesFail() + { + foreach (Type type in _invalidTypes) + { + object one = null, + two = null; + try + { + one = Tools.Randomizer.Create(type); + two = Tools.Randomizer.Create( + GenericConverter.AsMatchedGeneric(type, one.GetType()) ?? type + ); + + await TestInstance + .TryToCompare(one, two, CreateChainer()) + .Assert() + .IsAsync( + DifferenceHintResult.None, + TestContext.Current.CancellationToken, + $"Hint '{typeof(T).Name}' should not support type '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(one, two); + } + } + } + + /// Verifies the hint skips or throws if async is required. + [Fact] + public async Task TryToCompare_SyncForbiddenOrSkipped() + { + if (!RequiresAsync) + { + return; + } + + foreach (Type type in _validTypes) + { + object one = null, + two = null; + try + { + one = Tools.Randomizer.Create(type); + await Limiter.Hundred.StallUntilAsync( + $"Variant of same type: {GenericConverter.ExpandName(type)}, " + + $"Existing type: {GenericConverter.ExpandName(one)}.", + () => two = Tools.Mutator.Variant(type, one), + () => two.GetType() == one.GetType(), + TestContext.Current.CancellationToken + ); + + TestInstance + .Assert(x => + x.TryToCompare( + one, + two, + CreateChainer(Tools.Valuer.Options with { SkipAsyncValues = false }) + ) + ) + .Throws(); + + DifferenceHintResult result = TestInstance.TryToCompare( + one, + two, + CreateChainer(Tools.Valuer.Options with { SkipAsyncValues = true }) + ); + + result + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + result + .Data.Assert() + .IsEmpty( + $"Hint requiring async '{typeof(T).Name}' found differences with two random '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(one, two); + } + } + } + + /// Verifies the hint supports the correct types. + [Fact] + public async Task TryToAsyncGetHashCode_SupportsSameValidTypes() + { + CancellationToken ct = TestContext.Current.CancellationToken; + foreach (Type type in _validTypes) + { + object data = null, + dataCopy = null; + try + { + data = Tools.Randomizer.Create(type); + dataCopy = Tools.Duplicator.Copy(data); + + HashCodeHintAsyncResult dataHash = TestInstance.TryToAsyncGetHashCode( + data, + CreateChainer(), + ct + ); + dataHash + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + await TestInstance + .TryToAsyncGetHashCode(data, CreateChainer(), ct) + .Assert() + .IsAsync( + dataHash, + ct, + $"Hint '{typeof(T).Name}' generated different hash for same '{type.Name}'." + ); + await TestInstance + .TryToAsyncGetHashCode(dataCopy, CreateChainer(), ct) + .Assert() + .IsAsync( + dataHash, + ct, + $"Hint '{typeof(T).Name}' generated different hash for dupe '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(data, dataCopy); + } + } + } + + /// Verifies the hint supports the correct types. + /// When an exception is encountered. + [Fact] + public virtual async Task TryToAsyncGetHashCode_SupportsDifferentValidTypes() + { + CancellationToken ct = TestContext.Current.CancellationToken; + foreach (Type type in _validTypes) + { + object data = null, + dataDiffer = null; + try + { + data = Tools.Randomizer.Create(type); + dataDiffer = await Tools.Mutator.VariantAsync( + type, + data, + TestContext.Current.CancellationToken + ); + + HashCodeHintAsyncResult dataHash = TestInstance.TryToAsyncGetHashCode( + data, + CreateChainer(), + ct + ); + dataHash + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + + await Limiter.Few.AttemptAsync( + "Trying to generate object with different value hashes.", + () => + TestInstance + .TryToAsyncGetHashCode(dataDiffer, CreateChainer(), ct) + .Assert() + .IsNotAsync( + dataHash, + ct, + $"Hint '{typeof(T).Name}' generated same hash for different '{type.Name}'." + ), + TestContext.Current.CancellationToken + ); + } + catch (Exception e) + { + throw new EngineException( + $"Error while testing type {GenericConverter.ExpandName(type)}", + e + ); + } + finally + { + await Disposer.CleanupAsync(data, dataDiffer); + } + } + } + + /// Verifies the hint doesn't support the wrong types. + [Fact] + public async Task TryToAsyncGetHashCode_InvalidTypesFail() + { + CancellationToken ct = TestContext.Current.CancellationToken; + foreach (Type type in _invalidTypes) + { + object data = Tools.Randomizer.Create(type); + try + { + await TestInstance + .TryToAsyncGetHashCode(data, CreateChainer(), ct) + .Assert() + .IsAsync( + HashCodeHintAsyncResult.None, + TestContext.Current.CancellationToken, + $"Hint '{typeof(T).Name}' should not support type '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(data); + } + } + } + + /// Verifies the hint supports the correct types. + [Fact] + public async Task TryToGetHashCode_SupportsSameValidTypes() + { + if (RequiresAsync) + { + return; + } + + CancellationToken ct = TestContext.Current.CancellationToken; + foreach (Type type in _validTypes) + { + object data = null, + dataCopy = null; + try + { + data = Tools.Randomizer.Create(type); + dataCopy = Tools.Duplicator.Copy(data); + + HashCodeHintResult dataHash = TestInstance.TryToGetHashCode(data, CreateChainer()); + dataHash + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + await TestInstance + .TryToGetHashCode(data, CreateChainer()) + .Assert() + .IsAsync( + dataHash, + ct, + $"Hint '{typeof(T).Name}' generated different hash for same '{type.Name}'." + ); + await TestInstance + .TryToGetHashCode(dataCopy, CreateChainer()) + .Assert() + .IsAsync( + dataHash, + ct, + $"Hint '{typeof(T).Name}' generated different hash for dupe '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(data, dataCopy); + } + } + } + + /// Verifies the hint supports the correct types. + /// When an exception is encountered. + [Fact] + public virtual async Task TryToGetHashCode_SupportsDifferentValidTypes() + { + if (RequiresAsync) + { + return; + } + + CancellationToken ct = TestContext.Current.CancellationToken; + foreach (Type type in _validTypes) + { + object data = null, + dataDiffer = null; + try + { + data = Tools.Randomizer.Create(type); + dataDiffer = await Tools.Mutator.VariantAsync( + type, + data, + TestContext.Current.CancellationToken + ); + + HashCodeHintResult dataHash = TestInstance.TryToGetHashCode(data, CreateChainer()); + dataHash + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + + await Limiter.Few.AttemptAsync( + "Trying to generate object with different value hashes.", + () => + TestInstance + .TryToGetHashCode(dataDiffer, CreateChainer()) + .Assert() + .IsNotAsync( + dataHash, + ct, + $"Hint '{typeof(T).Name}' generated same hash for different '{type.Name}'." + ), + TestContext.Current.CancellationToken + ); + } + catch (Exception e) + { + throw new EngineException( + $"Error while testing type {GenericConverter.ExpandName(type)}", + e + ); + } + finally + { + await Disposer.CleanupAsync(data, dataDiffer); + } + } + } + + /// Verifies the hint doesn't support the wrong types. + [Fact] + public async Task TryToGetHashCode_InvalidTypesFail() + { + foreach (Type type in _invalidTypes) + { + object data = Tools.Randomizer.Create(type); + try + { + await TestInstance + .TryToGetHashCode(data, CreateChainer()) + .Assert() + .IsAsync( + HashCodeHintResult.None, + TestContext.Current.CancellationToken, + $"Hint '{typeof(T).Name}' should not support type '{type.Name}'." + ); + } + finally + { + await Disposer.CleanupAsync(data); + } + } + } + + /// Verifies the hint skips or throws if async is required. + [Fact] + public async Task TryToGetHashCode_SyncForbiddenOrSkipped() + { + if (!RequiresAsync) + { + return; + } + + foreach (Type type in _validTypes) + { + object data = null; + try + { + data = Tools.Randomizer.Create(type); + + TestInstance + .Assert(x => + x.TryToGetHashCode( + data, + CreateChainer(Tools.Valuer.Options with { SkipAsyncValues = false }) + ) + ) + .Throws(); + + HashCodeHintResult dataHash = TestInstance.TryToGetHashCode( + data, + CreateChainer(Tools.Valuer.Options with { SkipAsyncValues = true }) + ); + dataHash + .HasData.Assert() + .Is(true, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + dataHash + .Data.Assert() + .Is(0, $"Hint '{typeof(T).Name}' failed to support '{type.Name}'."); + } + finally + { + await Disposer.CleanupAsync(data); + } + } + } + + /// Create a chainer to use for testing. + /// Chainer to use for testing. + /// Options to pass via the chainer. + protected virtual IValuerChainer CreateChainer(ValuerOptions options = null) + { + return new ValuerChainer(options ?? Tools.Valuer.Options, new ValuerEngine()); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/ByValuerAsyncComparerTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/ByValuerAsyncComparerTests.cs new file mode 100644 index 00000000..924376e4 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/ByValuerAsyncComparerTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class ByValuerAsyncComparerTests() : AutoTester(typeof(ByValuerAsyncComparer<>)); diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/ByValuerComparerTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/ByValuerComparerTests.cs new file mode 100644 index 00000000..83187a31 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/ByValuerComparerTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class ByValuerComparerTests() : AutoTester(typeof(ByValuerComparer<>)); diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/ComparePriorityTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/ComparePriorityTests.cs new file mode 100644 index 00000000..523358c4 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/ComparePriorityTests.cs @@ -0,0 +1,54 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class ComparePriorityTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentException), typeof(FormatException)], + }; + + [Fact] + internal static void Disabled_SetToMin() + { + ((int)ComparePriority.Disabled).Assert().Is(int.MinValue); + } + + [Fact] + internal static void None_DefaultAtZero() + { + ((int)ComparePriority.None).Assert().Is(0); + } + + [Fact] + internal static void Highest_AtCap() + { + ((int)ComparePriority.Highest) + .Assert() + .Is(Enum.GetValues(typeof(ComparePriority)).Length - 2); + } + + [Fact] + internal static void Values_AllPositive() + { + Enum.GetValues(typeof(ComparePriority)) + .Cast() + .Except([(int)ComparePriority.Disabled]) + .Where(v => v < 0) + .Assert() + .IsEmpty(); + } + + [Fact] + internal static void Values_Unique() + { + Enum.GetValues(typeof(ComparePriority)) + .Cast() + .ToHashSet() + .Assert() + .HasCount(Enum.GetValues(typeof(ComparePriority)).Length); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceHintAsyncResultTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceHintAsyncResultTests.cs new file mode 100644 index 00000000..f637995e --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceHintAsyncResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class DifferenceHintAsyncResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + DifferenceHintAsyncResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceHintResultTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceHintResultTests.cs new file mode 100644 index 00000000..6f235c66 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceHintResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class DifferenceHintResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + DifferenceHintResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceTests.cs new file mode 100644 index 00000000..873198c7 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/DifferenceTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class DifferenceTests : AutoTester; diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/HashCodeHintAsyncResultTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/HashCodeHintAsyncResultTests.cs new file mode 100644 index 00000000..73a1a4cb --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/HashCodeHintAsyncResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class HashCodeHintAsyncResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + HashCodeHintAsyncResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/HashCodeHintResultTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/HashCodeHintResultTests.cs new file mode 100644 index 00000000..7edf4d74 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/HashCodeHintResultTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class HashCodeHintResultTests : AutoTester +{ + [Fact] + internal static void None_HasNoData() + { + HashCodeHintResult.None.HasData.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/ValuerChainerTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/ValuerChainerTests.cs new file mode 100644 index 00000000..01798ec9 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/ValuerChainerTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class ValuerChainerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(UnsupportedException), + typeof(ToolException), + typeof(EngineException), + ], + }; +} diff --git a/tests/Toolbox.Tests/ValuerTool/Engine/ValuerEngineTests.cs b/tests/Toolbox.Tests/ValuerTool/Engine/ValuerEngineTests.cs new file mode 100644 index 00000000..77ebe784 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Engine/ValuerEngineTests.cs @@ -0,0 +1,259 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.ValuerTool; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Engine; + +public sealed class ValuerEngineTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = [Tools.Valuer.Options], + IgnorableExceptions = + [ + typeof(UnsupportedException), + typeof(TargetException), + typeof(ToolException), + ], + }; + + [Theory, RandomData] + internal void Compare_NoHintsUnsupported(object expected, object actual) + { + TestInstance + .Assert(x => x.Compare(expected, actual, CreateHintChainer(null))) + .Throws(); + } + + [Theory, RandomData] + internal void Compare_NullResultSafe([Stub] ICompareHint hint, object expected, object actual) + { + TestInstance + .Assert(x => x.Compare(expected, actual, CreateHintChainer(hint))) + .Throws(); + } + + [Theory, RandomData] + internal void Compare_WithErrorHandling( + [Stub] ICompareHint hint, + object expected, + object actual, + ArgumentException error + ) + { + IEnumerable thrower() + { + yield return new Difference(""); + throw error; + } + + hint.TryToCompare(expected, actual, Arg.Any()) + .SetupReturn(new DifferenceHintResult(thrower())); + + TestInstance + .Assert(x => x.Compare(expected, actual, CreateHintChainer(hint)).ToList()) + .Throws(); + } + + [Theory, RandomData] + internal void CompareAsync_NoHintsUnsupported(object expected, object actual) + { + TestInstance + .Assert(x => + x.CompareAsync( + expected, + actual, + CreateHintChainer(null), + TestContext.Current.CancellationToken + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal void CompareAsync_NullResultSafe( + [Stub] ICompareHint hint, + object expected, + object actual + ) + { + TestInstance + .Assert(x => + x.CompareAsync( + expected, + actual, + CreateHintChainer(hint), + TestContext.Current.CancellationToken + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal void CompareAsync_WithErrorHandling( + [Stub] ICompareHint hint, + object expected, + object actual, + ArgumentException error + ) + { + hint.TryToAsyncCompare( + expected, + actual, + Arg.Any(), + TestContext.Current.CancellationToken + ) + .SetupReturn(Behavior.Throw(error)); + + TestInstance + .Assert(x => + x.CompareAsync( + expected, + actual, + CreateHintChainer(hint), + TestContext.Current.CancellationToken + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal Task CompareAsync_WithErrorHandlingDuringYield( + [Stub] ICompareHint hint, + object expected, + object actual, + ArgumentException error + ) + { + async IAsyncEnumerable thrower() + { + await Task.Delay(0, TestContext.Current.CancellationToken); + yield return new Difference(""); + throw error; + } + + hint.TryToAsyncCompare( + expected, + actual, + Arg.Any(), + TestContext.Current.CancellationToken + ) + .SetupReturn(new DifferenceHintAsyncResult(thrower())); + + return TestInstance + .CompareAsync( + expected, + actual, + CreateHintChainer(hint), + TestContext.Current.CancellationToken + ) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal void GetHashCode_NoHintsUnsupported(object item) + { + TestInstance + .Assert(x => x.GetHashCode(item, CreateHintChainer(null))) + .Throws(); + } + + [Theory, RandomData] + internal void GetHashCode_NullResultSafe([Stub] ICompareHint hint, object item) + { + TestInstance + .Assert(x => x.GetHashCode(item, CreateHintChainer(hint))) + .Throws(); + } + + [Theory, RandomData] + internal void GetHashCodeAsync_NoHintsUnsupported(object item) + { + TestInstance + .Assert(x => + x.GetHashCodeAsync( + item, + CreateHintChainer(null), + TestContext.Current.CancellationToken + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal void GetHashCodeAsync_NullResultSafe([Stub] ICompareHint hint, object item) + { + TestInstance + .Assert(x => + x.GetHashCodeAsync( + item, + CreateHintChainer(hint), + TestContext.Current.CancellationToken + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal void GetHashCodeAsync_WithErrorHandling( + [Stub] ICompareHint hint, + object item, + ArgumentException error + ) + { + hint.TryToAsyncGetHashCode( + item, + Arg.Any(), + TestContext.Current.CancellationToken + ) + .SetupReturn(Behavior.Throw(error)); + + TestInstance + .Assert(x => + x.GetHashCodeAsync( + item, + CreateHintChainer(hint), + TestContext.Current.CancellationToken + ) + ) + .Throws(); + } + + [Theory, RandomData] + internal Task GetHashCodeAsync_WithErrorHandlingDuringAwait( + [Stub] ICompareHint hint, + object item, + ArgumentException error + ) + { + hint.TryToAsyncGetHashCode( + item, + Arg.Any(), + TestContext.Current.CancellationToken + ) + .SetupReturn(new HashCodeHintAsyncResult(Task.FromException(error))); + + return TestInstance + .GetHashCodeAsync(item, CreateHintChainer(hint), TestContext.Current.CancellationToken) + .Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } + + private static ValuerChainer CreateHintChainer(ICompareHint hint) + { + return new ValuerChainer( + Tools.Valuer.Options with + { + IncludeFoundHints = false, + IncludeFrameworkHints = false, + Hints = hint != null ? [hint] : [], + }, + new ValuerEngine() + ); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Handlers/ConvertCompareHandlerTests.cs b/tests/Toolbox.Tests/ValuerTool/Handlers/ConvertCompareHandlerTests.cs new file mode 100644 index 00000000..e18f7041 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Handlers/ConvertCompareHandlerTests.cs @@ -0,0 +1,15 @@ +using Werecodent.CreateAndFake.ValuerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Handlers; + +public sealed class ConvertCompareHandlerTests() : AutoTester(typeof(ConvertCompareHandler<>)) +{ + protected override TesterMod OptionConfiguration { get; } = + opt => opt with { IgnorableExceptions = [typeof(InvalidCastException)] }; + + [Fact] + internal static void ConvertCompareHandler_InternalOnly() + { + typeof(ConvertCompareHandler<>).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Handlers/DefaultEqualityCompareHandlerTests.cs b/tests/Toolbox.Tests/ValuerTool/Handlers/DefaultEqualityCompareHandlerTests.cs new file mode 100644 index 00000000..2a08efa4 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Handlers/DefaultEqualityCompareHandlerTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.ValuerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Handlers; + +public sealed class DefaultEqualityCompareHandlerTests() + : AutoTester(typeof(DefaultEqualityCompareHandler)) +{ + [Fact] + internal static void DefaultEqualityCompareHandler_InternalOnly() + { + typeof(DefaultEqualityCompareHandler).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Handlers/ReflectionCompareHandlersTests.cs b/tests/Toolbox.Tests/ValuerTool/Handlers/ReflectionCompareHandlersTests.cs new file mode 100644 index 00000000..282dbfa8 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Handlers/ReflectionCompareHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ValuerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Handlers; + +public sealed class ReflectionCompareHandlersTests() : AutoTester(typeof(ReflectionCompareHandlers)) +{ + [Fact] + internal static void ReflectionCompareHandlers_InternalOnly() + { + typeof(ReflectionCompareHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Handlers/SystemCompareHandlersTests.cs b/tests/Toolbox.Tests/ValuerTool/Handlers/SystemCompareHandlersTests.cs new file mode 100644 index 00000000..7cc023af --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Handlers/SystemCompareHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ValuerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Handlers; + +public sealed class SystemCompareHandlersTests() : AutoTester(typeof(SystemCompareHandlers)) +{ + [Fact] + internal static void SystemCompareHandlers_InternalOnly() + { + typeof(SystemCompareHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Handlers/ValueCompareHandlersTests.cs b/tests/Toolbox.Tests/ValuerTool/Handlers/ValueCompareHandlersTests.cs new file mode 100644 index 00000000..9f42df0d --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Handlers/ValueCompareHandlersTests.cs @@ -0,0 +1,12 @@ +using Werecodent.CreateAndFake.ValuerTool.Handlers; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Handlers; + +public sealed class ValueCompareHandlersTests() : AutoTester(typeof(ValueCompareHandlers)) +{ + [Fact] + internal static void ValueCompareHandlers_InternalOnly() + { + typeof(ValueCompareHandlers).IsPublic.Assert().Is(false); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/AsyncEnumerableCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/AsyncEnumerableCompareHintTests.cs new file mode 100644 index 00000000..615e15d1 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/AsyncEnumerableCompareHintTests.cs @@ -0,0 +1,89 @@ +using System.Collections; +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class AsyncEnumerableCompareHintTests + : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(IAsyncEnumerable), + typeof(IAsyncEnumerable), + typeof(IAsyncEnumerable), + ]; + + private static readonly Type[] _InvalidTypes = [typeof(IEnumerable), typeof(DataHolderSample)]; + + protected override bool RequiresAsync { get; } = true; + + public AsyncEnumerableCompareHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + [Theory, RandomData] + internal Task TryToAsyncCompare_CanCheckCollectionType(IAsyncEnumerable data) + { + async IAsyncEnumerable iterate() + { + await foreach ( + string item in data.WithCancellation(TestContext.Current.CancellationToken) + .ConfigureAwait(false) + ) + { + yield return item; + } + } + + return TestInstance + .TryToAsyncCompare( + data, + iterate(), + CreateChainer(Tools.Valuer.Options with { CheckCollectionType = true }), + TestContext.Current.CancellationToken + ) + .Data.Assert() + .HasCountAsync(1, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal async Task TryToAsyncCompare_NoDifferencesWhenEqualWithDifferentTypes( + IAsyncEnumerable data + ) + { + IEnumerable data2 = await AsyncSeriesHelper.ToListAsync( + data, + Tools.Valuer.Options.Design.IterationLimit, + TestContext.Current.CancellationToken + ); + + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data2, + data, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + await result.Data.Assert().HasCountAsync(0, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_FindsDifferencesWithDifferentTypes( + IAsyncEnumerable data, + IEnumerable data2 + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data, + data2, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/AsyncSetCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/AsyncSetCompareHintTests.cs new file mode 100644 index 00000000..c32647fe --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/AsyncSetCompareHintTests.cs @@ -0,0 +1,81 @@ +using Werecodent.CreateAndFake.Design.Content; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class AsyncSetCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(IAsyncSet), + typeof(IAsyncSet), + typeof(IAsyncSet), + typeof(AsyncHashSet), + typeof(AsyncHashSet), + typeof(AsyncHashSet), + ]; + + protected override bool RequiresAsync { get; } = true; + + public AsyncSetCompareHintTests() + : base(_ValidTypes) { } + + [Theory, RandomData] + internal Task TryToAsyncCompare_RequiresSameItemType(HashSet data, IAsyncSet data2) + { + return TestInstance + .TryToAsyncCompare( + data, + data2, + CreateChainer( + Tools.Valuer.Options with + { + CheckCollectionType = true, + IncludeValueHashInComparison = false, + } + ), + TestContext.Current.CancellationToken + ) + .Data.Assert() + .HasCountAsync(1, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_NoDifferencesWhenEqualWithDifferentTypes(HashSet data) + { + IAsyncSet data2 = AsyncHashSet.CreateFromAsync( + data, + Tools.Valuer.ToAsyncComparer(), + data.Count, + TestContext.Current.CancellationToken + ); + + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data2, + data, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountAsync(0, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_FindsDifferencesWithDifferentTypes( + AsyncHashSet data, + HashSet data2 + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data, + data2, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/DefaultEqualityCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/DefaultEqualityCompareHintTests.cs new file mode 100644 index 00000000..93323d1b --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/DefaultEqualityCompareHintTests.cs @@ -0,0 +1,22 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class DefaultEqualityCompareHintTests + : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(BindingFlags), typeof(Func<>)]; + + private static readonly Type[] _InvalidTypes = [typeof(SeededRandom)]; + + public DefaultEqualityCompareHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + [Theory, RandomData] + internal void TryToCompare_MismatchedTypesDifferent(int value) + { + TestInstance.TryToCompare(value, new object(), CreateChainer()).Data.Assert().IsNotEmpty(); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/DictionaryCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/DictionaryCompareHintTests.cs new file mode 100644 index 00000000..3e921568 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/DictionaryCompareHintTests.cs @@ -0,0 +1,115 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class DictionaryCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(IDictionary), + typeof(Dictionary), + typeof(IDictionary), + ]; + + public DictionaryCompareHintTests() + : base(_ValidTypes) { } + + [Theory, RandomData] + internal void TryToCompare_SameKeyDifferentValuesWorks(Dictionary data) + { + Dictionary dupe = data.Tools().Copy(); + string key = data.First().Key; + dupe[key] = data[key].Tools().Variant(); + + TestInstance + .TryToCompare(data, dupe, CreateChainer()) + .Data.ToArray() + .Assert() + .IsNotEmpty( + "Hint didn't find differences with a modified key on '" + + GenericConverter.ExpandName(data) + + "'." + ); + } + + [Theory, RandomData] + internal void TryToCompare_CanCheckCollectionType(ConcurrentDictionary data) + { + TestInstance + .TryToCompare( + data, + data.ToFrozenDictionary(), + CreateChainer(Tools.Valuer.Options with { CheckCollectionType = true }) + ) + .Data.Assert() + .HasCount(1); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_CanCheckCollectionType(ConcurrentDictionary data) + { + return TestInstance + .TryToAsyncCompare( + data, + data.ToFrozenDictionary(), + CreateChainer(Tools.Valuer.Options with { CheckCollectionType = true }), + TestContext.Current.CancellationToken + ) + .Data.Assert() + .HasCountAsync(1, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_NoDifferencesWhenEqualWithDifferentTypes( + ConcurrentDictionary data + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data.ToFrozenDictionary(), + data, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountAsync(0, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_FindsDifferencesWithDifferentTypes( + ConcurrentDictionary data, + FrozenDictionary data2 + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data, + data2, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_DifferencesWithSameKeyButNotValues( + IDictionary data + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data, + data.ToDictionary(p => p.Key, p => p.Value.Tools().Variant()), + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/EnumerableCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/EnumerableCompareHintTests.cs new file mode 100644 index 00000000..977275b7 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/EnumerableCompareHintTests.cs @@ -0,0 +1,103 @@ +using System.Collections; +using System.Collections.Immutable; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class EnumerableCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(IList), + typeof(List), + typeof(List>), + ]; + + public EnumerableCompareHintTests() + : base(_ValidTypes) { } + + [Theory, RandomData] + internal void Compare_SizeMismatchOutOfBounds(List original) + { + IValuerChainer chainer = CreateChainer( + Tools.Valuer.Options with + { + IncludeValueHashInComparison = false, + } + ); + + List variant = original.Tools().Copy(); + variant.RemoveAt(variant.Count - 1); + + DifferenceHintResult result = TestInstance.TryToCompare(original, variant, chainer); + result.HasData.Assert().Is(true); + result.Data.Assert().HasCount(1); + result.Data.Single().ToString().Assert().Contains("'out of range'"); + + result = TestInstance.TryToCompare(variant, original, chainer); + result.HasData.Assert().Is(true); + result.Data.Assert().HasCount(1); + result.Data.Single().ToString().Assert().Contains("'out of range'"); + } + + [Theory, RandomData] + internal void TryToCompare_CanCheckCollectionType(LinkedList data) + { + TestInstance + .TryToCompare( + data, + data.ToImmutableList(), + CreateChainer(Tools.Valuer.Options with { CheckCollectionType = true }) + ) + .Data.Assert() + .HasCount(1); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_CanCheckCollectionType(LinkedList data) + { + return TestInstance + .TryToAsyncCompare( + data, + data.ToImmutableList(), + CreateChainer(Tools.Valuer.Options with { CheckCollectionType = true }), + TestContext.Current.CancellationToken + ) + .Data.Assert() + .HasCountAsync(1, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_NoDifferencesWhenEqualWithDifferentTypes( + LinkedList data + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data.ToImmutableList(), + data, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountAsync(0, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_FindsDifferencesWithDifferentTypes( + LinkedList data, + ImmutableList data2 + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data, + data2, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/EquatableCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/EquatableCompareHintTests.cs new file mode 100644 index 00000000..339381b7 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/EquatableCompareHintTests.cs @@ -0,0 +1,25 @@ +using Werecodent.CreateAndFake.Design.Reiteration; +using Werecodent.CreateAndFake.ValuerTool; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class EquatableCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(Limiter)]; + + public EquatableCompareHintTests() + : base(_ValidTypes) { } + + protected override IValuerChainer CreateChainer(ValuerOptions options = null) + { + return new ValuerChainer( + (options ?? Tools.Valuer.Options) with + { + UseEquatableComparisons = true, + }, + new ValuerEngine() + ); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/FakedCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/FakedCompareHintTests.cs new file mode 100644 index 00000000..5b62aa73 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/FakedCompareHintTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class FakedCompareHintTests : CompareHintTestBase +{ + [Theory, RandomData] + internal void Compare_MismatchedFakesDifference( + [Stub] object stub1, + [Stub] IEnumerable stub2 + ) + { + DifferenceHintResult result = TestInstance.TryToCompare(stub1, stub2, CreateChainer()); + + result.HasData.Assert().Is(true); + result.Data.Assert().IsNotEmpty(); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/HandlerCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/HandlerCompareHintTests.cs new file mode 100644 index 00000000..6ea9dea8 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/HandlerCompareHintTests.cs @@ -0,0 +1,31 @@ +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class HandlerCompareHintTests : CompareHintTestBase +{ + [Theory, RandomData] + internal void Compare_CanIncludeCurrentSeed(SeededRandom gen, [Copy] SeededRandom gen2) + { + TestInstance + .TryToCompare( + gen, + gen2, + CreateChainer(Tools.Valuer.Options with { IgnoreCurrentRandomSeed = false }) + ) + .Data.Assert() + .IsEmpty(); + + _ = gen.Next(); + + TestInstance + .TryToCompare( + gen, + gen2, + CreateChainer(Tools.Valuer.Options with { IgnoreCurrentRandomSeed = false }) + ) + .Data.Assert() + .IsNotEmpty(); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/PrivateObjectCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/PrivateObjectCompareHintTests.cs new file mode 100644 index 00000000..a411697d --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/PrivateObjectCompareHintTests.cs @@ -0,0 +1,35 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class PrivateObjectCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(DataHolderSample), typeof(FieldSample)]; + + private static readonly Type[] _InvalidTypes = Type.EmptyTypes; + + public PrivateObjectCompareHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + public override Task Tester_NoParameterMutation() + { + return Tools.Tester.PreventsNullRefExceptionAsync( + TestContext.Current.CancellationToken, + opt => opt with { InjectionValues = [Tools.Randomizer.Create()] } + ); + } + + [Theory, RandomData] + internal void Compare_DifferentObjectsDifferences(string value1, string value2) + { + var expected = new { Value = value1 }; + var actual = new { Value = value2 }; + + DifferenceHintResult result = TestInstance.TryToCompare(expected, actual, CreateChainer()); + + result.HasData.Assert().Is(true); + result.Data.Assert().IsNotEmpty(); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/PublicObjectCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/PublicObjectCompareHintTests.cs new file mode 100644 index 00000000..bf9c4334 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/PublicObjectCompareHintTests.cs @@ -0,0 +1,35 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class PublicObjectCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(DataHolderSample), typeof(FieldSample)]; + + private static readonly Type[] _InvalidTypes = Type.EmptyTypes; + + public PublicObjectCompareHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + public override Task Tester_NoParameterMutation() + { + return Tools.Tester.PreventsNullRefExceptionAsync( + TestContext.Current.CancellationToken, + opt => opt with { InjectionValues = [Tools.Randomizer.Create()] } + ); + } + + [Theory, RandomData] + internal void Compare_DifferentObjectsDifferences(string value1, string value2) + { + var expected = new { Value = value1 }; + var actual = new { Value = value2 }; + + DifferenceHintResult result = TestInstance.TryToCompare(expected, actual, CreateChainer()); + + result.HasData.Assert().Is(true); + result.Data.Assert().IsNotEmpty(); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/SetCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/SetCompareHintTests.cs new file mode 100644 index 00000000..b8aa92b6 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/SetCompareHintTests.cs @@ -0,0 +1,82 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class SetCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(ISet), + typeof(HashSet), + typeof(HashSet), + typeof(ISet), + typeof(ISet), + ]; + + public SetCompareHintTests() + : base(_ValidTypes) { } + + [Theory, RandomData] + internal void TryToCompare_CanCheckCollectionType(HashSet data) + { + TestInstance + .TryToCompare( + data, + data.ToFrozenSet(), + CreateChainer(Tools.Valuer.Options with { CheckCollectionType = true }) + ) + .Data.Assert() + .HasCount(1); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_CanCheckCollectionType(ImmutableHashSet data) + { + return TestInstance + .TryToAsyncCompare( + data, + data.ToFrozenSet(), + CreateChainer(Tools.Valuer.Options with { CheckCollectionType = true }), + TestContext.Current.CancellationToken + ) + .Data.Assert() + .HasCountAsync(1, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_NoDifferencesWhenEqualWithDifferentTypes( + ImmutableHashSet data + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data.ToFrozenSet(), + data, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountAsync(0, TestContext.Current.CancellationToken); + } + + [Theory, RandomData] + internal Task TryToAsyncCompare_FindsDifferencesWithDifferentTypes( + ImmutableHashSet data, + FrozenSet data2 + ) + { + DifferenceHintAsyncResult result = TestInstance.TryToAsyncCompare( + data, + data2, + CreateChainer(), + TestContext.Current.CancellationToken + ); + + result.HasData.Assert().Is(true); + return result.Data.Assert().HasCountMoreThanAsync(0, TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/StatelessCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/StatelessCompareHintTests.cs new file mode 100644 index 00000000..a3922196 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/StatelessCompareHintTests.cs @@ -0,0 +1,45 @@ +using System.Collections; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class StatelessCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(StatelessSample)]; + + private static readonly Type[] _InvalidTypes = + [ + typeof(DataHolderSample), + typeof(string), + typeof(IList), + typeof(int), + ]; + + public StatelessCompareHintTests() + : base(_ValidTypes, _InvalidTypes) { } + + public override Task TryToAsyncCompare_SupportsDifferentValidTypes() + { + // Stateless objects can't be different. + return Task.CompletedTask; + } + + public override Task TryToCompare_SupportsDifferentValidTypes() + { + // Stateless objects can't be different. + return Task.CompletedTask; + } + + public override Task TryToAsyncGetHashCode_SupportsDifferentValidTypes() + { + // Stateless objects can't be different. + return Task.CompletedTask; + } + + public override Task TryToGetHashCode_SupportsDifferentValidTypes() + { + // Stateless objects can't be different. + return Task.CompletedTask; + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/StreamCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/StreamCompareHintTests.cs new file mode 100644 index 00000000..e3141490 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/StreamCompareHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class StreamCompareHintTests : CompareHintTestBase; diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/StructuralEquatableCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/StructuralEquatableCompareHintTests.cs new file mode 100644 index 00000000..d729ed10 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/StructuralEquatableCompareHintTests.cs @@ -0,0 +1,25 @@ +using Werecodent.CreateAndFake.ValuerTool; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class StructuralEquatableCompareHintTests + : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(ValueTuple)]; + + public StructuralEquatableCompareHintTests() + : base(_ValidTypes) { } + + protected override IValuerChainer CreateChainer(ValuerOptions options = null) + { + return new ValuerChainer( + (options ?? Tools.Valuer.Options) with + { + UseEquatableComparisons = true, + }, + new ValuerEngine() + ); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/TaskCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/TaskCompareHintTests.cs new file mode 100644 index 00000000..5ab139f0 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/TaskCompareHintTests.cs @@ -0,0 +1,63 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool.Engine; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class TaskCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(Task), + typeof(Task), + typeof(Task), + typeof(Task), + typeof(Task), + typeof(Task), + ]; + + public TaskCompareHintTests() + : base(_ValidTypes) { } + + [Theory, RandomData] + internal void Compare_NonGenericTasksCompareByException(Exception ex) + { + Task taskA = Task.FromException(ex); + Task taskB = Task.FromException(ex); + Task taskC = Task.FromException(Tools.Mutator.Variant(ex)); + Task taskD = Task.CompletedTask; + IValuerChainer chainer = CreateChainer(); + TestInstance.TryToCompare(taskA, taskB, chainer).Assert().Is(new DifferenceHintResult([])); + TestInstance + .TryToCompare(taskA, taskC, chainer) + .Assert() + .IsNot(new DifferenceHintResult([])); + TestInstance + .TryToCompare(taskA, taskD, chainer) + .Assert() + .IsNot(new DifferenceHintResult([])); + } + + [Fact] + internal void Compare_NonGenericTasksCompareByStatus() + { + Task taskA = Task.CompletedTask; + Task taskB = Task.CompletedTask; + IValuerChainer chainer = CreateChainer(); + TestInstance.TryToCompare(taskA, taskB, chainer).Assert().Is(new DifferenceHintResult([])); + } + + [Fact] + internal Task GetHashCodeAsync_TimesOut() + { + return TestInstance + .TryToAsyncGetHashCode( + Task.Delay(500, TestContext.Current.CancellationToken), + CreateChainer(Tools.Valuer.Options with { AsyncTimeout = TimeSpan.Zero }), + TestContext.Current.CancellationToken + ) + .Data.Assert() + .ThrowsAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/ValueEquatableCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/ValueEquatableCompareHintTests.cs new file mode 100644 index 00000000..0a3d9a84 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/ValueEquatableCompareHintTests.cs @@ -0,0 +1,17 @@ +using Werecodent.CreateAndFake.Design.Comparisons; +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class ValueEquatableCompareHintTests : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(IValueEquatable), + typeof(ValueEquatableSample), + ]; + + public ValueEquatableCompareHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/ValueTaskCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/ValueTaskCompareHintTests.cs new file mode 100644 index 00000000..48ddf933 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/ValueTaskCompareHintTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class ValueTaskCompareHintTests : CompareHintTestBase; diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/ValuerAsyncComparableCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/ValuerAsyncComparableCompareHintTests.cs new file mode 100644 index 00000000..5c47b716 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/ValuerAsyncComparableCompareHintTests.cs @@ -0,0 +1,27 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.ValuerTool; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class ValuerAsyncComparableCompareHintTests + : CompareHintTestBase +{ + protected override bool RequiresAsync { get; } = true; + + [Theory, RandomData] + internal void TryToCompare_BlocksComparison(IValuerAsyncComparable data) + { + TestInstance + .Assert(x => x.TryToCompare(data, data, CreateChainer())) + .Throws(); + } + + [Theory, RandomData] + internal void TryToGetHashCode_BlocksHashing(IValuerAsyncComparable data) + { + TestInstance + .Assert(x => x.TryToGetHashCode(data, CreateChainer())) + .Throws(); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/ValuerComparableCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/ValuerComparableCompareHintTests.cs new file mode 100644 index 00000000..34322bd3 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/ValuerComparableCompareHintTests.cs @@ -0,0 +1,13 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class ValuerComparableCompareHintTests + : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = [typeof(ValuerComparableSample)]; + + public ValuerComparableCompareHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/ValuerTool/Hints/ValuerEquatableCompareHintTests.cs b/tests/Toolbox.Tests/ValuerTool/Hints/ValuerEquatableCompareHintTests.cs new file mode 100644 index 00000000..e9303040 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/Hints/ValuerEquatableCompareHintTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; +using Werecodent.CreateAndFake.ValuerTool; +using Werecodent.CreateAndFake.ValuerTool.Hints; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool.Hints; + +public sealed class ValuerEquatableCompareHintTests + : CompareHintTestBase +{ + private static readonly Type[] _ValidTypes = + [ + typeof(IValuerEquatable), + typeof(ValuerEquatableSample), + typeof(PrivateValuerEquatableSample), + ]; + + public ValuerEquatableCompareHintTests() + : base(_ValidTypes) { } +} diff --git a/tests/Toolbox.Tests/ValuerTool/ValuerOptionsTests.cs b/tests/Toolbox.Tests/ValuerTool/ValuerOptionsTests.cs new file mode 100644 index 00000000..ed04c217 --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/ValuerOptionsTests.cs @@ -0,0 +1,18 @@ +global using ValuerMod = System.Func< + Werecodent.CreateAndFake.ValuerTool.ValuerOptions, + Werecodent.CreateAndFake.ValuerTool.ValuerOptions +>; +using Werecodent.CreateAndFake.ValuerTool; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool; + +public sealed class ValuerOptionsTests : AutoTester +{ + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void ValuerOptions_ModFormRandomizable() + { + typeof(ValuerMod).Tools().CreateRandomInstance().Assert().IsNotNull(); + } +} diff --git a/tests/Toolbox.Tests/ValuerTool/ValuerTests.cs b/tests/Toolbox.Tests/ValuerTool/ValuerTests.cs new file mode 100644 index 00000000..a8f99d2c --- /dev/null +++ b/tests/Toolbox.Tests/ValuerTool/ValuerTests.cs @@ -0,0 +1,140 @@ +using Werecodent.CreateAndFake.Design.Exceptions; +using Werecodent.CreateAndFake.Design.Types; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.ValuerTool; +using Werecodent.CreateAndFake.ValuerTool.Engine; + +namespace Werecodent.CreateAndFake.Tests.ValuerTool; + +public sealed class ValuerTests : AutoTester +{ + protected override TesterMod OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = + [ + typeof(ToolException), + typeof(TimeoutException), + typeof(UnsupportedException), + ], + }; + + [Fact] + internal static void GetHashCode_MissingMatchThrows() + { + new Valuer(Tools.Valuer.Options with { IncludeFrameworkHints = false }) + .Assert(x => x.GetHashCode(new object())) + .Throws(); + } + + [Theory, RandomData] + internal static void GetHashCode_ValidHint(object data, int result, [Stub] ICompareHint hint) + { + hint.TryToGetHashCode(data, Arg.Any()) + .SetupReturn(new HashCodeHintResult(result)); + + new Valuer(Tools.Valuer.Options with { IncludeFrameworkHints = false, Hints = [hint] }) + .GetHashCode(data) + .Assert() + .Is(result); + + hint.Assert().Called(); + } + + [Fact] + internal static void Compare_MissingMatchThrows() + { + new Valuer(Tools.Valuer.Options with { IncludeFrameworkHints = false }) + .Assert(x => x.Compare(new object(), new object()).ToList()) + .Throws(); + } + + [Theory, RandomData] + internal static void Compare_ReferenceNoDifferences(object data) + { + new Valuer(Tools.Valuer.Options with { IncludeFrameworkHints = false }) + .Compare(data, data) + .Assert() + .IsEmpty(); + } + + [Theory, RandomData] + internal static void Compare_NullableWorks(int? item) + { + item.Assert().IsNotNull(); + item.Tools().Variant().Assert().IsNot(item); + item.Tools().Copy().Assert().Is(item); + + int? none = null; + none.Assert().IsNot(item); + none.Assert().Is(none); + } + + [Theory, RandomData] + internal static void Equals_NoDifferencesTrue( + object data1, + object data2, + [Stub] ICompareHint hint + ) + { + hint.TryToCompare(data1, data2, Arg.Any()) + .SetupReturn(new DifferenceHintResult([])); + + new Valuer(Tools.Valuer.Options with { IncludeFrameworkHints = false, Hints = [hint] }) + .Equals(data1, data2) + .Assert() + .Is(true); + } + + [Theory, RandomData] + internal static void Equals_DifferencesFalse( + object data1, + object data2, + [Stub] ICompareHint hint, + IEnumerable differences + ) + { + hint.TryToCompare(data1, data2, Arg.Any()) + .SetupReturn(new(differences), Times.Once); + + new Valuer(Tools.Valuer.Options with { IncludeFrameworkHints = false, Hints = [hint] }) + .Equals(data1, data2) + .Assert() + .Is(false); + + hint.Assert().Called(); + } + + [Theory, RandomData] + internal static void Compare_InfiniteLoopDetails( + object item1, + object item2, + [Fake] ICompareHint hint + ) + { + hint.TryToCompare(item1, item2, Arg.Any()) + .SetupReturn( + Behavior.Throw() + ); + + new Valuer(Tools.Valuer.Options with { IncludeFrameworkHints = false, Hints = [hint] }) + .Assert(x => x.Compare(item1, item2).ToList()) + .Throws() + .With(e => e.Message) + .Contains(GenericConverter.ExpandName(item1)); + } + + [Theory, RandomData] + internal static void GetHashCode_InfiniteLoopDetails(object item, [Fake] ICompareHint hint) + { + hint.TryToGetHashCode(item, Arg.Any()) + .SetupReturn(Behavior.Throw()); + + new Valuer(Tools.Valuer.Options with { IncludeFrameworkHints = false, Hints = [hint] }) + .Assert(x => x.GetHashCode(item)) + .Throws() + .With(e => e.Message) + .Contains(GenericConverter.ExpandName(item)); + } +} diff --git a/tests/Toolbox.Tests/testsettings.json b/tests/Toolbox.Tests/testsettings.json new file mode 100644 index 00000000..4e996d6f --- /dev/null +++ b/tests/Toolbox.Tests/testsettings.json @@ -0,0 +1,16 @@ +{ + "CreateAndFake": { + "Design": {}, + "Asserter": {}, + "Duplicator": {}, + "Extractor": {}, + "Faker": {}, + "Mutator": {}, + "Randomizer": {}, + "Runner": {}, + "Tester": {}, + "Valuer": { + "IncludeValueHashInComparison": true + } + } +} \ No newline at end of file diff --git a/tests/xUnit.v2.Tests/AutoTesterTests.cs b/tests/xUnit.v2.Tests/AutoTesterTests.cs new file mode 100644 index 00000000..5dd7e9b4 --- /dev/null +++ b/tests/xUnit.v2.Tests/AutoTesterTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class AutoTesterTests() : AutoTester(typeof(DataSample)); diff --git a/tests/xUnit.v2.Tests/AutoTester{T}Tests.cs b/tests/xUnit.v2.Tests/AutoTester{T}Tests.cs new file mode 100644 index 00000000..e58fb6ca --- /dev/null +++ b/tests/xUnit.v2.Tests/AutoTester{T}Tests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class AutoTester_T_Tests() : AutoTester; diff --git a/tests/xUnit.v2.Tests/CapAttributeTests.cs b/tests/xUnit.v2.Tests/CapAttributeTests.cs new file mode 100644 index 00000000..272f0cab --- /dev/null +++ b/tests/xUnit.v2.Tests/CapAttributeTests.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class CapAttributeTests : AutoTester +{ + protected override CapAttribute TestInstance { get; } = new CapAttribute(5, 10); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentOutOfRangeException)], + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CapAttribute))), + ], + }; + + [Fact] + internal static void Clone_BranchesOnMinSet() + { + new CapAttribute(1).Clone().Assert().Is(new CapAttribute(1)); + new CapAttribute(1, 2).Clone().Assert().Is(new CapAttribute(1, 2)); + } +} diff --git a/tests/xUnit.v2.Tests/CopyAttributeTests.cs b/tests/xUnit.v2.Tests/CopyAttributeTests.cs new file mode 100644 index 00000000..0acbdae1 --- /dev/null +++ b/tests/xUnit.v2.Tests/CopyAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class CopyAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CopyAttribute))), + ], + }; +} diff --git a/tests/xUnit.v2.Tests/CreateAndFake.xUnit.v2.Tests.csproj b/tests/xUnit.v2.Tests/CreateAndFake.xUnit.v2.Tests.csproj new file mode 100644 index 00000000..48c6e2eb --- /dev/null +++ b/tests/xUnit.v2.Tests/CreateAndFake.xUnit.v2.Tests.csproj @@ -0,0 +1,30 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + LEGACY + + + + + + + + + + + + + + + + + + diff --git a/tests/xUnit.v2.Tests/FakeAttributeTests.cs b/tests/xUnit.v2.Tests/FakeAttributeTests.cs new file mode 100644 index 00000000..35688e30 --- /dev/null +++ b/tests/xUnit.v2.Tests/FakeAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class FakeAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(FakeAttribute))), + ], + }; +} diff --git a/tests/xUnit.v2.Tests/InjectAttributeTests.cs b/tests/xUnit.v2.Tests/InjectAttributeTests.cs new file mode 100644 index 00000000..e68eddda --- /dev/null +++ b/tests/xUnit.v2.Tests/InjectAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class InjectAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(InjectAttribute))), + ], + }; +} diff --git a/tests/xUnit.v2.Tests/IntegrationTests.cs b/tests/xUnit.v2.Tests/IntegrationTests.cs new file mode 100644 index 00000000..bce0d245 --- /dev/null +++ b/tests/xUnit.v2.Tests/IntegrationTests.cs @@ -0,0 +1,97 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Data; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public static class IntegrationTests +{ + internal static MethodInfo AttributeMethod { get; } = + typeof(IntegrationTests).GetMethod( + nameof(Integration_AllAttributesWork), + BindingFlags.Static | BindingFlags.NonPublic + ); + + public sealed class Wrapper(IRandom gen) + { + public string NextName => gen.NextItem([]); + } + + [Theory, RandomData] + internal static void Integration_UsesParameterAttributes( + [Stub] IRandom gen, + [Inject] Wrapper context, + [Size(2)] string name + ) + { + name.Length.Assert().Is(2); + gen.NextItem(Arg.Any()).SetupReturn(name); + context.NextName.Assert().Is(name); + } + + [Theory, RandomData] + internal static void Integration_SyncParameterCoverage( + string firstName, + CancellationToken canceler, + out int value + ) + { + value = 5; + NameData.Values.Assert().Contains(firstName); + canceler.Assert().Is(CancellationToken.None); + value.Assert().Is(5); + } + + [Theory, RandomData] + internal static void Integration_AllAttributesWork( + [Cap(5)] int intCapMax, + [Copy] int intCopyMax, + [Cap(8, 11)] int intCapRange, + [Cap(5d)] double doubleCapMax, + [Cap(20f, 24f)] float floatCapRange, + [Copy] int intCopyRange, + [Stub] IRandom stubGen, + [Inject] Wrapper stubContext, + [Fake] IRandom fakeGen, + [Inject] Wrapper fakeContext, + [Size(2)] string[] stringSizeSet, + [Size(3, 5)] string[] stringSizeRange, + string stringNone, + [Unique] string stringUnique + ) + { + intCapMax.Assert().GreaterThanOrIs(0).And().LessThan(5); + intCopyMax.Assert().Is(intCapMax); + intCapRange.Assert().GreaterThanOrIs(8).And().LessThanOrIs(11); + doubleCapMax.Assert().GreaterThanOrIs(0d).And().LessThan(5d); + floatCapRange.Assert().GreaterThanOrIs(20f).And().LessThanOrIs(24f); + intCopyRange.Assert().Is(intCapRange); + stubGen.NextBytes(0).Assert().IsNull(); + stubContext.NextName.Assert().IsNull(); + fakeGen.NextBytes(0).Assert().IsNotNull(); + fakeContext.NextName.Assert().IsNotNull(); + stringSizeSet.Assert().HasCount(2); + stringSizeRange.Assert().HasCountMoreOrExactly(3).And().HasCountLessOrExactly(5); + stringNone.Assert().IsNot(stringSizeSet).And().IsNot(stringSizeRange); + stringUnique + .Assert() + .IsNot(stringNone) + .And() + .IsNot(stringSizeSet) + .And() + .IsNot(stringSizeRange); + } + + [Theory, RandomData] + internal static void Issue118_FixesStubTypeRandomData([Stub] Type type) + { + type.Assert().IsNotNull(); + } + + [Theory, RandomData] + internal static void Issue118_FixesStubTypeRandomDataSpecific([Stub] IReflectableType type) + { + type.GetTypeInfo().Assert().Is(typeof(Type)); + } +} diff --git a/tests/xUnit.v2.Tests/RandomDataAttributeTests.cs b/tests/xUnit.v2.Tests/RandomDataAttributeTests.cs new file mode 100644 index 00000000..ebc7cb38 --- /dev/null +++ b/tests/xUnit.v2.Tests/RandomDataAttributeTests.cs @@ -0,0 +1,64 @@ +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class RandomDataAttributeTests : AutoTester +{ + protected override RandomDataAttribute TestInstance { get; } = new() { Trials = 3 }; + + protected override Func OptionConfiguration { get; } = + opt => opt with { InjectionValues = [3, GetGeneratableMethod()] }; + + protected override bool EqualsOverrideUsesFullValueEquality { get; } = false; + + [Fact] + internal static void GetData_UsesTrials() + { + new RandomDataAttribute() { Trials = 0 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(0); + new RandomDataAttribute() { Trials = 1 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(1); + new RandomDataAttribute() { Trials = 2 } + .GetData(GetGeneratableMethod()) + .Assert() + .HasCount(2); + } + + [Theory, RandomData] + internal static void GetData_HandlesException([Fake] MethodInfo method) + { + method.IsGenericMethodDefinition.SetupReturn(Behavior.Throw(Times.Once)); + + using StringWriter writer = new(); + + TextWriter errorConsole = Console.Error; + Console.SetError(writer); + try + { + new RandomDataAttribute().GetData(method).Assert().IsEmpty().Also(method).Called(); + } + finally + { + Console.SetError(errorConsole); + } + } + + private static MethodInfo GetGeneratableMethod() + { + return Tools.Randomizer.Create(opt => + opt with + { + FinalCondition = m => + m is MethodInfo info + && !info.IsGenericMethod + && !info.IsGenericMethodDefinition, + } + ); + } +} diff --git a/tests/xUnit.v2.Tests/SizeAttributeTests.cs b/tests/xUnit.v2.Tests/SizeAttributeTests.cs new file mode 100644 index 00000000..93c342e0 --- /dev/null +++ b/tests/xUnit.v2.Tests/SizeAttributeTests.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class SizeAttributeTests : AutoTester +{ + protected override SizeAttribute TestInstance => + new(Tools.Gen.Next(1, 3), Tools.Gen.Next(3, 5)); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(SizeAttribute))), + ], + }; +} diff --git a/tests/xUnit.v2.Tests/StubAttributeTests.cs b/tests/xUnit.v2.Tests/StubAttributeTests.cs new file mode 100644 index 00000000..34ea54e5 --- /dev/null +++ b/tests/xUnit.v2.Tests/StubAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class StubAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(StubAttribute))), + ], + }; +} diff --git a/tests/xUnit.v2.Tests/UniqueAttributeTests.cs b/tests/xUnit.v2.Tests/UniqueAttributeTests.cs new file mode 100644 index 00000000..17c3913a --- /dev/null +++ b/tests/xUnit.v2.Tests/UniqueAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class UniqueAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(UniqueAttribute))), + ], + }; +} diff --git a/tests/xUnit.v2.Tests/XUnitTests.cs b/tests/xUnit.v2.Tests/XUnitTests.cs new file mode 100644 index 00000000..d5976b95 --- /dev/null +++ b/tests/xUnit.v2.Tests/XUnitTests.cs @@ -0,0 +1,13 @@ +using System.Reflection; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v2.Tests; + +public sealed class XUnitTests : AssemblyTester +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { AllowedTestNamePrefixes = ["Issue118"] }; + + protected override Assembly CodeAssembly { get; } = + Assembly.GetAssembly(typeof(RandomDataAttribute)); +} diff --git a/tests/xUnit.v2.Tests/testsettings.json b/tests/xUnit.v2.Tests/testsettings.json new file mode 100644 index 00000000..feb93701 --- /dev/null +++ b/tests/xUnit.v2.Tests/testsettings.json @@ -0,0 +1,14 @@ +{ + "CreateAndFake": { + "Design": {}, + "Asserter": {}, + "Duplicator": {}, + "Extractor": {}, + "Faker": {}, + "Mutator": {}, + "Randomizer": {}, + "Runner": {}, + "Tester": {}, + "Valuer": {} + } +} diff --git a/tests/xUnit.v3.Tests/AutoTesterTests.cs b/tests/xUnit.v3.Tests/AutoTesterTests.cs new file mode 100644 index 00000000..a9935c43 --- /dev/null +++ b/tests/xUnit.v3.Tests/AutoTesterTests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class AutoTesterTests() : AutoTester(typeof(DataSample)); diff --git a/tests/xUnit.v3.Tests/AutoTester{T}Tests.cs b/tests/xUnit.v3.Tests/AutoTester{T}Tests.cs new file mode 100644 index 00000000..842ee3b3 --- /dev/null +++ b/tests/xUnit.v3.Tests/AutoTester{T}Tests.cs @@ -0,0 +1,5 @@ +using Werecodent.CreateAndFake.Samples.Scenarios; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class AutoTester_T_Tests() : AutoTester; diff --git a/tests/xUnit.v3.Tests/CapAttributeTests.cs b/tests/xUnit.v3.Tests/CapAttributeTests.cs new file mode 100644 index 00000000..e02e5cfd --- /dev/null +++ b/tests/xUnit.v3.Tests/CapAttributeTests.cs @@ -0,0 +1,29 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class CapAttributeTests : AutoTester +{ + protected override CapAttribute TestInstance { get; } = new(5, 10); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + IgnorableExceptions = [typeof(ArgumentOutOfRangeException)], + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CapAttribute))), + ], + }; + + [Fact] + internal static void Clone_BranchesOnMinSet() + { + new CapAttribute(1).Clone().Assert().Is(new CapAttribute(1)); + new CapAttribute(1, 2).Clone().Assert().Is(new CapAttribute(1, 2)); + } +} diff --git a/tests/xUnit.v3.Tests/CopyAttributeTests.cs b/tests/xUnit.v3.Tests/CopyAttributeTests.cs new file mode 100644 index 00000000..2faf80cd --- /dev/null +++ b/tests/xUnit.v3.Tests/CopyAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class CopyAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(CopyAttribute))), + ], + }; +} diff --git a/tests/xUnit.v3.Tests/CreateAndFake.xUnit.v3.Tests.csproj b/tests/xUnit.v3.Tests/CreateAndFake.xUnit.v3.Tests.csproj new file mode 100644 index 00000000..f5b67dbc --- /dev/null +++ b/tests/xUnit.v3.Tests/CreateAndFake.xUnit.v3.Tests.csproj @@ -0,0 +1,30 @@ + + + + net11.0;net10.0;net9.0;net48 + + + + net11.0;net10.0;net9.0 + + + + exe + + + + + + + + + + + + + + + + + + diff --git a/tests/xUnit.v3.Tests/FakeAttributeTests.cs b/tests/xUnit.v3.Tests/FakeAttributeTests.cs new file mode 100644 index 00000000..5641667c --- /dev/null +++ b/tests/xUnit.v3.Tests/FakeAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class FakeAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(FakeAttribute))), + ], + }; +} diff --git a/tests/xUnit.v3.Tests/InjectAttributeTests.cs b/tests/xUnit.v3.Tests/InjectAttributeTests.cs new file mode 100644 index 00000000..9e2c99bb --- /dev/null +++ b/tests/xUnit.v3.Tests/InjectAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class InjectAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(InjectAttribute))), + ], + }; +} diff --git a/tests/xUnit.v3.Tests/IntegrationTests.cs b/tests/xUnit.v3.Tests/IntegrationTests.cs new file mode 100644 index 00000000..c67f64f6 --- /dev/null +++ b/tests/xUnit.v3.Tests/IntegrationTests.cs @@ -0,0 +1,83 @@ +using System.Reflection; +using Werecodent.CreateAndFake.Design.Randomization; +using Werecodent.CreateAndFake.FakerTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public static class IntegrationTests +{ + internal static MethodInfo AttributeMethod { get; } = + typeof(IntegrationTests).GetMethod( + nameof(Integration_AllAttributesWork), + BindingFlags.Static | BindingFlags.NonPublic + ); + + public sealed class Wrapper(IRandom gen) + { + public string NextName => gen.NextItem([]); + } + + [Theory, RandomData] + internal static void Integration_UsesParameterAttributes( + [Stub] IRandom gen, + [Inject] Wrapper context, + [Size(2)] string name + ) + { + name.Length.Assert().Is(2); + gen.NextItem(Arg.Any()).SetupReturn(name); + context.NextName.Assert().Is(name); + } + + [Theory, RandomData] + internal static void Integration_AllAttributesWork( + [Cap(5)] int intCapMax, + [Copy] int intCopyMax, + [Cap(8, 11)] int intCapRange, + [Cap(5d)] double doubleCapMax, + [Cap(20f, 24f)] float floatCapRange, + [Copy] int intCopyRange, + [Stub] IRandom stubGen, + [Inject] Wrapper stubContext, + [Fake] IRandom fakeGen, + [Inject] Wrapper fakeContext, + [Size(2)] string[] stringSizeSet, + [Size(3, 5)] string[] stringSizeRange, + string stringNone, + [Unique] string stringUnique + ) + { + intCapMax.Assert().GreaterThanOrIs(0).And().LessThan(5); + intCopyMax.Assert().Is(intCapMax); + intCapRange.Assert().GreaterThanOrIs(8).And().LessThanOrIs(11); + doubleCapMax.Assert().GreaterThanOrIs(0d).And().LessThan(5d); + floatCapRange.Assert().GreaterThanOrIs(20f).And().LessThanOrIs(24f); + intCopyRange.Assert().Is(intCapRange); + stubGen.NextBytes(0).Assert().IsNull(); + stubContext.NextName.Assert().IsNull(); + fakeGen.NextBytes(0).Assert().IsNotNull(); + fakeContext.NextName.Assert().IsNotNull(); + stringSizeSet.Assert().HasCount(2); + stringSizeRange.Assert().HasCountMoreOrExactly(3).And().HasCountLessOrExactly(5); + stringNone.Assert().IsNot(stringSizeSet).And().IsNot(stringSizeRange); + stringUnique + .Assert() + .IsNot(stringNone) + .And() + .IsNot(stringSizeSet) + .And() + .IsNot(stringSizeRange); + } + + [Theory, RandomData] + internal static void Issue118_FixesStubTypeRandomData([Stub] Type type) + { + type.Assert().IsNotNull(); + } + + [Theory, RandomData] + internal static void Issue118_FixesStubTypeRandomDataSpecific([Stub] IReflectableType type) + { + type.GetTypeInfo().Assert().Is(typeof(Type)); + } +} diff --git a/tests/xUnit.v3.Tests/RandomDataAttributeTests.cs b/tests/xUnit.v3.Tests/RandomDataAttributeTests.cs new file mode 100644 index 00000000..efae2c40 --- /dev/null +++ b/tests/xUnit.v3.Tests/RandomDataAttributeTests.cs @@ -0,0 +1,109 @@ +using System.Reflection; +using Werecodent.CreateAndFake.FakerTool; +using Xunit.Sdk; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +#pragma warning disable RCS1261 // Not available in all .NET versions. + +public static class RandomDataAttributeTests +{ + [Fact] + internal static async Task RandomDataAttribute_GuardsNulls() + { + await using DisposalTracker tracker = new(); + await Tools.Tester.PreventsNullRefExceptionAsync( + new RandomDataAttribute() { Trials = 3 }, + TestContext.Current.CancellationToken, + opt => + opt with + { + InjectionValues = [3, GetGeneratableMethod(), tracker], + OnlyDeclaredMethods = true, + } + ); + } + + [Fact] + internal static async Task RandomDataAttribute_NoParameterMutation() + { + await using DisposalTracker tracker = new(); + await Tools.Tester.PreventsParameterMutationAsync( + new RandomDataAttribute() { Trials = 3 }, + TestContext.Current.CancellationToken, + opt => + opt with + { + InjectionValues = [3, GetGeneratableMethod(), tracker], + MethodsToIgnore = [nameof(RandomDataAttribute.GetData)], + OnlyDeclaredMethods = true, + } + ); + } + + [Fact] + internal static async Task GetData_UsesTrials() + { + (await new RandomDataAttribute() { Trials = 0 }.GetData(GetGeneratableMethod(), null)) + .Assert() + .HasCount(0); + (await new RandomDataAttribute() { Trials = 1 }.GetData(GetGeneratableMethod(), null)) + .Assert() + .HasCount(1); + (await new RandomDataAttribute() { Trials = 2 }.GetData(GetGeneratableMethod(), null)) + .Assert() + .HasCount(2); + } + + [Theory, RandomData] + internal static async Task GetData_HandlesExceptionAndDisposal([Fake] MethodInfo method) + { + method.IsGenericMethodDefinition.SetupReturn(Behavior.Throw(Times.Once)); + + using StringWriter writer = new(); + + TextWriter errorConsole = Console.Error; + Console.SetError(writer); + try + { + _ = await new RandomDataAttribute() + .GetData(method, null) + .Assert() + .ThrowsNoAsync(TestContext.Current.CancellationToken) + .Also(() => method) + .Called(); + + Fake mockDisposable = Tools.Faker.Mock(); + mockDisposable.Setup(f => f.Dispose(), Behavior.Throw(Times.Once)); + + Fake mockAsyncDisposable = Tools.Faker.Mock(); + mockAsyncDisposable.Setup("DisposeAsync", [], Behavior.Throw(Times.Once)); + + await SafeDisposer + .TryTracking( + nameof(GetData_HandlesExceptionAndDisposal), + [mockDisposable.Dummy, mockAsyncDisposable.Dummy] + ) + .DisposeAsync(); + } + finally + { + Console.SetError(errorConsole); + } + } + + private static MethodInfo GetGeneratableMethod() + { + return Tools.Randomizer.Create(opt => + opt with + { + FinalCondition = m => + m is MethodInfo info + && !info.IsGenericMethod + && !info.IsGenericMethodDefinition, + } + ); + } +} + +#pragma warning restore diff --git a/tests/xUnit.v3.Tests/SafeDisposerTests.cs b/tests/xUnit.v3.Tests/SafeDisposerTests.cs new file mode 100644 index 00000000..7e06bb2b --- /dev/null +++ b/tests/xUnit.v3.Tests/SafeDisposerTests.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class SafeDisposerTests() : AutoTester(typeof(SafeDisposer)) +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + DisableParameterMutationTests = true, + DisableToolSetSupportTests = true, + InjectionValues = + [ + new List() + { + Tools.Randomizer.Create(), + Tools.Randomizer.Create(), + }.AsEnumerable(), + ], + }; +} diff --git a/tests/xUnit.v3.Tests/SizeAttributeTests.cs b/tests/xUnit.v3.Tests/SizeAttributeTests.cs new file mode 100644 index 00000000..9777273e --- /dev/null +++ b/tests/xUnit.v3.Tests/SizeAttributeTests.cs @@ -0,0 +1,22 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class SizeAttributeTests : AutoTester +{ + protected override SizeAttribute TestInstance => + new(Tools.Gen.Next(1, 3), Tools.Gen.Next(3, 5)); + + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(SizeAttribute))), + ], + }; +} diff --git a/tests/xUnit.v3.Tests/StubAttributeTests.cs b/tests/xUnit.v3.Tests/StubAttributeTests.cs new file mode 100644 index 00000000..4089f957 --- /dev/null +++ b/tests/xUnit.v3.Tests/StubAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class StubAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(StubAttribute))), + ], + }; +} diff --git a/tests/xUnit.v3.Tests/UniqueAttributeTests.cs b/tests/xUnit.v3.Tests/UniqueAttributeTests.cs new file mode 100644 index 00000000..bf519bbf --- /dev/null +++ b/tests/xUnit.v3.Tests/UniqueAttributeTests.cs @@ -0,0 +1,19 @@ +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class UniqueAttributeTests : AutoTester +{ + protected override Func OptionConfiguration { get; } = + opt => + opt with + { + InjectionValues = + [ + IntegrationTests.AttributeMethod, + IntegrationTests + .AttributeMethod.GetParameters() + .First(p => Attribute.IsDefined(p, typeof(UniqueAttribute))), + ], + }; +} diff --git a/tests/xUnit.v3.Tests/XUnitTests.cs b/tests/xUnit.v3.Tests/XUnitTests.cs new file mode 100644 index 00000000..de8c1f95 --- /dev/null +++ b/tests/xUnit.v3.Tests/XUnitTests.cs @@ -0,0 +1,13 @@ +using System.Reflection; +using Werecodent.CreateAndFake.TesterTool; + +namespace Werecodent.CreateAndFake.xUnit.v3.Tests; + +public sealed class XUnitTests : AssemblyTester +{ + protected override Func OptionConfiguration { get; } = + opt => opt with { AllowedTestNamePrefixes = ["Issue118"] }; + + protected override Assembly CodeAssembly { get; } = + Assembly.GetAssembly(typeof(RandomDataAttribute)); +} diff --git a/tests/xUnit.v3.Tests/testsettings.json b/tests/xUnit.v3.Tests/testsettings.json new file mode 100644 index 00000000..f624980e --- /dev/null +++ b/tests/xUnit.v3.Tests/testsettings.json @@ -0,0 +1,14 @@ +{ + "CreateAndFake": { + "Design": {}, + "Asserter": {}, + "Duplicator": {}, + "Extractor": {}, + "Faker": {}, + "Mutator": {}, + "Randomizer": {}, + "Runner": {}, + "Tester": {}, + "Valuer": {} + } +} \ No newline at end of file