diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..1b50c1aa6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,678 @@ +# Version: 4.1.1 (Using https://semver.org/) +# Updated: 2022-05-23 +# See https://github.com/RehanSaeed/EditorConfig/releases for release notes. +# See https://github.com/RehanSaeed/EditorConfig for updates to this file. +# See http://EditorConfig.org for more information about .editorconfig files. + +########################################## +# Common Settings +########################################## + +# This file is the top-most EditorConfig file +root = true + +# All Files +[*] +charset = utf-8 +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +########################################## +# File Extension Settings +########################################## + +# Visual Studio Solution Files +[*.sln] +indent_style = tab + +# Visual Studio XML Project Files +[*.{csproj,vbproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 2 + +# XML Configuration Files +[*.{xml,config,props,targets,nuspec,resx,ruleset,vsixmanifest,vsct}] +indent_size = 2 + +# JSON Files +[*.{json,json5,webmanifest}] +indent_size = 2 + +# YAML Files +[*.{yml,yaml}] +indent_size = 2 + +# Markdown Files +[*.{md,mdx}] +trim_trailing_whitespace = false + +# Web Files +[*.{htm,html,js,jsm,ts,tsx,cjs,cts,ctsx,mjs,mts,mtsx,css,sass,scss,less,pcss,svg,vue}] +indent_size = 2 + +# Batch Files +[*.{cmd,bat}] +end_of_line = crlf + +# Bash Files +[*.sh] +end_of_line = lf + +# Makefiles +[Makefile] +indent_style = tab + +########################################## +# Default .NET Code Style Severities +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/configuration-options#scope +########################################## + +[*.{cs,csx,cake,vb,vbx}] +# Default Severity for all .NET Code Style rules below +dotnet_analyzer_diagnostic.severity = warning + +########################################## +# Language Rules +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules +########################################## + +# .NET Style Rules +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#net-style-rules +[*.{cs,csx,cake,vb,vbx}] +# "this." and "Me." qualifiers +dotnet_style_qualification_for_field = true:warning +dotnet_style_qualification_for_property = true:warning +dotnet_style_qualification_for_method = true:warning +dotnet_style_qualification_for_event = true:warning +# Language keywords instead of framework type names for type references +dotnet_style_predefined_type_for_locals_parameters_members = true:warning +dotnet_style_predefined_type_for_member_access = true:warning +# Modifier preferences +dotnet_style_require_accessibility_modifiers = always:warning +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:warning +visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:warning +dotnet_style_readonly_field = true:warning +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:warning +# Expression-level preferences +dotnet_style_object_initializer = true:warning +dotnet_style_collection_initializer = true:warning +dotnet_style_explicit_tuple_names = true:warning +dotnet_style_prefer_inferred_tuple_names = true:warning +dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion +dotnet_diagnostic.IDE0045.severity = suggestion +dotnet_style_prefer_conditional_expression_over_return = false:suggestion +dotnet_diagnostic.IDE0046.severity = suggestion +dotnet_style_prefer_compound_assignment = true:warning +dotnet_style_prefer_simplified_interpolation = true:warning +dotnet_style_prefer_simplified_boolean_expressions = true:warning +# Null-checking preferences +dotnet_style_coalesce_expression = true:warning +dotnet_style_null_propagation = true:warning +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +# File header preferences +# file_header_template = \n© PROJECT-AUTHOR\n +# If you use StyleCop, you'll need to disable SA1636: File header copyright text should match. +# dotnet_diagnostic.SA1636.severity = none +# Undocumented +dotnet_style_operator_placement_when_wrapping = end_of_line:warning +csharp_style_prefer_null_check_over_type_check = true:warning + +# C# Style Rules +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#c-style-rules +[*.{cs,csx,cake}] +# 'var' preferences +csharp_style_var_for_built_in_types = true:warning +csharp_style_var_when_type_is_apparent = true:warning +csharp_style_var_elsewhere = true:warning +# Expression-bodied members +csharp_style_expression_bodied_methods = true:warning +csharp_style_expression_bodied_constructors = true:warning +csharp_style_expression_bodied_operators = true:warning +csharp_style_expression_bodied_properties = true:warning +csharp_style_expression_bodied_indexers = true:warning +csharp_style_expression_bodied_accessors = true:warning +csharp_style_expression_bodied_lambdas = true:warning +csharp_style_expression_bodied_local_functions = true:warning +# Pattern matching preferences +csharp_style_pattern_matching_over_is_with_cast_check = true:warning +csharp_style_pattern_matching_over_as_with_null_check = true:warning +csharp_style_prefer_switch_expression = true:warning +csharp_style_prefer_pattern_matching = true:warning +csharp_style_prefer_not_pattern = true:warning +# Expression-level preferences +csharp_style_inlined_variable_declaration = true:warning +csharp_prefer_simple_default_expression = true:warning +csharp_style_pattern_local_over_anonymous_function = true:warning +csharp_style_deconstructed_variable_declaration = true:warning +csharp_style_prefer_index_operator = true:warning +csharp_style_prefer_range_operator = true:warning +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning +# "Null" checking preferences +csharp_style_throw_expression = true:warning +csharp_style_conditional_delegate_call = true:warning +# Code block preferences +csharp_prefer_braces = true:warning +csharp_prefer_simple_using_statement = true:suggestion +dotnet_diagnostic.IDE0063.severity = suggestion +# 'using' directive preferences +csharp_using_directive_placement = inside_namespace:warning +# Modifier preferences +csharp_prefer_static_local_function = true:warning + +########################################## +# Unnecessary Code Rules +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/unnecessary-code-rules +########################################## + +# .NET Unnecessary code rules +[*.{cs,csx,cake,vb,vbx}] +dotnet_code_quality_unused_parameters = all:warning +dotnet_remove_unnecessary_suppression_exclusions = none:warning + +# C# Unnecessary code rules +[*.{cs,csx,cake}] +csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion +dotnet_diagnostic.IDE0058.severity = suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +dotnet_diagnostic.IDE0059.severity = suggestion + +########################################## +# Formatting Rules +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules +########################################## + +# .NET formatting rules +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#net-formatting-rules +[*.{cs,csx,cake,vb,vbx}] +# Organize using directives +dotnet_sort_system_directives_first = true +dotnet_separate_import_directive_groups = false +# Dotnet namespace options +dotnet_style_namespace_match_folder = true:suggestion +dotnet_diagnostic.IDE0130.severity = suggestion + +# C# formatting rules +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#c-formatting-rules +[*.{cs,csx,cake}] +# Newline options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#new-line-options +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true +# Indentation options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#indentation-options +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = no_change +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents_when_block = false +# Spacing options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#spacing-options +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_parentheses = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_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_call_parameter_list_parentheses = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_after_comma = true +csharp_space_before_comma = false +csharp_space_after_dot = false +csharp_space_before_dot = false +csharp_space_after_semicolon_in_for_statement = true +csharp_space_before_semicolon_in_for_statement = false +csharp_space_around_declaration_statements = false +csharp_space_before_open_square_brackets = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_square_brackets = false +# Wrap options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#wrap-options +csharp_preserve_single_line_statements = false +csharp_preserve_single_line_blocks = true +# Namespace options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#namespace-options +csharp_style_namespace_declarations = file_scoped:warning + +########################################## +# .NET Naming Rules +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/naming-rules +########################################## + +[*.{cs,csx,cake,vb,vbx}] + +########################################## +# Styles +########################################## + +# camel_case_style - Define the camelCase style +dotnet_naming_style.camel_case_style.capitalization = camel_case +# pascal_case_style - Define the PascalCase style +dotnet_naming_style.pascal_case_style.capitalization = pascal_case +# first_upper_style - The first character must start with an upper-case character +dotnet_naming_style.first_upper_style.capitalization = first_word_upper +# prefix_interface_with_i_style - Interfaces must be PascalCase and the first character of an interface must be an 'I' +dotnet_naming_style.prefix_interface_with_i_style.capitalization = pascal_case +dotnet_naming_style.prefix_interface_with_i_style.required_prefix = I +# prefix_type_parameters_with_t_style - Generic Type Parameters must be PascalCase and the first character must be a 'T' +dotnet_naming_style.prefix_type_parameters_with_t_style.capitalization = pascal_case +dotnet_naming_style.prefix_type_parameters_with_t_style.required_prefix = T +# disallowed_style - Anything that has this style applied is marked as disallowed +dotnet_naming_style.disallowed_style.capitalization = pascal_case +dotnet_naming_style.disallowed_style.required_prefix = ____RULE_VIOLATION____ +dotnet_naming_style.disallowed_style.required_suffix = ____RULE_VIOLATION____ +# internal_error_style - This style should never occur... if it does, it indicates a bug in file or in the parser using the file +dotnet_naming_style.internal_error_style.capitalization = pascal_case +dotnet_naming_style.internal_error_style.required_prefix = ____INTERNAL_ERROR____ +dotnet_naming_style.internal_error_style.required_suffix = ____INTERNAL_ERROR____ + +########################################## +# .NET Design Guideline Field Naming Rules +# Naming rules for fields follow the .NET Framework design guidelines +# https://docs.microsoft.com/dotnet/standard/design-guidelines/index +########################################## + +# All public/protected/protected_internal constant fields must be PascalCase +# https://docs.microsoft.com/dotnet/standard/design-guidelines/field +dotnet_naming_symbols.public_protected_constant_fields_group.applicable_accessibilities = public, protected, protected_internal +dotnet_naming_symbols.public_protected_constant_fields_group.required_modifiers = const +dotnet_naming_symbols.public_protected_constant_fields_group.applicable_kinds = field +dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.symbols = public_protected_constant_fields_group +dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.style = pascal_case_style +dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.severity = warning + +# All public/protected/protected_internal static readonly fields must be PascalCase +# https://docs.microsoft.com/dotnet/standard/design-guidelines/field +dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_accessibilities = public, protected, protected_internal +dotnet_naming_symbols.public_protected_static_readonly_fields_group.required_modifiers = static, readonly +dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_kinds = field +dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.symbols = public_protected_static_readonly_fields_group +dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style +dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.severity = warning + +# No other public/protected/protected_internal fields are allowed +# https://docs.microsoft.com/dotnet/standard/design-guidelines/field +dotnet_naming_symbols.other_public_protected_fields_group.applicable_accessibilities = public, protected, protected_internal +dotnet_naming_symbols.other_public_protected_fields_group.applicable_kinds = field +dotnet_naming_rule.other_public_protected_fields_disallowed_rule.symbols = other_public_protected_fields_group +dotnet_naming_rule.other_public_protected_fields_disallowed_rule.style = disallowed_style +dotnet_naming_rule.other_public_protected_fields_disallowed_rule.severity = error + +########################################## +# StyleCop Field Naming Rules +# Naming rules for fields follow the StyleCop analyzers +# This does not override any rules using disallowed_style above +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers +########################################## + +# All constant fields must be PascalCase +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1303.md +dotnet_naming_symbols.stylecop_constant_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private +dotnet_naming_symbols.stylecop_constant_fields_group.required_modifiers = const +dotnet_naming_symbols.stylecop_constant_fields_group.applicable_kinds = field +dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.symbols = stylecop_constant_fields_group +dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.style = pascal_case_style +dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.severity = warning + +# All static readonly fields must be PascalCase +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1311.md +dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private +dotnet_naming_symbols.stylecop_static_readonly_fields_group.required_modifiers = static, readonly +dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_kinds = field +dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.symbols = stylecop_static_readonly_fields_group +dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style +dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.severity = warning + +# No non-private instance fields are allowed +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md +dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected +dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_kinds = field +dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.symbols = stylecop_fields_must_be_private_group +dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.style = disallowed_style +dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.severity = error + +# Private fields must be camelCase +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1306.md +dotnet_naming_symbols.stylecop_private_fields_group.applicable_accessibilities = private +dotnet_naming_symbols.stylecop_private_fields_group.applicable_kinds = field +dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.symbols = stylecop_private_fields_group +dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.style = camel_case_style +dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.severity = warning + +# Local variables must be camelCase +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1312.md +dotnet_naming_symbols.stylecop_local_fields_group.applicable_accessibilities = local +dotnet_naming_symbols.stylecop_local_fields_group.applicable_kinds = local +dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.symbols = stylecop_local_fields_group +dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.style = camel_case_style +dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.severity = silent + +# This rule should never fire. However, it's included for at least two purposes: +# First, it helps to understand, reason about, and root-case certain types of issues, such as bugs in .editorconfig parsers. +# Second, it helps to raise immediate awareness if a new field type is added (as occurred recently in C#). +dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_accessibilities = * +dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_kinds = field +dotnet_naming_rule.sanity_check_uncovered_field_case_rule.symbols = sanity_check_uncovered_field_case_group +dotnet_naming_rule.sanity_check_uncovered_field_case_rule.style = internal_error_style +dotnet_naming_rule.sanity_check_uncovered_field_case_rule.severity = error + + +########################################## +# Other Naming Rules +########################################## + +# All of the following must be PascalCase: +# - Namespaces +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-namespaces +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md +# - Classes and Enumerations +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md +# - Delegates +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces#names-of-common-types +# - Constructors, Properties, Events, Methods +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-type-members +dotnet_naming_symbols.element_group.applicable_kinds = namespace, class, enum, struct, delegate, event, method, property +dotnet_naming_rule.element_rule.symbols = element_group +dotnet_naming_rule.element_rule.style = pascal_case_style +dotnet_naming_rule.element_rule.severity = warning + +# Interfaces use PascalCase and are prefixed with uppercase 'I' +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces +dotnet_naming_symbols.interface_group.applicable_kinds = interface +dotnet_naming_rule.interface_rule.symbols = interface_group +dotnet_naming_rule.interface_rule.style = prefix_interface_with_i_style +dotnet_naming_rule.interface_rule.severity = warning + +# Generics Type Parameters use PascalCase and are prefixed with uppercase 'T' +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces +dotnet_naming_symbols.type_parameter_group.applicable_kinds = type_parameter +dotnet_naming_rule.type_parameter_rule.symbols = type_parameter_group +dotnet_naming_rule.type_parameter_rule.style = prefix_type_parameters_with_t_style +dotnet_naming_rule.type_parameter_rule.severity = warning + +# Function parameters use camelCase +# https://docs.microsoft.com/dotnet/standard/design-guidelines/naming-parameters +dotnet_naming_symbols.parameters_group.applicable_kinds = parameter +dotnet_naming_rule.parameters_rule.symbols = parameters_group +dotnet_naming_rule.parameters_rule.style = camel_case_style +dotnet_naming_rule.parameters_rule.severity = warning + +########################################## +# License +########################################## +# The following applies as to the .editorconfig file ONLY, and is +# included below for reference, per the requirements of the license +# corresponding to this .editorconfig file. +# See: https://github.com/RehanSaeed/EditorConfig +# +# MIT License +# +# Copyright (c) 2017-2019 Muhammad Rehan Saeed +# Copyright (c) 2019 Henry Gabryjelski +# +# Permission is hereby granted, free of charge, to any +# person obtaining a copy of this software and associated +# documentation files (the "Software"), to deal in the +# Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, +# sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# OTHER DEALINGS IN THE SOFTWARE. +########################################## + +########################################## +# Custom rules +########################################## +[*.cs] +# See https://github.com/microsoft/component-detection/issues/202 +########################################## +# Provided by StyleCop.Analyzers +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers +########################################## + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1101.md +# Prefix local calls with this +dotnet_diagnostic.SA1101.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1105.md +# Single line comment should begin with a space +dotnet_diagnostic.SA1105.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1008.md +# Opening parenthesis should not be followed by a space. +dotnet_diagnostic.SA1008.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1009.md +# Closing parenthesis should not be followed by a space +dotnet_diagnostic.SA1009.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1011.md +# Closing square bracket should be followed by a space +dotnet_diagnostic.SA1011.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1012.md +# Opening brace should be preceded by a space +dotnet_diagnostic.SA1012.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1013.md +# Closing brace should be preceded by a space +dotnet_diagnostic.SA1013.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1013.md +# Opening brace should be preceded by a space +dotnet_diagnostic.SA1013.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1026.md +# The keyword 'new' should not be followed by a space or a blank line +dotnet_diagnostic.SA1026.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1108.md +# Block statements should not contain embedded comments +dotnet_diagnostic.SA1108.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1114.md +# Parameter list should follow declaration +dotnet_diagnostic.SA1114.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1117.md +# The parameters should all be placed on the same line or each parameter should be placed on its own line +dotnet_diagnostic.SA1117.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1118.md +# The parameter spans multiple lines +dotnet_diagnostic.SA1118.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1135.md +# Using directive for namespace '...' should be qualified +dotnet_diagnostic.SA1135.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1137.md +# Elements should have the same indentation +dotnet_diagnostic.SA1137.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1142.md +# Refer to tuple fields by name +dotnet_diagnostic.SA1142.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1200.md +# Using directive should appear within a namespace declaration +dotnet_diagnostic.SA1200.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1201.md +# A field should not follow a property +dotnet_diagnostic.SA1201.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1202.md +# Constant fields should appear before non-constant fields +dotnet_diagnostic.SA1202.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1203.md +# 'public' members should come before 'private' members +dotnet_diagnostic.SA1203.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1204.md +# Static members should appear before non-static members +dotnet_diagnostic.SA1204.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1208.md +# Using directive for '...' should appear before directive for '...' +dotnet_diagnostic.SA1208.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1210.md +# Using directives should be ordered alphabetically by the namespaces +dotnet_diagnostic.SA1210.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1214.md +# Readonly fields should appear before non-readonly fields +dotnet_diagnostic.SA1214.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1216.md +# Using static directives should be placed at the correct location +dotnet_diagnostic.SA1216.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1316.md +# Tuple element names should use correct casing +dotnet_diagnostic.SA1316.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md +# Field should be private +dotnet_diagnostic.SA1401.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1413.md +# Use trailing comma in multi-line initializers +dotnet_diagnostic.SA1413.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1414.md +# Tuple types in signatures should have element names +dotnet_diagnostic.SA1414.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1500.md +# Braces for multi-line statements should not share line +dotnet_diagnostic.SA1500.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1515.md +# Single-line comment should be preceded by blank line +dotnet_diagnostic.SA1515.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1518.md +# File is required to end with a single newline character +dotnet_diagnostic.SA1518.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1600.md +# Elements should be documented +dotnet_diagnostic.SA1600.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1602.md +# Enumeration items should be documented +dotnet_diagnostic.SA1602.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1604.md +# Element documentation should have summary +dotnet_diagnostic.SA1604.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1611.md +# The documentation for parameter '...' is missing +dotnet_diagnostic.SA1611.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1614.md +# Element parameter documentation should have text +dotnet_diagnostic.SA1614.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1615.md +# Element return value should be documented +dotnet_diagnostic.SA1615.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1616.md +# Element return value documentation should have text +dotnet_diagnostic.SA1616.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1617.md +# Void return value should not be documented +dotnet_diagnostic.SA1617.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1629.md +# Documentation text should end with a period +dotnet_diagnostic.SA1629.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1633.md +# The file header is missing or not located at the top of the file. +dotnet_diagnostic.SA1633.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1642.md +# Constructor summary documentation should begin with standard text +dotnet_diagnostic.SA1642.severity = suggestion + +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1648.md +# inheritdoc should be used with inheriting class +dotnet_diagnostic.SA1648.severity = suggestion + +########################################## +# Provided by Microsoft.VisualStudio.Threading.Analyzers +# https://github.com/Microsoft/vs-threading +########################################## + +# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD002.md +# Synchronously waiting on tasks or awaiters may cause deadlocks. Use await or JoinableTaskFactory.Run instead. +dotnet_diagnostic.VSTHRD002.severity = suggestion + +# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD103.md +# Result synchronously blocks. Use await instead. +dotnet_diagnostic.VSTHRD103.severity = suggestion + +# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD101.md +# Avoid using async lambda for a void returning delegate type, because any exceptions not handled by the delegate will crash the process +dotnet_diagnostic.VSTHRD101.severity = suggestion + +# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD104.md +# Expose an async version of this method that does not synchronously block. Then simplify this method to call that async method within a JoinableTaskFactory.Run delegate. +dotnet_diagnostic.VSTHRD104.severity = suggestion + +# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD111.md +# Add .ConfigureAwait(bool) to your await expression +dotnet_diagnostic.VSTHRD111.severity = suggestion + +# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD200.md +# Use "Async" suffix in names of methods that return an awaitable type +dotnet_diagnostic.VSTHRD200.severity = suggestion + +########################################## +# Provided by Roslyn +# https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/ +########################################## + +# https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0618 +# '...' is obsolete +dotnet_diagnostic.CS0618.severity = suggestion + +# https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1591 +# Missing XML comment for publicly visible type or member '...' +dotnet_diagnostic.CS1591.severity = suggestion diff --git a/.tours/add-a-telemetry-record.tour b/.tours/add-a-telemetry-record.tour deleted file mode 100644 index dca0f2ad5..000000000 --- a/.tours/add-a-telemetry-record.tour +++ /dev/null @@ -1,59 +0,0 @@ -{ - "$schema": "https://aka.ms/codetour-schema", - "title": "Add and using a telemetry record", - "steps": [ - { - "directory": "src/Common/Telemetry/Records", - "description": "Create a new file `MyTelemetryRecord.cs` in `./src/Common/Telemetry/Records/`", - "title": "Creating the file" - }, - { - "file": "src/Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs", - "selection": { - "start": { - "line": 3, - "character": 5 - }, - "end": { - "line": 3, - "character": 11 - } - }, - "description": "Make sure it's a public class.", - "title": "Configuring the class" - }, - { - "file": "src/Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs", - "selection": { - "start": { - "line": 3, - "character": 55 - }, - "end": { - "line": 3, - "character": 86 - } - }, - "description": "Derive `BaseDetectionTelemetryRecord`", - "title": "Inheritance" - }, - { - "file": "src/Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs", - "description": "Every telemetry record must have a unique `RecordName`", - "line": 5, - "title": "Record Name" - }, - { - "file": "src/Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs", - "description": "Add any additional properties you wish your record to track", - "line": 7, - "title": "Setting the properties" - }, - { - "file": "src/Detectors/linux/LinuxScanner.cs", - "description": "Here is an example of how you would use a telemetry record", - "line": 30, - "title": "Using your record" - } - ] -} \ No newline at end of file diff --git a/.tours/getting-started.tour b/.tours/getting-started.tour deleted file mode 100644 index 18170df15..000000000 --- a/.tours/getting-started.tour +++ /dev/null @@ -1,53 +0,0 @@ -{ - "$schema": "https://aka.ms/codetour-schema", - "title": "Getting Started", - "steps": [ - { - "title": "Introduction", - "description": "ComponentDetection is a command line package scanning tool. It produces a graph-based output of all detected components and supports a variety of open source package ecosystems. Let's take a look at how to run it." - }, - { - "file": ".vscode/launch.json", - "description": "These are some the basic arguments necessary for the tool to run. The most important of which are:\n\n* `scan` - the action we want to take\n* `SourceDirectory` - the root directory where we want the recursive scan to start\n\nFor a full breakdown of the arguments available check out [./docs/detector-arguments.md](./docs/detector-arguments.md)\n\nYou can run ComponentDetection with these default arguments using the shortcut `Ctrl`+`Shift`+`B`\n\n[Build](command:workbench.action.tasks.build)", - "line": 15, - "title": "Command Line Arguments" - }, - { - "title": "Concepts", - "description": "At a high level:\n\n* `ComponentDetection` starts from a `SourceDirectory` and iterates recursively through the files and directories\n* A `Detector` can specify a list of patterns which it's interested in\n* If a file name matches a pattern, the file contents are read and sent to the `Detector`\n* A `Detector` is responsible for producing a graph of `Components` as the output from processing a file\n* Once all files have been read and processed, `ComponentDetection` accumulates all of the graphs into a final output manifest" - }, - { - "directory": "src/Detectors", - "description": "There are many detectors, at least 1 for each package ecosystem. Let's take a look at a simple example.", - "title": "Detectors Folder" - }, - { - "file": "src/Detectors/cocoapods/PodComponentDetector.cs", - "description": "Here is an example of a `Detector` for cocoapods components", - "line": 15, - "title": "Detector Class" - }, - { - "file": "src/Detectors/cocoapods/PodComponentDetector.cs", - "description": "These are the file patterns which the `Detector` is interested in", - "line": 21, - "title": "Search Patterns" - }, - { - "file": "src/Detectors/cocoapods/PodComponentDetector.cs", - "description": "Here is where we register a detected `PodComponent` in the output graph for this file.", - "line": 330, - "title": "Registering Components" - }, - { - "directory": "src/Contracts/TypedComponent", - "description": "There are many component types, one for each package ecosystem. That allows us to keep only the information relavant for each ecosystem.", - "title": "TypedComponents Folder" - }, - { - "title": "Wrap Up", - "description": "Run ComponentDetection (remember: `Ctrl`+`Shift`+`B`) and take a look at the final output in `./scan-output/bcde-output.json`." - } - ], - "isPrimary": true -} \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props index 352dc82de..1681b2d4b 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,40 +1,32 @@ - - netcoreapp3.1 - latest - true - true - + + netcoreapp3.1 + latest + true + true + latest + AllEnabledByDefault + true + true + - - Microsoft - Microsoft - Copyright © Microsoft Corporation. All rights reserved. - true - MIT - https://github.com/microsoft/component-detection - https://github.com/microsoft/component-detection.git - git - https://github.com/microsoft/component-detection/releases - + + Microsoft + Microsoft + Copyright © Microsoft Corporation. All rights reserved. + true + MIT + https://github.com/microsoft/component-detection + https://github.com/microsoft/component-detection.git + git + https://github.com/microsoft/component-detection/releases + - - - - - + + + + + - - $(MSBuildThisFileDirectory)analyzers.ruleset - true - NU1608,NU5119 - - - true - - - - - diff --git a/Directory.Packages.props b/Directory.Packages.props index 77f5c7b4e..290927d33 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,17 +9,17 @@ - - + + - - - + + - - - + + + + @@ -29,8 +29,8 @@ - - + + diff --git a/analyzers.ruleset b/analyzers.ruleset deleted file mode 100644 index 5d9637319..000000000 --- a/analyzers.ruleset +++ /dev/null @@ -1,503 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/update-syft.md b/docs/update-syft.md new file mode 100644 index 000000000..8e96ca932 --- /dev/null +++ b/docs/update-syft.md @@ -0,0 +1,51 @@ +# Updating Syft + +For container detection we use [Syft][1]. +Occasionally, as new versions of Syft are released, we need to update the version we use. +To do this: + +1. Ensure you're authenticated to Azure and our Azure Container Registry + + ``` + az login + az acr login --name governancecontainerregistry + ``` + +2. Find the [latest version of Syft][2] +3. Pull the latest container image + + ``` + $ docker pull docker.io/anchore/syft:v{LATEST} + v0.53.4: Pulling from anchore/syft + 0d60d5ab2113: Pull complete + 26136f3e3dd3: Pull complete + 497aa7f04842: Pull complete + Digest: sha256:37e85e8efdeaabb1b6f65c5bc175b664cb05d1aaddd0d922130b8e25d6e49726 + Status: Downloaded newer image for anchore/syft:v{LATEST} + docker.io/anchore/syft:v{LATEST} + ``` + +4. Retag the container image + + ``` + $ docker tag docker.io/anchore/syft:v{LATEST} governancecontainerregistry.azurecr.io/syft:v{LATEST} + ``` + +5. Push the new image to the registry + + ``` + $ docker push governancecontainerregistry.azurecr.io/syft:v{LATEST} + The push refers to repository [governancecontainerregistry.azurecr.io/syft] + 9c858c120b14: Pushed + 840f3b941d62: Pushed + 21ce82bb7448: Pushed + v{LATEST: digest: sha256:04ed9c717a814fdccf52758b67333632a0ff16840fc393f5fba5864285eaebbe size: 945 + ``` + +6. Update the container reference in [`LinuxScanner`][3] +7. Update [the models][4] that map the Syft output + +[1]: https://github.com/anchore/syft +[2]: https://github.com/anchore/syft/releases/latest +[3]: https://github.com/microsoft/component-detection/blob/aaf865e38112fb2448f5866ab06d5898358403f6/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs#L20 +[4]: https://github.com/microsoft/component-detection/blob/main/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs diff --git a/src/Microsoft.ComponentDetection.Common/AsyncExecution.cs b/src/Microsoft.ComponentDetection.Common/AsyncExecution.cs index f72b85da5..3284f19f2 100644 --- a/src/Microsoft.ComponentDetection.Common/AsyncExecution.cs +++ b/src/Microsoft.ComponentDetection.Common/AsyncExecution.cs @@ -13,9 +13,9 @@ public static async Task ExecuteWithTimeoutAsync(Func> toExecute, throw new ArgumentNullException(nameof(toExecute)); } - Task work = Task.Run(toExecute); + var work = Task.Run(toExecute); - bool completedInTime = await Task.Run(() => work.Wait(timeout)); + var completedInTime = await Task.Run(() => work.Wait(timeout)); if (!completedInTime) { throw new TimeoutException($"The execution did not complete in the alotted time ({timeout.TotalSeconds} seconds) and has been terminated prior to completion"); @@ -31,8 +31,8 @@ public static async Task ExecuteVoidWithTimeoutAsync(Action toExecute, TimeSpan throw new ArgumentNullException(nameof(toExecute)); } - Task work = Task.Run(toExecute); - bool completedInTime = await Task.Run(() => work.Wait(timeout)); + var work = Task.Run(toExecute); + var completedInTime = await Task.Run(() => work.Wait(timeout)); if (!completedInTime) { throw new TimeoutException($"The execution did not complete in the alotted time ({timeout.TotalSeconds} seconds) and has been terminated prior to completion"); diff --git a/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs b/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs index 59646e790..b937f3aa5 100644 --- a/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs +++ b/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs @@ -22,7 +22,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable additionalCandidateCommands = additionalCandidateCommands ?? Enumerable.Empty(); parameters = parameters ?? new string[0]; var allCommands = new[] { command }.Concat(additionalCandidateCommands); - if (!commandLocatableCache.TryGetValue(command, out string validCommand)) + if (!this.commandLocatableCache.TryGetValue(command, out var validCommand)) { foreach (var commandToTry in allCommands) { @@ -36,7 +36,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable if (result.ExitCode == 0) { - commandLocatableCache[command] = validCommand = commandToTry; + this.commandLocatableCache[command] = validCommand = commandToTry; break; } } @@ -53,7 +53,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable public async Task ExecuteCommand(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters) { - var isCommandLocatable = await CanCommandBeLocated(command, additionalCandidateCommands); + var isCommandLocatable = await this.CanCommandBeLocated(command, additionalCandidateCommands); if (!isCommandLocatable) { throw new InvalidOperationException( @@ -68,7 +68,7 @@ public async Task ExecuteCommand(string command, IEn using var record = new CommandLineInvocationTelemetryRecord(); - var pathToRun = commandLocatableCache[command]; + var pathToRun = this.commandLocatableCache[command]; var joinedParameters = string.Join(" ", parameters); try { @@ -119,8 +119,8 @@ private static Task RunProcessAsync(string fileName, process.StartInfo.WorkingDirectory = workingDirectory.FullName; } - string errorText = string.Empty; - string stdOutText = string.Empty; + var errorText = string.Empty; + var stdOutText = string.Empty; var t1 = new Task(() => { @@ -147,12 +147,12 @@ private static Task RunProcessAsync(string fileName, public async Task CanCommandBeLocated(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters) { - return await CanCommandBeLocated(command, additionalCandidateCommands, workingDirectory: null, parameters); + return await this.CanCommandBeLocated(command, additionalCandidateCommands, workingDirectory: null, parameters); } public async Task ExecuteCommand(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters) { - return await ExecuteCommand(command, additionalCandidateCommands, workingDirectory: null, parameters); + return await this.ExecuteCommand(command, additionalCandidateCommands, workingDirectory: null, parameters); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs index d2009f071..82818660b 100644 --- a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs +++ b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs @@ -14,21 +14,21 @@ public class ComponentStreamEnumerable : IEnumerable public ComponentStreamEnumerable(IEnumerable fileEnumerable, ILogger logger) { - ToEnumerate = fileEnumerable; - Logger = logger; + this.ToEnumerate = fileEnumerable; + this.Logger = logger; } public IEnumerator GetEnumerator() { - foreach (var filePairing in ToEnumerate) + foreach (var filePairing in this.ToEnumerate) { if (!filePairing.File.Exists) { - Logger.LogWarning($"File {filePairing.File.FullName} does not exist on disk."); + this.Logger.LogWarning($"File {filePairing.File.FullName} does not exist on disk."); yield break; } - using var stream = SafeOpenFile(filePairing.File); + using var stream = this.SafeOpenFile(filePairing.File); if (stream == null) { @@ -41,7 +41,7 @@ public IEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator(); + return this.GetEnumerator(); } private Stream SafeOpenFile(FileInfo file) @@ -52,13 +52,13 @@ private Stream SafeOpenFile(FileInfo file) } catch (UnauthorizedAccessException) { - Logger.LogWarning($"Unauthorized access exception caught when trying to open {file.FullName}"); + this.Logger.LogWarning($"Unauthorized access exception caught when trying to open {file.FullName}"); return null; } catch (Exception e) { - Logger.LogWarning($"Unhandled exception caught when trying to open {file.FullName}"); - Logger.LogException(e, isError: false); + this.Logger.LogWarning($"Unhandled exception caught when trying to open {file.FullName}"); + this.Logger.LogException(e, isError: false); return null; } } diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs index 9f415a0e5..f97bcfefb 100644 --- a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs +++ b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs @@ -18,14 +18,14 @@ public class ComponentStreamEnumerableFactory : IComponentStreamEnumerableFactor public IEnumerable GetComponentStreams(DirectoryInfo directory, IEnumerable searchPatterns, ExcludeDirectoryPredicate directoryExclusionPredicate, bool recursivelyScanDirectories = true) { - SafeFileEnumerable enumerable = new SafeFileEnumerable(directory, searchPatterns, Logger, PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories); - return new ComponentStreamEnumerable(enumerable, Logger); + var enumerable = new SafeFileEnumerable(directory, searchPatterns, this.Logger, this.PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories); + return new ComponentStreamEnumerable(enumerable, this.Logger); } public IEnumerable GetComponentStreams(DirectoryInfo directory, Func fileMatchingPredicate, ExcludeDirectoryPredicate directoryExclusionPredicate, bool recursivelyScanDirectories = true) { - SafeFileEnumerable enumerable = new SafeFileEnumerable(directory, fileMatchingPredicate, Logger, PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories); - return new ComponentStreamEnumerable(enumerable, Logger); + var enumerable = new SafeFileEnumerable(directory, fileMatchingPredicate, this.Logger, this.PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories); + return new ComponentStreamEnumerable(enumerable, this.Logger); } } } diff --git a/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs b/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs index 3813aa4fd..5346f9487 100644 --- a/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs +++ b/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs @@ -28,18 +28,18 @@ public ComponentRecorder(ILogger log = null, bool enableManualTrackingOfExplicit public TypedComponent GetComponent(string componentId) { - return singleFileRecorders.Select(x => x.GetComponent(componentId)?.Component).Where(x => x != null).FirstOrDefault(); + return this.singleFileRecorders.Select(x => x.GetComponent(componentId)?.Component).Where(x => x != null).FirstOrDefault(); } public IEnumerable GetDetectedComponents() { IEnumerable detectedComponents; - if (singleFileRecorders == null) + if (this.singleFileRecorders == null) { return Enumerable.Empty(); } - detectedComponents = singleFileRecorders + detectedComponents = this.singleFileRecorders .Select(singleFileRecorder => singleFileRecorder.GetDetectedComponents().Values) .SelectMany(x => x) .GroupBy(x => x.Component.Id) @@ -69,11 +69,11 @@ public ISingleFileComponentRecorder CreateSingleFileComponentRecorder(string loc throw new ArgumentNullException(nameof(location)); } - var matching = singleFileRecorders.FirstOrDefault(x => x.ManifestFileLocation == location); + var matching = this.singleFileRecorders.FirstOrDefault(x => x.ManifestFileLocation == location); if (matching == null) { - matching = new SingleFileComponentRecorder(location, this, enableManualTrackingOfExplicitReferences, log); - singleFileRecorders.Add(matching); + matching = new SingleFileComponentRecorder(location, this, this.enableManualTrackingOfExplicitReferences, this.log); + this.singleFileRecorders.Add(matching); } return matching; @@ -81,12 +81,12 @@ public ISingleFileComponentRecorder CreateSingleFileComponentRecorder(string loc internal DependencyGraph GetDependencyGraphForLocation(string location) { - return singleFileRecorders.Single(x => x.ManifestFileLocation == location).DependencyGraph; + return this.singleFileRecorders.Single(x => x.ManifestFileLocation == location).DependencyGraph; } public IReadOnlyDictionary GetDependencyGraphsByLocation() { - return singleFileRecorders.Where(x => x.DependencyGraph.HasComponents()) + return this.singleFileRecorders.Where(x => x.DependencyGraph.HasComponents()) .ToImmutableDictionary(x => x.ManifestFileLocation, x => x.DependencyGraph as IDependencyGraph); } @@ -98,7 +98,7 @@ public class SingleFileComponentRecorder : ISingleFileComponentRecorder internal DependencyGraph DependencyGraph { get; } - IDependencyGraph ISingleFileComponentRecorder.DependencyGraph => DependencyGraph; + IDependencyGraph ISingleFileComponentRecorder.DependencyGraph => this.DependencyGraph; private readonly ConcurrentDictionary detectedComponentsInternal = new ConcurrentDictionary(); @@ -108,15 +108,15 @@ public class SingleFileComponentRecorder : ISingleFileComponentRecorder public SingleFileComponentRecorder(string location, ComponentRecorder recorder, bool enableManualTrackingOfExplicitReferences, ILogger log) { - ManifestFileLocation = location; + this.ManifestFileLocation = location; this.recorder = recorder; this.log = log; - DependencyGraph = new DependencyGraph(enableManualTrackingOfExplicitReferences); + this.DependencyGraph = new DependencyGraph(enableManualTrackingOfExplicitReferences); } public DetectedComponent GetComponent(string componentId) { - if (detectedComponentsInternal.TryGetValue(componentId, out var detectedComponent)) + if (this.detectedComponentsInternal.TryGetValue(componentId, out var detectedComponent)) { return detectedComponent; } @@ -127,7 +127,7 @@ public DetectedComponent GetComponent(string componentId) public IReadOnlyDictionary GetDetectedComponents() { // Should this be immutable? - return detectedComponentsInternal; + return this.detectedComponentsInternal; } public void RegisterUsage( @@ -150,42 +150,42 @@ public void RegisterUsage( #if DEBUG if (detectedComponent.FilePaths?.Any() ?? false) { - log?.LogWarning("Detector should not populate DetectedComponent.FilePaths!"); + this.log?.LogWarning("Detector should not populate DetectedComponent.FilePaths!"); } if (detectedComponent.DependencyRoots?.Any() ?? false) { - log?.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!"); + this.log?.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!"); } if (detectedComponent.DevelopmentDependency.HasValue) { - log?.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!"); + this.log?.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!"); } #endif - string componentId = detectedComponent.Component.Id; + var componentId = detectedComponent.Component.Id; DetectedComponent storedComponent = null; - lock (registerUsageLock) + lock (this.registerUsageLock) { - storedComponent = detectedComponentsInternal.GetOrAdd(componentId, detectedComponent); - AddComponentToGraph(ManifestFileLocation, detectedComponent, isExplicitReferencedDependency, parentComponentId, isDevelopmentDependency, dependencyScope); + storedComponent = this.detectedComponentsInternal.GetOrAdd(componentId, detectedComponent); + this.AddComponentToGraph(this.ManifestFileLocation, detectedComponent, isExplicitReferencedDependency, parentComponentId, isDevelopmentDependency, dependencyScope); } } public void AddAdditionalRelatedFile(string relatedFilePath) { - DependencyGraph.AddAdditionalRelatedFile(relatedFilePath); + this.DependencyGraph.AddAdditionalRelatedFile(relatedFilePath); } public IList GetAdditionalRelatedFiles() { - return DependencyGraph.GetAdditionalRelatedFiles().ToImmutableList(); + return this.DependencyGraph.GetAdditionalRelatedFiles().ToImmutableList(); } public IComponentRecorder GetParentComponentRecorder() { - return recorder; + return this.recorder; } private void AddComponentToGraph( @@ -204,7 +204,7 @@ private void AddComponentToGraph( DependencyScope = dependencyScope, }; - DependencyGraph.AddComponent(componentNode, parentComponentId); + this.DependencyGraph.AddComponent(componentNode, parentComponentId); } } } diff --git a/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs b/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs index b7360c05d..0d4175a36 100644 --- a/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs +++ b/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs @@ -21,7 +21,7 @@ internal class DependencyGraph : IDependencyGraph public DependencyGraph(bool enableManualTrackingOfExplicitReferences) { - componentNodes = new ConcurrentDictionary(); + this.componentNodes = new ConcurrentDictionary(); this.enableManualTrackingOfExplicitReferences = enableManualTrackingOfExplicitReferences; } @@ -37,7 +37,7 @@ public void AddComponent(ComponentRefNode componentNode, string parentComponentI throw new ArgumentNullException(nameof(componentNode.Id)); } - componentNodes.AddOrUpdate(componentNode.Id, componentNode, (key, currentNode) => + this.componentNodes.AddOrUpdate(componentNode.Id, componentNode, (key, currentNode) => { currentNode.IsExplicitReferencedDependency |= componentNode.IsExplicitReferencedDependency; @@ -55,17 +55,17 @@ public void AddComponent(ComponentRefNode componentNode, string parentComponentI return currentNode; }); - AddDependency(componentNode.Id, parentComponentId); + this.AddDependency(componentNode.Id, parentComponentId); } public bool Contains(string componentId) { - return componentNodes.ContainsKey(componentId); + return this.componentNodes.ContainsKey(componentId); } public ICollection GetDependenciesForComponent(string componentId) { - return componentNodes[componentId].DependencyIds; + return this.componentNodes[componentId].DependencyIds; } public ICollection GetExplicitReferencedDependencyIds(string componentId) @@ -75,53 +75,53 @@ public ICollection GetExplicitReferencedDependencyIds(string componentId throw new ArgumentNullException(nameof(componentId)); } - if (!componentNodes.TryGetValue(componentId, out var componentRef)) + if (!this.componentNodes.TryGetValue(componentId, out var componentRef)) { throw new ArgumentException(string.Format(Resources.MissingNodeInDependencyGraph, componentId), paramName: nameof(componentId)); } IList explicitReferencedDependencyIds = new List(); - GetExplicitReferencedDependencies(componentRef, explicitReferencedDependencyIds, new HashSet()); + this.GetExplicitReferencedDependencies(componentRef, explicitReferencedDependencyIds, new HashSet()); return explicitReferencedDependencyIds; } public void AddAdditionalRelatedFile(string additionalRelatedFile) { - AdditionalRelatedFiles.AddOrUpdate(additionalRelatedFile, 0, (notUsed, notUsed2) => 0); + this.AdditionalRelatedFiles.AddOrUpdate(additionalRelatedFile, 0, (notUsed, notUsed2) => 0); } public HashSet GetAdditionalRelatedFiles() { - return AdditionalRelatedFiles.Keys.ToImmutableHashSet().ToHashSet(); + return this.AdditionalRelatedFiles.Keys.ToImmutableHashSet().ToHashSet(); } public bool HasComponents() { - return componentNodes.Count > 0; + return this.componentNodes.Count > 0; } public bool? IsDevelopmentDependency(string componentId) { - return componentNodes[componentId].IsDevelopmentDependency; + return this.componentNodes[componentId].IsDevelopmentDependency; } public DependencyScope? GetDependencyScope(string componentId) { - return componentNodes[componentId].DependencyScope; + return this.componentNodes[componentId].DependencyScope; } public IEnumerable GetAllExplicitlyReferencedComponents() { - return componentNodes.Values - .Where(componentRefNode => IsExplicitReferencedDependency(componentRefNode)) + return this.componentNodes.Values + .Where(componentRefNode => this.IsExplicitReferencedDependency(componentRefNode)) .Select(componentRefNode => componentRefNode.Id); } private void GetExplicitReferencedDependencies(ComponentRefNode component, IList explicitReferencedDependencyIds, ISet visited) { - if (IsExplicitReferencedDependency(component)) + if (this.IsExplicitReferencedDependency(component)) { explicitReferencedDependencyIds.Add(component.Id); } @@ -132,15 +132,15 @@ private void GetExplicitReferencedDependencies(ComponentRefNode component, IList { if (!visited.Contains(parentId)) { - GetExplicitReferencedDependencies(componentNodes[parentId], explicitReferencedDependencyIds, visited); + this.GetExplicitReferencedDependencies(this.componentNodes[parentId], explicitReferencedDependencyIds, visited); } } } private bool IsExplicitReferencedDependency(ComponentRefNode component) { - return (enableManualTrackingOfExplicitReferences && component.IsExplicitReferencedDependency) || - (!enableManualTrackingOfExplicitReferences && !component.DependedOnByIds.Any()); + return (this.enableManualTrackingOfExplicitReferences && component.IsExplicitReferencedDependency) || + (!this.enableManualTrackingOfExplicitReferences && !component.DependedOnByIds.Any()); } private void AddDependency(string componentId, string parentComponentId) @@ -150,28 +150,28 @@ private void AddDependency(string componentId, string parentComponentId) return; } - if (!componentNodes.TryGetValue(parentComponentId, out var parentComponentRefNode)) + if (!this.componentNodes.TryGetValue(parentComponentId, out var parentComponentRefNode)) { throw new ArgumentException(string.Format(Resources.MissingNodeInDependencyGraph, parentComponentId), nameof(parentComponentId)); } parentComponentRefNode.DependencyIds.Add(componentId); - componentNodes[componentId].DependedOnByIds.Add(parentComponentId); + this.componentNodes[componentId].DependedOnByIds.Add(parentComponentId); } IEnumerable IDependencyGraph.GetDependenciesForComponent(string componentId) { - return GetDependenciesForComponent(componentId).ToImmutableList(); + return this.GetDependenciesForComponent(componentId).ToImmutableList(); } IEnumerable IDependencyGraph.GetComponents() { - return componentNodes.Keys.ToImmutableList(); + return this.componentNodes.Keys.ToImmutableList(); } bool IDependencyGraph.IsComponentExplicitlyReferenced(string componentId) { - return IsExplicitReferencedDependency(componentNodes[componentId]); + return this.IsExplicitReferencedDependency(this.componentNodes[componentId]); } internal class ComponentRefNode @@ -190,8 +190,8 @@ internal class ComponentRefNode internal ComponentRefNode() { - DependencyIds = new HashSet(); - DependedOnByIds = new HashSet(); + this.DependencyIds = new HashSet(); + this.DependedOnByIds = new HashSet(); } } } diff --git a/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs b/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs index ddd7413df..37e182f03 100644 --- a/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs +++ b/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs @@ -1,13 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.ComponentDetection.Contracts.BcdeModels; namespace Microsoft.ComponentDetection.Common { /// - /// Merges dependnecy Scope in their order of Priority. - /// Higher priority scope, as indicated by its lower enum value is given precendence. + /// Merges dependnecy Scope in their order of Priority. + /// Higher priority scope, as indicated by its lower enum value is given precendence. /// public class DependencyScopeComparer { diff --git a/src/Microsoft.ComponentDetection.Common/DockerReference/DigestUtility.cs b/src/Microsoft.ComponentDetection.Common/DockerReference/DigestUtility.cs index c01fc8fda..c7c64e240 100644 --- a/src/Microsoft.ComponentDetection.Common/DockerReference/DigestUtility.cs +++ b/src/Microsoft.ComponentDetection.Common/DockerReference/DigestUtility.cs @@ -26,7 +26,7 @@ public static bool CheckDigest(string digest, bool throwError = true) return false; } - string algorithm = digest.Substring(0, indexOfColon); + var algorithm = digest.Substring(0, indexOfColon); if (!AlgorithmsSizes.ContainsKey(algorithm)) { diff --git a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceException.cs b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceException.cs index 5ed79c7e0..0535090c1 100644 --- a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceException.cs +++ b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceException.cs @@ -16,7 +16,7 @@ public class ReferenceInvalidFormatException : DockerReferenceException { private const string ErrorMessage = "invalid reference format"; - public ReferenceInvalidFormatException(string reference) + public ReferenceInvalidFormatException(string reference) : base(reference, ErrorMessage) { } @@ -117,4 +117,4 @@ public InvalidDigestLengthError(string reference) { } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceUtility.cs b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceUtility.cs index 023db51ca..140d1197f 100644 --- a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceUtility.cs +++ b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceUtility.cs @@ -1,7 +1,4 @@ using Microsoft.ComponentDetection.Contracts; -using System; -using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; // transcribed from https://github.com/containers/image/blob/c1a5f92d0ebbf9e0bf187b3353dd400472b388eb/docker/reference/reference.go @@ -42,7 +39,7 @@ public class DockerReferenceUtility public static DockerReference ParseQualifiedName(string qualifiedName) { - Regex regexp = DockerRegex.ReferenceRegexp; + var regexp = DockerRegex.ReferenceRegexp; if (!regexp.IsMatch(qualifiedName)) { if (string.IsNullOrWhiteSpace(qualifiedName)) @@ -66,8 +63,8 @@ public static DockerReference ParseQualifiedName(string qualifiedName) throw new ReferenceNameTooLongException(name); } - Reference reference = new Reference(); - + var reference = new Reference(); + var nameMatch = DockerRegex.AnchoredNameRegexp.Match(name).Groups; if (nameMatch.Count == 3) { @@ -96,7 +93,7 @@ public static (string, string) SplitDockerDomain(string name) string domain; string reminder; - int indexOfSlash = name.IndexOf('/'); + var indexOfSlash = name.IndexOf('/'); if (indexOfSlash == -1 || !( name.LastIndexOf('.', indexOfSlash) != -1 || name.LastIndexOf(':', indexOfSlash) != -1 || @@ -116,7 +113,7 @@ public static (string, string) SplitDockerDomain(string name) domain = DEFAULTDOMAIN; } - if (domain == DEFAULTDOMAIN && reminder.IndexOf('/') != -1) + if (domain == DEFAULTDOMAIN && reminder.IndexOf('/') == -1) { reminder = $"{OFFICIALREPOSITORYNAME}/{reminder}"; } @@ -131,10 +128,10 @@ public static DockerReference ParseFamiliarName(string name) throw new ReferenceNameNotCanonicalException(name); } - (string domain, string remainder) = SplitDockerDomain(name); + (var domain, var remainder) = SplitDockerDomain(name); string remoteName; - int tagSeparatorIndex = remainder.IndexOf(':'); + var tagSeparatorIndex = remainder.IndexOf(':'); if (tagSeparatorIndex > -1) { remoteName = remainder.Substring(0, tagSeparatorIndex); @@ -169,59 +166,7 @@ public static DockerReference ParseAll(string name) private static DockerReference CreateDockerReference(Reference options) { - if (!string.IsNullOrEmpty(options.Repository) && string.IsNullOrEmpty(options.Domain)) - { - if (!string.IsNullOrEmpty(options.Digest)) - { - return new DigestReference - { - Digest = options.Digest, - }; - } - else - { - throw new ReferenceNameEmptyException(string.Empty); - } - } - else if (string.IsNullOrEmpty(options.Tag)) - { - if (string.IsNullOrEmpty(options.Digest)) - { - return new CanonicalReference - { - Domain = options.Domain, - Repository = options.Repository, - Digest = options.Digest, - }; - } - else - { - return new RepositoryReference - { - Domain = options.Domain, - Repository = options.Repository, - }; - } - } - else if (string.IsNullOrEmpty(options.Digest)) - { - return new TaggedReference - { - Domain = options.Domain, - Repository = options.Repository, - Tag = options.Tag, - }; - } - else - { - return new DualReference - { - Domain = options.Domain, - Repository = options.Repository, - Tag = options.Tag, - Digest = options.Digest, - }; - } + return DockerReference.CreateDockerReference(options.Repository, options.Domain, options.Digest, options.Tag); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerRegex.cs b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerRegex.cs index 780460668..1d51c6251 100644 --- a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerRegex.cs +++ b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerRegex.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; @@ -71,10 +69,10 @@ public static Regex Capture(params Regex[] regexps) DomainComponentRegexp, Optional( Repeated( - new Regex(@"\."), + new Regex(@"\."), DomainComponentRegexp)), Optional( - new Regex(":"), + new Regex(":"), new Regex("[0-9]+"))); public static Regex AnchoredDigestRegexp = Anchored(DigestRegexp); @@ -107,4 +105,4 @@ public static Regex Capture(params Regex[] regexps) public static Regex AnchoredIdentifierRegexp = Anchored(IdentifierRegexp); } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/DockerService.cs b/src/Microsoft.ComponentDetection.Common/DockerService.cs index e1bef86db..20c1606f8 100644 --- a/src/Microsoft.ComponentDetection.Common/DockerService.cs +++ b/src/Microsoft.ComponentDetection.Common/DockerService.cs @@ -37,7 +37,7 @@ public async Task CanPingDockerAsync(CancellationToken cancellationToken = } catch (Exception e) { - Logger.LogException(e, false); + this.Logger.LogException(e, false); return false; } } @@ -45,7 +45,7 @@ public async Task CanPingDockerAsync(CancellationToken cancellationToken = public async Task CanRunLinuxContainersAsync(CancellationToken cancellationToken = default) { using var record = new DockerServiceSystemInfoTelemetryRecord(); - if (!await CanPingDockerAsync(cancellationToken)) + if (!await this.CanPingDockerAsync(cancellationToken)) { return false; } @@ -78,7 +78,7 @@ public async Task ImageExistsLocallyAsync(string image, CancellationToken } catch (Exception e) { - record.ExceptionMessage = e.Message; + record.ExceptionMessage = e.Message; return false; } } @@ -120,7 +120,7 @@ public async Task InspectImageAsync(string image, Cancellation { var imageInspectResponse = await Client.Images.InspectImageAsync(image, cancellationToken); record.ImageInspectResponse = JsonConvert.SerializeObject(imageInspectResponse); - + var baseImageRef = string.Empty; var baseImageDigest = string.Empty; @@ -128,12 +128,12 @@ public async Task InspectImageAsync(string image, Cancellation imageInspectResponse.Config.Labels?.TryGetValue(BaseImageDigestAnnotation, out baseImageDigest); record.BaseImageRef = baseImageRef; - record.BaseImageDigest = baseImageDigest; + record.BaseImageDigest = baseImageDigest; var layers = imageInspectResponse.RootFS?.Layers - .Select((diffId, index) => + .Select((diffId, index) => new DockerLayer - { + { DiffId = diffId, LayerIndex = index, }); @@ -165,7 +165,7 @@ public async Task InspectImageAsync(string image, Cancellation Image = image, Command = JsonConvert.SerializeObject(command), }; - await TryPullImageAsync(image, cancellationToken); + await this.TryPullImageAsync(image, cancellationToken); var container = await CreateContainerAsync(image, command, cancellationToken); record.Container = JsonConvert.SerializeObject(container); var stream = await AttachContainerAsync(container.ID, cancellationToken); diff --git a/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs b/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs index 223e7942b..4b05e5fe9 100644 --- a/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs +++ b/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs @@ -10,7 +10,7 @@ public class EnvironmentVariableService : IEnvironmentVariableService { public bool DoesEnvironmentVariableExist(string name) { - return GetEnvironmentVariable(name) != null; + return this.GetEnvironmentVariable(name) != null; } public string GetEnvironmentVariable(string name) @@ -27,7 +27,7 @@ public string GetEnvironmentVariable(string name) public bool IsEnvironmentVariableValueTrue(string name) { - _ = bool.TryParse(GetEnvironmentVariable(name), out bool result); + _ = bool.TryParse(this.GetEnvironmentVariable(name), out var result); return result; } } diff --git a/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs b/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs index 8ce3c554a..d7e9dacdb 100644 --- a/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs +++ b/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs @@ -34,7 +34,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu { if (!root.Exists) { - Logger?.LogError($"Root directory doesn't exist: {root.FullName}"); + this.Logger?.LogError($"Root directory doesn't exist: {root.FullName}"); s.OnCompleted(); return Task.CompletedTask; } @@ -52,7 +52,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu var sw = Stopwatch.StartNew(); - Logger?.LogInfo($"Starting enumeration of {root.FullName}"); + this.Logger?.LogInfo($"Starting enumeration of {root.FullName}"); var fileCount = 0; var directoryCount = 0; @@ -73,7 +73,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu if (di.Attributes.HasFlag(FileAttributes.ReparsePoint)) { - var realPath = PathUtilityService.ResolvePhysicalPath(di.FullName); + var realPath = this.PathUtilityService.ResolvePhysicalPath(di.FullName); realDirectory = new DirectoryInfo(realPath); } @@ -91,7 +91,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu return true; }); - var initialIterator = new FileSystemEnumerable(root.FullName, Transform, new EnumerationOptions() + var initialIterator = new FileSystemEnumerable(root.FullName, this.Transform, new EnumerationOptions() { RecurseSubdirectories = false, IgnoreInaccessible = true, @@ -145,7 +145,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu var scan = new ActionBlock( di => { - var enumerator = new FileSystemEnumerable(di.FullName, Transform, new EnumerationOptions() + var enumerator = new FileSystemEnumerable(di.FullName, this.Transform, new EnumerationOptions() { RecurseSubdirectories = true, IgnoreInaccessible = true, @@ -188,7 +188,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu }, () => { sw.Stop(); - Logger?.LogInfo($"Enumerated {fileCount} files and {directoryCount} directories in {sw.Elapsed}"); + this.Logger?.LogInfo($"Enumerated {fileCount} files and {directoryCount} directories in {sw.Elapsed}"); s.OnCompleted(); }); }); @@ -201,13 +201,13 @@ private FileSystemInfo Transform(ref FileSystemEntry entry) private IObservable CreateDirectoryWalker(DirectoryInfo di, ExcludeDirectoryPredicate directoryExclusionPredicate, int minimumConnectionCount, IEnumerable filePatterns) { - return GetDirectoryScanner(di, new ConcurrentDictionary(), directoryExclusionPredicate, filePatterns, true).Replay() // Returns a replay subject which will republish anything found to new subscribers. + return this.GetDirectoryScanner(di, new ConcurrentDictionary(), directoryExclusionPredicate, filePatterns, true).Replay() // Returns a replay subject which will republish anything found to new subscribers. .AutoConnect(minimumConnectionCount); // Specifies that this connectable observable should start when minimumConnectionCount subscribe. } private bool MatchesAnyPattern(FileInfo fi, params string[] searchPatterns) { - return searchPatterns != null && searchPatterns.Any(sp => PathUtilityService.MatchesPattern(sp, fi.Name)); + return searchPatterns != null && searchPatterns.Any(sp => this.PathUtilityService.MatchesPattern(sp, fi.Name)); } /// @@ -219,22 +219,22 @@ private bool MatchesAnyPattern(FileInfo fi, params string[] searchPatterns) /// Pattern used to filter files. public void Initialize(DirectoryInfo root, ExcludeDirectoryPredicate directoryExclusionPredicate, int minimumConnectionCount, IEnumerable filePatterns = null) { - pendingScans.GetOrAdd(root, new Lazy>(() => CreateDirectoryWalker(root, directoryExclusionPredicate, minimumConnectionCount, filePatterns))); + this.pendingScans.GetOrAdd(root, new Lazy>(() => this.CreateDirectoryWalker(root, directoryExclusionPredicate, minimumConnectionCount, filePatterns))); } public IObservable Subscribe(DirectoryInfo root, IEnumerable patterns) { var patternArray = patterns.ToArray(); - if (pendingScans.TryGetValue(root, out var scannerObservable)) + if (this.pendingScans.TryGetValue(root, out var scannerObservable)) { - Logger.LogVerbose(string.Join(":", patterns)); + this.Logger.LogVerbose(string.Join(":", patterns)); var inner = scannerObservable.Value.Where(fsi => { if (fsi is FileInfo fi) { - return MatchesAnyPattern(fi, patternArray); + return this.MatchesAnyPattern(fi, patternArray); } else { @@ -250,7 +250,7 @@ public IObservable Subscribe(DirectoryInfo root, IEnumerable GetFilteredComponentStreamObservable(DirectoryInfo root, IEnumerable patterns, IComponentRecorder componentRecorder) { - var observable = Subscribe(root, patterns).OfType().SelectMany(f => patterns.Select(sp => new + var observable = this.Subscribe(root, patterns).OfType().SelectMany(f => patterns.Select(sp => new { SearchPattern = sp, File = f, @@ -259,11 +259,11 @@ public IObservable GetFilteredComponentStreamObservable(Director var searchPattern = x.SearchPattern; var fileName = x.File.Name; - return PathUtilityService.MatchesPattern(searchPattern, fileName); + return this.PathUtilityService.MatchesPattern(searchPattern, fileName); }).Where(x => x.File.Exists) .Select(x => { - var lazyComponentStream = new LazyComponentStream(x.File, x.SearchPattern, Logger); + var lazyComponentStream = new LazyComponentStream(x.File, x.SearchPattern, this.Logger); return new ProcessRequest { ComponentStream = lazyComponentStream, @@ -276,7 +276,7 @@ public IObservable GetFilteredComponentStreamObservable(Director public void StartScan(DirectoryInfo root) { - if (pendingScans.TryRemove(root, out var scannerObservable)) + if (this.pendingScans.TryRemove(root, out var scannerObservable)) { // scannerObservable.Connect(); } @@ -286,7 +286,7 @@ public void StartScan(DirectoryInfo root) public void Reset() { - pendingScans.Clear(); + this.pendingScans.Clear(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/FileWritingService.cs b/src/Microsoft.ComponentDetection.Common/FileWritingService.cs index a39b47211..fc44ad6e6 100644 --- a/src/Microsoft.ComponentDetection.Common/FileWritingService.cs +++ b/src/Microsoft.ComponentDetection.Common/FileWritingService.cs @@ -23,14 +23,14 @@ public void Init(string basePath) throw new InvalidUserInputException($"The path {basePath} does not exist.", new DirectoryNotFoundException()); } - BasePath = string.IsNullOrEmpty(basePath) ? Path.GetTempPath() : basePath; + this.BasePath = string.IsNullOrEmpty(basePath) ? Path.GetTempPath() : basePath; } public void AppendToFile(string relativeFilePath, string text) { - relativeFilePath = ResolveFilePath(relativeFilePath); + relativeFilePath = this.ResolveFilePath(relativeFilePath); - lock (lockObject) + lock (this.lockObject) { File.AppendAllText(relativeFilePath, text); } @@ -38,9 +38,9 @@ public void AppendToFile(string relativeFilePath, string text) public void WriteFile(string relativeFilePath, string text) { - relativeFilePath = ResolveFilePath(relativeFilePath); + relativeFilePath = this.ResolveFilePath(relativeFilePath); - lock (lockObject) + lock (this.lockObject) { File.WriteAllText(relativeFilePath, text); } @@ -53,19 +53,19 @@ public void WriteFile(FileInfo absolutePath, string text) public string ResolveFilePath(string relativeFilePath) { - EnsureInit(); + this.EnsureInit(); if (relativeFilePath.Contains("{timestamp}")) { - relativeFilePath = relativeFilePath.Replace("{timestamp}", timestamp); + relativeFilePath = relativeFilePath.Replace("{timestamp}", this.timestamp); } - relativeFilePath = Path.Combine(BasePath, relativeFilePath); + relativeFilePath = Path.Combine(this.BasePath, relativeFilePath); return relativeFilePath; } private void EnsureInit() { - if (string.IsNullOrEmpty(BasePath)) + if (string.IsNullOrEmpty(this.BasePath)) { throw new InvalidOperationException("Base path has not yet been initialized in File Writing Service!"); } diff --git a/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs b/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs index 5b15d112d..1baae8558 100644 --- a/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs +++ b/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs @@ -14,21 +14,21 @@ private byte[] SafeOpenFile() { try { - using var fs = fileInfo.OpenRead(); + using var fs = this.fileInfo.OpenRead(); - var buffer = new byte[fileInfo.Length]; - fs.Read(buffer, 0, (int)fileInfo.Length); + var buffer = new byte[this.fileInfo.Length]; + fs.Read(buffer, 0, (int)this.fileInfo.Length); return buffer; } catch (UnauthorizedAccessException) { - logger?.LogWarning($"Unauthorized access exception caught when trying to open {fileInfo.FullName}"); + this.logger?.LogWarning($"Unauthorized access exception caught when trying to open {this.fileInfo.FullName}"); } catch (Exception e) { - logger?.LogWarning($"Unhandled exception caught when trying to open {fileInfo.FullName}"); - logger?.LogException(e, isError: false); + this.logger?.LogWarning($"Unhandled exception caught when trying to open {this.fileInfo.FullName}"); + this.logger?.LogException(e, isError: false); } return new byte[0]; @@ -36,14 +36,14 @@ private byte[] SafeOpenFile() public LazyComponentStream(FileInfo fileInfo, string pattern, ILogger logger) { - Pattern = pattern; - Location = fileInfo.FullName; + this.Pattern = pattern; + this.Location = fileInfo.FullName; this.fileInfo = fileInfo; this.logger = logger; - fileBuffer = new Lazy(SafeOpenFile); + this.fileBuffer = new Lazy(this.SafeOpenFile); } - public Stream Stream => new MemoryStream(fileBuffer.Value); + public Stream Stream => new MemoryStream(this.fileBuffer.Value); public string Pattern { get; set; } diff --git a/src/Microsoft.ComponentDetection.Common/Logger.cs b/src/Microsoft.ComponentDetection.Common/Logger.cs index fc2977e63..dfed734c5 100644 --- a/src/Microsoft.ComponentDetection.Common/Logger.cs +++ b/src/Microsoft.ComponentDetection.Common/Logger.cs @@ -27,45 +27,45 @@ public class Logger : ILogger public void Init(VerbosityMode verbosity) { - WriteToFile = true; - Verbosity = verbosity; + this.WriteToFile = true; + this.Verbosity = verbosity; try { - FileWritingService.WriteFile(LogRelativePath, string.Empty); - LogInfo($"Log file: {FileWritingService.ResolveFilePath(LogRelativePath)}"); + this.FileWritingService.WriteFile(LogRelativePath, string.Empty); + this.LogInfo($"Log file: {this.FileWritingService.ResolveFilePath(LogRelativePath)}"); } catch (Exception) { - WriteToFile = false; - LogError("There was an issue writing to the log file, for the remainder of execution verbose output will be written to the console."); - Verbosity = VerbosityMode.Verbose; + this.WriteToFile = false; + this.LogError("There was an issue writing to the log file, for the remainder of execution verbose output will be written to the console."); + this.Verbosity = VerbosityMode.Verbose; } } public void LogCreateLoggingGroup() { - PrintToConsole(NewLine, VerbosityMode.Normal); - AppendToFile(NewLine); + this.PrintToConsole(NewLine, VerbosityMode.Normal); + this.AppendToFile(NewLine); } public void LogWarning(string message) { - LogInternal("WARN", message); + this.LogInternal("WARN", message); } public void LogInfo(string message) { - LogInternal("INFO", message); + this.LogInternal("INFO", message); } public void LogVerbose(string message) { - LogInternal("VERBOSE", message, VerbosityMode.Verbose); + this.LogInternal("VERBOSE", message, VerbosityMode.Verbose); } public void LogError(string message) { - LogInternal("ERROR", message, VerbosityMode.Quiet); + this.LogInternal("ERROR", message, VerbosityMode.Quiet); } private void LogInternal(string prefix, string message, VerbosityMode verbosity = VerbosityMode.Normal) @@ -73,15 +73,15 @@ private void LogInternal(string prefix, string message, VerbosityMode verbosity var formattedPrefix = string.IsNullOrWhiteSpace(prefix) ? string.Empty : $"[{prefix}] "; var text = $"{formattedPrefix}{message} {NewLine}"; - PrintToConsole(text, verbosity); - AppendToFile(text); + this.PrintToConsole(text, verbosity); + this.AppendToFile(text); } public void LogFailedReadingFile(string filePath, Exception e) { - PrintToConsole(NewLine, VerbosityMode.Verbose); - LogFailedProcessingFile(filePath); - LogException(e, isError: false); + this.PrintToConsole(NewLine, VerbosityMode.Verbose); + this.LogFailedProcessingFile(filePath); + this.LogException(e, isError: false); using var record = new FailedReadingFileRecord { FilePath = filePath, @@ -97,7 +97,7 @@ public void LogException( [CallerMemberName] string callerMemberName = "", [CallerLineNumber] int callerLineNumber = 0) { - string tag = isError ? "[ERROR]" : "[INFO]"; + var tag = isError ? "[ERROR]" : "[INFO]"; var fullExceptionText = $"{tag} Exception encountered." + NewLine + $"CallerMember: [{callerMemberName} : {callerLineNumber}]" + NewLine + @@ -109,45 +109,45 @@ public void LogException( if (isError) { - PrintToConsole(consoleText, VerbosityMode.Quiet); + this.PrintToConsole(consoleText, VerbosityMode.Quiet); } else { - PrintToConsole(consoleText, VerbosityMode.Verbose); + this.PrintToConsole(consoleText, VerbosityMode.Verbose); } - AppendToFile(fullExceptionText); + this.AppendToFile(fullExceptionText); } // TODO: All these vso specific logs should go away public void LogBuildWarning(string message) { - PrintToConsole($"##vso[task.LogIssue type=warning;]{message}{NewLine}", VerbosityMode.Quiet); + this.PrintToConsole($"##vso[task.LogIssue type=warning;]{message}{NewLine}", VerbosityMode.Quiet); } public void LogBuildError(string message) { - PrintToConsole($"##vso[task.LogIssue type=error;]{message}{NewLine}", VerbosityMode.Quiet); + this.PrintToConsole($"##vso[task.LogIssue type=error;]{message}{NewLine}", VerbosityMode.Quiet); } private void LogFailedProcessingFile(string filePath) { - LogVerbose($"Could not read component details from file {filePath} {NewLine}"); + this.LogVerbose($"Could not read component details from file {filePath} {NewLine}"); } private void AppendToFile(string text) { - if (WriteToFile) + if (this.WriteToFile) { - FileWritingService.AppendToFile(LogRelativePath, text); + this.FileWritingService.AppendToFile(LogRelativePath, text); } } private void PrintToConsole(string text, VerbosityMode minVerbosity) { - if (Verbosity >= minVerbosity) + if (this.Verbosity >= minVerbosity) { - ConsoleWriter.Write(text); + this.ConsoleWriter.Write(text); } } } diff --git a/src/Microsoft.ComponentDetection.Common/Microsoft.ComponentDetection.Common.csproj b/src/Microsoft.ComponentDetection.Common/Microsoft.ComponentDetection.Common.csproj index 8df30202a..57f866733 100644 --- a/src/Microsoft.ComponentDetection.Common/Microsoft.ComponentDetection.Common.csproj +++ b/src/Microsoft.ComponentDetection.Common/Microsoft.ComponentDetection.Common.csproj @@ -1,5 +1,5 @@  - + @@ -29,4 +29,4 @@ - \ No newline at end of file + diff --git a/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs b/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs index 4a93e88ea..7c75e3ea7 100644 --- a/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs +++ b/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs @@ -34,18 +34,18 @@ public bool IsRunningOnWindowsContainer { get { - if (!isRunningOnWindowsContainer.HasValue) + if (!this.isRunningOnWindowsContainer.HasValue) { - lock (isRunningOnWindowsContainerLock) + lock (this.isRunningOnWindowsContainerLock) { - if (!isRunningOnWindowsContainer.HasValue) + if (!this.isRunningOnWindowsContainer.HasValue) { - isRunningOnWindowsContainer = CheckIfRunningOnWindowsContainer(); + this.isRunningOnWindowsContainer = this.CheckIfRunningOnWindowsContainer(); } } } - return isRunningOnWindowsContainer.Value; + return this.isRunningOnWindowsContainer.Value; } } @@ -113,11 +113,11 @@ public string ResolvePhysicalPath(string path) { if (IsWindows) { - return ResolvePhysicalPathWindows(path); + return this.ResolvePhysicalPathWindows(path); } else if (IsLinux) { - return ResolvePhysicalPathLinux(path); + return this.ResolvePhysicalPathLinux(path); } return path; @@ -130,27 +130,27 @@ public string ResolvePhysicalPathWindows(string path) throw new PlatformNotSupportedException("Attempted to call a function that makes windows-only SDK calls"); } - if (IsRunningOnWindowsContainer) + if (this.IsRunningOnWindowsContainer) { return path; } - if (resolvedPaths.TryGetValue(path, out string cachedPath)) + if (this.resolvedPaths.TryGetValue(path, out var cachedPath)) { return cachedPath; } - DirectoryInfo symlink = new DirectoryInfo(path); + var symlink = new DirectoryInfo(path); - using SafeFileHandle directoryHandle = CreateFile(symlink.FullName, 0, 2, IntPtr.Zero, CreationDispositionRead, FileFlagBackupSemantics, IntPtr.Zero); + using var directoryHandle = CreateFile(symlink.FullName, 0, 2, IntPtr.Zero, CreationDispositionRead, FileFlagBackupSemantics, IntPtr.Zero); if (directoryHandle.IsInvalid) { return path; } - StringBuilder resultBuilder = new StringBuilder(InitalPathBufferSize); - int mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), resultBuilder, resultBuilder.Capacity, 0); + var resultBuilder = new StringBuilder(InitalPathBufferSize); + var mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), resultBuilder, resultBuilder.Capacity, 0); // If GetFinalPathNameByHandle needs a bigger buffer, it will tell us the size it needs (including the null terminator) in finalPathNameResultCode if (mResult > InitalPathBufferSize) @@ -164,11 +164,11 @@ public string ResolvePhysicalPathWindows(string path) return path; } - string result = resultBuilder.ToString(); + var result = resultBuilder.ToString(); result = result.StartsWith(LongPathPrefix) ? result.Substring(LongPathPrefix.Length) : result; - resolvedPaths.TryAdd(path, result); + this.resolvedPaths.TryAdd(path, result); return result; } @@ -180,7 +180,7 @@ public string ResolvePhysicalPathLinux(string path) throw new PlatformNotSupportedException("Attempted to call a function that makes linux-only library calls"); } - IntPtr pointer = IntPtr.Zero; + var pointer = IntPtr.Zero; try { pointer = RealPathLinux(path, IntPtr.Zero); @@ -197,7 +197,7 @@ public string ResolvePhysicalPathLinux(string path) } catch (Exception ex) { - Logger.LogException(ex, isError: false, printException: true); + this.Logger.LogException(ex, isError: false, printException: true); return path; } finally @@ -218,7 +218,7 @@ private bool CheckIfRunningOnWindowsContainer() // This isn't the best way to do this in C#, but netstandard doesn't seem to support the service api calls // that we need to do this without shelling out - Process process = new Process() + var process = new Process() { StartInfo = new ProcessStartInfo { @@ -231,7 +231,7 @@ private bool CheckIfRunningOnWindowsContainer() }, }; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); process.Start(); while (!process.HasExited) @@ -244,7 +244,7 @@ private bool CheckIfRunningOnWindowsContainer() if (sb.ToString().Contains("Container Execution Agent")) { - Logger.LogWarning("Detected execution in a Windows container. Currently windows containers < 1809 do not support symlinks well, so disabling symlink resolution/dedupe behavior"); + this.Logger.LogWarning("Detected execution in a Windows container. Currently windows containers < 1809 do not support symlinks well, so disabling symlink resolution/dedupe behavior"); return true; } else diff --git a/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs b/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs index e299f3e00..ca9625104 100644 --- a/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs +++ b/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs @@ -12,11 +12,11 @@ public static class PatternMatchingUtility public static FilePatternMatcher GetFilePatternMatcher(IEnumerable patterns) { - var ordinalComparison = Expression.Constant(System.StringComparison.Ordinal, typeof(System.StringComparison)); - var asSpan = typeof(System.MemoryExtensions).GetMethod("AsSpan", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(string) }, new ParameterModifier[0]); - var equals = typeof(System.MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]); - var startsWith = typeof(System.MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]); - var endsWith = typeof(System.MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]); + var ordinalComparison = Expression.Constant(StringComparison.Ordinal, typeof(StringComparison)); + var asSpan = typeof(MemoryExtensions).GetMethod("AsSpan", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(string) }, new ParameterModifier[0]); + var equals = typeof(MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]); + var startsWith = typeof(MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]); + var endsWith = typeof(MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]); var predicates = new List(); var left = Expression.Parameter(typeof(ReadOnlySpan), "fileName"); @@ -53,4 +53,4 @@ public static FilePatternMatcher GetFilePatternMatcher(IEnumerable patte return func; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/Resources.Designer.cs b/src/Microsoft.ComponentDetection.Common/Resources.Designer.cs index 08908f0d6..08bb65d5d 100644 --- a/src/Microsoft.ComponentDetection.Common/Resources.Designer.cs +++ b/src/Microsoft.ComponentDetection.Common/Resources.Designer.cs @@ -10,8 +10,8 @@ namespace Microsoft.ComponentDetection.Common { using System; - - + + /// /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -23,15 +23,15 @@ namespace Microsoft.ComponentDetection.Common { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { - + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } - + /// /// Returns the cached ResourceManager instance used by this class. /// @@ -45,7 +45,7 @@ internal Resources() { return resourceMan; } } - + /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. @@ -59,7 +59,7 @@ internal Resources() { resourceCulture = value; } } - + /// /// Looks up a localized string similar to The component object does not have a componentId specified. /// @@ -68,7 +68,7 @@ internal static string MissingComponentId { return ResourceManager.GetString("MissingComponentId", resourceCulture); } } - + /// /// Looks up a localized string similar to Node with id {0} has not be inserted in the dependency graph. /// diff --git a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs index 3cee65b90..6e2aef8e9 100644 --- a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs +++ b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs @@ -29,9 +29,9 @@ public SafeFileEnumerable(DirectoryInfo directory, IEnumerable searchPat this.directoryExclusionPredicate = directoryExclusionPredicate; this.recursivelyScanDirectories = recursivelyScanDirectories; this.pathUtilityService = pathUtilityService; - enumeratedDirectories = previouslyEnumeratedDirectories; + this.enumeratedDirectories = previouslyEnumeratedDirectories; - enumerationOptions = new EnumerationOptions() + this.enumerationOptions = new EnumerationOptions() { IgnoreInaccessible = true, RecurseSubdirectories = this.recursivelyScanDirectories, @@ -48,9 +48,9 @@ public SafeFileEnumerable(DirectoryInfo directory, Func fileMatc public IEnumerator GetEnumerator() { - var previouslyEnumeratedDirectories = enumeratedDirectories ?? new HashSet(); + var previouslyEnumeratedDirectories = this.enumeratedDirectories ?? new HashSet(); - var fse = new FileSystemEnumerable(directory.FullName, (ref FileSystemEntry entry) => + var fse = new FileSystemEnumerable(this.directory.FullName, (ref FileSystemEntry entry) => { if (!(entry.ToFileSystemInfo() is FileInfo fi)) { @@ -58,7 +58,7 @@ public IEnumerator GetEnumerator() } var foundPattern = entry.FileName.ToString(); - foreach (var searchPattern in searchPatterns) + foreach (var searchPattern in this.searchPatterns) { if (PathUtilityService.MatchesPattern(searchPattern, ref entry)) { @@ -67,7 +67,7 @@ public IEnumerator GetEnumerator() } return new MatchedFile() { File = fi, Pattern = foundPattern }; - }, enumerationOptions) + }, this.enumerationOptions) { ShouldIncludePredicate = (ref FileSystemEntry entry) => { @@ -76,7 +76,7 @@ public IEnumerator GetEnumerator() return false; } - foreach (var searchPattern in searchPatterns) + foreach (var searchPattern in this.searchPatterns) { if (PathUtilityService.MatchesPattern(searchPattern, ref entry)) { @@ -88,7 +88,7 @@ public IEnumerator GetEnumerator() }, ShouldRecursePredicate = (ref FileSystemEntry entry) => { - if (!recursivelyScanDirectories) + if (!this.recursivelyScanDirectories) { return false; } @@ -99,7 +99,7 @@ public IEnumerator GetEnumerator() if (entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) { - var realPath = pathUtilityService.ResolvePhysicalPath(targetPath); + var realPath = this.pathUtilityService.ResolvePhysicalPath(targetPath); seenPreviously = previouslyEnumeratedDirectories.Contains(realPath); previouslyEnumeratedDirectories.Add(realPath); @@ -118,12 +118,12 @@ public IEnumerator GetEnumerator() if (seenPreviously) { - logger.LogVerbose($"Encountered real path {targetPath} before. Short-Circuiting directory traversal"); + this.logger.LogVerbose($"Encountered real path {targetPath} before. Short-Circuiting directory traversal"); return false; } // This is actually a *directory* name (not FileName) and the directory containing that directory. - if (entry.IsDirectory && directoryExclusionPredicate != null && directoryExclusionPredicate(entry.FileName, entry.Directory)) + if (entry.IsDirectory && this.directoryExclusionPredicate != null && this.directoryExclusionPredicate(entry.FileName, entry.Directory)) { return false; } @@ -134,7 +134,7 @@ public IEnumerator GetEnumerator() foreach (var file in fse) { - if (fileMatchingPredicate == null || fileMatchingPredicate(file.File)) + if (this.fileMatchingPredicate == null || this.fileMatchingPredicate(file.File)) { yield return file; } @@ -143,7 +143,7 @@ public IEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator(); + return this.GetEnumerator(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs index 541793b08..b528d73c9 100644 --- a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs +++ b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs @@ -17,7 +17,7 @@ public class SafeFileEnumerableFactory : ISafeFileEnumerableFactory public IEnumerable CreateSafeFileEnumerable(DirectoryInfo directory, IEnumerable searchPatterns, ExcludeDirectoryPredicate directoryExclusionPredicate) { - return new SafeFileEnumerable(directory, searchPatterns, Logger, PathUtilityService, directoryExclusionPredicate); + return new SafeFileEnumerable(directory, searchPatterns, this.Logger, this.PathUtilityService, directoryExclusionPredicate); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs b/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs index a6e1c5260..493f12bc3 100644 --- a/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs +++ b/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs @@ -19,7 +19,7 @@ public class TabularStringFormat public TabularStringFormat(IList columns, char horizontalLineChar = DefaultHorizontalLineChar, char verticalLineChar = DefaultVerticalLineChar, string tableTitle = null) { this.columns = columns; - totalWidth = columns.Count + 1 + columns.Sum(x => x.Width); + this.totalWidth = columns.Count + 1 + columns.Sum(x => x.Width); this.horizontalLineChar = horizontalLineChar; this.verticalLineChar = verticalLineChar; this.tableTitle = tableTitle; @@ -27,40 +27,40 @@ public TabularStringFormat(IList columns, char horizontalLineChar = Defa public string GenerateString(IEnumerable> rows) { - StringBuilder sb = new StringBuilder(); - if (!string.IsNullOrWhiteSpace(tableTitle)) + var sb = new StringBuilder(); + if (!string.IsNullOrWhiteSpace(this.tableTitle)) { - PrintTitleSection(sb); + this.PrintTitleSection(sb); } else { - WriteFlatLine(sb, false); + this.WriteFlatLine(sb, false); } - sb.Append(verticalLineChar); - foreach (var column in columns) + sb.Append(this.verticalLineChar); + foreach (var column in this.columns) { sb.Append(column.Header.PadRight(column.Width)); - sb.Append(verticalLineChar); + sb.Append(this.verticalLineChar); } - WriteFlatLine(sb); + this.WriteFlatLine(sb); foreach (var row in rows) { - sb.Append(verticalLineChar); - if (row.Count != columns.Count) + sb.Append(this.verticalLineChar); + if (row.Count != this.columns.Count) { throw new InvalidOperationException("All rows must have length equal to the number of columns present."); } - for (var i = 0; i < columns.Count; i++) + for (var i = 0; i < this.columns.Count; i++) { - var dataString = columns[i].Format != null ? string.Format(columns[i].Format, row[i]) : row[i].ToString(); - sb.Append(dataString.PadRight(columns[i].Width)); - sb.Append(verticalLineChar); + var dataString = this.columns[i].Format != null ? string.Format(this.columns[i].Format, row[i]) : row[i].ToString(); + sb.Append(dataString.PadRight(this.columns[i].Width)); + sb.Append(this.verticalLineChar); } - WriteFlatLine(sb); + this.WriteFlatLine(sb); } return sb.ToString(); @@ -68,37 +68,37 @@ public string GenerateString(IEnumerable> rows) private void PrintTitleSection(StringBuilder sb) { - WriteFlatLine(sb, false); - var tableWidth = columns.Sum(column => column.Width); - sb.Append(verticalLineChar); - sb.Append(tableTitle.PadRight(tableWidth + columns.Count - 1)); - sb.Append(verticalLineChar); + this.WriteFlatLine(sb, false); + var tableWidth = this.columns.Sum(column => column.Width); + sb.Append(this.verticalLineChar); + sb.Append(this.tableTitle.PadRight(tableWidth + this.columns.Count - 1)); + sb.Append(this.verticalLineChar); sb.AppendLine(); - sb.Append(verticalLineChar); - for (var i = 0; i < columns.Count - 1; i++) + sb.Append(this.verticalLineChar); + for (var i = 0; i < this.columns.Count - 1; i++) { - sb.Append(string.Empty.PadRight(columns[i].Width, horizontalLineChar)); - sb.Append(horizontalLineChar); + sb.Append(string.Empty.PadRight(this.columns[i].Width, this.horizontalLineChar)); + sb.Append(this.horizontalLineChar); } - sb.Append(string.Empty.PadRight(columns[columns.Count - 1].Width, horizontalLineChar)); - sb.Append(verticalLineChar); + sb.Append(string.Empty.PadRight(this.columns[this.columns.Count - 1].Width, this.horizontalLineChar)); + sb.Append(this.verticalLineChar); sb.AppendLine(); } private void WriteFlatLine(StringBuilder sb, bool withPipes = true) { - var splitCharacter = withPipes ? verticalLineChar : horizontalLineChar; + var splitCharacter = withPipes ? this.verticalLineChar : this.horizontalLineChar; sb.AppendLine(); sb.Append(splitCharacter); - for (var i = 0; i < columns.Count; i++) + for (var i = 0; i < this.columns.Count; i++) { - sb.Append(string.Empty.PadRight(columns[i].Width, horizontalLineChar)); + sb.Append(string.Empty.PadRight(this.columns[i].Width, this.horizontalLineChar)); sb.Append(splitCharacter); } sb.AppendLine(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs index 3b786a00f..7314acd12 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs @@ -8,7 +8,7 @@ public class TelemetryServiceAttribute : Attribute public TelemetryServiceAttribute(string serviceType) { - ServiceType = serviceType; + this.ServiceType = serviceType; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs index 3eec11a5e..6dfec5e82 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs @@ -27,12 +27,12 @@ internal class CommandLineTelemetryService : ITelemetryService public void Flush() { - FileWritingService.WriteFile(TelemetryRelativePath, JsonConvert.SerializeObject(records)); + this.FileWritingService.WriteFile(TelemetryRelativePath, JsonConvert.SerializeObject(records)); } public void PostRecord(IDetectionTelemetryRecord record) { - if (telemetryMode != TelemetryMode.Disabled) + if (this.telemetryMode != TelemetryMode.Disabled) { var jsonRecord = JObject.FromObject(record); jsonRecord.Add("Timestamp", DateTime.UtcNow); @@ -40,16 +40,16 @@ public void PostRecord(IDetectionTelemetryRecord record) records.Enqueue(jsonRecord); - if (telemetryMode == TelemetryMode.Debug) + if (this.telemetryMode == TelemetryMode.Debug) { - Logger.LogInfo(jsonRecord.ToString()); + this.Logger.LogInfo(jsonRecord.ToString()); } } } public void SetMode(TelemetryMode mode) { - telemetryMode = mode; + this.telemetryMode = mode; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs index b303df421..f7cb52677 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs @@ -15,15 +15,15 @@ public abstract class BaseDetectionTelemetryRecord : IDetectionTelemetryRecord protected BaseDetectionTelemetryRecord() { - stopwatch.Start(); + this.stopwatch.Start(); } public void StopExecutionTimer() { - if (stopwatch.IsRunning) + if (this.stopwatch.IsRunning) { - stopwatch.Stop(); - ExecutionTime = stopwatch.Elapsed; + this.stopwatch.Stop(); + this.ExecutionTime = this.stopwatch.Elapsed; } } @@ -31,21 +31,21 @@ public void StopExecutionTimer() protected virtual void Dispose(bool disposing) { - if (!disposedValue) + if (!this.disposedValue) { if (disposing) { - StopExecutionTimer(); + this.StopExecutionTimer(); TelemetryRelay.Instance.PostTelemetryRecord(this); } - disposedValue = true; + this.disposedValue = true; } } public void Dispose() { - Dispose(true); + this.Dispose(true); } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs index 45650e3cf..4b47a1884 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs @@ -19,23 +19,23 @@ public class CommandLineInvocationTelemetryRecord : BaseDetectionTelemetryRecord internal void Track(CommandLineExecutionResult result, string path, string parameters) { - ExitCode = result.ExitCode; - StandardError = result.StdErr; - TrackCommon(path, parameters); + this.ExitCode = result.ExitCode; + this.StandardError = result.StdErr; + this.TrackCommon(path, parameters); } internal void Track(Exception ex, string path, string parameters) { - ExitCode = -1; - UnhandledException = ex.ToString(); - TrackCommon(path, parameters); + this.ExitCode = -1; + this.UnhandledException = ex.ToString(); + this.TrackCommon(path, parameters); } private void TrackCommon(string path, string parameters) { - PathThatWasRan = path; - Parameters = parameters; - StopExecutionTimer(); + this.PathThatWasRan = path; + this.Parameters = parameters; + this.StopExecutionTimer(); } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs index 3b599bdc3..57d986b22 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs @@ -10,8 +10,8 @@ public class DetectedComponentScopeRecord : BaseDetectionTelemetryRecord [MethodImpl(MethodImplOptions.Synchronized)] public void IncrementProvidedScopeCount() - { - MavenProvidedScopeCount++; + { + this.MavenProvidedScopeCount++; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceImageExistsLocallyTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceImageExistsLocallyTelemetryRecord.cs index 76ed90104..16fe97210 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceImageExistsLocallyTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceImageExistsLocallyTelemetryRecord.cs @@ -3,11 +3,11 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records public class DockerServiceImageExistsLocallyTelemetryRecord : BaseDetectionTelemetryRecord { public override string RecordName => "DockerServiceImageExistsLocally"; - + public string Image { get; set; } - + public string ImageInspectResponse { get; set; } - + public string ExceptionMessage { get; set; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceInspectImageTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceInspectImageTelemetryRecord.cs index ee5b0ce79..7ec37c2f2 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceInspectImageTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceInspectImageTelemetryRecord.cs @@ -9,7 +9,7 @@ public class DockerServiceInspectImageTelemetryRecord : BaseDetectionTelemetryRe public string BaseImageDigest { get; set; } public string BaseImageRef { get; set; } - + public string ImageInspectResponse { get; set; } public string ExceptionMessage { get; set; } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceSystemInfoTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceSystemInfoTelemetryRecord.cs index 4e8e163e7..aa566e103 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceSystemInfoTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceSystemInfoTelemetryRecord.cs @@ -3,9 +3,9 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records public class DockerServiceSystemInfoTelemetryRecord : BaseDetectionTelemetryRecord { public override string RecordName => "DockerServiceSystemInfo"; - + public string SystemInfo { get; set; } - + public string ExceptionMessage { get; set; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTelemetryRecord.cs index 70bd5d63d..03bb1a44f 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTelemetryRecord.cs @@ -3,15 +3,15 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records public class DockerServiceTelemetryRecord : BaseDetectionTelemetryRecord { public override string RecordName => "DockerService"; - + public string Image { get; set; } - + public string Command { get; set; } - + public string Container { get; set; } - + public string Stdout { get; set; } - + public string Stderr { get; set; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTryPullImageTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTryPullImageTelemetryRecord.cs index c73942482..a1ed32435 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTryPullImageTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTryPullImageTelemetryRecord.cs @@ -3,7 +3,7 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records public class DockerServiceTryPullImageTelemetryRecord : BaseDetectionTelemetryRecord { public override string RecordName => "DockerServiceTryPullImage"; - + public string Image { get; set; } public string CreateImageProgress { get; set; } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs index 0f811c343..262466b60 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs @@ -3,11 +3,11 @@ public class LinuxContainerDetectorMissingVersion : BaseDetectionTelemetryRecord { public override string RecordName { get; } = "MissingVersion"; - + public string Distribution { get; set; } - + public string Release { get; set; } - public string[] PackageNames { get; set; } + public string[] PackageNames { get; set; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerSyftTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerSyftTelemetryRecord.cs index 706126097..84a859eab 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerSyftTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerSyftTelemetryRecord.cs @@ -3,7 +3,7 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records public class LinuxScannerSyftTelemetryRecord : BaseDetectionTelemetryRecord { public override string RecordName => "LinuxScannerSyftTelemetry"; - + public string LinuxComponents { get; set; } public string Exception { get; set; } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs index fef3a5a10..fe8147509 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs @@ -11,7 +11,7 @@ public class LinuxScannerTelemetryRecord : BaseDetectionTelemetryRecord public string ScanStdErr { get; set; } public string FailedDeserializingScannerOutput { get; set; } - + public bool SemaphoreFailure { get; set; } public string ScannerVersion { get; set; } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs index 4f691ca43..3e1f7dc64 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs @@ -16,20 +16,20 @@ public class NuGetProjectAssetsTelemetryRecord : IDetectionTelemetryRecord, IDis protected virtual void Dispose(bool disposing) { - if (!disposedValue) + if (!this.disposedValue) { if (disposing) { TelemetryRelay.Instance.PostTelemetryRecord(this); } - disposedValue = true; + this.disposedValue = true; } } public void Dispose() { - Dispose(true); + this.Dispose(true); } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs index 39ba28e89..4102fc25e 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs @@ -1,6 +1,4 @@ -using System.Net; - -namespace Microsoft.ComponentDetection.Common.Telemetry.Records +namespace Microsoft.ComponentDetection.Common.Telemetry.Records { public class PypiCacheTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs index 25866d5e0..8dcae5fa3 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs @@ -29,7 +29,7 @@ public class ContainerDetails // Summary: // The digest of the exact image used as the base image - // This is to avoid errors if there are ref updates between build time and scan time + // This is to avoid errors if there are ref updates between build time and scan time public string BaseImageDigest { get; set; } // Summary: diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs index 4f6774f1f..5c72f728c 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs @@ -1,11 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Microsoft.ComponentDetection.Contracts.BcdeModels +namespace Microsoft.ComponentDetection.Contracts.BcdeModels { - /// Used to communicate Dependency Scope of Component. - /// Currently only populated for Maven component. + /// Used to communicate Dependency Scope of Component. + /// Currently only populated for Maven component. /// The values are ordered in terms of priority, which is used to resolve the scope for duplicate component while merging them. /// public enum DependencyScope diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DockerLayer.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DockerLayer.cs index 8dacf105f..1ab815a80 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DockerLayer.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DockerLayer.cs @@ -1,6 +1,6 @@ namespace Microsoft.ComponentDetection.Contracts.BcdeModels { - public class DockerLayer + public class DockerLayer { // Summary: // the command/script that was executed in order to create the layer. @@ -19,4 +19,4 @@ public class DockerLayer // Note: only includes non-empty layers public int LayerIndex { get; set; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/LayerMappedLinuxComponents.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/LayerMappedLinuxComponents.cs index 760dd725e..cf07bde94 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/LayerMappedLinuxComponents.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/LayerMappedLinuxComponents.cs @@ -3,10 +3,10 @@ namespace Microsoft.ComponentDetection.Contracts.BcdeModels { - public class LayerMappedLinuxComponents + public class LayerMappedLinuxComponents { public IEnumerable LinuxComponents { get; set; } public DockerLayer DockerLayer { get; set; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs index ff3ff79c4..1812bf7f0 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Newtonsoft.Json; @@ -24,6 +24,7 @@ public class TypedComponentConverter : JsonConverter { ComponentType.Linux, typeof(LinuxComponent) }, { ComponentType.Conda, typeof(CondaComponent) }, { ComponentType.DockerReference, typeof(DockerReferenceComponent) }, + { ComponentType.Vcpkg, typeof(VcpkgComponent) } }; public override bool CanConvert(Type objectType) @@ -35,10 +36,10 @@ public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { - JToken jo = JToken.Load(reader); + var jo = JToken.Load(reader); var value = (ComponentType)Enum.Parse(typeof(ComponentType), (string)jo["type"]); - var targetType = componentTypesToTypes[value]; + var targetType = this.componentTypesToTypes[value]; var instanceOfTypedComponent = Activator.CreateInstance(targetType, true); serializer.Populate(jo.CreateReader(), instanceOfTypedComponent); diff --git a/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs b/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs index 8a957614a..a3e8aa0f6 100644 --- a/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs @@ -17,22 +17,22 @@ public class DetectedComponent /// Id of the layer the component was found, this is only necessary if the component was found inside a container. public DetectedComponent(TypedComponent.TypedComponent component, IComponentDetector detector = null, int? containerDetailsId = null, int? containerLayerId = null) { - Component = component; - FilePaths = new HashSet(); - DetectedBy = detector; - ContainerDetailIds = new HashSet(); - ContainerLayerIds = new Dictionary>(); + this.Component = component; + this.FilePaths = new HashSet(); + this.DetectedBy = detector; + this.ContainerDetailIds = new HashSet(); + this.ContainerLayerIds = new Dictionary>(); if (containerDetailsId.HasValue) { - ContainerDetailIds.Add(containerDetailsId.Value); + this.ContainerDetailIds.Add(containerDetailsId.Value); if (containerLayerId.HasValue) { - ContainerLayerIds.Add(containerDetailsId.Value, new List() { containerLayerId.Value }); + this.ContainerLayerIds.Add(containerDetailsId.Value, new List() { containerLayerId.Value }); } } } - private string DebuggerDisplay => $"{Component.DebuggerDisplay}"; + private string DebuggerDisplay => $"{this.Component.DebuggerDisplay}"; /// /// Gets or sets the detector that detected this component. @@ -57,7 +57,7 @@ public DetectedComponent(TypedComponent.TypedComponent component, IComponentDete /// Gets or sets the layer within a container where this component was found. public IDictionary> ContainerLayerIds { get; set; } - + /// Gets or sets Dependency Scope of the component. public DependencyScope? DependencyScope { get; set; } @@ -65,9 +65,9 @@ public DetectedComponent(TypedComponent.TypedComponent component, IComponentDete /// The file path to add to the hashset. public void AddComponentFilePath(string filePath) { - lock (hashLock) + lock (this.hashLock) { - FilePaths.Add(filePath); + this.FilePaths.Add(filePath); } } } diff --git a/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs b/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs index 12c995077..7724a52ca 100644 --- a/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs +++ b/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs @@ -41,5 +41,8 @@ public enum DetectorClass /// Indicates a detector applies to Vcpkg packages. Vcpkg, + + /// Indicates a detector applies to Docker references. + DockerReference, } } diff --git a/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs b/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs index b8472bd4e..8728f3556 100644 --- a/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs +++ b/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs @@ -1,11 +1,71 @@ namespace Microsoft.ComponentDetection.Contracts { #pragma warning disable SA1402 - public abstract class DockerReference + public class DockerReference { - public abstract DockerReferenceKind Kind { get; } + public virtual DockerReferenceKind Kind { get; } - public abstract TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent(); + public virtual TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() + { + throw new System.NotImplementedException(); + } + + public static DockerReference CreateDockerReference(string repository, string domain, string digest, string tag) + { + if (!string.IsNullOrEmpty(repository) && string.IsNullOrEmpty(domain)) + { + if (!string.IsNullOrEmpty(digest)) + { + return new DigestReference + { + Digest = digest, + }; + } + else + { + throw new System.InvalidOperationException("Repository name must have at least one component"); + } + } + else if (string.IsNullOrEmpty(tag)) + { + if (string.IsNullOrEmpty(digest)) + { + return new CanonicalReference + { + Domain = domain, + Repository = repository, + Digest = digest, + }; + } + else + { + return new RepositoryReference + { + Domain = domain, + Repository = repository, + }; + } + } + else if (string.IsNullOrEmpty(digest)) + { + return new TaggedReference + { + Domain = domain, + Repository = repository, + Tag = tag, + }; + } + else + { + return new DualReference + { + Domain = domain, + Repository = repository, + Tag = tag, + Digest = digest, + }; + } + } } public enum DockerReferenceKind @@ -20,11 +80,11 @@ public enum DockerReferenceKind public class Reference { public string Tag { get; set; } - + public string Digest { get; set; } - + public string Repository { get; set; } - + public string Domain { get; set; } } @@ -32,19 +92,19 @@ public class Reference public class DigestReference : DockerReference { public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Digest; - + public string Digest; public override string ToString() { - return $"{Digest}"; + return $"{this.Digest}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Digest = Digest, + Digest = this.Digest, }; } } @@ -53,25 +113,25 @@ public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceCo public class CanonicalReference : DockerReference { public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Canonical; - + public string Domain; - + public string Repository; - + public string Digest; public override string ToString() { - return $"{Domain}/{Repository}@${Digest}"; + return $"{this.Domain}/{this.Repository}@${this.Digest}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Domain = Domain, - Digest = Digest, - Name = Repository, + Domain = this.Domain, + Digest = this.Digest, + Repository = this.Repository, }; } } @@ -80,22 +140,22 @@ public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceCo public class RepositoryReference : DockerReference { public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Repository; - + public string Domain; - + public string Repository; - + public override string ToString() { - return $"{Repository}"; + return $"{this.Repository}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Domain = Domain, - Name = Repository, + Domain = this.Domain, + Repository = this.Repository, }; } } @@ -104,25 +164,25 @@ public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceCo public class TaggedReference : DockerReference { public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Tagged; - + public string Domain; - + public string Repository; - + public string Tag; - + public override string ToString() { - return $"{Domain}/{Repository}:${Tag}"; + return $"{this.Domain}/{this.Repository}:${this.Tag}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Domain = Domain, - Tag = Tag, - Name = Repository, + Domain = this.Domain, + Tag = this.Tag, + Repository = this.Repository, }; } } @@ -131,29 +191,29 @@ public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceCo public class DualReference : DockerReference { public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Dual; - + public string Domain; - + public string Repository; - + public string Tag; - + public string Digest; public override string ToString() { - return $"{Domain}/{Repository}:${Tag}@${Digest}"; + return $"{this.Domain}/{this.Repository}:${this.Tag}@${this.Digest}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Domain = Domain, - Digest = Digest, - Tag = Tag, - Name = Repository, + Domain = this.Domain, + Digest = this.Digest, + Tag = this.Tag, + Repository = this.Repository, }; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs index d6428b456..45a13523f 100644 --- a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs @@ -63,20 +63,20 @@ public abstract class FileComponentDetector : IComponentDetector /// public async virtual Task ExecuteDetectorAsync(ScanRequest request) { - ComponentRecorder = request.ComponentRecorder; - Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1); - return await ScanDirectoryAsync(request); + this.ComponentRecorder = request.ComponentRecorder; + this.Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1); + return await this.ScanDirectoryAsync(request); } /// private Task ScanDirectoryAsync(ScanRequest request) { - CurrentScanRequest = request; + this.CurrentScanRequest = request; - var filteredObservable = Scanner.GetFilteredComponentStreamObservable(request.SourceDirectory, SearchPatterns, request.ComponentRecorder); + var filteredObservable = this.Scanner.GetFilteredComponentStreamObservable(request.SourceDirectory, this.SearchPatterns, request.ComponentRecorder); - Logger?.LogVerbose($"Registered {GetType().FullName}"); - return ProcessAsync(filteredObservable, request.DetectorArgs); + this.Logger?.LogVerbose($"Registered {this.GetType().FullName}"); + return this.ProcessAsync(filteredObservable, request.DetectorArgs); } /// @@ -87,14 +87,14 @@ private Task ScanDirectoryAsync(ScanRequest reques /// protected Task> GetFileStreamsAsync(DirectoryInfo sourceDirectory, ExcludeDirectoryPredicate exclusionPredicate) { - return Task.FromResult(ComponentStreamEnumerableFactory.GetComponentStreams(sourceDirectory, SearchPatterns, exclusionPredicate)); + return Task.FromResult(this.ComponentStreamEnumerableFactory.GetComponentStreams(sourceDirectory, this.SearchPatterns, exclusionPredicate)); } private async Task ProcessAsync(IObservable processRequests, IDictionary detectorArgs) { - var processor = new ActionBlock(async processRequest => await OnFileFound(processRequest, detectorArgs)); + var processor = new ActionBlock(async processRequest => await this.OnFileFound(processRequest, detectorArgs)); - var preprocessedObserbable = await OnPrepareDetection(processRequests, detectorArgs); + var preprocessedObserbable = await this.OnPrepareDetection(processRequests, detectorArgs); await preprocessedObserbable.ForEachAsync(processRequest => processor.Post(processRequest)); @@ -102,12 +102,12 @@ private async Task ProcessAsync(IObservable - /// Gets the set of categories this detector is a member of. + /// Gets the set of categories this detector is a member of. /// Names of the enumeration comprise some of the built in categories. /// If the category "All" is specified, the detector will always run. /// @@ -44,7 +44,7 @@ public interface IComponentDetector /// /// Component detectors implementing this interface are, by default, off. This is used during composition to opt detectors out of being on by default. - /// If opted in, they should behave like a normal detector. + /// If opted in, they should behave like a normal detector. /// public interface IDefaultOffComponentDetector : IComponentDetector { diff --git a/src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs b/src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs index 49bbe9d87..8dc317935 100644 --- a/src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs +++ b/src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs @@ -13,7 +13,7 @@ public interface IDetectorDependencies IFileUtilityService FileUtilityService { get; set; } IObservableDirectoryWalkerFactory DirectoryWalkerFactory { get; set; } - + IDockerService DockerService { get; set; } IEnvironmentVariableService EnvironmentVariableService { get; set; } diff --git a/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs b/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs index 5c9891a5c..13e1b4e42 100644 --- a/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs +++ b/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs @@ -6,12 +6,12 @@ public class NpmAuthor { public NpmAuthor(string name, string email = null) { - Name = name ?? throw new ArgumentNullException(nameof(name)); - Email = string.IsNullOrEmpty(email) ? null : email; + this.Name = name ?? throw new ArgumentNullException(nameof(name)); + this.Email = string.IsNullOrEmpty(email) ? null : email; } public string Name { get; set; } - + public string Email { get; set; } } } diff --git a/src/Microsoft.ComponentDetection.Contracts/ScanRequest.cs b/src/Microsoft.ComponentDetection.Contracts/ScanRequest.cs index 62d7fc75c..26108919f 100644 --- a/src/Microsoft.ComponentDetection.Contracts/ScanRequest.cs +++ b/src/Microsoft.ComponentDetection.Contracts/ScanRequest.cs @@ -15,11 +15,11 @@ public class ScanRequest /// Detector component recorder. public ScanRequest(DirectoryInfo sourceDirectory, ExcludeDirectoryPredicate directoryExclusionPredicate, ILogger logger, IDictionary detectorArgs, IEnumerable imagesToScan, IComponentRecorder componentRecorder) { - SourceDirectory = sourceDirectory; - DirectoryExclusionPredicate = directoryExclusionPredicate; - DetectorArgs = detectorArgs; - ImagesToScan = imagesToScan; - ComponentRecorder = componentRecorder; + this.SourceDirectory = sourceDirectory; + this.DirectoryExclusionPredicate = directoryExclusionPredicate; + this.DetectorArgs = detectorArgs; + this.ImagesToScan = imagesToScan; + this.ComponentRecorder = componentRecorder; } /// Gets the source directory to consider the working directory for the detection operation. diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs index 0859dd0f6..ca196e6b6 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs @@ -11,8 +11,8 @@ private CargoComponent() public CargoComponent(string name, string version) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Cargo)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Cargo)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Cargo)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Cargo)); } public string Name { get; set; } @@ -21,8 +21,8 @@ public CargoComponent(string name, string version) public override ComponentType Type => ComponentType.Cargo; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("cargo", string.Empty, Name, Version, null, string.Empty); + public override PackageURL PackageUrl => new PackageURL("cargo", string.Empty, this.Name, this.Version, null, string.Empty); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs index feddfebd1..55637e208 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs @@ -9,14 +9,14 @@ private CondaComponent() public CondaComponent(string name, string version, string build, string channel, string subdir, string @namespace, string url, string md5) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Conda)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Conda)); - Build = build; - Channel = channel; - Subdir = subdir; - Namespace = @namespace; - Url = url; - MD5 = md5; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Conda)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Conda)); + this.Build = build; + this.Channel = channel; + this.Subdir = subdir; + this.Namespace = @namespace; + this.Url = url; + this.MD5 = md5; } public string Build { get; set; } @@ -37,6 +37,6 @@ public CondaComponent(string name, string version, string build, string channel, public override ComponentType Type => ComponentType.Conda; - public override string Id => $"{Name} {Version} {Build} {Channel} {Subdir} {Namespace} {Url} {MD5} - {Type}"; + public override string Id => $"{this.Name} {this.Version} {this.Build} {this.Channel} {this.Subdir} {this.Namespace} {this.Url} {this.MD5} - {this.Type}"; } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs index 27916aa41..c104665ff 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs @@ -6,12 +6,12 @@ private DockerImageComponent() { /* Reserved for deserialization */ } - + public DockerImageComponent(string hash, string name = null, string tag = null) { - Digest = ValidateRequiredInput(hash, nameof(Digest), nameof(ComponentType.DockerImage)); - Name = name; - Tag = tag; + this.Digest = this.ValidateRequiredInput(hash, nameof(this.Digest), nameof(ComponentType.DockerImage)); + this.Name = name; + this.Tag = tag; } public string Name { get; set; } @@ -22,6 +22,6 @@ public DockerImageComponent(string hash, string name = null, string tag = null) public override ComponentType Type => ComponentType.DockerImage; - public override string Id => $"{Name} {Tag} {Digest}"; + public override string Id => $"{this.Name} {this.Tag} {this.Digest}"; } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs index 0c99b229b..5ad27a1ed 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs @@ -7,19 +7,18 @@ private DockerReferenceComponent() /* Reserved for deserialization */ } - public DockerReferenceComponent(string hash, string name = null, string tag = null) + public DockerReferenceComponent(string hash, string repository = null, string tag = null) { - Digest = ValidateRequiredInput(hash, nameof(Digest), nameof(ComponentType.DockerReference)); - Name = name; - Tag = tag; - } + this.Digest = this.ValidateRequiredInput(hash, nameof(this.Digest), nameof(ComponentType.DockerReference)); + this.Repository = repository; + this.Tag = tag; + } public DockerReferenceComponent(DockerReference reference) { - FullReference = reference; - } + } - public string Name { get; set; } + public string Repository { get; set; } public string Digest { get; set; } @@ -29,8 +28,14 @@ public DockerReferenceComponent(DockerReference reference) public override ComponentType Type => ComponentType.DockerReference; - public DockerReference FullReference { get; set; } + public DockerReference FullReference + { + get + { + return DockerReference.CreateDockerReference(this.Repository, this.Domain, this.Digest, this.Tag); + } + } - public override string Id => $"{Name} {Tag} {Digest}"; + public override string Id => $"{this.Repository} {this.Tag} {this.Digest}"; } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs index 0da30ec3e..fd1fb3bfd 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs @@ -11,14 +11,14 @@ private GitComponent() public GitComponent(Uri repositoryUrl, string commitHash) { - RepositoryUrl = ValidateRequiredInput(repositoryUrl, nameof(RepositoryUrl), nameof(ComponentType.Git)); - CommitHash = ValidateRequiredInput(commitHash, nameof(CommitHash), nameof(ComponentType.Git)); + this.RepositoryUrl = this.ValidateRequiredInput(repositoryUrl, nameof(this.RepositoryUrl), nameof(ComponentType.Git)); + this.CommitHash = this.ValidateRequiredInput(commitHash, nameof(this.CommitHash), nameof(ComponentType.Git)); } public GitComponent(Uri repositoryUrl, string commitHash, string tag) : this(repositoryUrl, commitHash) { - Tag = tag; + this.Tag = tag; } public Uri RepositoryUrl { get; set; } @@ -29,6 +29,6 @@ public GitComponent(Uri repositoryUrl, string commitHash, string tag) public override ComponentType Type => ComponentType.Git; - public override string Id => $"{RepositoryUrl} : {CommitHash} - {Type}"; + public override string Id => $"{this.RepositoryUrl} : {this.CommitHash} - {this.Type}"; } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs index d6bb745ba..ad6cca046 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs @@ -12,16 +12,16 @@ private GoComponent() public GoComponent(string name, string version) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Go)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Go)); - Hash = string.Empty; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Go)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Go)); + this.Hash = string.Empty; } public GoComponent(string name, string version, string hash) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Go)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Go)); - Hash = ValidateRequiredInput(hash, nameof(Hash), nameof(ComponentType.Go)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Go)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Go)); + this.Hash = this.ValidateRequiredInput(hash, nameof(this.Hash), nameof(ComponentType.Go)); } public string Name { get; set; } @@ -32,12 +32,12 @@ public GoComponent(string name, string version, string hash) public override ComponentType Type => ComponentType.Go; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; public override bool Equals(object other) { - GoComponent otherComponent = other as GoComponent; - return otherComponent != null && Equals(otherComponent); + var otherComponent = other as GoComponent; + return otherComponent != null && this.Equals(otherComponent); } public bool Equals(GoComponent other) @@ -47,18 +47,16 @@ public bool Equals(GoComponent other) return false; } - return Name == other.Name && - Version == other.Version && - Hash == other.Hash; + return this.Name == other.Name && this.Version == other.Version && this.Hash == other.Hash; } public override int GetHashCode() { - return Name.GetHashCode() ^ Version.GetHashCode() ^ Hash.GetHashCode(); + return this.Name.GetHashCode() ^ this.Version.GetHashCode() ^ this.Hash.GetHashCode(); } // Commit should be used in place of version when available // https://github.com/package-url/purl-spec/blame/180c46d266c45aa2bd81a2038af3f78e87bb4a25/README.rst#L610 - public override PackageURL PackageUrl => new PackageURL("golang", null, Name, string.IsNullOrWhiteSpace(Hash) ? Version : Hash, null, null); + public override PackageURL PackageUrl => new PackageURL("golang", null, this.Name, string.IsNullOrWhiteSpace(this.Hash) ? this.Version : this.Hash, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs index 0b03bb5a3..30f18aaf0 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs @@ -11,10 +11,10 @@ private LinuxComponent() public LinuxComponent(string distribution, string release, string name, string version) { - Distribution = ValidateRequiredInput(distribution, nameof(Distribution), nameof(ComponentType.Linux)); - Release = ValidateRequiredInput(release, nameof(Release), nameof(ComponentType.Linux)); - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Linux)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Linux)); + this.Distribution = this.ValidateRequiredInput(distribution, nameof(this.Distribution), nameof(ComponentType.Linux)); + this.Release = this.ValidateRequiredInput(release, nameof(this.Release), nameof(ComponentType.Linux)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Linux)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Linux)); } public string Distribution { get; set; } @@ -27,7 +27,7 @@ public LinuxComponent(string distribution, string release, string name, string v public override ComponentType Type => ComponentType.Linux; - public override string Id => $"{Distribution} {Release} {Name} {Version} - {Type}"; + public override string Id => $"{this.Distribution} {this.Release} {this.Name} {this.Version} - {this.Type}"; public override PackageURL PackageUrl { @@ -35,18 +35,18 @@ public override PackageURL PackageUrl { string packageType = null; - if (IsUbuntu() || IsDebian()) + if (this.IsUbuntu() || this.IsDebian()) { packageType = "deb"; } - else if (IsCentOS() || IsFedora() || IsRHEL()) + else if (this.IsCentOS() || this.IsFedora() || this.IsRHEL()) { packageType = "rpm"; } if (packageType != null) { - return new PackageURL(packageType, Distribution, Name, Version, null, null); + return new PackageURL(packageType, this.Distribution, this.Name, this.Version, null, null); } return null; @@ -55,27 +55,27 @@ public override PackageURL PackageUrl private bool IsUbuntu() { - return Distribution.ToLowerInvariant() == "ubuntu"; + return this.Distribution.ToLowerInvariant() == "ubuntu"; } private bool IsDebian() { - return Distribution.ToLowerInvariant() == "debian"; + return this.Distribution.ToLowerInvariant() == "debian"; } private bool IsCentOS() { - return Distribution.ToLowerInvariant() == "centos"; + return this.Distribution.ToLowerInvariant() == "centos"; } private bool IsFedora() { - return Distribution.ToLowerInvariant() == "fedora"; + return this.Distribution.ToLowerInvariant() == "fedora"; } private bool IsRHEL() { - return Distribution.ToLowerInvariant() == "red hat enterprise linux"; + return this.Distribution.ToLowerInvariant() == "red hat enterprise linux"; } } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs index b418ead37..a644b052f 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs @@ -11,9 +11,9 @@ private MavenComponent() public MavenComponent(string groupId, string artifactId, string version) { - GroupId = ValidateRequiredInput(groupId, nameof(GroupId), nameof(ComponentType.Maven)); - ArtifactId = ValidateRequiredInput(artifactId, nameof(ArtifactId), nameof(ComponentType.Maven)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Maven)); + this.GroupId = this.ValidateRequiredInput(groupId, nameof(this.GroupId), nameof(ComponentType.Maven)); + this.ArtifactId = this.ValidateRequiredInput(artifactId, nameof(this.ArtifactId), nameof(ComponentType.Maven)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Maven)); } public string GroupId { get; set; } @@ -24,8 +24,8 @@ public MavenComponent(string groupId, string artifactId, string version) public override ComponentType Type => ComponentType.Maven; - public override string Id => $"{GroupId} {ArtifactId} {Version} - {Type}"; + public override string Id => $"{this.GroupId} {this.ArtifactId} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("maven", GroupId, ArtifactId, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("maven", this.GroupId, this.ArtifactId, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs index afad4cdf8..c656caebc 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs @@ -12,10 +12,10 @@ private NpmComponent() public NpmComponent(string name, string version, string hash = null, NpmAuthor author = null) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Npm)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Npm)); - Hash = hash; // Not required; only found in package-lock.json, not package.json - Author = author; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Npm)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Npm)); + this.Hash = hash; // Not required; only found in package-lock.json, not package.json + this.Author = author; } public string Name { get; set; } @@ -28,8 +28,8 @@ public NpmComponent(string name, string version, string hash = null, NpmAuthor a public override ComponentType Type => ComponentType.Npm; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("npm", null, Name, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("npm", null, this.Name, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs index cfbcdf15e..683d95d92 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs @@ -11,9 +11,9 @@ private NuGetComponent() public NuGetComponent(string name, string version, string[] authors = null) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.NuGet)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.NuGet)); - Authors = authors; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.NuGet)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.NuGet)); + this.Authors = authors; } public string Name { get; set; } @@ -24,8 +24,8 @@ public NuGetComponent(string name, string version, string[] authors = null) public override ComponentType Type => ComponentType.NuGet; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("nuget", null, Name, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("nuget", null, this.Name, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs index 063552227..584cd34b7 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs @@ -11,10 +11,10 @@ private OtherComponent() public OtherComponent(string name, string version, Uri downloadUrl, string hash) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Other)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Other)); - DownloadUrl = ValidateRequiredInput(downloadUrl, nameof(DownloadUrl), nameof(ComponentType.Other)); - Hash = hash; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Other)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Other)); + this.DownloadUrl = this.ValidateRequiredInput(downloadUrl, nameof(this.DownloadUrl), nameof(ComponentType.Other)); + this.Hash = hash; } public string Name { get; set; } @@ -27,6 +27,6 @@ public OtherComponent(string name, string version, Uri downloadUrl, string hash) public override ComponentType Type => ComponentType.Other; - public override string Id => $"{Name} {Version} {DownloadUrl} - {Type}"; + public override string Id => $"{this.Name} {this.Version} {this.DownloadUrl} - {this.Type}"; } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs index b11792f17..e83365e2e 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs @@ -11,8 +11,8 @@ private PipComponent() public PipComponent(string name, string version) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Pip)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Pip)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Pip)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Pip)); } public string Name { get; set; } @@ -21,8 +21,8 @@ public PipComponent(string name, string version) public override ComponentType Type => ComponentType.Pip; - public override string Id => $"{Name} {Version} - {Type}".ToLowerInvariant(); + public override string Id => $"{this.Name} {this.Version} - {this.Type}".ToLowerInvariant(); - public override PackageURL PackageUrl => new PackageURL("pypi", null, Name, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("pypi", null, this.Name, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs index ee958473c..3a2fa8ab4 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs @@ -12,9 +12,9 @@ private PodComponent() public PodComponent(string name, string version, string specRepo = "") { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Pod)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Pod)); - SpecRepo = specRepo; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Pod)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Pod)); + this.SpecRepo = specRepo; } public string Name { get; set; } @@ -25,19 +25,19 @@ public PodComponent(string name, string version, string specRepo = "") public override ComponentType Type => ComponentType.Pod; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; public override PackageURL PackageUrl { - get + get { var qualifiers = new SortedDictionary(); - if (!string.IsNullOrWhiteSpace(SpecRepo)) + if (!string.IsNullOrWhiteSpace(this.SpecRepo)) { - qualifiers.Add("repository_url", SpecRepo); + qualifiers.Add("repository_url", this.SpecRepo); } - return new PackageURL("cocoapods", null, Name, Version, qualifiers, null); + return new PackageURL("cocoapods", null, this.Name, this.Version, qualifiers, null); } } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs index 2b6779a67..130e4acdb 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs @@ -11,9 +11,9 @@ private RubyGemsComponent() public RubyGemsComponent(string name, string version, string source = "") { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.RubyGems)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.RubyGems)); - Source = source; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.RubyGems)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.RubyGems)); + this.Source = source; } public string Name { get; set; } @@ -24,8 +24,8 @@ public RubyGemsComponent(string name, string version, string source = "") public override ComponentType Type => ComponentType.RubyGems; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("gem", null, Name, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("gem", null, this.Name, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs index 5ec716c5e..1dac70180 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs @@ -12,13 +12,12 @@ private SpdxComponent() public SpdxComponent(string spdxVersion, Uri documentNamespace, string name, string checksum, string rootElementId, string path) { - SpdxVersion = ValidateRequiredInput(spdxVersion, nameof(SpdxVersion), nameof(ComponentType.Spdx)); - DocumentNamespace = - ValidateRequiredInput(documentNamespace, nameof(DocumentNamespace), nameof(ComponentType.Spdx)); - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Spdx)); - Checksum = ValidateRequiredInput(checksum, nameof(Checksum), nameof(ComponentType.Spdx)); - RootElementId = ValidateRequiredInput(rootElementId, nameof(RootElementId), nameof(ComponentType.Spdx)); - Path = ValidateRequiredInput(path, nameof(Path), nameof(ComponentType.Spdx)); + this.SpdxVersion = this.ValidateRequiredInput(spdxVersion, nameof(this.SpdxVersion), nameof(ComponentType.Spdx)); + this.DocumentNamespace = this.ValidateRequiredInput(documentNamespace, nameof(this.DocumentNamespace), nameof(ComponentType.Spdx)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Spdx)); + this.Checksum = this.ValidateRequiredInput(checksum, nameof(this.Checksum), nameof(ComponentType.Spdx)); + this.RootElementId = this.ValidateRequiredInput(rootElementId, nameof(this.RootElementId), nameof(ComponentType.Spdx)); + this.Path = this.ValidateRequiredInput(path, nameof(this.Path), nameof(ComponentType.Spdx)); } public override ComponentType Type => ComponentType.Spdx; @@ -35,6 +34,6 @@ public SpdxComponent(string spdxVersion, Uri documentNamespace, string name, str public string Path { get; } - public override string Id => $"{Name}-{SpdxVersion}-{Checksum}"; + public override string Id => $"{this.Name}-{this.SpdxVersion}-{this.Checksum}"; } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs index 0bf401458..503ff4591 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs @@ -28,19 +28,19 @@ internal TypedComponent() public virtual PackageURL PackageUrl { get; } [JsonIgnore] - internal string DebuggerDisplay => $"{Id}"; + internal string DebuggerDisplay => $"{this.Id}"; protected string ValidateRequiredInput(string input, string fieldName, string componentType) { return string.IsNullOrWhiteSpace(input) - ? throw new ArgumentNullException(fieldName, NullPropertyExceptionMessage(fieldName, componentType)) + ? throw new ArgumentNullException(fieldName, this.NullPropertyExceptionMessage(fieldName, componentType)) : input; } protected T ValidateRequiredInput(T input, string fieldName, string componentType) { // Null coalescing for generic types is not available until C# 8 - return EqualityComparer.Default.Equals(input, default(T)) ? throw new ArgumentNullException(fieldName, NullPropertyExceptionMessage(fieldName, componentType)) : input; + return EqualityComparer.Default.Equals(input, default(T)) ? throw new ArgumentNullException(fieldName, this.NullPropertyExceptionMessage(fieldName, componentType)) : input; } protected string NullPropertyExceptionMessage(string propertyName, string componentType) diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs index 41037f922..3765b6632 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs @@ -1,4 +1,4 @@ -using PackageUrl; +using PackageUrl; namespace Microsoft.ComponentDetection.Contracts.TypedComponent { @@ -11,13 +11,15 @@ private VcpkgComponent() public VcpkgComponent(string spdxid, string name, string version, string triplet = null, string portVersion = null, string description = null, string downloadLocation = null) { - SPDXID = ValidateRequiredInput(spdxid, nameof(SPDXID), nameof(ComponentType.Vcpkg)); - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Vcpkg)); - Version = version; - PortVersion = portVersion; - Triplet = triplet; - Description = description; - DownloadLocation = downloadLocation; + int.TryParse(portVersion, out var port); + + this.SPDXID = this.ValidateRequiredInput(spdxid, nameof(this.SPDXID), nameof(ComponentType.Vcpkg)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Vcpkg)); + this.Version = version; + this.PortVersion = port; + this.Triplet = triplet; + this.Description = description; + this.DownloadLocation = downloadLocation; } public string SPDXID { get; set; } @@ -32,7 +34,7 @@ public VcpkgComponent(string spdxid, string name, string version, string triplet public string Description { get; set; } - public string PortVersion { get; set; } + public int PortVersion { get; set; } public override ComponentType Type => ComponentType.Vcpkg; @@ -40,13 +42,13 @@ public override string Id { get { - if (PortVersion != null) + if (this.PortVersion > 0) { - return $"{Name} {Version}#{PortVersion} - {Type}"; + return $"{this.Name} {this.Version}#{this.PortVersion} - {this.Type}"; } else { - return $"{Name} {Version} - {Type}"; + return $"{this.Name} {this.Version} - {this.Type}"; } } } @@ -55,17 +57,17 @@ public override PackageURL PackageUrl { get { - if (PortVersion != null) + if (this.PortVersion > 0) { - return new PackageURL($"pkg:vcpkg/{Name}@{Version}?port_version={PortVersion}"); + return new PackageURL($"pkg:vcpkg/{this.Name}@{this.Version}?port_version={this.PortVersion}"); } - else if (Version != null) + else if (this.Version != null) { - return new PackageURL($"pkg:vcpkg/{Name}@{Version}"); + return new PackageURL($"pkg:vcpkg/{this.Name}@{this.Version}"); } else { - return new PackageURL($"pkg:vcpkg/{Name}"); + return new PackageURL($"pkg:vcpkg/{this.Name}"); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs index a368ac227..cec5a37c4 100644 --- a/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs @@ -35,9 +35,9 @@ private class Pod : IYamlConvertible public IList Dependencies { get; set; } - public string Podspec => Name.Split('/', 2)[0]; + public string Podspec => this.Name.Split('/', 2)[0]; - public bool IsSubspec => Name != Podspec; + public bool IsSubspec => this.Name != this.Podspec; public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { @@ -49,18 +49,18 @@ public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObj var podInfo = parser.Consume(); var components = podInfo.Value.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries); - Name = components[0].Trim(); - Version = components[1].Trim(); + this.Name = components[0].Trim(); + this.Version = components[1].Trim(); if (hasDependencies) { - Dependencies = (IList)nestedObjectDeserializer(typeof(IList)); + this.Dependencies = (IList)nestedObjectDeserializer(typeof(IList)); parser.Consume(); } else { - Dependencies = Array.Empty(); + this.Dependencies = Array.Empty(); } } @@ -76,16 +76,16 @@ private class PodDependency : IYamlConvertible public string PodVersion { get; set; } - public string Podspec => PodName.Split('/', 2)[0]; + public string Podspec => this.PodName.Split('/', 2)[0]; - public bool IsSubspec => PodName != Podspec; + public bool IsSubspec => this.PodName != this.Podspec; public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { var scalar = parser.Consume(); var components = scalar.Value.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries); - PodName = components[0].Trim(); - PodVersion = components.Length > 1 ? components[1].Trim() : null; + this.PodName = components[0].Trim(); + this.PodVersion = components.Length > 1 ? components[1].Trim() : null; } public void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) @@ -122,17 +122,17 @@ private class PodfileLock public PodfileLock() { - Dependencies = Array.Empty(); - PodspecRepositories = new Dictionary>(); - PodspecChecksums = new Dictionary(); - ExternalSources = new Dictionary>(); - CheckoutOptions = new Dictionary>(); - Pods = Array.Empty(); + this.Dependencies = Array.Empty(); + this.PodspecRepositories = new Dictionary>(); + this.PodspecChecksums = new Dictionary(); + this.ExternalSources = new Dictionary>(); + this.CheckoutOptions = new Dictionary>(); + this.Pods = Array.Empty(); } public string GetSpecRepositoryOfSpec(string specName) { - foreach (var repository in PodspecRepositories) + foreach (var repository in this.PodspecRepositories) { if (repository.Value.Contains(specName)) { @@ -159,17 +159,17 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - Logger.LogVerbose($"Found {file.Pattern}: {file.Location}"); + this.Logger.LogVerbose($"Found {file.Pattern}: {file.Location}"); try { var podfileLock = await ParsePodfileLock(file); - ProcessPodfileLock(singleFileComponentRecorder, podfileLock); + this.ProcessPodfileLock(singleFileComponentRecorder, podfileLock); } catch (Exception e) { - Logger.LogFailedReadingFile(file.Location, e); + this.Logger.LogFailedReadingFile(file.Location, e); } } @@ -205,7 +205,7 @@ private void ProcessPodfileLock( // Check if the pod is a root component and add it to the list of discovered components if (rootPodspecs.Contains(pod.Podspec)) { - if (nonRootComponents.TryGetValue(key, out DetectedComponent existingComponent)) + if (nonRootComponents.TryGetValue(key, out var existingComponent)) { rootComponents.TryAdd(key, existingComponent); nonRootComponents.Remove(key); @@ -241,9 +241,9 @@ private void ProcessPodfileLock( // Check if the Podspec comes from a git repository or not TypedComponent typedComponent; string key; - if (podfileLock.CheckoutOptions.TryGetValue(pod.Podspec, out IDictionary checkoutOptions) - && checkoutOptions.TryGetValue(":git", out string gitOption) - && checkoutOptions.TryGetValue(":commit", out string commitOption)) + if (podfileLock.CheckoutOptions.TryGetValue(pod.Podspec, out var checkoutOptions) + && checkoutOptions.TryGetValue(":git", out var gitOption) + && checkoutOptions.TryGetValue(":commit", out var commitOption)) { // Create the Git component gitOption = NormalizePodfileGitUri(gitOption); @@ -265,7 +265,7 @@ private void ProcessPodfileLock( // Check if the pod is a root component and add it to the list of discovered components if (rootPodspecs.Contains(pod.Podspec)) { - if (nonRootComponents.TryGetValue(key, out DetectedComponent existingComponent)) + if (nonRootComponents.TryGetValue(key, out var existingComponent)) { rootComponents.TryAdd(key, existingComponent); nonRootComponents.Remove(key); @@ -284,7 +284,7 @@ private void ProcessPodfileLock( podSpecs.TryAdd(pod.Podspec, key); // Update the pod dependencies map - if (podDependencies.TryGetValue(key, out List dependencies)) + if (podDependencies.TryGetValue(key, out var dependencies)) { dependencies.AddRange(pod.Dependencies); } @@ -301,7 +301,7 @@ private void ProcessPodfileLock( foreach (var dependency in pod.Value) { - if (podSpecs.TryGetValue(dependency.Podspec, out string dependencyKey)) + if (podSpecs.TryGetValue(dependency.Podspec, out var dependencyKey)) { if (dependencyKey != pod.Key) { @@ -311,7 +311,7 @@ private void ProcessPodfileLock( } else { - Logger.LogWarning($"Missing podspec declaration. podspec={dependency.Podspec}, version={dependency.PodVersion}"); + this.Logger.LogWarning($"Missing podspec declaration. podspec={dependency.Podspec}, version={dependency.PodVersion}"); } } } @@ -335,7 +335,7 @@ private void ProcessPodfileLock( { var dependency = dependencies.Dequeue(); - if (rootComponents.TryGetValue(dependency, out DetectedComponent detectedRootComponent)) + if (rootComponents.TryGetValue(dependency, out var detectedRootComponent)) { // Found another root component singleFileComponentRecorder.RegisterUsage( @@ -343,7 +343,7 @@ private void ProcessPodfileLock( isExplicitReferencedDependency: true, parentComponentId: rootComponent.Value.Component.Id); } - else if (nonRootComponents.TryGetValue(dependency, out DetectedComponent detectedComponent)) + else if (nonRootComponents.TryGetValue(dependency, out var detectedComponent)) { singleFileComponentRecorder.RegisterUsage( detectedComponent, @@ -351,7 +351,7 @@ private void ProcessPodfileLock( parentComponentId: rootComponent.Value.Component.Id); // Add the new dependecies to the queue - if (dependenciesMap.TryGetValue(dependency, out HashSet newDependencies)) + if (dependenciesMap.TryGetValue(dependency, out var newDependencies)) { newDependencies.ToList().ForEach(dependencies.Enqueue); } @@ -385,9 +385,9 @@ private static (Pod pod, string key, DetectedComponent detectedComponent)[] Read // Check if the Podspec comes from a git repository or not TypedComponent typedComponent; string key; - if (podfileLock.CheckoutOptions.TryGetValue(pod.Podspec, out IDictionary checkoutOptions) - && checkoutOptions.TryGetValue(":git", out string gitOption) - && checkoutOptions.TryGetValue(":commit", out string commitOption)) + if (podfileLock.CheckoutOptions.TryGetValue(pod.Podspec, out var checkoutOptions) + && checkoutOptions.TryGetValue(":git", out var gitOption) + && checkoutOptions.TryGetValue(":commit", out var commitOption)) { // Create the Git component gitOption = NormalizePodfileGitUri(gitOption); diff --git a/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs index f13691d14..7818e4dc5 100644 --- a/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs @@ -14,7 +14,7 @@ namespace Microsoft.ComponentDetection.Detectors.Dockerfile { [Export(typeof(IComponentDetector))] - public class DockerfileComponentDetector : FileComponentDetector + public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffComponentDetector { [Import] public ICommandLineInvocationService CommandLineInvocationService { get; set; } @@ -22,9 +22,9 @@ public class DockerfileComponentDetector : FileComponentDetector [Import] public IEnvironmentVariableService EnvVarService { get; set; } - public override string Id { get; } = "Docker Reference"; + public override string Id { get; } = "DockerReference"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod) }; + public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.DockerReference) }; public override IList SearchPatterns { get; } = new List { "dockerfile", "dockerfile.*", "*.dockerfile" }; @@ -39,7 +39,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; var filePath = file.Location; - Logger.LogInfo($"Discovered dockerfile: {file.Location}"); + this.Logger.LogInfo($"Discovered dockerfile: {file.Location}"); string contents; using (var reader = new StreamReader(file.Stream)) @@ -48,7 +48,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio } var stageNameMap = new Dictionary(); - var dockerFileComponent = ParseDockerFile(contents, file.Location, singleFileComponentRecorder, stageNameMap); + var dockerFileComponent = this.ParseDockerFile(contents, file.Location, singleFileComponentRecorder, stageNameMap); } private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFileComponentRecorder singleFileComponentRecorder, Dictionary stageNameMap) @@ -57,7 +57,7 @@ private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFi var instructions = dockerfileModel.Items; foreach (var instruction in instructions) { - var imageReference = ProcessDockerfileConstruct(instruction, dockerfileModel.EscapeChar, stageNameMap); + var imageReference = this.ProcessDockerfileConstruct(instruction, dockerfileModel.EscapeChar, stageNameMap); if (imageReference != null) { singleFileComponentRecorder.RegisterUsage(new DetectedComponent(imageReference.ToTypedDockerReferenceComponent())); @@ -69,33 +69,41 @@ private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFi private DockerReference ProcessDockerfileConstruct(DockerfileConstruct construct, char escapeChar, Dictionary stageNameMap) { - var instructionKeyword = construct.Type; - DockerReference baseImage = null; - if (instructionKeyword == ConstructType.Instruction) - { - var constructType = construct.GetType().Name; - switch (constructType) + try + { + var instructionKeyword = construct.Type; + DockerReference baseImage = null; + if (instructionKeyword == ConstructType.Instruction) { - case "FromInstruction": - baseImage = ParseFromInstruction(construct, escapeChar, stageNameMap); - break; - case "CopyInstruction": - baseImage = ParseCopyInstruction(construct, escapeChar, stageNameMap); - break; - default: - break; + var constructType = construct.GetType().Name; + switch (constructType) + { + case "FromInstruction": + baseImage = this.ParseFromInstruction(construct, escapeChar, stageNameMap); + break; + case "CopyInstruction": + baseImage = this.ParseCopyInstruction(construct, escapeChar, stageNameMap); + break; + default: + break; + } } - } - return baseImage; + return baseImage; + } catch (Exception e) + { + this.Logger.LogError($"Failed to detect a DockerReference component, the component will not be registered. \n Error Message: <{e.Message}>"); + this.Logger.LogException(e, isError: true, printException: true); + return null; + } } private DockerReference ParseFromInstruction(DockerfileConstruct construct, char escapeChar, Dictionary stageNameMap) { var tokens = construct.Tokens.ToArray(); var resolvedFromStatement = construct.ResolveVariables(escapeChar).TrimEnd(); - var fromInstruction = (Valleysoft.DockerfileModel.FromInstruction)construct; - string reference = fromInstruction.ImageName; + var fromInstruction = (FromInstruction)construct; + var reference = fromInstruction.ImageName; if (string.IsNullOrWhiteSpace(resolvedFromStatement) || string.IsNullOrEmpty(reference)) { return null; @@ -118,7 +126,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char if (!string.IsNullOrEmpty(stageNameReference)) { - if (HasUnresolvedVariables(stageNameReference)) + if (this.HasUnresolvedVariables(stageNameReference)) { return null; } @@ -126,7 +134,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char return DockerReferenceUtility.ParseFamiliarName(stageNameReference); } - if (HasUnresolvedVariables(reference)) + if (this.HasUnresolvedVariables(reference)) { return null; } @@ -137,7 +145,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char escapeChar, Dictionary stageNameMap) { var resolvedCopyStatement = construct.ResolveVariables(escapeChar).TrimEnd(); - var copyInstruction = (Valleysoft.DockerfileModel.CopyInstruction)construct; + var copyInstruction = (CopyInstruction)construct; var reference = copyInstruction.FromStageName; if (string.IsNullOrWhiteSpace(resolvedCopyStatement) || string.IsNullOrWhiteSpace(reference)) { @@ -147,7 +155,7 @@ private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char stageNameMap.TryGetValue(reference, out var stageNameReference); if (!string.IsNullOrEmpty(stageNameReference)) { - if (HasUnresolvedVariables(stageNameReference)) + if (this.HasUnresolvedVariables(stageNameReference)) { return null; } @@ -157,7 +165,7 @@ private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char } } - if (HasUnresolvedVariables(reference)) + if (this.HasUnresolvedVariables(reference)) { return null; } diff --git a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs index 705216a91..f475d3658 100644 --- a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs @@ -3,7 +3,6 @@ using System.Composition; using System.IO; using System.Linq; -using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.ComponentDetection.Common.Telemetry.Records; @@ -45,7 +44,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var file = processRequest.ComponentStream; var projectRootDirectory = Directory.GetParent(file.Location); - if (projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) + if (this.projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) { return; } @@ -53,26 +52,26 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var wasGoCliScanSuccessful = false; try { - if (!IsGoCliManuallyDisabled()) + if (!this.IsGoCliManuallyDisabled()) { - wasGoCliScanSuccessful = await UseGoCliToScan(file.Location, singleFileComponentRecorder); + wasGoCliScanSuccessful = await this.UseGoCliToScan(file.Location, singleFileComponentRecorder); } else { - Logger.LogInfo("Go cli scan was manually disabled, fallback strategy performed." + - " More info: https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy"); + this.Logger.LogInfo("Go cli scan was manually disabled, fallback strategy performed." + + " More info: https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy"); } } catch (Exception ex) { - Logger.LogError($"Failed to detect components using go cli. Location: {file.Location}"); - Logger.LogException(ex, isError: true, printException: true); + this.Logger.LogError($"Failed to detect components using go cli. Location: {file.Location}"); + this.Logger.LogException(ex, isError: true, printException: true); } finally { if (wasGoCliScanSuccessful) { - projectRoots.Add(projectRootDirectory.FullName); + this.projectRoots.Add(projectRootDirectory.FullName); } else { @@ -81,15 +80,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio { case ".mod": { - Logger.LogVerbose("Found Go.mod: " + file.Location); - ParseGoModFile(singleFileComponentRecorder, file); + this.Logger.LogVerbose("Found Go.mod: " + file.Location); + this.ParseGoModFile(singleFileComponentRecorder, file); break; } case ".sum": { - Logger.LogVerbose("Found Go.sum: " + file.Location); - ParseGoSumFile(singleFileComponentRecorder, file); + this.Logger.LogVerbose("Found Go.sum: " + file.Location); + this.ParseGoSumFile(singleFileComponentRecorder, file); break; } @@ -110,32 +109,32 @@ private async Task UseGoCliToScan(string location, ISingleFileComponentRec var projectRootDirectory = Directory.GetParent(location); record.ProjectRoot = projectRootDirectory.FullName; - var isGoAvailable = await CommandLineInvocationService.CanCommandBeLocated("go", null, workingDirectory: projectRootDirectory, new[] { "version" }); + var isGoAvailable = await this.CommandLineInvocationService.CanCommandBeLocated("go", null, workingDirectory: projectRootDirectory, new[] { "version" }); record.IsGoAvailable = isGoAvailable; if (!isGoAvailable) { - Logger.LogInfo("Go CLI was not found in the system"); + this.Logger.LogInfo("Go CLI was not found in the system"); return false; } - Logger.LogInfo("Go CLI was found in system and will be used to generate dependency graph. " + - "Detection time may be improved by activating fallback strategy (https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy). " + - "But, it will introduce noise into the detected components."); - var goDependenciesProcess = await CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-m", "-json", "all" }); + this.Logger.LogInfo("Go CLI was found in system and will be used to generate dependency graph. " + + "Detection time may be improved by activating fallback strategy (https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy). " + + "But, it will introduce noise into the detected components."); + var goDependenciesProcess = await this.CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-m", "-json", "all" }); if (goDependenciesProcess.ExitCode != 0) { - Logger.LogError($"Go CLI command \"go list -m -json all\" failed with error:\n {goDependenciesProcess.StdErr}"); - Logger.LogError($"Go CLI could not get dependency build list at location: {location}. Fallback go.sum/go.mod parsing will be used."); + this.Logger.LogError($"Go CLI command \"go list -m -json all\" failed with error:\n {goDependenciesProcess.StdErr}"); + this.Logger.LogError($"Go CLI could not get dependency build list at location: {location}. Fallback go.sum/go.mod parsing will be used."); return false; } - RecordBuildDependencies(goDependenciesProcess.StdOut, singleFileComponentRecorder); + this.RecordBuildDependencies(goDependenciesProcess.StdOut, singleFileComponentRecorder); - var generateGraphProcess = await CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new List { "mod", "graph" }.ToArray()); + var generateGraphProcess = await this.CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new List { "mod", "graph" }.ToArray()); if (generateGraphProcess.ExitCode == 0) { - PopulateDependencyGraph(generateGraphProcess.StdOut, singleFileComponentRecorder); + this.PopulateDependencyGraph(generateGraphProcess.StdOut, singleFileComponentRecorder); record.WasGraphSuccessful = true; } @@ -148,7 +147,7 @@ private void ParseGoModFile( { using var reader = new StreamReader(file.Stream); - string line = reader.ReadLine(); + var line = reader.ReadLine(); while (line != null && !line.StartsWith("require (")) { line = reader.ReadLine(); @@ -157,13 +156,13 @@ private void ParseGoModFile( // Stopping at the first ) restrict the detection to only the require section. while ((line = reader.ReadLine()) != null && !line.EndsWith(")")) { - if (TryToCreateGoComponentFromModLine(line, out var goComponent)) + if (this.TryToCreateGoComponentFromModLine(line, out var goComponent)) { singleFileComponentRecorder.RegisterUsage(new DetectedComponent(goComponent)); } else { - Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]"); + this.Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]"); } } } @@ -185,8 +184,8 @@ private bool TryToCreateGoComponentFromModLine(string line, out GoComponent goCo return true; } - //For more information about the format of the go.sum file - //visit https://golang.org/cmd/go/#hdr-Module_authentication_using_go_sum + // For more information about the format of the go.sum file + // visit https://golang.org/cmd/go/#hdr-Module_authentication_using_go_sum private void ParseGoSumFile( ISingleFileComponentRecorder singleFileComponentRecorder, IComponentStream file) @@ -196,20 +195,20 @@ private void ParseGoSumFile( string line; while ((line = reader.ReadLine()) != null) { - if (TryToCreateGoComponentFromSumLine(line, out var goComponent)) + if (this.TryToCreateGoComponentFromSumLine(line, out var goComponent)) { singleFileComponentRecorder.RegisterUsage(new DetectedComponent(goComponent)); } else { - Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]"); + this.Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]"); } } } private bool TryToCreateGoComponentFromSumLine(string line, out GoComponent goComponent) { - Match m = GoSumRegex.Match(line); + var m = GoSumRegex.Match(line); if (m.Success) { goComponent = new GoComponent(m.Groups["name"].Value, m.Groups["version"].Value, m.Groups["hash"].Value); @@ -239,16 +238,16 @@ private void PopulateDependencyGraph(string goGraphOutput, ISingleFileComponentR continue; } - Logger.LogWarning("Unexpected relationship output from go mod graph:"); - Logger.LogWarning(relationship); + this.Logger.LogWarning("Unexpected relationship output from go mod graph:"); + this.Logger.LogWarning(relationship); continue; } GoComponent parentComponent; GoComponent childComponent; - var isParentParsed = TryCreateGoComponentFromRelationshipPart(components[0], out parentComponent); - var isChildParsed = TryCreateGoComponentFromRelationshipPart(components[1], out childComponent); + var isParentParsed = this.TryCreateGoComponentFromRelationshipPart(components[0], out parentComponent); + var isChildParsed = this.TryCreateGoComponentFromRelationshipPart(components[1], out childComponent); if (!isParentParsed) { @@ -258,14 +257,14 @@ private void PopulateDependencyGraph(string goGraphOutput, ISingleFileComponentR if (isChildParsed) { - if (IsModuleInBuildList(componentRecorder, parentComponent) && IsModuleInBuildList(componentRecorder, childComponent)) + if (this.IsModuleInBuildList(componentRecorder, parentComponent) && this.IsModuleInBuildList(componentRecorder, childComponent)) { componentRecorder.RegisterUsage(new DetectedComponent(childComponent), parentComponentId: parentComponent.Id); } } else { - Logger.LogWarning($"Failed to parse components from relationship string {relationship}"); + this.Logger.LogWarning($"Failed to parse components from relationship string {relationship}"); } } } @@ -325,7 +324,7 @@ private bool TryCreateGoComponentFromRelationshipPart(string relationship, out G private bool IsGoCliManuallyDisabled() { - return EnvVarService.IsEnvironmentVariableValueTrue("DisableGoCliScan"); + return this.EnvVarService.IsEnvironmentVariableValueTrue("DisableGoCliScan"); } private class GoBuildModule diff --git a/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs index 873f4eba1..0382b0a8a 100644 --- a/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs @@ -31,8 +31,8 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs) { - if (await IsAntLocallyAvailableAsync()) + if (await this.IsAntLocallyAvailableAsync()) { return processRequests; } - Logger.LogVerbose("Skipping Ivy detection as ant is not available in the local PATH."); + this.Logger.LogVerbose("Skipping Ivy detection as ant is not available in the local PATH."); return Enumerable.Empty().ToObservable(); } @@ -80,18 +80,18 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio { if (File.Exists(ivySettingsFilePath)) { - Logger.LogInfo($"Processing {ivyXmlFile.Location} and ivysettings.xml."); - await ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, ivySettingsFilePath); + this.Logger.LogInfo($"Processing {ivyXmlFile.Location} and ivysettings.xml."); + await this.ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, ivySettingsFilePath); } else { - Logger.LogInfo($"Processing {ivyXmlFile.Location}."); - await ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, null); + this.Logger.LogInfo($"Processing {ivyXmlFile.Location}."); + await this.ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, null); } } else { - Logger.LogError($"File {ivyXmlFile.Location} passed to OnFileFound, but does not exist!"); + this.Logger.LogError($"File {ivyXmlFile.Location} passed to OnFileFound, but does not exist!"); } } @@ -102,28 +102,28 @@ private async Task ProcessIvyAndIvySettingsFilesAsync( { try { - string workingDirectory = Path.Combine(Path.GetTempPath(), "ComponentDetection_Ivy"); - Logger.LogVerbose($"Preparing temporary Ivy project in {workingDirectory}"); + var workingDirectory = Path.Combine(Path.GetTempPath(), "ComponentDetection_Ivy"); + this.Logger.LogVerbose($"Preparing temporary Ivy project in {workingDirectory}"); if (Directory.Exists(workingDirectory)) { Directory.Delete(workingDirectory, recursive: true); } - InitTemporaryAntProject(workingDirectory, ivyXmlFile, ivySettingsXmlFile); - if (await RunAntToDetectDependenciesAsync(workingDirectory)) + this.InitTemporaryAntProject(workingDirectory, ivyXmlFile, ivySettingsXmlFile); + if (await this.RunAntToDetectDependenciesAsync(workingDirectory)) { - string instructionsFile = Path.Combine(workingDirectory, "target", "RegisterUsage.json"); - RegisterUsagesFromFile(singleFileComponentRecorder, instructionsFile); + var instructionsFile = Path.Combine(workingDirectory, "target", "RegisterUsage.json"); + this.RegisterUsagesFromFile(singleFileComponentRecorder, instructionsFile); } Directory.Delete(workingDirectory, recursive: true); } catch (Exception e) { - Logger.LogError("Exception occurred during Ivy file processing: " + e); + this.Logger.LogError("Exception occurred during Ivy file processing: " + e); // If something went wrong, just ignore the file - Logger.LogFailedReadingFile(ivyXmlFile, e); + this.Logger.LogFailedReadingFile(ivyXmlFile, e); } } @@ -138,15 +138,15 @@ private void InitTemporaryAntProject(string workingDirectory, string ivyXmlFile, var assembly = Assembly.GetExecutingAssembly(); - using (Stream fileIn = assembly.GetManifestResourceStream("Microsoft.ComponentDetection.Detectors.ivy.Resources.build.xml")) - using (FileStream fileOut = File.Create(Path.Combine(workingDirectory, "build.xml"))) + using (var fileIn = assembly.GetManifestResourceStream("Microsoft.ComponentDetection.Detectors.ivy.Resources.build.xml")) + using (var fileOut = File.Create(Path.Combine(workingDirectory, "build.xml"))) { fileIn.CopyTo(fileOut); } Directory.CreateDirectory(Path.Combine(workingDirectory, "java-src")); - using (Stream fileIn = assembly.GetManifestResourceStream("Microsoft.ComponentDetection.Detectors.ivy.Resources.java_src.IvyComponentDetectionAntTask.java")) - using (FileStream fileOut = File.Create(Path.Combine(workingDirectory, "java-src", "IvyComponentDetectionAntTask.java"))) + using (var fileIn = assembly.GetManifestResourceStream("Microsoft.ComponentDetection.Detectors.ivy.Resources.java_src.IvyComponentDetectionAntTask.java")) + using (var fileOut = File.Create(Path.Combine(workingDirectory, "java-src", "IvyComponentDetectionAntTask.java"))) { fileIn.CopyTo(fileOut); } @@ -156,40 +156,40 @@ private async Task IsAntLocallyAvailableAsync() { // Note: calling CanCommandBeLocated populates a cache of valid commands. If it is not called before ExecuteCommand, // ExecuteCommand calls CanCommandBeLocated with no arguments, which fails. - return await CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, AntVersionArgument); + return await this.CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, AntVersionArgument); } private async Task RunAntToDetectDependenciesAsync(string workingDirectory) { - bool ret = false; - Logger.LogVerbose($"Executing command `ant resolve-dependencies` in directory {workingDirectory}"); - CommandLineExecutionResult result = await CommandLineInvocationService.ExecuteCommand(PrimaryCommand, additionalCandidateCommands: AdditionalValidCommands, "-buildfile", workingDirectory, "resolve-dependencies"); + var ret = false; + this.Logger.LogVerbose($"Executing command `ant resolve-dependencies` in directory {workingDirectory}"); + var result = await this.CommandLineInvocationService.ExecuteCommand(PrimaryCommand, additionalCandidateCommands: AdditionalValidCommands, "-buildfile", workingDirectory, "resolve-dependencies"); if (result.ExitCode == 0) { - Logger.LogVerbose("Ant command succeeded"); + this.Logger.LogVerbose("Ant command succeeded"); ret = true; } else { - Logger.LogError($"Ant command failed with return code {result.ExitCode}"); + this.Logger.LogError($"Ant command failed with return code {result.ExitCode}"); } if (string.IsNullOrWhiteSpace(result.StdOut)) { - Logger.LogVerbose("Ant command wrote nothing to stdout."); + this.Logger.LogVerbose("Ant command wrote nothing to stdout."); } else { - Logger.LogVerbose("Ant command stdout:\n" + result.StdOut); + this.Logger.LogVerbose("Ant command stdout:\n" + result.StdOut); } if (string.IsNullOrWhiteSpace(result.StdErr)) { - Logger.LogVerbose("Ant command wrote nothing to stderr."); + this.Logger.LogVerbose("Ant command wrote nothing to stderr."); } else { - Logger.LogWarning("Ant command stderr:\n" + result.StdErr); + this.Logger.LogWarning("Ant command stderr:\n" + result.StdErr); } return ret; @@ -210,14 +210,14 @@ private static MavenComponent JsonGavToComponent(JToken gav) private void RegisterUsagesFromFile(ISingleFileComponentRecorder singleFileComponentRecorder, string instructionsFile) { - JObject instructionsJson = JObject.Parse(File.ReadAllText(instructionsFile)); - JContainer instructionsList = (JContainer)instructionsJson["RegisterUsage"]; - foreach (JToken dep in instructionsList) - { - MavenComponent component = JsonGavToComponent(dep["gav"]); - bool isDevDependency = dep.Value("DevelopmentDependency"); - MavenComponent parentComponent = JsonGavToComponent(dep["parent_gav"]); - bool isResolved = dep.Value("resolved"); + var instructionsJson = JObject.Parse(File.ReadAllText(instructionsFile)); + var instructionsList = (JContainer)instructionsJson["RegisterUsage"]; + foreach (var dep in instructionsList) + { + var component = JsonGavToComponent(dep["gav"]); + var isDevDependency = dep.Value("DevelopmentDependency"); + var parentComponent = JsonGavToComponent(dep["parent_gav"]); + var isResolved = dep.Value("resolved"); if (isResolved) { singleFileComponentRecorder.RegisterUsage( @@ -228,7 +228,7 @@ private void RegisterUsagesFromFile(ISingleFileComponentRecorder singleFileCompo } else { - Logger.LogWarning($"Dependency \"{component.Id}\" could not be resolved by Ivy, and so has not been recorded by Component Detection."); + this.Logger.LogWarning($"Dependency \"{component.Id}\" could not be resolved by Ivy, and so has not been recorded by Component Detection."); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs b/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs index 69d8fa481..12d715675 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs @@ -3,11 +3,12 @@ // Can convert JSON Schema to C# using quicktype.io. // (change name of top Coordinate class to SyftOutput) // -using System; -using System.Collections.Generic; namespace Microsoft.ComponentDetection.Detectors.Linux.Contracts { + using System; + using System.Collections.Generic; + public partial class SyftOutput { public Relationship[] ArtifactRelationships { get; set; } @@ -313,7 +314,7 @@ public partial struct ConfigurationUnion public static implicit operator ConfigurationUnion(double Double) => new ConfigurationUnion { Double = Double }; public static implicit operator ConfigurationUnion(long Integer) => new ConfigurationUnion { Integer = Integer }; public static implicit operator ConfigurationUnion(string String) => new ConfigurationUnion { String = String }; - public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null; + public bool IsNull => this.AnythingArray == null && this.Bool == null && this.Double == null && this.Integer == null && this.AnythingMap == null && this.String == null; } public partial struct Author diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs index 0ea1393f2..1d19c78ba 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs @@ -46,26 +46,26 @@ public async Task ExecuteDetectorAsync(ScanRequest if (imagesToProcess == null || !imagesToProcess.Any()) { - Logger.LogInfo("No instructions received to scan docker images."); + this.Logger.LogInfo("No instructions received to scan docker images."); return EmptySuccessfulScan(); } var cancellationTokenSource = new CancellationTokenSource(GetTimeout(request.DetectorArgs)); - if (!await DockerService.CanRunLinuxContainersAsync(cancellationTokenSource.Token)) + if (!await this.DockerService.CanRunLinuxContainersAsync(cancellationTokenSource.Token)) { using var record = new LinuxContainerDetectorUnsupportedOs { Os = RuntimeInformation.OSDescription, }; - Logger.LogInfo("Linux containers are not available on this host."); + this.Logger.LogInfo("Linux containers are not available on this host."); return EmptySuccessfulScan(); } var results = Enumerable.Empty(); try { - results = await ProcessImagesAsync(imagesToProcess, request.ComponentRecorder, cancellationTokenSource.Token); + results = await this.ProcessImagesAsync(imagesToProcess, request.ComponentRecorder, cancellationTokenSource.Token); } catch (OperationCanceledException) { @@ -91,15 +91,15 @@ private async Task> ProcessImagesAsync( try { // Check image exists locally. Try docker pull if not - if (!(await DockerService.ImageExistsLocallyAsync(image, cancellationToken) || - await DockerService.TryPullImageAsync(image, cancellationToken))) + if (!(await this.DockerService.ImageExistsLocallyAsync(image, cancellationToken) || + await this.DockerService.TryPullImageAsync(image, cancellationToken))) { throw new InvalidUserInputException( $"Docker image {image} could not be found locally and could not be pulled. Verify the image is either available locally or through docker pull.", null); } - var imageDetails = await DockerService.InspectImageAsync(image, cancellationToken); + var imageDetails = await this.DockerService.InspectImageAsync(image, cancellationToken); // Unable to fetch image details if (imageDetails == null) @@ -111,7 +111,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken))) } catch (Exception e) { - Logger.LogWarning($"Processing of image {image} failed with exception: {e.Message}"); + this.Logger.LogWarning($"Processing of image {image} failed with exception: {e.Message}"); using var record = new LinuxContainerDetectorImageDetectionFailed { ExceptionType = e.GetType().ToString(), @@ -130,9 +130,9 @@ await DockerService.TryPullImageAsync(image, cancellationToken))) { var internalContainerDetails = kvp.Value; var image = kvp.Key; - int baseImageLayerCount = await GetBaseImageLayerCount(internalContainerDetails, image, cancellationToken); + var baseImageLayerCount = await this.GetBaseImageLayerCount(internalContainerDetails, image, cancellationToken); - //Update the layer information to specify if a layer was fond in the specified baseImage + // Update the layer information to specify if a layer was fond in the specified baseImage internalContainerDetails.Layers = internalContainerDetails.Layers.Select(layer => new DockerLayer { DiffId = layer.DiffId, @@ -140,7 +140,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken))) IsBaseImage = layer.LayerIndex < baseImageLayerCount, }); - var layers = await LinuxScanner.ScanLinuxAsync(kvp.Value.ImageId, internalContainerDetails.Layers, baseImageLayerCount, cancellationToken); + var layers = await this.LinuxScanner.ScanLinuxAsync(kvp.Value.ImageId, internalContainerDetails.Layers, baseImageLayerCount, cancellationToken); var components = layers.SelectMany(layer => layer.LinuxComponents.Select(linuxComponent => new DetectedComponent(linuxComponent, null, internalContainerDetails.Id, layer.DockerLayer.LayerIndex))); internalContainerDetails.Layers = layers.Select(layer => layer.DockerLayer); @@ -154,7 +154,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken))) } catch (Exception e) { - Logger.LogWarning($"Scanning of image {kvp.Key} failed with exception: {e.Message}"); + this.Logger.LogWarning($"Scanning of image {kvp.Key} failed with exception: {e.Message}"); using var record = new LinuxContainerDetectorImageDetectionFailed { ExceptionType = e.GetType().ToString(), @@ -212,28 +212,32 @@ private async Task GetBaseImageLayerCount(ContainerDetails scannedImageDeta if (string.IsNullOrEmpty(scannedImageDetails.BaseImageRef)) { record.BaseImageLayerMessage = $"Base image annotations not found on image {image}, Results will not be mapped to base image layers"; - Logger.LogInfo(record.BaseImageLayerMessage); + this.Logger.LogInfo(record.BaseImageLayerMessage); + return 0; + } else if (scannedImageDetails.BaseImageRef == "scratch") { + record.BaseImageLayerMessage = $"{image} has no base image"; + this.Logger.LogInfo(record.BaseImageLayerMessage); return 0; } var baseImageDigest = scannedImageDetails.BaseImageDigest; - var refWithDigest = scannedImageDetails.BaseImageRef + (baseImageDigest != string.Empty ? $"@{baseImageDigest}" : string.Empty); + var refWithDigest = scannedImageDetails.BaseImageRef + (!string.IsNullOrEmpty(baseImageDigest) ? $"@{baseImageDigest}" : string.Empty); record.BaseImageDigest = baseImageDigest; record.BaseImageRef = scannedImageDetails.BaseImageRef; - if (!(await DockerService.ImageExistsLocallyAsync(refWithDigest, cancellationToken) || - await DockerService.TryPullImageAsync(refWithDigest, cancellationToken))) + if (!(await this.DockerService.ImageExistsLocallyAsync(refWithDigest, cancellationToken) || + await this.DockerService.TryPullImageAsync(refWithDigest, cancellationToken))) { record.BaseImageLayerMessage = $"Base image {refWithDigest} could not be found locally and could not be pulled. Results will not be mapped to base image layers"; - Logger.LogInfo(record.BaseImageLayerMessage); + this.Logger.LogInfo(record.BaseImageLayerMessage); return 0; } - var baseImageDetails = await DockerService.InspectImageAsync(refWithDigest, cancellationToken); - if (!ValidateBaseImageLayers(scannedImageDetails, baseImageDetails)) + var baseImageDetails = await this.DockerService.InspectImageAsync(refWithDigest, cancellationToken); + if (!this.ValidateBaseImageLayers(scannedImageDetails, baseImageDetails)) { record.BaseImageLayerMessage = $"Docker image {image} was set to have base image {refWithDigest} but is not built off of it. Results will not be mapped to base image layers"; - Logger.LogInfo(record.BaseImageLayerMessage); + this.Logger.LogInfo(record.BaseImageLayerMessage); return 0; } diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs index 5b3ba1493..b48381162 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs @@ -17,7 +17,7 @@ namespace Microsoft.ComponentDetection.Detectors.Linux [Export(typeof(ILinuxScanner))] public class LinuxScanner : ILinuxScanner { - private const string ScannerImage = "governancecontainerregistry.azurecr.io/syft:0.49.0@sha256:6c2e6bdffa548140b71db87dba9353099cb58103fcd532ab3d68c495248e5adf"; + private const string ScannerImage = "governancecontainerregistry.azurecr.io/syft:v0.53.4@sha256:04ed9c717a814fdccf52758b67333632a0ff16840fc393f5fba5864285eaebbe"; private static readonly IList CmdParameters = new List { @@ -58,19 +58,19 @@ public async Task> ScanLinuxAsync(string try { var command = new List { imageHash }.Concat(CmdParameters).ToList(); - (stdout, stderr) = await DockerService.CreateAndRunContainerAsync(ScannerImage, command, cancellationToken); + (stdout, stderr) = await this.DockerService.CreateAndRunContainerAsync(ScannerImage, command, cancellationToken); } catch (Exception e) { syftTelemetryRecord.Exception = JsonConvert.SerializeObject(e); - Logger.LogException(e, false); + this.Logger.LogException(e, false); throw; } } else { record.SemaphoreFailure = true; - Logger.LogWarning($"Failed to enter the docker semaphore for image {imageHash}"); + this.Logger.LogWarning($"Failed to enter the docker semaphore for image {imageHash}"); } } finally diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs b/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs index 679ae7e48..c4ad7fc0d 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs @@ -10,7 +10,7 @@ public class GraphNode { public GraphNode(T value) { - Value = value; + this.Value = value; } public T Value { get; set; } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs index 01ed2656f..cbf479e41 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs @@ -29,27 +29,27 @@ public class MavenCommandService : IMavenCommandService public async Task MavenCLIExists() { - return await CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, MvnVersionArgument); + return await this.CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, MvnVersionArgument); } public async Task GenerateDependenciesFile(ProcessRequest processRequest) { var pomFile = processRequest.ComponentStream; - var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={BcdeMvnDependencyFileName}", "-DoutputType=text", $"-f{pomFile.Location}" }; - var result = await CommandLineInvocationService.ExecuteCommand(PrimaryCommand, AdditionalValidCommands, cliParameters); + var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={this.BcdeMvnDependencyFileName}", "-DoutputType=text", $"-f{pomFile.Location}" }; + var result = await this.CommandLineInvocationService.ExecuteCommand(PrimaryCommand, AdditionalValidCommands, cliParameters); if (result.ExitCode != 0) { - Logger.LogVerbose($"Mvn execution failed for pom file: {pomFile.Location}"); - Logger.LogError(string.IsNullOrEmpty(result.StdErr) ? result.StdOut : result.StdErr); + this.Logger.LogVerbose($"Mvn execution failed for pom file: {pomFile.Location}"); + this.Logger.LogError(string.IsNullOrEmpty(result.StdErr) ? result.StdOut : result.StdErr); } } public void ParseDependenciesFile(ProcessRequest processRequest) { - using StreamReader sr = new StreamReader(processRequest.ComponentStream.Stream); + using var sr = new StreamReader(processRequest.ComponentStream.Stream); var lines = sr.ReadToEnd().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); - ParserService.Parse(lines, processRequest.SingleFileComponentRecorder); + this.ParserService.Parse(lines, processRequest.SingleFileComponentRecorder); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs index 610adc433..b4e95a2b3 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Net; using System.Text.RegularExpressions; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.BcdeModels; @@ -10,7 +9,7 @@ namespace Microsoft.ComponentDetection.Detectors.Maven { public static class MavenParsingUtilities { - private static readonly Dictionary MavenScopeToDependencyScopeMapping = new Dictionary() + private static readonly Dictionary MavenScopeToDependencyScopeMapping = new Dictionary() { { "compile", DependencyScope.MavenCompile }, { "provided", DependencyScope.MavenProvided }, @@ -51,7 +50,7 @@ private static (string groupId, string artifactId, string version, bool? isDevel } // 'MavenCompile' is a default scope for maven dependencies. - DependencyScope dependencyScope = DependencyScope.MavenCompile; + var dependencyScope = DependencyScope.MavenCompile; var groupId = results[0]; var artifactId = results[1]; var version = results[3]; @@ -60,8 +59,8 @@ private static (string groupId, string artifactId, string version, bool? isDevel { dependencyScope = MavenScopeToDependencyScopeMapping.TryGetValue( Regex.Match(results[4], @"^([\w]+)").Value, - out dependencyScope) - ? dependencyScope + out dependencyScope) + ? dependencyScope : throw new InvalidOperationException($"Invalid scope ('{results[4]}') found for '{mavenComponentString}' found in generated dependency graph."); isDevDependency = dependencyScope == DependencyScope.MavenTest; } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs index 8efc18f47..95dfe38a7 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs @@ -21,12 +21,12 @@ public class MavenStyleDependencyGraphParser private void StartDependencyCategory(string categoryName) { - if (DependencyCategory != null) + if (this.DependencyCategory != null) { throw new InvalidOperationException("Current category must be finished before starting new category."); } - DependencyCategory = new GraphNode(categoryName); + this.DependencyCategory = new GraphNode(categoryName); } public GraphNode Parse(string[] lines) @@ -34,21 +34,21 @@ public GraphNode Parse(string[] lines) foreach (var line in lines) { var localLine = line.Trim(TrimCharacters); - if (!string.IsNullOrWhiteSpace(localLine) && DependencyCategory == null) + if (!string.IsNullOrWhiteSpace(localLine) && this.DependencyCategory == null) { - StartDependencyCategory(localLine); + this.StartDependencyCategory(localLine); } else { var splitterOrDefault = ComponentSplitters.FirstOrDefault(x => localLine.Contains(x)); if (splitterOrDefault != null) { - TrackDependency(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim()); + this.TrackDependency(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim()); } } } - return DependencyCategory; + return this.DependencyCategory; } public void Parse(string[] lines, ISingleFileComponentRecorder singleFileComponentRecorder) @@ -56,10 +56,10 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone foreach (var line in lines) { var localLine = line.Trim(TrimCharacters); - if (!string.IsNullOrWhiteSpace(localLine) && topLevelComponent == null) + if (!string.IsNullOrWhiteSpace(localLine) && this.topLevelComponent == null) { var topLevelMavenStringInfo = MavenParsingUtilities.GenerateDetectedComponentAndMetadataFromMavenString(localLine); - topLevelComponent = topLevelMavenStringInfo.Component; + this.topLevelComponent = topLevelMavenStringInfo.Component; singleFileComponentRecorder.RegisterUsage( topLevelMavenStringInfo.Component, isDevelopmentDependency: topLevelMavenStringInfo.IsDevelopmentDependency, @@ -71,7 +71,7 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone if (splitterOrDefault != null) { - RecordDependencies(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim(), singleFileComponentRecorder); + this.RecordDependencies(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim(), singleFileComponentRecorder); } } } @@ -79,40 +79,40 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone private void TrackDependency(int position, string versionedComponent) { - while (stack.Count > 0 && stack.Peek().ParseLevel >= position) + while (this.stack.Count > 0 && this.stack.Peek().ParseLevel >= position) { - stack.Pop(); + this.stack.Pop(); } var myNode = new GraphNodeAtLevel(position, versionedComponent); - if (stack.Count > 0) + if (this.stack.Count > 0) { - var parent = stack.Peek(); + var parent = this.stack.Peek(); parent.Children.Add(myNode); myNode.Parents.Add(parent); } else { - DependencyCategory.Children.Add(myNode); + this.DependencyCategory.Children.Add(myNode); } - stack.Push(myNode); + this.stack.Push(myNode); } private void RecordDependencies(int position, string versionedComponent, ISingleFileComponentRecorder componentRecorder) { - while (tupleStack.Count > 0 && tupleStack.Peek().ParseLevel >= position) + while (this.tupleStack.Count > 0 && this.tupleStack.Peek().ParseLevel >= position) { - tupleStack.Pop(); + this.tupleStack.Pop(); } var componentAndDevDependencyTuple = MavenParsingUtilities.GenerateDetectedComponentAndMetadataFromMavenString(versionedComponent); var newTuple = (ParseLevel: position, componentAndDevDependencyTuple.Component); - if (tupleStack.Count > 0) + if (this.tupleStack.Count > 0) { - var parent = tupleStack.Peek().Component; + var parent = this.tupleStack.Peek().Component; componentRecorder.RegisterUsage(parent); componentRecorder.RegisterUsage( newTuple.Component, @@ -125,12 +125,12 @@ private void RecordDependencies(int position, string versionedComponent, ISingle componentRecorder.RegisterUsage( newTuple.Component, isExplicitReferencedDependency: true, - parentComponentId: topLevelComponent.Component.Id, + parentComponentId: this.topLevelComponent.Component.Id, isDevelopmentDependency: componentAndDevDependencyTuple.IsDevelopmentDependency, dependencyScope: componentAndDevDependencyTuple.dependencyScope); } - tupleStack.Push(newTuple); + this.tupleStack.Push(newTuple); } private class GraphNodeAtLevel : GraphNode @@ -140,7 +140,7 @@ private class GraphNodeAtLevel : GraphNode public GraphNodeAtLevel(int level, T value) : base(value) { - ParseLevel = level; + this.ParseLevel = level; } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs index c7c72de52..c23328b1a 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs @@ -32,15 +32,15 @@ public class MvnCliComponentDetector : FileComponentDetector protected override async Task> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs) { - if (!await MavenCommandService.MavenCLIExists()) + if (!await this.MavenCommandService.MavenCLIExists()) { - Logger.LogVerbose("Skipping maven detection as maven is not available in the local PATH."); + this.Logger.LogVerbose("Skipping maven detection as maven is not available in the local PATH."); return Enumerable.Empty().ToObservable(); } - var processPomFile = new ActionBlock(MavenCommandService.GenerateDependenciesFile); + var processPomFile = new ActionBlock(this.MavenCommandService.GenerateDependenciesFile); - await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => + await this.RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => { processPomFile.Post(processRequest); }); @@ -49,7 +49,8 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => await processPomFile.Completion; - return ComponentStreamEnumerableFactory.GetComponentStreams(CurrentScanRequest.SourceDirectory, new[] { MavenCommandService.BcdeMvnDependencyFileName }, CurrentScanRequest.DirectoryExclusionPredicate) + return this.ComponentStreamEnumerableFactory.GetComponentStreams(this.CurrentScanRequest.SourceDirectory, new[] { + this.MavenCommandService.BcdeMvnDependencyFileName }, this.CurrentScanRequest.DirectoryExclusionPredicate) .Select(componentStream => { // The file stream is going to be disposed after the iteration is finished @@ -64,7 +65,7 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => Location = componentStream.Location, Pattern = componentStream.Pattern, }, - SingleFileComponentRecorder = ComponentRecorder.CreateSingleFileComponentRecorder( + SingleFileComponentRecorder = this.ComponentRecorder.CreateSingleFileComponentRecorder( Path.Combine(Path.GetDirectoryName(componentStream.Location), "pom.xml")), }; }) @@ -73,7 +74,7 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) { - MavenCommandService.ParseDependenciesFile(processRequest); + this.MavenCommandService.ParseDependenciesFile(processRequest); File.Delete(processRequest.ComponentStream.Location); @@ -82,15 +83,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio private IObservable RemoveNestedPomXmls(IObservable componentStreams) { - List directoryItemFacades = new List(); - Dictionary directoryItemFacadesByPath = new Dictionary(); + var directoryItemFacades = new List(); + var directoryItemFacadesByPath = new Dictionary(); return Observable.Create(s => { return componentStreams.Subscribe( processRequest => { var item = processRequest.ComponentStream; - string currentDir = item.Location; + var currentDir = item.Location; DirectoryItemFacade last = null; do { @@ -135,7 +136,7 @@ private IObservable RemoveNestedPomXmls(IObservable string.Equals(Path.GetFileName(x.Location), "pom.xml", StringComparison.OrdinalIgnoreCase)) != null) { - Logger.LogVerbose($"Ignoring pom.xml at {item.Location}, as it has a parent pom.xml that will be processed at {current.Name}\\pom.xml ."); + this.Logger.LogVerbose($"Ignoring pom.xml at {item.Location}, as it has a parent pom.xml that will be processed at {current.Name}\\pom.xml ."); break; } diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs index 05c52dd1b..1a74c24d0 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs @@ -43,16 +43,16 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio contents = await reader.ReadToEndAsync(); } - await SafeProcessAllPackageJTokens(filePath, contents, (token) => + await this.SafeProcessAllPackageJTokens(filePath, contents, (token) => { if (token["name"] == null || token["version"] == null) { - Logger.LogInfo($"{filePath} does not contain a name and/or version. These are required fields for a valid package.json file." + - $"It and its dependencies will not be registered."); + this.Logger.LogInfo($"{filePath} does not contain a name and/or version. These are required fields for a valid package.json file." + + $"It and its dependencies will not be registered."); return false; } - return ProcessIndividualPackageJTokens(filePath, singleFileComponentRecorder, token); + return this.ProcessIndividualPackageJTokens(filePath, singleFileComponentRecorder, token); }); } @@ -60,13 +60,13 @@ private async Task SafeProcessAllPackageJTokens(string sourceFilePath, string co { try { - await ProcessAllPackageJTokensAsync(contents, jtokenProcessor); + await this.ProcessAllPackageJTokensAsync(contents, jtokenProcessor); } catch (Exception e) { // If something went wrong, just ignore the component - Logger.LogBuildWarning($"Could not parse Jtokens from file {sourceFilePath}."); - Logger.LogFailedReadingFile(sourceFilePath, e); + this.Logger.LogBuildWarning($"Could not parse Jtokens from file {sourceFilePath}."); + this.Logger.LogFailedReadingFile(sourceFilePath, e); return; } } @@ -83,15 +83,15 @@ protected virtual bool ProcessIndividualPackageJTokens(string filePath, ISingleF var name = packageJToken["name"].ToString(); var version = packageJToken["version"].ToString(); var authorToken = packageJToken["author"]; - + if (!SemanticVersion.TryParse(version, out _)) { - Logger.LogWarning($"Unable to parse version \"{version}\" for package \"{name}\" found at path \"{filePath}\". This may indicate an invalid npm package component and it will not be registered."); + this.Logger.LogWarning($"Unable to parse version \"{version}\" for package \"{name}\" found at path \"{filePath}\". This may indicate an invalid npm package component and it will not be registered."); return false; } - NpmComponent npmComponent = new NpmComponent(name, version, author: GetAuthor(authorToken, name, filePath)); - + var npmComponent = new NpmComponent(name, version, author: this.GetAuthor(authorToken, name, filePath)); + singleFileComponentRecorder.RegisterUsage(new DetectedComponent(npmComponent)); return true; } @@ -106,12 +106,12 @@ private NpmAuthor GetAuthor(JToken authorToken, string packageName, string fileP string authorName; string authorEmail; - string authorSingleStringPattern = @"^(?([^<(]+?)?)[ \t]*(?:<(?([^>(]+?))>)?[ \t]*(?:\(([^)]+?)\)|$)"; - Match authorMatch = new Regex(authorSingleStringPattern).Match(authorString); + var authorSingleStringPattern = @"^(?([^<(]+?)?)[ \t]*(?:<(?([^>(]+?))>)?[ \t]*(?:\(([^)]+?)\)|$)"; + var authorMatch = new Regex(authorSingleStringPattern).Match(authorString); /* * for parsing author in Json Format - * for e.g. + * for e.g. * "author": { * "name": "John Doe", * "email": "johndoe@outlook.com", @@ -127,25 +127,25 @@ private NpmAuthor GetAuthor(JToken authorToken, string packageName, string fileP * for e.g. * "author": "John Doe https://jd.com" */ - } + } else if (authorMatch.Success) { authorName = authorMatch.Groups["name"].ToString().Trim(); authorEmail = authorMatch.Groups["email"].ToString().Trim(); - } + } else { - Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered."); + this.Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered."); return null; } if (string.IsNullOrEmpty(authorName)) { - Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered."); + this.Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered."); return null; } return new NpmAuthor(authorName, authorEmail); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs index 58a9677fb..1c9f32fa2 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs @@ -49,15 +49,15 @@ public class NpmComponentDetectorWithRoots : FileComponentDetector protected override Task> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs) { - return Task.FromResult(RemoveNodeModuleNestedFiles(processRequests) + return Task.FromResult(this.RemoveNodeModuleNestedFiles(processRequests) .Where(pr => { if (pr.ComponentStream.Pattern.Equals(LernaSearchPattern)) { // Lock LernaFiles so we don't add while we are enumerating in processFiles - lock (lernaFilesLock) + lock (this.lernaFilesLock) { - LernaFiles.Add(pr); + this.LernaFiles.Add(pr); return false; } } @@ -72,15 +72,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - IEnumerable packageJsonComponentStream = ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(file.Location).Directory, packageJsonPattern, (name, directoryName) => false, false); + var packageJsonComponentStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(file.Location).Directory, packageJsonPattern, (name, directoryName) => false, false); - bool foundUnderLerna = false; + var foundUnderLerna = false; IList lernaFilesClone; // ToList LernaFiles to generate a copy we can act on without holding the lock for a long time - lock (lernaFilesLock) + lock (this.lernaFilesLock) { - lernaFilesClone = LernaFiles.ToList(); + lernaFilesClone = this.LernaFiles.ToList(); } foreach (var lernaProcessRequest in lernaFilesClone) @@ -88,31 +88,31 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var lernaFile = lernaProcessRequest.ComponentStream; // We have extra validation on lock files not found below a lerna.json - if (PathUtilityService.IsFileBelowAnother(lernaFile.Location, file.Location)) + if (this.PathUtilityService.IsFileBelowAnother(lernaFile.Location, file.Location)) { foundUnderLerna = true; break; } } - await SafeProcessAllPackageJTokens(file, (token) => + await this.SafeProcessAllPackageJTokens(file, (token) => { if (!foundUnderLerna && (token["name"] == null || token["version"] == null || string.IsNullOrWhiteSpace(token["name"].Value()) || string.IsNullOrWhiteSpace(token["version"].Value()))) { - Logger.LogInfo($"{file.Location} does not contain a valid name and/or version. These are required fields for a valid package-lock.json file." + - $"It and its dependencies will not be registered."); + this.Logger.LogInfo($"{file.Location} does not contain a valid name and/or version. These are required fields for a valid package-lock.json file." + + $"It and its dependencies will not be registered."); return false; } - ProcessIndividualPackageJTokens(singleFileComponentRecorder, token, packageJsonComponentStream, skipValidation: foundUnderLerna); + this.ProcessIndividualPackageJTokens(singleFileComponentRecorder, token, packageJsonComponentStream, skipValidation: foundUnderLerna); return true; }); } private IObservable RemoveNodeModuleNestedFiles(IObservable componentStreams) { - List directoryItemFacades = new List(); - Dictionary directoryItemFacadesByPath = new Dictionary(); + var directoryItemFacades = new List(); + var directoryItemFacadesByPath = new Dictionary(); return Observable.Create(s => { @@ -120,11 +120,11 @@ private IObservable RemoveNodeModuleNestedFiles(IObservable { var item = processRequest.ComponentStream; - string currentDir = item.Location; + var currentDir = item.Location; DirectoryItemFacade last = null; do { - currentDir = PathUtilityService.GetParentDirectory(currentDir); + currentDir = this.PathUtilityService.GetParentDirectory(currentDir); // We've reached the top / root if (currentDir == null) @@ -135,7 +135,7 @@ private IObservable RemoveNodeModuleNestedFiles(IObservable item.Location.Contains(folder)); + var skippedFolder = this.SkippedFolders.FirstOrDefault(folder => item.Location.Contains(folder)); // When node_modules is part of the path down to a given item, we skip the item. Otherwise, we yield the item. if (string.IsNullOrEmpty(skippedFolder)) @@ -144,7 +144,7 @@ private IObservable RemoveNodeModuleNestedFiles(IObservable packageJsonComponentStream, bool skipValidation = false) { - JToken dependencies = packageLockJToken["dependencies"]; - Queue<(JProperty, TypedComponent)> topLevelDependencies = new Queue<(JProperty, TypedComponent)>(); + var dependencies = packageLockJToken["dependencies"]; + var topLevelDependencies = new Queue<(JProperty, TypedComponent)>(); var dependencyLookup = dependencies.Children().ToDictionary(dependency => dependency.Name); foreach (var stream in packageJsonComponentStream) { - using StreamReader file = new StreamReader(stream.Stream); - using JsonTextReader reader = new JsonTextReader(file); + using var file = new StreamReader(stream.Stream); + using var reader = new JsonTextReader(file); var packageJsonToken = JToken.ReadFrom(reader); - bool enqueued = TryEnqueueFirstLevelDependencies(topLevelDependencies, packageJsonToken["dependencies"], dependencyLookup, skipValidation: skipValidation); - enqueued = enqueued && TryEnqueueFirstLevelDependencies(topLevelDependencies, packageJsonToken["devDependencies"], dependencyLookup, skipValidation: skipValidation); + var enqueued = this.TryEnqueueFirstLevelDependencies(topLevelDependencies, packageJsonToken["dependencies"], dependencyLookup, skipValidation: skipValidation); + enqueued = enqueued && this.TryEnqueueFirstLevelDependencies(topLevelDependencies, packageJsonToken["devDependencies"], dependencyLookup, skipValidation: skipValidation); if (!enqueued) { // This represents a mismatch between lock file and package.json, break out and do not register anything for these files @@ -248,7 +248,7 @@ protected void ProcessIndividualPackageJTokens(ISingleFileComponentRecorder sing throw new InvalidOperationException(string.Format("InvalidPackageJson -- There must be a package.json file at '{0}' for components to be registered", singleFileComponentRecorder.ManifestFileLocation)); } - TraverseRequirementAndDependencyTree(topLevelDependencies, dependencyLookup, singleFileComponentRecorder); + this.TraverseRequirementAndDependencyTree(topLevelDependencies, dependencyLookup, singleFileComponentRecorder); } private void TraverseRequirementAndDependencyTree(IEnumerable<(JProperty, TypedComponent)> topLevelDependencies, IDictionary dependencyLookup, ISingleFileComponentRecorder singleFileComponentRecorder) @@ -256,24 +256,24 @@ private void TraverseRequirementAndDependencyTree(IEnumerable<(JProperty, TypedC // iterate through everything for a top level dependency with a single explicitReferencedDependency value foreach (var (currentDependency, _) in topLevelDependencies) { - var typedComponent = NpmComponentUtilities.GetTypedComponent(currentDependency, NpmRegistryHost, Logger); + var typedComponent = NpmComponentUtilities.GetTypedComponent(currentDependency, NpmRegistryHost, this.Logger); if (typedComponent == null) { continue; } - HashSet previouslyAddedComponents = new HashSet { typedComponent.Id }; - Queue<(JProperty, TypedComponent)> subQueue = new Queue<(JProperty, TypedComponent)>(); + var previouslyAddedComponents = new HashSet { typedComponent.Id }; + var subQueue = new Queue<(JProperty, TypedComponent)>(); NpmComponentUtilities.TraverseAndRecordComponents(currentDependency, singleFileComponentRecorder, typedComponent, explicitReferencedDependency: typedComponent); - EnqueueDependencies(subQueue, currentDependency.Value["dependencies"], parentComponent: typedComponent); - TryEnqueueFirstLevelDependencies(subQueue, currentDependency.Value["requires"], dependencyLookup, parentComponent: typedComponent); + this.EnqueueDependencies(subQueue, currentDependency.Value["dependencies"], parentComponent: typedComponent); + this.TryEnqueueFirstLevelDependencies(subQueue, currentDependency.Value["requires"], dependencyLookup, parentComponent: typedComponent); while (subQueue.Count != 0) { var (currentSubDependency, parentComponent) = subQueue.Dequeue(); - var typedSubComponent = NpmComponentUtilities.GetTypedComponent(currentSubDependency, NpmRegistryHost, Logger); + var typedSubComponent = NpmComponentUtilities.GetTypedComponent(currentSubDependency, NpmRegistryHost, this.Logger); // only process components that we haven't seen before that have been brought in by the same explicitReferencedDependency, resolves circular npm 'requires' loop if (typedSubComponent == null || previouslyAddedComponents.Contains(typedSubComponent.Id)) @@ -285,8 +285,8 @@ private void TraverseRequirementAndDependencyTree(IEnumerable<(JProperty, TypedC NpmComponentUtilities.TraverseAndRecordComponents(currentSubDependency, singleFileComponentRecorder, typedSubComponent, explicitReferencedDependency: typedComponent, parentComponent.Id); - EnqueueDependencies(subQueue, currentSubDependency.Value["dependencies"], parentComponent: typedSubComponent); - TryEnqueueFirstLevelDependencies(subQueue, currentSubDependency.Value["requires"], dependencyLookup, parentComponent: typedSubComponent); + this.EnqueueDependencies(subQueue, currentSubDependency.Value["dependencies"], parentComponent: typedSubComponent); + this.TryEnqueueFirstLevelDependencies(subQueue, currentSubDependency.Value["requires"], dependencyLookup, parentComponent: typedSubComponent); } } } @@ -307,7 +307,7 @@ private void EnqueueDependencies(Queue<(JProperty, TypedComponent)> queue, JToke private bool TryEnqueueFirstLevelDependencies(Queue<(JProperty, TypedComponent)> queue, JToken dependencies, IDictionary dependencyLookup, Queue parentComponentQueue = null, TypedComponent parentComponent = null, bool skipValidation = false) { - bool isValid = true; + var isValid = true; if (dependencies != null) { foreach (JProperty dependency in dependencies) @@ -317,7 +317,7 @@ private bool TryEnqueueFirstLevelDependencies(Queue<(JProperty, TypedComponent)> continue; } - bool inLock = dependencyLookup.TryGetValue(dependency.Name, out JProperty dependencyProperty); + var inLock = dependencyLookup.TryGetValue(dependency.Name, out var dependencyProperty); if (inLock) { queue.Enqueue((dependencyProperty, parentComponent)); @@ -336,4 +336,4 @@ private bool TryEnqueueFirstLevelDependencies(Queue<(JProperty, TypedComponent)> return isValid; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentUtilities.cs index 8e8792614..a41d65685 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentUtilities.cs @@ -19,8 +19,8 @@ public static class NpmComponentUtilities public static void TraverseAndRecordComponents(JProperty currentDependency, ISingleFileComponentRecorder singleFileComponentRecorder, TypedComponent component, TypedComponent explicitReferencedDependency, string parentComponentId = null) { - JValue devJValue = currentDependency.Value["dev"] as JValue; - bool isDevDependency = devJValue == null ? false : (bool)devJValue; + var devJValue = currentDependency.Value["dev"] as JValue; + var isDevDependency = devJValue == null ? false : (bool)devJValue; AddOrUpdateDetectedComponent(singleFileComponentRecorder, component, isDevDependency, parentComponentId, isExplicitReferencedDependency: string.Equals(component.Id, explicitReferencedDependency.Id)); } @@ -38,9 +38,9 @@ public static DetectedComponent AddOrUpdateDetectedComponent( public static TypedComponent GetTypedComponent(JProperty currentDependency, string npmRegistryHost, ILogger logger) { - string name = currentDependency.Name; - string version = currentDependency.Value["version"].ToString(); - string hash = currentDependency.Value["integrity"]?.ToString(); // https://docs.npmjs.com/configuring-npm/package-lock-json.html#integrity + var name = currentDependency.Name; + var version = currentDependency.Value["version"].ToString(); + var hash = currentDependency.Value["integrity"]?.ToString(); // https://docs.npmjs.com/configuring-npm/package-lock-json.html#integrity if (!IsPackageNameValid(name)) { @@ -48,7 +48,7 @@ public static TypedComponent GetTypedComponent(JProperty currentDependency, stri return null; } - if (!SemanticVersion.TryParse(version, out SemanticVersion result) && !TryParseNpmVersion(npmRegistryHost, name, version, out result)) + if (!SemanticVersion.TryParse(version, out var result) && !TryParseNpmVersion(npmRegistryHost, name, version, out result)) { logger.LogInfo($"Version string {version} for component {name} is invalid or unsupported and a component will not be recorded."); return null; @@ -61,7 +61,7 @@ public static TypedComponent GetTypedComponent(JProperty currentDependency, stri public static bool TryParseNpmVersion(string npmRegistryHost, string packageName, string versionString, out SemanticVersion version) { - if (Uri.TryCreate(versionString, UriKind.Absolute, out Uri parsedUri)) + if (Uri.TryCreate(versionString, UriKind.Absolute, out var parsedUri)) { if (string.Equals(npmRegistryHost, parsedUri.Host, StringComparison.OrdinalIgnoreCase)) { @@ -77,8 +77,8 @@ public static bool TryParseNpmRegistryVersion(string packageName, Uri versionStr { try { - string file = Path.GetFileNameWithoutExtension(versionString.LocalPath); - string potentialVersion = file.Replace($"{packageName}-", string.Empty); + var file = Path.GetFileNameWithoutExtension(versionString.LocalPath); + var potentialVersion = file.Replace($"{packageName}-", string.Empty); return SemanticVersion.TryParse(potentialVersion, out version); } @@ -93,8 +93,8 @@ public static IDictionary> TryGetAllPackageJso { yarnWorkspaces = new List(); - using StreamReader file = new StreamReader(stream); - using JsonTextReader reader = new JsonTextReader(file); + using var file = new StreamReader(stream); + using var reader = new JsonTextReader(file); IDictionary dependencies = new Dictionary(); IDictionary devDependencies = new Dictionary(); @@ -132,7 +132,7 @@ private static IDictionary> AttachDevInformati returnedDependencies[item.Key] = new Dictionary(); } - if (returnedDependencies[item.Key].TryGetValue(item.Value, out bool wasDev)) + if (returnedDependencies[item.Key].TryGetValue(item.Value, out var wasDev)) { returnedDependencies[item.Key][item.Value] = wasDev && isDev; } diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs index d93dc9911..2a93ef106 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs @@ -31,18 +31,20 @@ public class NuGetComponentDetector : FileComponentDetector private readonly IList repositoryPathKeyNames = new List { "repositorypath", "globalpackagesfolder" }; + private static readonly IEnumerable LowConfidencePackages = new[] { "Newtonsoft.Json" }; + protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) { var stream = processRequest.ComponentStream; - bool ignoreNugetConfig = detectorArgs.TryGetValue("NuGet.IncludeRepositoryPaths", out string includeRepositoryPathsValue) && includeRepositoryPathsValue.Equals(bool.FalseString, StringComparison.OrdinalIgnoreCase); - + var ignoreNugetConfig = detectorArgs.TryGetValue("NuGet.IncludeRepositoryPaths", out var includeRepositoryPathsValue) && includeRepositoryPathsValue.Equals(bool.FalseString, StringComparison.OrdinalIgnoreCase); + if (NugetConfigFileName.Equals(stream.Pattern, StringComparison.OrdinalIgnoreCase)) { - await ProcessAdditionalDirectory(processRequest, ignoreNugetConfig); + await this.ProcessAdditionalDirectory(processRequest, ignoreNugetConfig); } else { - await ProcessFile(processRequest); + await this.ProcessFile(processRequest); } } @@ -50,24 +52,24 @@ private async Task ProcessAdditionalDirectory(ProcessRequest processRequest, boo { var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var stream = processRequest.ComponentStream; - + if (!ignoreNugetConfig) { - var additionalPaths = GetRepositoryPathsFromNugetConfig(stream); - Uri rootPath = new Uri(CurrentScanRequest.SourceDirectory.FullName + Path.DirectorySeparatorChar); + var additionalPaths = this.GetRepositoryPathsFromNugetConfig(stream); + var rootPath = new Uri(this.CurrentScanRequest.SourceDirectory.FullName + Path.DirectorySeparatorChar); foreach (var additionalPath in additionalPaths) { // Only paths outside of our sourceDirectory need to be added if (!rootPath.IsBaseOf(new Uri(additionalPath.FullName + Path.DirectorySeparatorChar))) { - Logger.LogInfo($"Found path override in nuget configuration file. Adding {additionalPath} to the package search path."); - Logger.LogWarning($"Path {additionalPath} is not rooted in the source tree. More components may be detected than expected if this path is shared across code projects."); + this.Logger.LogInfo($"Found path override in nuget configuration file. Adding {additionalPath} to the package search path."); + this.Logger.LogWarning($"Path {additionalPath} is not rooted in the source tree. More components may be detected than expected if this path is shared across code projects."); - Scanner.Initialize(additionalPath, (name, directoryName) => false, 1); + this.Scanner.Initialize(additionalPath, (name, directoryName) => false, 1); - await Scanner.GetFilteredComponentStreamObservable(additionalPath, SearchPatterns.Where(sp => !NugetConfigFileName.Equals(sp)), singleFileComponentRecorder.GetParentComponentRecorder()) - .ForEachAsync(async fi => await ProcessFile(fi)); + await this.Scanner.GetFilteredComponentStreamObservable(additionalPath, this.SearchPatterns.Where(sp => !NugetConfigFileName.Equals(sp)), singleFileComponentRecorder.GetParentComponentRecorder()) + .ForEachAsync(async fi => await this.ProcessFile(fi)); } } } @@ -95,45 +97,48 @@ private async Task ProcessFile(ProcessRequest processRequest) return; } - using MemoryStream nuspecStream = new MemoryStream(nuspecBytes, false); + using var nuspecStream = new MemoryStream(nuspecBytes, false); - XmlDocument doc = new XmlDocument(); + var doc = new XmlDocument(); doc.Load(nuspecStream); XmlNode packageNode = doc["package"]; XmlNode metadataNode = packageNode["metadata"]; - string name = metadataNode["id"].InnerText; - string version = metadataNode["version"].InnerText; + var name = metadataNode["id"].InnerText; + var version = metadataNode["version"].InnerText; - string[] authors = metadataNode["authors"]?.InnerText.Split(",").Select(author => author.Trim()).ToArray(); + var authors = metadataNode["authors"]?.InnerText.Split(",").Select(author => author.Trim()).ToArray(); - if (!NuGetVersion.TryParse(version, out NuGetVersion parsedVer)) + if (!NuGetVersion.TryParse(version, out var parsedVer)) { - Logger.LogInfo($"Version '{version}' from {stream.Location} could not be parsed as a NuGet version"); + this.Logger.LogInfo($"Version '{version}' from {stream.Location} could not be parsed as a NuGet version"); return; } - NuGetComponent component = new NuGetComponent(name, version, authors); - singleFileComponentRecorder.RegisterUsage(new DetectedComponent(component)); + var component = new NuGetComponent(name, version, authors); + if (!LowConfidencePackages.Contains(name, StringComparer.OrdinalIgnoreCase)) + { + singleFileComponentRecorder.RegisterUsage(new DetectedComponent(component)); + } } catch (Exception e) { // If something went wrong, just ignore the component - Logger.LogFailedReadingFile(stream.Location, e); + this.Logger.LogFailedReadingFile(stream.Location, e); } } private IList GetRepositoryPathsFromNugetConfig(IComponentStream componentStream) { - List potentialPaths = new List(); - List paths = new List(); + var potentialPaths = new List(); + var paths = new List(); try { // Can be made async in later versions of .net standard. - XElement root = XElement.Load(componentStream.Stream); + var root = XElement.Load(componentStream.Stream); var config = root.Elements().SingleOrDefault(x => x.Name == "config"); @@ -144,9 +149,9 @@ private IList GetRepositoryPathsFromNugetConfig(IComponentStream foreach (var entry in config.Elements()) { - if (entry.Attributes().Any(x => repositoryPathKeyNames.Contains(x.Value.ToLower()))) + if (entry.Attributes().Any(x => this.repositoryPathKeyNames.Contains(x.Value.ToLower()))) { - string value = entry.Attributes().SingleOrDefault(x => string.Equals(x.Name.LocalName, "value", StringComparison.OrdinalIgnoreCase))?.Value; + var value = entry.Attributes().SingleOrDefault(x => string.Equals(x.Name.LocalName, "value", StringComparison.OrdinalIgnoreCase))?.Value; if (!string.IsNullOrEmpty(value)) { @@ -169,13 +174,13 @@ private IList GetRepositoryPathsFromNugetConfig(IComponentStream { path = new DirectoryInfo(Path.GetFullPath(potentialPath)); } - else if (IsValidPath(componentStream.Location)) + else if (this.IsValidPath(componentStream.Location)) { path = new DirectoryInfo(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(componentStream.Location), potentialPath))); } else { - Logger.LogWarning($"Excluding discovered path {potentialPath} from location {componentStream.Location} as it could not be determined to be valid."); + this.Logger.LogWarning($"Excluding discovered path {potentialPath} from location {componentStream.Location} as it could not be determined to be valid."); continue; } diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetNuspecUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetNuspecUtilities.cs index 2058983e7..909b0e543 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetNuspecUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetNuspecUtilities.cs @@ -24,7 +24,7 @@ public static async Task GetNuspecBytesAsync(Stream nupkgStream) using var archive = new ZipArchive(nupkgStream, ZipArchiveMode.Read, true); // get the first entry ending in .nuspec at the root of the package - ZipArchiveEntry nuspecEntry = + var nuspecEntry = archive.Entries.FirstOrDefault(x => x.Name.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase) && x.FullName.IndexOf('/') == -1); @@ -51,8 +51,8 @@ public static async Task GetNuspecBytesAsync(Stream nupkgStream) public static async Task GetNuspecBytesFromNuspecStream(Stream nuspecStream, long nuspecLength) { - byte[] nuspecBytes = new byte[nuspecLength]; - int bytesReadSoFar = 0; + var nuspecBytes = new byte[nuspecLength]; + var bytesReadSoFar = 0; while (bytesReadSoFar < nuspecBytes.Length) { bytesReadSoFar += await nuspecStream.ReadAsync(nuspecBytes, bytesReadSoFar, nuspecBytes.Length - bytesReadSoFar); diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetPackagesConfigDetector.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetPackagesConfigDetector.cs new file mode 100644 index 000000000..e534ec6eb --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetPackagesConfigDetector.cs @@ -0,0 +1,44 @@ +namespace Microsoft.ComponentDetection.Detectors.NuGet +{ + using System; + using System.Collections.Generic; + using System.Composition; + using System.Threading.Tasks; + using global::NuGet.Packaging; + using Microsoft.ComponentDetection.Contracts; + using Microsoft.ComponentDetection.Contracts.Internal; + using Microsoft.ComponentDetection.Contracts.TypedComponent; + + [Export(typeof(IComponentDetector))] + public class NuGetPackagesConfigDetector : FileComponentDetector, IExperimentalDetector + { + public override IList SearchPatterns => new[] { "packages.config" }; + + public override string Id => "NuGetPackagesConfig"; + + public override IEnumerable Categories => + new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.NuGet) }; + + public override IEnumerable SupportedComponentTypes => new[] { ComponentType.NuGet }; + + public override int Version => 1; + + protected override Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) + { + var packagesConfig = new PackagesConfigReader(processRequest.ComponentStream.Stream); + foreach (var package in packagesConfig.GetPackages()) + { + processRequest.SingleFileComponentRecorder.RegisterUsage( + new DetectedComponent( + new NuGetComponent( + package.PackageIdentity.Id, + package.PackageIdentity.Version.ToNormalizedString())), + true, + null, + package.IsDevelopmentDependency); + } + + return Task.CompletedTask; + } + } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs index cb88bc642..8855f93bd 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs @@ -52,10 +52,9 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary frameworkComponents = GetFrameworkComponents(lockFile); - var explicitReferencedDependencies = - GetTopLevelLibraries(lockFile) - .Select(x => GetLibraryComponentWithDependencyLookup(lockFile.Libraries, x.name, x.version, x.versionRange)) + var frameworkComponents = this.GetFrameworkComponents(lockFile); + var explicitReferencedDependencies = this.GetTopLevelLibraries(lockFile) + .Select(x => this.GetLibraryComponentWithDependencyLookup(lockFile.Libraries, x.name, x.version, x.versionRange)) .ToList(); var explicitlyReferencedComponentIds = explicitReferencedDependencies @@ -63,20 +62,20 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary target.GetTargetLibrary(x.Name)).Where(x => x != null)) { - NavigateAndRegister(target, explicitlyReferencedComponentIds, singleFileComponentRecorder, library, null, frameworkComponents); + this.NavigateAndRegister(target, explicitlyReferencedComponentIds, singleFileComponentRecorder, library, null, frameworkComponents); } } } catch (Exception e) { // If something went wrong, just ignore the package - Logger.LogFailedReadingFile(processRequest.ComponentStream.Location, e); + this.Logger.LogFailedReadingFile(processRequest.ComponentStream.Location, e); } return Task.CompletedTask; @@ -84,7 +83,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary dotnetRuntimePackageNames, HashSet visited = null) { - if (IsAFrameworkComponent(dotnetRuntimePackageNames, library.Name, library.Dependencies) - || library.Type == ProjectDependencyType) + if (this.IsAFrameworkComponent(dotnetRuntimePackageNames, library.Name, library.Dependencies) + || library.Type == ProjectDependencyType) { return; } @@ -127,7 +126,7 @@ private void NavigateAndRegister( else { visited.Add(dependency.Id); - NavigateAndRegister(target, explicitlyReferencedComponentIds, singleFileComponentRecorder, targetLibrary, libraryComponent.Component.Id, dotnetRuntimePackageNames, visited); + this.NavigateAndRegister(target, explicitlyReferencedComponentIds, singleFileComponentRecorder, targetLibrary, libraryComponent.Component.Id, dotnetRuntimePackageNames, visited); } } } @@ -138,14 +137,14 @@ private bool IsAFrameworkComponent(HashSet frameworkComponents, string l if (isAFrameworkComponent) { - frameworkComponentsThatWereOmmittedWithCount.AddOrUpdate(libraryName, 1, (name, existing) => existing + 1); + this.frameworkComponentsThatWereOmmittedWithCount.AddOrUpdate(libraryName, 1, (name, existing) => existing + 1); if (dependencies != null) { // Also track shallow children if this is a top level library so we have a rough count of how many things have been ommitted + root relationships foreach (var item in dependencies) { - frameworkComponentsThatWereOmmittedWithCount.AddOrUpdate(item.Id, 1, (name, existing) => existing + 1); + this.frameworkComponentsThatWereOmmittedWithCount.AddOrUpdate(item.Id, 1, (name, existing) => existing + 1); } } } @@ -166,7 +165,7 @@ private bool IsAFrameworkComponent(HashSet frameworkComponents, string l } } - // Next, we need to resolve project references -- This is a little funky, because project references are only stored via path in + // Next, we need to resolve project references -- This is a little funky, because project references are only stored via path in // project.assets.json, so we first build a list of all paths and then compare what is top level to them to resolve their // associated library. var projectDirectory = Path.GetDirectoryName(lockFile.PackageSpec.RestoreMetadata.ProjectPath); @@ -218,11 +217,11 @@ private LockFileLibrary GetLibraryComponentWithDependencyLookup(IList GetFrameworkComponents(LockFile lockFile) var frameworkDependencies = new HashSet(); foreach (var projectFileDependencyGroup in lockFile.ProjectFileDependencyGroups) { - var topLevelLibraries = GetTopLevelLibraries(lockFile); + var topLevelLibraries = this.GetTopLevelLibraries(lockFile); foreach (var (name, version, versionRange) in topLevelLibraries) { - if (netCoreFrameworkNames.Contains(name)) + if (this.netCoreFrameworkNames.Contains(name)) { frameworkDependencies.Add(name); foreach (var target in lockFile.Targets) { var matchingLibrary = target.Libraries.FirstOrDefault(x => x.Name == name); - HashSet dependencyComponents = GetDependencyComponentIds(lockFile, target, matchingLibrary.Dependencies); + var dependencyComponents = this.GetDependencyComponentIds(lockFile, target, matchingLibrary.Dependencies); frameworkDependencies.UnionWith(dependencyComponents); } } } } - foreach (var netstandardDep in netStandardDependencies) + foreach (var netstandardDep in this.netStandardDependencies) { frameworkDependencies.Add(netstandardDep); } @@ -262,7 +261,7 @@ private HashSet GetFrameworkComponents(LockFile lockFile) private HashSet GetDependencyComponentIds(LockFile lockFile, LockFileTarget target, IList dependencies, HashSet visited = null) { visited = visited ?? new HashSet(); - HashSet currentComponents = new HashSet(); + var currentComponents = new HashSet(); foreach (var dependency in dependencies) { if (visited.Contains(dependency.Id)) @@ -279,14 +278,14 @@ private HashSet GetDependencyComponentIds(LockFile lockFile, LockFileTar else { visited.Add(dependency.Id); - currentComponents.UnionWith(GetDependencyComponentIds(lockFile, target, libraryToExpand.Dependencies, visited)); + currentComponents.UnionWith(this.GetDependencyComponentIds(lockFile, target, libraryToExpand.Dependencies, visited)); } } return currentComponents; } - // This list is meant to encompass all net standard dependencies, but likely contains some net core app 1.x ones, too. + // This list is meant to encompass all net standard dependencies, but likely contains some net core app 1.x ones, too. // The specific guidance we got around populating this list is to do so based on creating a dotnet core 1.x app to make sure we had the complete // set of netstandard.library files that could show up in later sdk versions. private readonly string[] netStandardDependencies = new[] diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs b/src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs index 938ee8b5a..6c1acc376 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs @@ -63,7 +63,7 @@ public class PyPiClient : IPyPiClient public PyPiClient() { - cacheTelemetry = new PypiCacheTelemetryRecord() + this.cacheTelemetry = new PypiCacheTelemetryRecord() { NumCacheHits = 0, FinalCacheSize = 0, @@ -72,8 +72,8 @@ public PyPiClient() ~PyPiClient() { - cacheTelemetry.FinalCacheSize = cachedResponses.Count; - cacheTelemetry.Dispose(); + this.cacheTelemetry.FinalCacheSize = this.cachedResponses.Count; + this.cacheTelemetry.Dispose(); } /// @@ -84,23 +84,23 @@ public PyPiClient() /// The cached response or a new result from PyPi. private async Task GetAndCachePyPiResponse(string uri) { - if (!checkedMaxEntriesVariable) + if (!this.checkedMaxEntriesVariable) { - InitializeNonDefaultMemoryCache(); + this.InitializeNonDefaultMemoryCache(); } - if (cachedResponses.TryGetValue(uri, out HttpResponseMessage result)) + if (this.cachedResponses.TryGetValue(uri, out HttpResponseMessage result)) { - cacheTelemetry.NumCacheHits++; - Logger.LogVerbose("Retrieved cached Python data from " + uri); + this.cacheTelemetry.NumCacheHits++; + this.Logger.LogVerbose("Retrieved cached Python data from " + uri); return result; } - Logger.LogInfo("Getting Python data from " + uri); + this.Logger.LogInfo("Getting Python data from " + uri); var response = await HttpClient.GetAsync(uri); - + // The `first - wins` response accepted into the cache. This might be different from the input if another caller wins the race. - return await cachedResponses.GetOrCreateAsync(uri, cacheEntry => + return await this.cachedResponses.GetOrCreateAsync(uri, cacheEntry => { cacheEntry.SlidingExpiration = TimeSpan.FromSeconds(CACHEINTERVALSECONDS); // This entry will expire after CACHEINTERVALSECONDS seconds from last use cacheEntry.Size = 1; // Specify a size of 1 so a set number of entries can always be in the cache @@ -109,19 +109,19 @@ private async Task GetAndCachePyPiResponse(string uri) } /// - /// On the initial caching attempt, see if the user specified an override for + /// On the initial caching attempt, see if the user specified an override for /// PyPiMaxCacheEntries and recreate the cache if needed. /// private void InitializeNonDefaultMemoryCache() { - var maxEntriesVariable = EnvironmentVariableService.GetEnvironmentVariable("PyPiMaxCacheEntries"); + var maxEntriesVariable = this.EnvironmentVariableService.GetEnvironmentVariable("PyPiMaxCacheEntries"); if (!string.IsNullOrEmpty(maxEntriesVariable) && long.TryParse(maxEntriesVariable, out var maxEntries)) { - Logger.LogInfo($"Setting IPyPiClient max cache entries to {maxEntries}"); - cachedResponses = new MemoryCache(new MemoryCacheOptions { SizeLimit = maxEntries }); + this.Logger.LogInfo($"Setting IPyPiClient max cache entries to {maxEntries}"); + this.cachedResponses = new MemoryCache(new MemoryCacheOptions { SizeLimit = maxEntries }); } - checkedMaxEntriesVariable = true; + this.checkedMaxEntriesVariable = true; } public async Task> FetchPackageDependencies(string name, string version, PythonProjectRelease release) @@ -129,15 +129,15 @@ public async Task> FetchPackageDependencies(st var dependencies = new List(); var uri = release.Url.ToString(); - var response = await GetAndCachePyPiResponse(uri); + var response = await this.GetAndCachePyPiResponse(uri); if (!response.IsSuccessStatusCode) { - Logger.LogWarning($"Http GET at {release.Url} failed with status code {response.StatusCode}"); + this.Logger.LogWarning($"Http GET at {release.Url} failed with status code {response.StatusCode}"); return dependencies; } - ZipArchive package = new ZipArchive(await response.Content.ReadAsStreamAsync()); + var package = new ZipArchive(await response.Content.ReadAsStreamAsync()); var entry = package.GetEntry($"{name.Replace('-', '_')}-{version}.dist-info/METADATA"); @@ -147,7 +147,7 @@ public async Task> FetchPackageDependencies(st return dependencies; } - List content = new List(); + var content = new List(); using (var stream = entry.Open()) { using var streamReader = new StreamReader(stream); @@ -197,25 +197,25 @@ public async Task>> GetRele { using var r = new PypiRetryTelemetryRecord { Name = spec.Name, DependencySpecifiers = spec.DependencySpecifiers?.ToArray(), StatusCode = result.Result.StatusCode }; - Logger.LogWarning($"Received {(int)result.Result.StatusCode} {result.Result.ReasonPhrase} from {requestUri}. Waiting {timeSpan} before retry attempt {retryCount}"); + this.Logger.LogWarning($"Received {(int)result.Result.StatusCode} {result.Result.ReasonPhrase} from {requestUri}. Waiting {timeSpan} before retry attempt {retryCount}"); - Interlocked.Increment(ref retries); + Interlocked.Increment(ref this.retries); }) .ExecuteAsync(() => { - if (Interlocked.Read(ref retries) >= MAXRETRIES) + if (Interlocked.Read(ref this.retries) >= MAXRETRIES) { return Task.FromResult(null); } - return GetAndCachePyPiResponse(requestUri); + return this.GetAndCachePyPiResponse(requestUri); }); if (request == null) { using var r = new PypiMaxRetriesReachedTelemetryRecord { Name = spec.Name, DependencySpecifiers = spec.DependencySpecifiers?.ToArray() }; - Logger.LogWarning($"Call to pypi.org failed, but no more retries allowed!"); + this.Logger.LogWarning($"Call to pypi.org failed, but no more retries allowed!"); return new SortedDictionary>(); } @@ -224,7 +224,7 @@ public async Task>> GetRele { using var r = new PypiFailureTelemetryRecord { Name = spec.Name, DependencySpecifiers = spec.DependencySpecifiers?.ToArray(), StatusCode = request.StatusCode }; - Logger.LogWarning($"Received {(int)request.StatusCode} {request.ReasonPhrase} from {requestUri}"); + this.Logger.LogWarning($"Received {(int)request.StatusCode} {request.ReasonPhrase} from {requestUri}"); return new SortedDictionary>(); } @@ -247,8 +247,8 @@ public async Task>> GetRele } catch (ArgumentException ae) { - Logger.LogError($"Component {release.Key} : {JsonConvert.SerializeObject(release.Value)} could not be added to the sorted list of pip components for spec={spec.Name}. Usually this happens with unexpected PyPi version formats (e.g. prerelease/dev versions). Error details follow:"); - Logger.LogException(ae, true); + this.Logger.LogError($"Component {release.Key} : {JsonConvert.SerializeObject(release.Value)} could not be added to the sorted list of pip components for spec={spec.Name}. Usually this happens with unexpected PyPi version formats (e.g. prerelease/dev versions). Error details follow:"); + this.Logger.LogException(ae, true); continue; } } @@ -256,4 +256,4 @@ public async Task>> GetRele return versions; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs index eb1a63811..9114acc50 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs @@ -31,10 +31,10 @@ public class PipComponentDetector : FileComponentDetector protected override async Task> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs) { - CurrentScanRequest.DetectorArgs.TryGetValue("Pip.PythonExePath", out string pythonExePath); - if (!await PythonCommandService.PythonExists(pythonExePath)) + this.CurrentScanRequest.DetectorArgs.TryGetValue("Pip.PythonExePath", out var pythonExePath); + if (!await this.PythonCommandService.PythonExists(pythonExePath)) { - Logger.LogInfo($"No python found on system. Python detection will not run."); + this.Logger.LogInfo($"No python found on system. Python detection will not run."); return Enumerable.Empty().ToObservable(); } @@ -44,13 +44,13 @@ protected override async Task> OnPrepareDetection(IO protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) { - CurrentScanRequest.DetectorArgs.TryGetValue("Pip.PythonExePath", out string pythonExePath); + this.CurrentScanRequest.DetectorArgs.TryGetValue("Pip.PythonExePath", out var pythonExePath); var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; try { - var initialPackages = await PythonCommandService.ParseFile(file.Location, pythonExePath); + var initialPackages = await this.PythonCommandService.ParseFile(file.Location, pythonExePath); var listedPackage = initialPackages.Where(tuple => tuple.Item1 != null) .Select(tuple => tuple.Item1) .Where(x => !string.IsNullOrWhiteSpace(x)) @@ -58,7 +58,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio .Where(x => !x.PackageIsUnsafe()) .ToList(); - var roots = await PythonResolver.ResolveRoots(listedPackage); + var roots = await this.PythonResolver.ResolveRoots(listedPackage); RecordComponents( singleFileComponentRecorder, @@ -71,7 +71,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio } catch (Exception e) { - Logger.LogFailedReadingFile(file.Location, e); + this.Logger.LogFailedReadingFile(file.Location, e); } } @@ -121,4 +121,4 @@ private static void RecordComponents( } } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs index 495b843cf..84efab5de 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs @@ -11,7 +11,7 @@ namespace Microsoft.ComponentDetection.Detectors.Pip [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PipDependencySpecification { - private string DebuggerDisplay => $"{Name} ({string.Join(';', DependencySpecifiers)})"; + private string DebuggerDisplay => $"{this.Name} ({string.Join(';', this.DependencySpecifiers)})"; /// /// Gets or sets the package (ex: pyyaml). @@ -58,7 +58,7 @@ public class PipDependencySpecification /// public bool PackageIsUnsafe() { - return PackagesToIgnore.Contains(Name); + return PackagesToIgnore.Contains(this.Name); } /// @@ -79,20 +79,20 @@ public PipDependencySpecification(string packageString, bool requiresDist = fals { var distMatch = RequiresDistRegex.Match(packageString); - for (int i = 1; i < distMatch.Groups.Count; i++) + for (var i = 1; i < distMatch.Groups.Count; i++) { if (string.IsNullOrWhiteSpace(distMatch.Groups[i].Value)) { continue; } - if (string.IsNullOrWhiteSpace(Name)) + if (string.IsNullOrWhiteSpace(this.Name)) { - Name = distMatch.Groups[i].Value; + this.Name = distMatch.Groups[i].Value; } else { - DependencySpecifiers = distMatch.Groups[i].Value.Split(','); + this.DependencySpecifiers = distMatch.Groups[i].Value.Split(','); } } } @@ -103,20 +103,20 @@ public PipDependencySpecification(string packageString, bool requiresDist = fals if (nameMatches.Captures.Count > 0) { - Name = nameMatches.Captures[0].Value; + this.Name = nameMatches.Captures[0].Value; } else { - Name = packageString; + this.Name = packageString; } if (versionMatches.Captures.Count > 0) { - DependencySpecifiers = versionMatches.Captures[0].Value.Split(','); + this.DependencySpecifiers = versionMatches.Captures[0].Value.Split(','); } } - DependencySpecifiers = DependencySpecifiers.Where(x => !x.Contains("python_version")).ToList(); + this.DependencySpecifiers = this.DependencySpecifiers.Where(x => !x.Contains("python_version")).ToList(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PipGraphNode.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PipGraphNode.cs index 22606f725..a6aad1e77 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PipGraphNode.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PipGraphNode.cs @@ -11,7 +11,7 @@ public class PipGraphNode { public PipGraphNode(PipComponent value) { - Value = value; + this.Value = value; } public PipComponent Value { get; set; } @@ -20,4 +20,4 @@ public PipGraphNode(PipComponent value) public List Parents { get; } = new List(); } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs index 5ff88f1f2..c58334d2a 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs @@ -18,7 +18,7 @@ public class PythonCommandService : IPythonCommandService public async Task PythonExists(string pythonPath = null) { - return !string.IsNullOrEmpty(await ResolvePython(pythonPath)); + return !string.IsNullOrEmpty(await this.ResolvePython(pythonPath)); } public async Task> ParseFile(string filePath, string pythonPath = null) @@ -30,13 +30,13 @@ public async Task PythonExists(string pythonPath = null) if (filePath.EndsWith(".py")) { - return (await ParseSetupPyFile(filePath, pythonPath)) + return (await this.ParseSetupPyFile(filePath, pythonPath)) .Select(component => (component, null)) .ToList(); } else if (filePath.EndsWith(".txt")) { - return ParseRequirementsTextFile(filePath); + return this.ParseRequirementsTextFile(filePath); } else { @@ -46,7 +46,7 @@ public async Task PythonExists(string pythonPath = null) private async Task> ParseSetupPyFile(string filePath, string pythonExePath = null) { - var pythonExecutable = await ResolvePython(pythonExePath); + var pythonExecutable = await this.ResolvePython(pythonExePath); if (string.IsNullOrEmpty(pythonExecutable)) { @@ -55,7 +55,7 @@ private async Task> ParseSetupPyFile(string filePath, string pytho // This calls out to python and prints out an array like: [ packageA, packageB, packageC ] // We need to have python interpret this file because install_requires can be composed at runtime - var command = await CommandLineInvocationService.ExecuteCommand(pythonExecutable, null, $"-c \"import distutils.core; setup=distutils.core.run_setup('{filePath.Replace('\\', '/')}'); print(setup.install_requires)\""); + var command = await this.CommandLineInvocationService.ExecuteCommand(pythonExecutable, null, $"-c \"import distutils.core; setup=distutils.core.run_setup('{filePath.Replace('\\', '/')}'); print(setup.install_requires)\""); if (command.ExitCode != 0) { @@ -128,9 +128,9 @@ private async Task> ParseSetupPyFile(string filePath, string pytho private async Task ResolvePython(string pythonPath = null) { - string pythonCommand = string.IsNullOrEmpty(pythonPath) ? "python" : pythonPath; + var pythonCommand = string.IsNullOrEmpty(pythonPath) ? "python" : pythonPath; - if (await CanCommandBeLocated(pythonCommand)) + if (await this.CanCommandBeLocated(pythonCommand)) { return pythonCommand; } @@ -140,7 +140,7 @@ private async Task ResolvePython(string pythonPath = null) private async Task CanCommandBeLocated(string pythonPath) { - return await CommandLineInvocationService.CanCommandBeLocated(pythonPath, new List { "python3", "python2" }, "--version"); + return await this.CommandLineInvocationService.CanCommandBeLocated(pythonPath, new List { "python3", "python2" }, "--version"); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs index 2444149f9..a563c6642 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs @@ -32,7 +32,7 @@ public async Task> ResolveRoots(IList> ResolveRoots(IList(); + return await this.ProcessQueue(state) ?? new List(); } private async Task> ProcessQueue(PythonResolverState state) @@ -68,7 +68,7 @@ private async Task> ProcessQueue(PythonResolverState state) var (root, currentNode) = state.ProcessingQueue.Dequeue(); // gather all dependencies for the current node - var dependencies = (await FetchPackageDependencies(state, currentNode)).Where(x => !x.PackageIsUnsafe()); + var dependencies = (await this.FetchPackageDependencies(state, currentNode)).Where(x => !x.PackageIsUnsafe()); foreach (var dependencyNode in dependencies) { @@ -81,13 +81,13 @@ private async Task> ProcessQueue(PythonResolverState state) } else if (node != null) { - Logger.LogWarning($"Candidate version ({node.Value.Id}) for {dependencyNode.Name} already exists in map and the version is NOT valid."); - Logger.LogWarning($"Specifiers: {string.Join(',', dependencyNode.DependencySpecifiers)} for package {currentNode.Name} caused this."); + this.Logger.LogWarning($"Candidate version ({node.Value.Id}) for {dependencyNode.Name} already exists in map and the version is NOT valid."); + this.Logger.LogWarning($"Specifiers: {string.Join(',', dependencyNode.DependencySpecifiers)} for package {currentNode.Name} caused this."); // The currently selected version is invalid, try to see if there is another valid version available - if (!await InvalidateAndReprocessAsync(state, node, dependencyNode)) + if (!await this.InvalidateAndReprocessAsync(state, node, dependencyNode)) { - Logger.LogWarning($"Version Resolution for {dependencyNode.Name} failed, assuming last valid version is used."); + this.Logger.LogWarning($"Version Resolution for {dependencyNode.Name} failed, assuming last valid version is used."); // there is no valid version available for the node, dependencies are incompatible, } @@ -95,7 +95,7 @@ private async Task> ProcessQueue(PythonResolverState state) else { // We haven't encountered this package before, so let's fetch it and find a candidate - var result = await PypiClient.GetReleases(dependencyNode); + var result = await this.PypiClient.GetReleases(dependencyNode); if (result.Keys.Any()) { @@ -103,13 +103,13 @@ private async Task> ProcessQueue(PythonResolverState state) var candidateVersion = state.ValidVersionMap[dependencyNode.Name].Keys.Any() ? state.ValidVersionMap[dependencyNode.Name].Keys.Last() : null; - AddGraphNode(state, state.NodeReferences[currentNode.Name], dependencyNode.Name, candidateVersion); + this.AddGraphNode(state, state.NodeReferences[currentNode.Name], dependencyNode.Name, candidateVersion); state.ProcessingQueue.Enqueue((root, dependencyNode)); } else { - Logger.LogWarning($"Dependency Package {dependencyNode.Name} not found in Pypi. Skipping package"); + this.Logger.LogWarning($"Dependency Package {dependencyNode.Name} not found in Pypi. Skipping package"); } } } @@ -146,7 +146,7 @@ private async Task InvalidateAndReprocessAsync( node.Value = new PipComponent(pipComponent.Name, candidateVersion); - var dependencies = (await FetchPackageDependencies(state, newSpec)).ToDictionary(x => x.Name, x => x); + var dependencies = (await this.FetchPackageDependencies(state, newSpec)).ToDictionary(x => x.Name, x => x); var toRemove = new List(); foreach (var child in node.Children) @@ -159,7 +159,7 @@ private async Task InvalidateAndReprocessAsync( } else if (!PythonVersionUtilities.VersionValidForSpec(pipChild.Version, newDependency.DependencySpecifiers)) { - if (!await InvalidateAndReprocessAsync(state, child, newDependency)) + if (!await this.InvalidateAndReprocessAsync(state, child, newDependency)) { return false; } @@ -187,7 +187,7 @@ private async Task> FetchPackageDependencies( return new List(); } - return await PypiClient.FetchPackageDependencies(spec.Name, candidateVersion, packageToFetch); + return await this.PypiClient.FetchPackageDependencies(spec.Name, candidateVersion, packageToFetch); } private void AddGraphNode(PythonResolverState state, PipGraphNode parent, string name, string version) diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersion.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersion.cs index 9fb9a63a0..2662144fa 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersion.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersion.cs @@ -16,7 +16,7 @@ public class PythonVersion : IComparable public bool Valid { get; set; } - public bool IsReleasedPackage => string.IsNullOrEmpty(PreReleaseLabel) && !PreReleaseNumber.HasValue && !DevNumber.HasValue; + public bool IsReleasedPackage => string.IsNullOrEmpty(this.PreReleaseLabel) && !this.PreReleaseNumber.HasValue && !this.DevNumber.HasValue; public int Epoch { get; set; } @@ -41,60 +41,60 @@ public PythonVersion(string version) var toOperate = version; if (version.EndsWith(".*")) { - Floating = true; + this.Floating = true; toOperate = toOperate.Replace(".*", string.Empty); } - match = PythonVersionRegex.Match(version); + this.match = PythonVersionRegex.Match(version); - if (!match.Success || !string.Equals(match.Value, toOperate, StringComparison.OrdinalIgnoreCase)) + if (!this.match.Success || !string.Equals(this.match.Value, toOperate, StringComparison.OrdinalIgnoreCase)) { - Valid = false; + this.Valid = false; return; } - var groups = match.Groups; + var groups = this.match.Groups; // Epoch is optional, implicitly 0 if not present - if (groups["epoch"].Success && int.TryParse(groups["epoch"].Value, out int epoch)) + if (groups["epoch"].Success && int.TryParse(groups["epoch"].Value, out var epoch)) { - Epoch = epoch; + this.Epoch = epoch; } else { - Epoch = 0; + this.Epoch = 0; } - Release = groups["release"].Success ? groups["release"].Value : string.Empty; - PreReleaseLabel = groups["pre_l"].Success ? groups["pre_l"].Value : string.Empty; + this.Release = groups["release"].Success ? groups["release"].Value : string.Empty; + this.PreReleaseLabel = groups["pre_l"].Success ? groups["pre_l"].Value : string.Empty; - if (groups["pre_n"].Success && int.TryParse(groups["pre_n"].Value, out int preReleaseNumber)) + if (groups["pre_n"].Success && int.TryParse(groups["pre_n"].Value, out var preReleaseNumber)) { - PreReleaseNumber = preReleaseNumber; + this.PreReleaseNumber = preReleaseNumber; } - if (groups["post_n1"].Success && int.TryParse(groups["post_n1"].Value, out int postRelease1)) + if (groups["post_n1"].Success && int.TryParse(groups["post_n1"].Value, out var postRelease1)) { - PostNumber = postRelease1; + this.PostNumber = postRelease1; } - if (groups["post_n2"].Success && int.TryParse(groups["post_n2"].Value, out int postRelease2)) + if (groups["post_n2"].Success && int.TryParse(groups["post_n2"].Value, out var postRelease2)) { - PostNumber = postRelease2; + this.PostNumber = postRelease2; } if (groups["dev_l"].Success) { - DevLabel = groups["dev_l"].Value; - DevNumber = 0; + this.DevLabel = groups["dev_l"].Value; + this.DevNumber = 0; } - if (groups["dev_n"].Success && int.TryParse(groups["dev_n"].Value, out int devNumber)) + if (groups["dev_n"].Success && int.TryParse(groups["dev_n"].Value, out var devNumber)) { - DevNumber = devNumber; + this.DevNumber = devNumber; } - Valid = true; + this.Valid = true; } public static bool operator >(PythonVersion operand1, PythonVersion operand2) @@ -124,39 +124,39 @@ public int CompareTo(PythonVersion other) return 1; } - if (Epoch > other.Epoch) + if (this.Epoch > other.Epoch) { return 1; } - else if (Epoch < other.Epoch) + else if (this.Epoch < other.Epoch) { return -1; } - if (!string.Equals(Release, other.Release, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(this.Release, other.Release, StringComparison.OrdinalIgnoreCase)) { - int result = CompareReleaseVersions(this, other); + var result = CompareReleaseVersions(this, other); if (result != 0) { return result; } } - int preReleaseComparison = ComparePreRelease(this, other); + var preReleaseComparison = ComparePreRelease(this, other); if (preReleaseComparison != 0) { return preReleaseComparison; } - int postNumberComparison = ComparePostNumbers(this, other); + var postNumberComparison = ComparePostNumbers(this, other); if (postNumberComparison != 0) { return postNumberComparison; } - int devNumberComparison = CompareDevValues(this, other); + var devNumberComparison = CompareDevValues(this, other); return devNumberComparison; } @@ -277,8 +277,8 @@ private static int CompareDevValues(PythonVersion a, PythonVersion b) private static int CompareReleaseVersions(PythonVersion a, PythonVersion b) { - List aSplit = a.Release.Split('.').Select(x => int.Parse(x)).ToList(); - List bSplit = b.Release.Split('.').Select(x => int.Parse(x)).ToList(); + var aSplit = a.Release.Split('.').Select(x => int.Parse(x)).ToList(); + var bSplit = b.Release.Split('.').Select(x => int.Parse(x)).ToList(); int longer; int shorter; @@ -307,7 +307,7 @@ private static int CompareReleaseVersions(PythonVersion a, PythonVersion b) lengthCompare = 0; } - for (int i = 0; i < shorter; i++) + for (var i = 0; i < shorter; i++) { if (aSplit[i] > bSplit[i]) { @@ -327,4 +327,4 @@ private static int CompareReleaseVersions(PythonVersion a, PythonVersion b) return lengthCompare; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersionComparer.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersionComparer.cs index 58502141b..6e73594cf 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersionComparer.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersionComparer.cs @@ -6,8 +6,8 @@ public class PythonVersionComparer : IComparer { public int Compare(string x, string y) { - PythonVersion xVer = new PythonVersion(x); - PythonVersion yVer = new PythonVersion(y); + var xVer = new PythonVersion(x); + var yVer = new PythonVersion(y); return xVer.CompareTo(yVer); } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersionUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersionUtilities.cs index 73524658e..08b49d5fb 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersionUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersionUtilities.cs @@ -28,16 +28,16 @@ public static bool VersionValidForSpec(string version, IList specs) private static bool VersionValidForSpec(string version, string spec) { - char[] opChars = new char[] { '=', '<', '>', '~', '!' }; + var opChars = new char[] { '=', '<', '>', '~', '!' }; var specArray = spec.ToCharArray(); - int i = 0; + var i = 0; while (i < spec.Length && i < 3 && opChars.Contains(specArray[i])) { i++; } - string op = spec.Substring(0, i); + var op = spec.Substring(0, i); var targetVer = new PythonVersion(version); var specVer = new PythonVersion(spec.Substring(i)); @@ -84,7 +84,7 @@ public static bool CheckEquality(string version, string specVer, bool fuzzy = fa return true; } - int i = 0; + var i = 0; var splitVersion = version.Split('.'); var splitSpecVer = specVer.Split('.'); @@ -93,7 +93,7 @@ public static bool CheckEquality(string version, string specVer, bool fuzzy = fa if (fuzzy && i == (splitSpecVer.Length - 1)) { // Fuzzy matching excludes everything after first two - if (splitVersion.Length > i && int.TryParse(splitVersion[i], out int lVer) && int.TryParse(splitSpecVer[i], out int rVer) && lVer >= rVer) + if (splitVersion.Length > i && int.TryParse(splitVersion[i], out var lVer) && int.TryParse(splitSpecVer[i], out var rVer) && lVer >= rVer) { return true; } diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/Package.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/Package.cs index 26983714c..1bbeafaa0 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/Package.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/Package.cs @@ -17,7 +17,7 @@ public class Package public override string ToString() { - return name; + return this.name; } } #pragma warning restore SA1300 diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetector.cs index affc9c8d1..32164f19c 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetector.cs @@ -27,7 +27,7 @@ public class PnpmComponentDetector : FileComponentDetector public PnpmComponentDetector() { - NeedsAutomaticRootDependencyCalculation = true; + this.NeedsAutomaticRootDependencyCalculation = true; } protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) @@ -35,21 +35,21 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - Logger.LogVerbose("Found yaml file: " + file.Location); - string skippedFolder = SkippedFolders.FirstOrDefault(folder => file.Location.Contains(folder)); + this.Logger.LogVerbose("Found yaml file: " + file.Location); + var skippedFolder = this.SkippedFolders.FirstOrDefault(folder => file.Location.Contains(folder)); if (!string.IsNullOrEmpty(skippedFolder)) { - Logger.LogVerbose($"Skipping found file, it was detected as being within a {skippedFolder} folder."); + this.Logger.LogVerbose($"Skipping found file, it was detected as being within a {skippedFolder} folder."); } try { var pnpmYaml = await PnpmParsingUtilities.DeserializePnpmYamlFile(file); - RecordDependencyGraphFromFile(pnpmYaml, singleFileComponentRecorder); + this.RecordDependencyGraphFromFile(pnpmYaml, singleFileComponentRecorder); } catch (Exception e) { - Logger.LogFailedReadingFile(file.Location, e); + this.Logger.LogFailedReadingFile(file.Location, e); } } @@ -64,7 +64,7 @@ private void RecordDependencyGraphFromFile(PnpmYaml yaml, ISingleFileComponentRe } var parentDetectedComponent = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPath(pnpmPackagePath: packageKeyValue.Key); - bool isDevDependency = packageKeyValue.Value != null && PnpmParsingUtilities.IsPnpmPackageDevDependency(packageKeyValue.Value); + var isDevDependency = packageKeyValue.Value != null && PnpmParsingUtilities.IsPnpmPackageDevDependency(packageKeyValue.Value); singleFileComponentRecorder.RegisterUsage(parentDetectedComponent, isDevelopmentDependency: isDevDependency); parentDetectedComponent = singleFileComponentRecorder.GetComponent(parentDetectedComponent.Component.Id); @@ -73,12 +73,12 @@ private void RecordDependencyGraphFromFile(PnpmYaml yaml, ISingleFileComponentRe foreach (var dependency in packageKeyValue.Value.dependencies) { // Ignore local packages. - if (IsLocalDependency(dependency)) + if (this.IsLocalDependency(dependency)) { continue; } - var childDetectedComponent = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPath(pnpmPackagePath: CreatePnpmPackagePathFromDependency(dependency.Key, dependency.Value)); + var childDetectedComponent = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPath(pnpmPackagePath: this.CreatePnpmPackagePathFromDependency(dependency.Key, dependency.Value)); // Older code used the root's dev dependency value. We're leaving this null until we do a second pass to look at each components' top level referrers. singleFileComponentRecorder.RegisterUsage(childDetectedComponent, parentComponentId: parentDetectedComponent.Component.Id, isDevelopmentDependency: null); @@ -110,4 +110,4 @@ private string CreatePnpmPackagePathFromDependency(string dependencyName, string return dependencyVersion.Contains('/') ? dependencyVersion : $"/{dependencyName}/{dependencyVersion}"; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmParsingUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmParsingUtilities.cs index 585941698..8bada0f7e 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmParsingUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmParsingUtilities.cs @@ -39,7 +39,7 @@ public static bool IsPnpmPackageDevDependency(Package pnpmPackage) private static (string Name, string Version) ExtractNameAndVersionFromPnpmPackagePath(string pnpmPackagePath) { var pnpmComponentDefSections = pnpmPackagePath.Trim('/').Split('/'); - (string packageVersion, int indexVersionIsAt) = GetPackageVersion(pnpmComponentDefSections); + (var packageVersion, var indexVersionIsAt) = GetPackageVersion(pnpmComponentDefSections); if (indexVersionIsAt == -1) { // No version = not expected input diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/pnpmVersionSpecification.md b/src/Microsoft.ComponentDetection.Detectors/pnpm/pnpmVersionSpecification.md index 96a55d864..44f073c07 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/pnpmVersionSpecification.md +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/pnpmVersionSpecification.md @@ -14,7 +14,7 @@ is going to be represented in the lock files of pnpm as: This nomenclature is known for the pnpm community as the package path, and is normally found as the package definition in the section Packages of the lock files (pnpm-lock.yml and shrinkwrap.yml). Normally most of the packages has this structure but there others situations like [peer dependencies](https://pnpm.js.org/en/how-peers-are-resolved), where the path format can change to represent the peer dependency combination, for example: -First the regular case, suppose that we have in the package.json a dependency defined as +First the regular case, suppose that we have in the package.json a dependency defined as ``` { @@ -31,7 +31,7 @@ using the command pnpm install this is going to create a folder structure like |- foo (hardlink) |- abc (symlink) ``` -and the entry in the lock file is going to looks like +and the entry in the lock file is going to looks like ``` /foo/1.0.0 ``` diff --git a/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs index fd031bfdf..ef743bce0 100644 --- a/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs @@ -12,7 +12,7 @@ namespace Microsoft.ComponentDetection.Detectors.Poetry { [Export(typeof(IComponentDetector))] - public class PoetryComponentDetector : FileComponentDetector, IDefaultOffComponentDetector + public class PoetryComponentDetector : FileComponentDetector, IExperimentalDetector { public override string Id => "Poetry"; @@ -20,7 +20,7 @@ public class PoetryComponentDetector : FileComponentDetector, IDefaultOffCompone public override IEnumerable SupportedComponentTypes => new[] { ComponentType.Pip }; - public override int Version { get; } = 1; + public override int Version { get; } = 2; public override IEnumerable Categories => new List { "Python" }; @@ -28,7 +28,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary(); poetryLock.package.ToList().ForEach(package => diff --git a/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs index 3ca15704f..5bed9ed60 100644 --- a/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs @@ -1,26 +1,26 @@ // Ruby detection highlights and todos: -// +// // Dependencies are "fuzzy versions": // this in and of itself could be solved by deferring dependency resolution alone until after all components are registered. // Different sections of Ruby's lockfile can point into other sections, and the authoritative version is not replicated across // sections-- it's only stored in, say, the Gems section. -// +// // Git components are even stranger in Ruby land: -// they have an annotation for a git component that is a "name" that has no relationship to how we normally think of -// a GitComponent (remote / version). The mapping from git component name to a GitComponent can't really be handled -// in ComponentRecorder today, because "component name" for a Git component is a Ruby specific concept. +// they have an annotation for a git component that is a "name" that has no relationship to how we normally think of +// a GitComponent (remote / version). The mapping from git component name to a GitComponent can't really be handled +// in ComponentRecorder today, because "component name" for a Git component is a Ruby specific concept. // This could be pointing to a sideloaded storage in ComponentRecorder (e.g. a style storage that detectors // could use to track related state as their execution goes on). -// +// // The basic approach in ruby is to do two passes: // first, make sure you have all authoritative components, then, resolve and register all dependency relationships. -// +// // If we had sideloaded state for nodes in the graph, I could see us at least being able to remove the "name" mapping from ruby. // Deferred dependencies is a lot more complicated, you would basically need a way to set up a pointer to a component based on a mapped value // (in this case, just component name sans version) that would be resolved in an arbitrary way after the graph writing was "done". // I don't think this is impossible (having a custom delegate for a detector to identify and map nodes to one another seems pretty easy), // but seems complicated. -// +// // There is a possibility to use manual root detection instead of automatic: // Gemfile.lock comes with a section called "Dependencies", in the section are listed the dependencies that the user specified in the Gemfile, // is necessary to investigate if this section is a new adition or always has been there. @@ -67,18 +67,18 @@ private class Dependency public string Location { get; } - public string Id => $"{Name}:{Location}"; + public string Id => $"{this.Name}:{this.Location}"; public Dependency(string name, string location) { - Name = name; - Location = location; + this.Name = name; + this.Location = location; } } public RubyComponentDetector() { - NeedsAutomaticRootDependencyCalculation = true; + this.NeedsAutomaticRootDependencyCalculation = true; } protected override Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) @@ -86,8 +86,8 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary(string.Format("{0}:{1}", name, file.Location), addComponent); dependencies.TryAdd(string.Format("{0}:{1}", name, file.Location), new List()); break; @@ -154,8 +154,8 @@ private void ParseGemLockFile(ISingleFileComponentRecorder singleFileComponentRe else { // Throw this line away. Is this malformed? We were expecting a header - Logger.LogVerbose(lines[0]); - Logger.LogVerbose("Appears to be malformed/is not expected here. Expected heading."); + this.Logger.LogVerbose(lines[0]); + this.Logger.LogVerbose("Appears to be malformed/is not expected here. Expected heading."); lines.RemoveAt(0); } } @@ -165,14 +165,14 @@ private void ParseGemLockFile(ISingleFileComponentRecorder singleFileComponentRe singleFileComponentRecorder.RegisterUsage(detectedComponent); } - foreach (string key in dependencies.Keys) + foreach (var key in dependencies.Keys) { - foreach (Dependency dependency in dependencies[key]) + foreach (var dependency in dependencies[key]) { // there are cases that we ommit the dependency - // because its version is not valid like for example + // because its version is not valid like for example // is a relative version instead of an absolute one - // because of that there are children elements + // because of that there are children elements // that does not contains a entry in the dictionary // those elements should be removed if (components.ContainsKey(dependency.Id)) @@ -188,7 +188,7 @@ private void ParseSection(SectionType sectionType, List lines, Dictionar string name, remote, revision; name = remote = revision = string.Empty; - bool wasParentDependencyExcluded = false; + var wasParentDependencyExcluded = false; while (lines.Count > 0) { @@ -230,9 +230,9 @@ private void ParseSection(SectionType sectionType, List lines, Dictionar var version = splits[1].Substring(1, splits[1].Length - 2); TypedComponent newComponent; - if (IsVersionRelative(version)) + if (this.IsVersionRelative(version)) { - Logger.LogWarning($"Found component with invalid version, name = {name} and version = {version}"); + this.Logger.LogWarning($"Found component with invalid version, name = {name} and version = {version}"); wasParentDependencyExcluded = true; continue; } @@ -246,8 +246,8 @@ private void ParseSection(SectionType sectionType, List lines, Dictionar newComponent = new GitComponent(new Uri(remote), revision); } - DetectedComponent addComponent = new DetectedComponent(newComponent); - string lookupKey = string.Format("{0}:{1}", name, file.Location); + var addComponent = new DetectedComponent(newComponent); + var lookupKey = string.Format("{0}:{1}", name, file.Location); if (components.ContainsKey(lookupKey)) { diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs b/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs index aaed25503..d19b2160f 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs @@ -14,10 +14,10 @@ public class CargoDependencyData public CargoDependencyData() { - CargoWorkspaces = new HashSet(); - CargoWorkspaceExclusions = new HashSet(); - NonDevDependencies = new List(); - DevDependencies = new List(); + this.CargoWorkspaces = new HashSet(); + this.CargoWorkspaceExclusions = new HashSet(); + this.NonDevDependencies = new List(); + this.DevDependencies = new List(); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs index 8b2e711ae..bf8b19cc2 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs @@ -29,16 +29,14 @@ public class CargoPackage public override bool Equals(object obj) { var package = obj as CargoPackage; - return package != null && - name.Equals(package.name) && - version.Equals(package.version, StringComparison.OrdinalIgnoreCase); + return package != null && this.name.Equals(package.name) && this.version.Equals(package.version, StringComparison.OrdinalIgnoreCase); } public override int GetHashCode() { var hashCode = -2143789899; - hashCode = (hashCode * -1521134295) + EqualityComparer.Default.GetHashCode(name); - hashCode = (hashCode * -1521134295) + EqualityComparer.Default.GetHashCode(version.ToLowerInvariant()); + hashCode = (hashCode * -1521134295) + EqualityComparer.Default.GetHashCode(this.name); + hashCode = (hashCode * -1521134295) + EqualityComparer.Default.GetHashCode(this.version.ToLowerInvariant()); return hashCode; } } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs b/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs index 2115c6e3b..030214021 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs @@ -13,7 +13,7 @@ public class DependencySpecification public DependencySpecification() { - dependencies = new Dictionary>>(); + this.dependencies = new Dictionary>>(); } public void Add(string name, string cargoVersionSpecifier) @@ -25,27 +25,27 @@ public void Add(string name, string cargoVersionSpecifier) ranges.Add(new Range(specifier.Trim())); } - if (!dependencies.ContainsKey(name)) + if (!this.dependencies.ContainsKey(name)) { - dependencies.Add(name, new HashSet>()); + this.dependencies.Add(name, new HashSet>()); } - dependencies[name].Add(ranges); + this.dependencies[name].Add(ranges); } public bool MatchesPackage(CargoPackage package) { - if (!dependencies.ContainsKey(package.name)) + if (!this.dependencies.ContainsKey(package.name)) { return false; } - foreach (var ranges in dependencies[package.name]) + foreach (var ranges in this.dependencies[package.name]) { var allSatisfied = true; foreach (var range in ranges) { - if (SemVersion.TryParse(package.version, out SemVersion sv)) + if (SemVersion.TryParse(package.version, out var sv)) { if (!range.IsSatisfied(sv)) { diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs index df47d2875..53d212e74 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs @@ -37,23 +37,23 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary cargoTomlComponentStream = ComponentStreamEnumerableFactory.GetComponentStreams(lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, (name, directoryName) => false, recursivelyScanDirectories: false); + var lockFileInfo = new FileInfo(cargoLockFile.Location); + var cargoTomlComponentStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, (name, directoryName) => false, recursivelyScanDirectories: false); - CargoDependencyData cargoDependencyData = RustCrateUtilities.ExtractRootDependencyAndWorkspaceSpecifications(cargoTomlComponentStream, singleFileComponentRecorder); + var cargoDependencyData = RustCrateUtilities.ExtractRootDependencyAndWorkspaceSpecifications(cargoTomlComponentStream, singleFileComponentRecorder); // If workspaces have been defined in the root cargo.toml file, scan for specified cargo.toml manifests - int numWorkspaceComponentStreams = 0; - int expectedWorkspaceTomlCount = cargoDependencyData.CargoWorkspaces.Count; + var numWorkspaceComponentStreams = 0; + var expectedWorkspaceTomlCount = cargoDependencyData.CargoWorkspaces.Count; if (expectedWorkspaceTomlCount > 0) { - string rootCargoTomlLocation = Path.Combine(lockFileInfo.DirectoryName, "Cargo.toml"); + var rootCargoTomlLocation = Path.Combine(lockFileInfo.DirectoryName, "Cargo.toml"); - IEnumerable cargoTomlWorkspaceComponentStreams = ComponentStreamEnumerableFactory.GetComponentStreams( + var cargoTomlWorkspaceComponentStreams = this.ComponentStreamEnumerableFactory.GetComponentStreams( lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, RustCrateUtilities.BuildExcludeDirectoryPredicateFromWorkspaces(lockFileInfo, cargoDependencyData.CargoWorkspaces, cargoDependencyData.CargoWorkspaceExclusions), @@ -68,14 +68,14 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary 1) { - Logger.LogWarning($"We are expecting exactly 1 accompanying Cargo.toml file next to the cargo.lock file found at {cargoLockFile.Location}"); + this.Logger.LogWarning($"We are expecting exactly 1 accompanying Cargo.toml file next to the cargo.lock file found at {cargoLockFile.Location}"); return Task.CompletedTask; } // If there is a mismatch between the number of expected and found workspaces, exit if (expectedWorkspaceTomlCount > numWorkspaceComponentStreams) { - Logger.LogWarning($"We are expecting at least {expectedWorkspaceTomlCount} accompanying Cargo.toml file(s) from workspaces outside of the root directory {lockFileInfo.DirectoryName}, but found {numWorkspaceComponentStreams}"); + this.Logger.LogWarning($"We are expecting at least {expectedWorkspaceTomlCount} accompanying Cargo.toml file(s) from workspaces outside of the root directory {lockFileInfo.DirectoryName}, but found {numWorkspaceComponentStreams}"); return Task.CompletedTask; } @@ -85,7 +85,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary public static CargoDependencyData ExtractRootDependencyAndWorkspaceSpecifications(IEnumerable cargoTomlComponentStream, ISingleFileComponentRecorder singleFileComponentRecorder) { - CargoDependencyData cargoDependencyData = new CargoDependencyData(); + var cargoDependencyData = new CargoDependencyData(); // The file handle is disposed if you call .First() on cargoTomlComponentStream // Since multiple Cargo.toml files for 1 Cargo.lock file obviously doesn't make sense @@ -56,18 +56,18 @@ public static CargoDependencyData ExtractRootDependencyAndWorkspaceSpecification singleFileComponentRecorder.AddAdditionalRelatedFile(cargoTomlFile.Location); // Extract the workspaces present, if any - if (cargoToml.ContainsKey(RustCrateUtilities.WorkspaceKey)) + if (cargoToml.ContainsKey(WorkspaceKey)) { - TomlTable workspaces = cargoToml.Get(RustCrateUtilities.WorkspaceKey); + var workspaces = cargoToml.Get(WorkspaceKey); - TomlObject workspaceMembers = workspaces.ContainsKey(RustCrateUtilities.WorkspaceMemberKey) ? workspaces[RustCrateUtilities.WorkspaceMemberKey] : null; - TomlObject workspaceExclusions = workspaces.ContainsKey(RustCrateUtilities.WorkspaceExcludeKey) ? workspaces[RustCrateUtilities.WorkspaceExcludeKey] : null; + var workspaceMembers = workspaces.ContainsKey(WorkspaceMemberKey) ? workspaces[WorkspaceMemberKey] : null; + var workspaceExclusions = workspaces.ContainsKey(WorkspaceExcludeKey) ? workspaces[WorkspaceExcludeKey] : null; if (workspaceMembers != null) { if (workspaceMembers.TomlType != TomlObjectType.Array) { - throw new InvalidRustTomlFileException($"In accompanying Cargo.toml file expected {RustCrateUtilities.WorkspaceMemberKey} within {RustCrateUtilities.WorkspaceKey} to be of type Array, but found {workspaceMembers.TomlType}"); + throw new InvalidRustTomlFileException($"In accompanying Cargo.toml file expected {WorkspaceMemberKey} within {WorkspaceKey} to be of type Array, but found {workspaceMembers.TomlType}"); } // TomlObject arrays do not natively implement a HashSet get, so add from a list @@ -78,14 +78,14 @@ public static CargoDependencyData ExtractRootDependencyAndWorkspaceSpecification { if (workspaceExclusions.TomlType != TomlObjectType.Array) { - throw new InvalidRustTomlFileException($"In accompanying Cargo.toml file expected {RustCrateUtilities.WorkspaceExcludeKey} within {RustCrateUtilities.WorkspaceKey} to be of type Array, but found {workspaceExclusions.TomlType}"); + throw new InvalidRustTomlFileException($"In accompanying Cargo.toml file expected {WorkspaceExcludeKey} within {WorkspaceKey} to be of type Array, but found {workspaceExclusions.TomlType}"); } cargoDependencyData.CargoWorkspaceExclusions.UnionWith(workspaceExclusions.Get>()); } } - RustCrateUtilities.GenerateDependencies(cargoToml, cargoDependencyData.NonDevDependencies, cargoDependencyData.DevDependencies); + GenerateDependencies(cargoToml, cargoDependencyData.NonDevDependencies, cargoDependencyData.DevDependencies); break; } @@ -110,7 +110,7 @@ public static void ExtractDependencySpecifications(IEnumerable singleFileComponentRecorder.AddAdditionalRelatedFile(cargoTomlFile.Location); - RustCrateUtilities.GenerateDependencies(cargoToml, nonDevDependencySpecifications, devDependencySpecifications); + GenerateDependencies(cargoToml, nonDevDependencySpecifications, devDependencySpecifications); } } @@ -122,8 +122,8 @@ public static void ExtractDependencySpecifications(IEnumerable /// Current list of development dependencies. private static void GenerateDependencies(TomlTable cargoToml, IList nonDevDependencySpecifications, IList devDependencySpecifications) { - var dependencySpecification = RustCrateUtilities.GenerateDependencySpecifications(cargoToml, RustCrateUtilities.NonDevDependencyKeys); - var devDependencySpecification = RustCrateUtilities.GenerateDependencySpecifications(cargoToml, RustCrateUtilities.DevDependencyKeys); + var dependencySpecification = GenerateDependencySpecifications(cargoToml, NonDevDependencyKeys); + var devDependencySpecification = GenerateDependencySpecifications(cargoToml, DevDependencyKeys); // If null, this indicates the toml is an internal file that should not be tracked as a component. if (dependencySpecification != null) @@ -146,15 +146,15 @@ private static void GenerateDependencies(TomlTable cargoToml, IList public static ExcludeDirectoryPredicate BuildExcludeDirectoryPredicateFromWorkspaces(FileInfo rootLockFileInfo, HashSet definedWorkspaces, HashSet definedExclusions) { - Dictionary workspaceGlobs = BuildGlobMatchingFromWorkspaces(rootLockFileInfo, definedWorkspaces); + var workspaceGlobs = BuildGlobMatchingFromWorkspaces(rootLockFileInfo, definedWorkspaces); // Since the paths come in as relative, make them fully qualified - HashSet fullyQualifiedExclusions = definedExclusions.Select(x => Path.Combine(rootLockFileInfo.DirectoryName, x)).ToHashSet(); + var fullyQualifiedExclusions = definedExclusions.Select(x => Path.Combine(rootLockFileInfo.DirectoryName, x)).ToHashSet(); // The predicate will be evaluated with the current directory name to search and the full path of its parent. Return true when it should be excluded from search. return (ReadOnlySpan nameOfDirectoryToConsider, ReadOnlySpan pathOfParentOfDirectoryToConsider) => { - string currentPath = Path.Combine(pathOfParentOfDirectoryToConsider.ToString(), nameOfDirectoryToConsider.ToString()); + var currentPath = Path.Combine(pathOfParentOfDirectoryToConsider.ToString(), nameOfDirectoryToConsider.ToString()); return !workspaceGlobs.Values.Any(x => x.IsMatch(currentPath)) || fullyQualifiedExclusions.Contains(currentPath); }; @@ -168,22 +168,22 @@ public static ExcludeDirectoryPredicate BuildExcludeDirectoryPredicateFromWorksp /// private static Dictionary BuildGlobMatchingFromWorkspaces(FileInfo rootLockFileInfo, HashSet definedWorkspaces) { - Dictionary directoryGlobs = new Dictionary + var directoryGlobs = new Dictionary { { rootLockFileInfo.DirectoryName, Glob.Parse(rootLockFileInfo.DirectoryName) }, }; // For the given workspaces, add their paths to search list - foreach (string workspace in definedWorkspaces) + foreach (var workspace in definedWorkspaces) { - string currentPath = rootLockFileInfo.DirectoryName; - string[] directoryPathParts = workspace.Split('/'); + var currentPath = rootLockFileInfo.DirectoryName; + var directoryPathParts = workspace.Split('/'); // When multiple levels of subdirectory are present, each directory parent must be added or the directory will not be reached // For example, ROOT/test-space/first-test/src/Cargo.toml requires the following directories be matched: // ROOT/test-space, ROOT/test-space/first-test, ROOT/test-space/first-test, ROOT/test-space/first-test/src // Each directory is matched explicitly instead of performing a StartsWith due to the potential of Glob character matching - foreach (string pathPart in directoryPathParts) + foreach (var pathPart in directoryPathParts) { currentPath = Path.Combine(currentPath, pathPart); directoryGlobs[currentPath] = Glob.Parse(currentPath); @@ -251,7 +251,7 @@ private static void FollowRoots(Dictionary packagesDict, I var regexMatch = DependencyFormatRegex.Match(dependency); if (regexMatch.Success) { - if (SemVersion.TryParse(regexMatch.Groups[2].Value, out SemVersion sv)) + if (SemVersion.TryParse(regexMatch.Groups[2].Value, out var sv)) { var name = regexMatch.Groups[1].Value; var version = sv.ToString(); @@ -420,7 +420,7 @@ private static CargoPackage DependencyStringToCargoPackage(string depString) var regexMatch = DependencyFormatRegex.Match(depString); if (regexMatch.Success) { - if (SemVersion.TryParse(regexMatch.Groups[2].Value, out SemVersion sv)) + if (SemVersion.TryParse(regexMatch.Groups[2].Value, out var sv)) { var dependencyPackage = new CargoPackage { @@ -470,7 +470,7 @@ private static IEnumerable GetDependencies(TomlTable cargoToml, IEnum var properties = configs.Get(config.Key); foreach (var propertyKey in properties.Keys) { - var isRelevantKey = tomlDependencyKeys.Any(dependencyKey => + var isRelevantKey = tomlDependencyKeys.Any(dependencyKey => string.Equals(propertyKey, dependencyKey, StringComparison.InvariantCultureIgnoreCase)); if (isRelevantKey) diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateV2Detector.cs b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateV2Detector.cs index 3598ef97f..bcaae2295 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateV2Detector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateV2Detector.cs @@ -37,23 +37,23 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary cargoTomlComponentStream = ComponentStreamEnumerableFactory.GetComponentStreams(lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, (name, directoryName) => false, recursivelyScanDirectories: false); + var lockFileInfo = new FileInfo(cargoLockFile.Location); + var cargoTomlComponentStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, (name, directoryName) => false, recursivelyScanDirectories: false); - CargoDependencyData cargoDependencyData = RustCrateUtilities.ExtractRootDependencyAndWorkspaceSpecifications(cargoTomlComponentStream, singleFileComponentRecorder); + var cargoDependencyData = RustCrateUtilities.ExtractRootDependencyAndWorkspaceSpecifications(cargoTomlComponentStream, singleFileComponentRecorder); // If workspaces have been defined in the root cargo.toml file, scan for specified cargo.toml manifests - int numWorkspaceComponentStreams = 0; - int expectedWorkspaceTomlCount = cargoDependencyData.CargoWorkspaces.Count; + var numWorkspaceComponentStreams = 0; + var expectedWorkspaceTomlCount = cargoDependencyData.CargoWorkspaces.Count; if (expectedWorkspaceTomlCount > 0) { - string rootCargoTomlLocation = Path.Combine(lockFileInfo.DirectoryName, "Cargo.toml"); + var rootCargoTomlLocation = Path.Combine(lockFileInfo.DirectoryName, "Cargo.toml"); - IEnumerable cargoTomlWorkspaceComponentStreams = ComponentStreamEnumerableFactory.GetComponentStreams( + var cargoTomlWorkspaceComponentStreams = this.ComponentStreamEnumerableFactory.GetComponentStreams( lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, RustCrateUtilities.BuildExcludeDirectoryPredicateFromWorkspaces(lockFileInfo, cargoDependencyData.CargoWorkspaces, cargoDependencyData.CargoWorkspaceExclusions), @@ -68,14 +68,14 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary 1) { - Logger.LogWarning($"We are expecting exactly 1 accompanying Cargo.toml file next to the cargo.lock file found at {cargoLockFile.Location}"); + this.Logger.LogWarning($"We are expecting exactly 1 accompanying Cargo.toml file next to the cargo.lock file found at {cargoLockFile.Location}"); return Task.CompletedTask; } // If there is a mismatch between the number of expected and found workspaces, exit if (expectedWorkspaceTomlCount > numWorkspaceComponentStreams) { - Logger.LogWarning($"We are expecting at least {expectedWorkspaceTomlCount} accompanying Cargo.toml file(s) from workspaces outside of the root directory {lockFileInfo.DirectoryName}, but found {numWorkspaceComponentStreams}"); + this.Logger.LogWarning($"We are expecting at least {expectedWorkspaceTomlCount} accompanying Cargo.toml file(s) from workspaces outside of the root directory {lockFileInfo.DirectoryName}, but found {numWorkspaceComponentStreams}"); return Task.CompletedTask; } @@ -85,7 +85,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary=0.0.0 - ComparatorType = Operator.GreaterThanOrEqual; - Version = new SemVersion(0, 0, 0); + this.ComparatorType = Operator.GreaterThanOrEqual; + this.Version = new SemVersion(0, 0, 0); } else if (!partialVersion.Minor.HasValue) { - Version = new SemVersion(partialVersion.Major.Value + 1, 0, 0); + this.Version = new SemVersion(partialVersion.Major.Value + 1, 0, 0); } else { - Version = new SemVersion(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); + this.Version = new SemVersion(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); } break; case Operator.GreaterThan: - ComparatorType = Operator.GreaterThanOrEqual; + this.ComparatorType = Operator.GreaterThanOrEqual; if (!partialVersion.Major.HasValue) { // >* is unsatisfiable, so use <0.0.0 - ComparatorType = Operator.LessThan; - Version = new SemVersion(0, 0, 0); + this.ComparatorType = Operator.LessThan; + this.Version = new SemVersion(0, 0, 0); } else if (!partialVersion.Minor.HasValue) { // eg. >1.x -> >=2.0 - Version = new SemVersion(partialVersion.Major.Value + 1, 0, 0); + this.Version = new SemVersion(partialVersion.Major.Value + 1, 0, 0); } else { // eg. >1.2.x -> >=1.3 - Version = new SemVersion(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); + this.Version = new SemVersion(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); } break; default: // <1.2.x means <1.2.0 // >=1.2.x means >=1.2.0 - Version = partialVersion.ToZeroVersion(); + this.Version = partialVersion.ToZeroVersion(); break; } } else { - Version = partialVersion.ToZeroVersion(); + this.Version = partialVersion.ToZeroVersion(); } } @@ -108,8 +108,8 @@ public Comparator(Operator comparatorType, SemVersion comparatorVersion) throw new NullReferenceException("Null comparator version"); } - ComparatorType = comparatorType; - Version = comparatorVersion; + this.ComparatorType = comparatorType; + this.Version = comparatorVersion; } public static Tuple TryParse(string input) @@ -145,18 +145,18 @@ private static Operator ParseComparatorType(string input) public bool IsSatisfied(SemVersion version) { - switch (ComparatorType) + switch (this.ComparatorType) { case Operator.Equal: - return version == Version; + return version == this.Version; case Operator.LessThan: - return version < Version; + return version < this.Version; case Operator.LessThanOrEqual: - return version <= Version; + return version <= this.Version; case Operator.GreaterThan: - return version > Version; + return version > this.Version; case Operator.GreaterThanOrEqual: - return version >= Version; + return version >= this.Version; default: throw new InvalidOperationException("Comparator type not recognised."); } @@ -175,17 +175,17 @@ public bool Intersects(Comparator other) c.ComparatorType == Operator.Equal || c.ComparatorType == Operator.LessThanOrEqual; - if (Version > other.Version && (operatorIsLessThan(this) || operatorIsGreaterThan(other))) + if (this.Version > other.Version && (operatorIsLessThan(this) || operatorIsGreaterThan(other))) { return true; } - if (Version < other.Version && (operatorIsGreaterThan(this) || operatorIsLessThan(other))) + if (this.Version < other.Version && (operatorIsGreaterThan(this) || operatorIsLessThan(other))) { return true; } - if (Version == other.Version && ( + if (this.Version == other.Version && ( (operatorIncludesEqual(this) && operatorIncludesEqual(other)) || (operatorIsLessThan(this) && operatorIsLessThan(other)) || (operatorIsGreaterThan(this) && operatorIsGreaterThan(other)))) @@ -208,7 +208,7 @@ public enum Operator public override string ToString() { string operatorString = null; - switch (ComparatorType) + switch (this.ComparatorType) { case Operator.Equal: operatorString = "="; @@ -229,7 +229,7 @@ public override string ToString() throw new InvalidOperationException("Comparator type not recognised."); } - return string.Format("{0}{1}", operatorString, Version); + return string.Format("{0}{1}", operatorString, this.Version); } public bool Equals(Comparator other) @@ -239,17 +239,17 @@ public bool Equals(Comparator other) return false; } - return ComparatorType == other.ComparatorType && Version == other.Version; + return this.ComparatorType == other.ComparatorType && this.Version == other.Version; } public override bool Equals(object other) { - return Equals(other as Comparator); + return this.Equals(other as Comparator); } public override int GetHashCode() { - return ToString().GetHashCode(); + return this.ToString().GetHashCode(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/ComparatorSet.cs b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/ComparatorSet.cs index 604e10da9..03dfe17ab 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/ComparatorSet.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/ComparatorSet.cs @@ -1,9 +1,9 @@ // This file was copied from the SemanticVersioning package found at https://github.com/adamreeve/semver.net. // The range logic from SemanticVersioning is needed in the Rust detector to supplement the Semver versioning package // that is used elsewhere in this project. -// +// // This is a temporary solution, so avoid using this functionality outside of the Rust detector. The following -// issues describe the problems with the SemanticVersioning package that make it problematic to use for versioning. +// issues describe the problems with the SemanticVersioning package that make it problematic to use for versioning. // https://github.com/adamreeve/semver.net/issues/46 // https://github.com/adamreeve/semver.net/issues/47 @@ -20,7 +20,7 @@ internal class ComparatorSet : IEquatable public ComparatorSet(string spec) { - comparators = new List { }; + this.comparators = new List { }; spec = spec.Trim(); if (spec == string.Empty) @@ -28,12 +28,12 @@ public ComparatorSet(string spec) spec = "*"; } - int position = 0; - int end = spec.Length; + var position = 0; + var end = spec.Length; while (position < end) { - int iterStartPosition = position; + var iterStartPosition = position; // A comparator set might be an advanced range specifier // like ~1.2.3, ^1.2, or 1.*. @@ -50,7 +50,7 @@ public ComparatorSet(string spec) if (result != null) { position += result.Item1; - comparators.AddRange(result.Item2); + this.comparators.AddRange(result.Item2); } } @@ -59,7 +59,7 @@ public ComparatorSet(string spec) if (comparatorResult != null) { position += comparatorResult.Item1; - comparators.Add(comparatorResult.Item2); + this.comparators.Add(comparatorResult.Item2); } if (position == iterStartPosition) @@ -77,13 +77,13 @@ private ComparatorSet(IEnumerable comparators) public bool IsSatisfied(SemVersion version) { - bool satisfied = comparators.All(c => c.IsSatisfied(version)); + var satisfied = this.comparators.All(c => c.IsSatisfied(version)); if (version.Prerelease != string.Empty) { // If the version is a pre-release, then one of the // comparators must have the same version and also include // a pre-release tag. - return satisfied && comparators.Any(c => + return satisfied && this.comparators.Any(c => c.Version.Prerelease != string.Empty && c.Version.Major == version.Major && c.Version.Minor == version.Minor && @@ -170,25 +170,25 @@ public bool Equals(ComparatorSet other) return false; } - var thisSet = new HashSet(comparators); + var thisSet = new HashSet(this.comparators); return thisSet.SetEquals(other.comparators); } public override bool Equals(object other) { - return Equals(other as ComparatorSet); + return this.Equals(other as ComparatorSet); } public override string ToString() { - return string.Join(" ", comparators.Select(c => c.ToString()).ToArray()); + return string.Join(" ", this.comparators.Select(c => c.ToString()).ToArray()); } public override int GetHashCode() { // XOR is commutative, so this hash code is independent // of the order of comparators. - return comparators.Aggregate(0, (accum, next) => accum ^ next.GetHashCode()); + return this.comparators.Aggregate(0, (accum, next) => accum ^ next.GetHashCode()); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Desugarer.cs b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Desugarer.cs index e91dd7cad..a251026b6 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Desugarer.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Desugarer.cs @@ -1,9 +1,9 @@ // This file was copied from the SemanticVersioning package found at https://github.com/adamreeve/semver.net. // The range logic from SemanticVersioning is needed in the Rust detector to supplement the Semver versioning package // that is used elsewhere in this project. -// +// // This is a temporary solution, so avoid using this functionality outside of the Rust detector. The following -// issues describe the problems with the SemanticVersioning package that make it problematic to use for versioning. +// issues describe the problems with the SemanticVersioning package that make it problematic to use for versioning. // https://github.com/adamreeve/semver.net/issues/46 // https://github.com/adamreeve/semver.net/issues/47 @@ -17,7 +17,7 @@ internal static class Desugarer { private const string VersionChars = @"[0-9a-zA-Z\-\+\.\*]"; - // tilde and caret requirements can't also have wildcards in them + // tilde and caret requirements can't also have wildcards in them private const string VersionCharsNoWildcard = @"[0-9a-zA-Z\-\+\.]"; private static readonly Regex TildePatternRegex = new Regex( @@ -147,7 +147,7 @@ public static Tuple HyphenRange(string spec) // Lower range has any non-supplied values replaced with zero var minVersion = minPartialVersion.ToZeroVersion(); - Comparator.Operator maxOperator = maxPartialVersion.IsFull() + var maxOperator = maxPartialVersion.IsFull() ? Comparator.Operator.LessThanOrEqual : Comparator.Operator.LessThan; SemVersion maxVersion = null; diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/PartialVersion.cs b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/PartialVersion.cs index cd7c9c604..5d66fe3e5 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/PartialVersion.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/PartialVersion.cs @@ -1,9 +1,9 @@ // This file was copied from the SemanticVersioning package found at https://github.com/adamreeve/semver.net. // The range logic from SemanticVersioning is needed in the Rust detector to supplement the Semver versioning package // that is used elsewhere in this project. -// +// // This is a temporary solution, so avoid using this functionality outside of the Rust detector. The following -// issues describe the problems with the SemanticVersioning package that make it problematic to use for versioning. +// issues describe the problems with the SemanticVersioning package that make it problematic to use for versioning. // https://github.com/adamreeve/semver.net/issues/46 // https://github.com/adamreeve/semver.net/issues/47 @@ -61,22 +61,22 @@ public PartialVersion(string input) if (xValues.Contains(match.Groups[1].Value)) { - Major = null; + this.Major = null; } else { - Major = int.Parse(match.Groups[1].Value); + this.Major = int.Parse(match.Groups[1].Value); } if (match.Groups[2].Success) { if (xValues.Contains(match.Groups[3].Value)) { - Minor = null; + this.Minor = null; } else { - Minor = int.Parse(match.Groups[3].Value); + this.Minor = int.Parse(match.Groups[3].Value); } } @@ -84,32 +84,28 @@ public PartialVersion(string input) { if (xValues.Contains(match.Groups[5].Value)) { - Patch = null; + this.Patch = null; } else { - Patch = int.Parse(match.Groups[5].Value); + this.Patch = int.Parse(match.Groups[5].Value); } } if (match.Groups[6].Success) { - PreRelease = match.Groups[7].Value; + this.PreRelease = match.Groups[7].Value; } } public SemVersion ToZeroVersion() { - return new SemVersion( - Major ?? 0, - Minor ?? 0, - Patch ?? 0, - PreRelease); + return new SemVersion(this.Major ?? 0, this.Minor ?? 0, this.Patch ?? 0, this.PreRelease); } public bool IsFull() { - return Major.HasValue && Minor.HasValue && Patch.HasValue; + return this.Major.HasValue && this.Minor.HasValue && this.Patch.HasValue; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Range.cs b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Range.cs index 751997846..781160d83 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Range.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Range.cs @@ -1,9 +1,9 @@ // This file was copied from the SemanticVersioning package found at https://github.com/adamreeve/semver.net. // The range logic from SemanticVersioning is needed in the Rust detector to supplement the Semver versioning package // that is used elsewhere in this project. -// +// // This is a temporary solution, so avoid using this functionality outside of the Rust detector. The following -// issues describe the problems with the SemanticVersioning package that make it problematic to use for versioning. +// issues describe the problems with the SemanticVersioning package that make it problematic to use for versioning. // https://github.com/adamreeve/semver.net/issues/46 // https://github.com/adamreeve/semver.net/issues/47 @@ -33,13 +33,13 @@ public Range(string rangeSpec, bool loose = false) { this.rangeSpec = rangeSpec; var comparatorSetSpecs = rangeSpec.Split(new[] { "||" }, StringSplitOptions.None); - comparatorSets = comparatorSetSpecs.Select(s => new ComparatorSet(s)).ToArray(); + this.comparatorSets = comparatorSetSpecs.Select(s => new ComparatorSet(s)).ToArray(); } private Range(IEnumerable comparatorSets) { this.comparatorSets = comparatorSets.ToArray(); - rangeSpec = string.Join(" || ", comparatorSets.Select(cs => cs.ToString()).ToArray()); + this.rangeSpec = string.Join(" || ", comparatorSets.Select(cs => cs.ToString()).ToArray()); } /// @@ -49,7 +49,7 @@ private Range(IEnumerable comparatorSets) /// true if the range is satisfied by the version. public bool IsSatisfied(SemVersion version) { - return comparatorSets.Any(s => s.IsSatisfied(version)); + return this.comparatorSets.Any(s => s.IsSatisfied(version)); } /// @@ -63,8 +63,8 @@ public bool IsSatisfied(string versionString, bool loose = false) { try { - SemVersion.TryParse(versionString, out SemVersion version, loose); - return IsSatisfied(version); + SemVersion.TryParse(versionString, out var version, loose); + return this.IsSatisfied(version); } catch (ArgumentException) { @@ -79,7 +79,7 @@ public bool IsSatisfied(string versionString, bool loose = false) /// An IEnumerable of satisfying versions. public IEnumerable Satisfying(IEnumerable versions) { - return versions.Where(IsSatisfied); + return versions.Where(this.IsSatisfied); } /// @@ -91,7 +91,7 @@ public IEnumerable Satisfying(IEnumerable versions) /// An IEnumerable of satisfying version strings. public IEnumerable Satisfying(IEnumerable versions, bool loose = false) { - return versions.Where(v => IsSatisfied(v, loose)); + return versions.Where(v => this.IsSatisfied(v, loose)); } /// @@ -101,7 +101,7 @@ public IEnumerable Satisfying(IEnumerable versions, bool loose = /// The maximum satisfying version, or null if no versions satisfied this range. public SemVersion MaxSatisfying(IEnumerable versions) { - return Satisfying(versions).Max(); + return this.Satisfying(versions).Max(); } /// @@ -112,8 +112,8 @@ public SemVersion MaxSatisfying(IEnumerable versions) /// The maximum satisfying version string, or null if no versions satisfied this range. public string MaxSatisfying(IEnumerable versionStrings, bool loose = false) { - var versions = ValidVersions(versionStrings, loose); - var maxVersion = MaxSatisfying(versions); + var versions = this.ValidVersions(versionStrings, loose); + var maxVersion = this.MaxSatisfying(versions); return maxVersion == null ? null : maxVersion.ToString(); } @@ -124,7 +124,7 @@ public string MaxSatisfying(IEnumerable versionStrings, bool loose = fal /// The Range intersection. public Range Intersect(Range other) { - var allIntersections = comparatorSets.SelectMany( + var allIntersections = this.comparatorSets.SelectMany( thisCs => other.comparatorSets.Select(thisCs.Intersect)) .Where(cs => cs != null).ToList(); @@ -142,7 +142,7 @@ public Range Intersect(Range other) /// The range string. public override string ToString() { - return rangeSpec; + return this.rangeSpec; } public bool Equals(Range other) @@ -152,13 +152,13 @@ public bool Equals(Range other) return false; } - var thisSet = new HashSet(comparatorSets); + var thisSet = new HashSet(this.comparatorSets); return thisSet.SetEquals(other.comparatorSets); } public override bool Equals(object other) { - return Equals(other as Range); + return this.Equals(other as Range); } public static bool operator ==(Range a, Range b) @@ -180,7 +180,7 @@ public override int GetHashCode() { // XOR is commutative, so this hash code is independent // of the order of comparators. - return comparatorSets.Aggregate(0, (accum, next) => accum ^ next.GetHashCode()); + return this.comparatorSets.Aggregate(0, (accum, next) => accum ^ next.GetHashCode()); } // Static convenience methods diff --git a/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs index f988a3301..316d333e9 100644 --- a/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs @@ -15,32 +15,32 @@ namespace Microsoft.ComponentDetection.Detectors.Spdx { /// /// Spdx22ComponentDetector discover SPDX SBOM files in JSON format and create components with the information about - /// what SPDX document describes. + /// what SPDX document describes. /// [Export(typeof(IComponentDetector))] - public class Spdx22ComponentDetector : FileComponentDetector, IDefaultOffComponentDetector + public class Spdx22ComponentDetector : FileComponentDetector, IDefaultOffComponentDetector { public override string Id => "SPDX22SBOM"; - + public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Spdx) }; - + public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Spdx }; public override int Version => 1; - + public override IList SearchPatterns { get; } = new List { "*.spdx.json" }; private readonly IEnumerable supportedSPDXVersions = new List { "SPDX-2.2" }; protected override Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) { - Logger.LogVerbose($"Discovered SPDX2.2 manifest file at: {processRequest.ComponentStream.Location}"); + this.Logger.LogVerbose($"Discovered SPDX2.2 manifest file at: {processRequest.ComponentStream.Location}"); var file = processRequest.ComponentStream; try { - var hash = GetSHA1HashFromStream(file.Stream); + var hash = this.GetSHA1HashFromStream(file.Stream); // Reset buffer to starting position after hash generation. file.Stream.Seek(0, SeekOrigin.Begin); @@ -54,35 +54,35 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary(reader); if (document != null) { - if (IsSPDXVersionSupported(document)) + if (this.IsSPDXVersionSupported(document)) { - var sbomComponent = ConvertJObjectToSbomComponent(processRequest, document, hash); + var sbomComponent = this.ConvertJObjectToSbomComponent(processRequest, document, hash); processRequest.SingleFileComponentRecorder.RegisterUsage(new DetectedComponent(sbomComponent)); } else { - Logger.LogWarning($"Discovered SPDX at {processRequest.ComponentStream.Location} is not SPDX-2.2 document, skipping"); + this.Logger.LogWarning($"Discovered SPDX at {processRequest.ComponentStream.Location} is not SPDX-2.2 document, skipping"); } } else { - Logger.LogWarning($"Discovered SPDX file at {processRequest.ComponentStream.Location} is not a valid document, skipping"); + this.Logger.LogWarning($"Discovered SPDX file at {processRequest.ComponentStream.Location} is not a valid document, skipping"); } } catch (JsonReaderException) { - Logger.LogWarning($"Unable to parse file at {processRequest.ComponentStream.Location}, skipping"); + this.Logger.LogWarning($"Unable to parse file at {processRequest.ComponentStream.Location}, skipping"); } } catch (Exception e) { - Logger.LogFailedReadingFile(file.Location, e); + this.Logger.LogFailedReadingFile(file.Location, e); } return Task.CompletedTask; } - - private bool IsSPDXVersionSupported(JObject document) => supportedSPDXVersions.Contains(document["spdxVersion"]?.ToString(), StringComparer.OrdinalIgnoreCase); + + private bool IsSPDXVersionSupported(JObject document) => this.supportedSPDXVersions.Contains(document["spdxVersion"]?.ToString(), StringComparer.OrdinalIgnoreCase); private SpdxComponent ConvertJObjectToSbomComponent(ProcessRequest processRequest, JObject document, string fileHash) { @@ -93,12 +93,12 @@ private SpdxComponent ConvertJObjectToSbomComponent(ProcessRequest processReques if (rootElements != null && rootElements.Count() > 1) { - Logger.LogWarning($"SPDX file at {processRequest.ComponentStream.Location} has more than one element in documentDescribes, first will be selected as root element."); + this.Logger.LogWarning($"SPDX file at {processRequest.ComponentStream.Location} has more than one element in documentDescribes, first will be selected as root element."); } - + if (rootElements != null && rootElements.Any()) { - Logger.LogWarning($"SPDX file at {processRequest.ComponentStream.Location} does not have root elements in documentDescribes section, considering SPDXRef-Document as a root element."); + this.Logger.LogWarning($"SPDX file at {processRequest.ComponentStream.Location} does not have root elements in documentDescribes section, considering SPDXRef-Document as a root element."); } var rootElementId = rootElements?.FirstOrDefault() ?? "SPDXRef-Document"; @@ -115,4 +115,4 @@ private string GetSHA1HashFromStream(Stream stream) #pragma warning restore CA5350 } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs index 60a8e99c6..f2195bb0f 100644 --- a/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs @@ -3,10 +3,7 @@ using System.Composition; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using System.Threading.Tasks; -using Microsoft.ComponentDetection.Common; -using Microsoft.ComponentDetection.Common.Telemetry.Records; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.Internal; using Microsoft.ComponentDetection.Contracts.TypedComponent; @@ -41,15 +38,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - Logger.LogWarning($"vcpkg detector found {file}"); + this.Logger.LogWarning($"vcpkg detector found {file}"); var projectRootDirectory = Directory.GetParent(file.Location); - if (projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) + if (this.projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) { return; } - await ParseSpdxFile(singleFileComponentRecorder, file); + await this.ParseSpdxFile(singleFileComponentRecorder, file); } private async Task ParseSpdxFile( @@ -81,7 +78,7 @@ private async Task ParseSpdxFile( continue; } - Logger.LogWarning($"parsed package {item.Name}"); + this.Logger.LogWarning($"parsed package {item.Name}"); if (item.SPDXID == "SPDXRef-port") { var split = item.VersionInfo.Split('#'); @@ -110,7 +107,7 @@ private async Task ParseSpdxFile( } catch (Exception) { - Logger.LogWarning($"failed while handling {item.Name}"); + this.Logger.LogWarning($"failed while handling {item.Name}"); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs index 84ecc45fc..2e2dc429d 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs @@ -9,8 +9,8 @@ namespace Microsoft.ComponentDetection.Detectors.Yarn.Parsers { /// /// https://github.com/yarnpkg/yarn/issues/5629 - /// - /// Yarn uses something that is "Almost-YAML", and we haven't found a YAML parser + /// + /// Yarn uses something that is "Almost-YAML", and we haven't found a YAML parser /// that understands Almost-YAML yet, so here's ours... /// /// In V1, this represents a file of newline delimited blocks in the form: @@ -55,16 +55,16 @@ public class YarnBlockFile : IYarnBlockFile private YarnBlockFile(IList parsedFileLines) { - fileLines = parsedFileLines; + this.fileLines = parsedFileLines; - if (fileLines.Count > 0) + if (this.fileLines.Count > 0) { - ReadVersionHeader(); + this.ReadVersionHeader(); } else { - VersionHeader = string.Empty; - YarnLockVersion = YarnLockVersion.Invalid; + this.VersionHeader = string.Empty; + this.YarnLockVersion = YarnLockVersion.Invalid; } } @@ -75,8 +75,8 @@ public static async Task CreateBlockFileAsync(Stream stream) throw new ArgumentNullException(nameof(stream)); } - List fileLines = new List(); - using (StreamReader reader = new StreamReader(stream)) + var fileLines = new List(); + using (var reader = new StreamReader(stream)) { while (!reader.EndOfStream) { @@ -89,9 +89,9 @@ public static async Task CreateBlockFileAsync(Stream stream) public IEnumerator GetEnumerator() { - while (ReadToNextMajorBlock()) + while (this.ReadToNextMajorBlock()) { - yield return ParseBlock(); + yield return this.ParseBlock(); } yield break; @@ -99,38 +99,38 @@ public IEnumerator GetEnumerator() private void ReadVersionHeader() { - YarnLockVersion = YarnLockVersion.Invalid; + this.YarnLockVersion = YarnLockVersion.Invalid; do { - if (fileLines[fileLineIndex].StartsWith("#")) + if (this.fileLines[this.fileLineIndex].StartsWith("#")) { - if (fileLines[fileLineIndex].Contains("yarn lockfile")) + if (this.fileLines[this.fileLineIndex].Contains("yarn lockfile")) { - YarnLockVersion = YarnLockVersion.V1; - VersionHeader = fileLines[fileLineIndex]; + this.YarnLockVersion = YarnLockVersion.V1; + this.VersionHeader = this.fileLines[this.fileLineIndex]; break; } } - else if (string.IsNullOrEmpty(fileLines[fileLineIndex])) + else if (string.IsNullOrEmpty(this.fileLines[this.fileLineIndex])) { // If the comment header does not specify V1, a V2 metadata block will follow a line break - if (IncrementIndex()) + if (this.IncrementIndex()) { - if (fileLines[fileLineIndex].StartsWith("__metadata:")) + if (this.fileLines[this.fileLineIndex].StartsWith("__metadata:")) { - VersionHeader = fileLines[fileLineIndex]; - YarnLockVersion = YarnLockVersion.V2; + this.VersionHeader = this.fileLines[this.fileLineIndex]; + this.YarnLockVersion = YarnLockVersion.V2; - YarnBlock metadataBlock = ParseBlock(); + var metadataBlock = this.ParseBlock(); if (metadataBlock.Values.ContainsKey("version") && metadataBlock.Values.ContainsKey("cacheKey")) { break; } - VersionHeader = null; - YarnLockVersion = YarnLockVersion.Invalid; + this.VersionHeader = null; + this.YarnLockVersion = YarnLockVersion.Invalid; } } } @@ -139,7 +139,7 @@ private void ReadVersionHeader() break; } } - while (IncrementIndex()); + while (this.IncrementIndex()); } /// @@ -149,34 +149,34 @@ private void ReadVersionHeader() /// private YarnBlock ParseBlock(int level = 0) { - string currentLevelDelimiter = " "; - for (int i = 0; i < level; i++) + var currentLevelDelimiter = " "; + for (var i = 0; i < level; i++) { currentLevelDelimiter = currentLevelDelimiter + " "; } // Assuming the pointer has been set up to a block - YarnBlock block = new YarnBlock { Title = fileLines[fileLineIndex].TrimEnd(':').Trim('\"').Trim() }; + var block = new YarnBlock { Title = this.fileLines[this.fileLineIndex].TrimEnd(':').Trim('\"').Trim() }; - while (IncrementIndex()) + while (this.IncrementIndex()) { - if (!fileLines[fileLineIndex].StartsWith(currentLevelDelimiter) || string.IsNullOrWhiteSpace(fileLines[fileLineIndex])) + if (!this.fileLines[this.fileLineIndex].StartsWith(currentLevelDelimiter) || string.IsNullOrWhiteSpace(this.fileLines[this.fileLineIndex])) { break; } - if (fileLines[fileLineIndex].EndsWith(":")) + if (this.fileLines[this.fileLineIndex].EndsWith(":")) { - block.Children.Add(ParseBlock(level + 1)); - fileLineIndex--; + block.Children.Add(this.ParseBlock(level + 1)); + this.fileLineIndex--; } else { - string toParse = fileLines[fileLineIndex].Trim(); + var toParse = this.fileLines[this.fileLineIndex].Trim(); // Yarn V1 and V2 have slightly different formats, where V2 adds a : between property name and value // Match on the specified version - var matches = YarnLockVersion == YarnLockVersion.V1 ? YarnV1Regex.Match(toParse) : YarnV2Regex.Match(toParse); + var matches = this.YarnLockVersion == YarnLockVersion.V1 ? YarnV1Regex.Match(toParse) : YarnV2Regex.Match(toParse); if (matches.Groups.Count != 3) // Whole group + two captures { @@ -186,7 +186,7 @@ private YarnBlock ParseBlock(int level = 0) block.Values.Add(matches.Groups[1].Value.Trim('\"'), matches.Groups[2].Value.Trim('\"')); } - if (!Peek() || !fileLines[fileLineIndex].StartsWith(currentLevelDelimiter) || string.IsNullOrWhiteSpace(fileLines[fileLineIndex])) + if (!this.Peek() || !this.fileLines[this.fileLineIndex].StartsWith(currentLevelDelimiter) || string.IsNullOrWhiteSpace(this.fileLines[this.fileLineIndex])) { break; } @@ -197,7 +197,7 @@ private YarnBlock ParseBlock(int level = 0) IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator(); + return this.GetEnumerator(); } /// @@ -209,13 +209,13 @@ private bool ReadToNextMajorBlock() string line; do { - if (!IncrementIndex()) + if (!this.IncrementIndex()) { return false; } else { - line = fileLines[fileLineIndex]; + line = this.fileLines[this.fileLineIndex]; } } while (string.IsNullOrWhiteSpace(line) || line.StartsWith(" ") || line.StartsWith("\t") || line.StartsWith("#")); @@ -225,9 +225,9 @@ private bool ReadToNextMajorBlock() private bool IncrementIndex() { - fileLineIndex++; + this.fileLineIndex++; - return Peek(); + return this.Peek(); } /// @@ -236,7 +236,7 @@ private bool IncrementIndex() /// private bool Peek() { - if (fileLineIndex >= fileLines.Count) + if (this.fileLineIndex >= this.fileLines.Count) { return false; } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs index 71e30558b..49892f8e2 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs @@ -33,18 +33,18 @@ public YarnLockFile Parse(IYarnBlockFile blockFile, ILogger logger) throw new ArgumentNullException(nameof(blockFile)); } - YarnLockFile file = new YarnLockFile { LockVersion = blockFile.YarnLockVersion }; + var file = new YarnLockFile { LockVersion = blockFile.YarnLockVersion }; IList entries = new List(); foreach (var block in blockFile) { - YarnEntry yarnEntry = new YarnEntry(); + var yarnEntry = new YarnEntry(); var satisfiedPackages = block.Title.Split(',').Select(x => x.Trim()) - .Select(GenerateBlockTitleNormalizer(block)); + .Select(this.GenerateBlockTitleNormalizer(block)); foreach (var package in satisfiedPackages) { - if (!TryReadNameAndSatisfiedVersion(package, out Tuple parsed)) + if (!this.TryReadNameAndSatisfiedVersion(package, out var parsed)) { continue; } @@ -63,7 +63,7 @@ public YarnLockFile Parse(IYarnBlockFile blockFile, ILogger logger) continue; } - if (!block.Values.TryGetValue(VersionString, out string version)) + if (!block.Values.TryGetValue(VersionString, out var version)) { logger.LogWarning($"Failed to read a version for {yarnEntry.Name}. The entry will be skipped."); continue; @@ -71,7 +71,7 @@ public YarnLockFile Parse(IYarnBlockFile blockFile, ILogger logger) yarnEntry.Version = version; - if (block.Values.TryGetValue(Resolved, out string resolved)) + if (block.Values.TryGetValue(Resolved, out var resolved)) { yarnEntry.Resolved = resolved; } @@ -117,10 +117,10 @@ private Func GenerateBlockTitleNormalizer(YarnBlock block) return blockTitleMember; } - var versionValue = block.Values.FirstOrDefault(x => string.Equals(x.Key, YarnLockParser.VersionString, StringComparison.OrdinalIgnoreCase)); + var versionValue = block.Values.FirstOrDefault(x => string.Equals(x.Key, VersionString, StringComparison.OrdinalIgnoreCase)); if (default(KeyValuePair).Equals(versionValue)) { - Logger.LogWarning("Block without version detected"); + this.Logger.LogWarning("Block without version detected"); return blockTitleMember; } @@ -131,25 +131,25 @@ private Func GenerateBlockTitleNormalizer(YarnBlock block) private bool TryReadNameAndSatisfiedVersion(string nameVersionPairing, out Tuple output) { output = null; - string workingString = nameVersionPairing; + var workingString = nameVersionPairing; workingString = workingString.TrimEnd(':'); workingString = workingString.Trim('\"'); - bool startsWithAtSign = false; + var startsWithAtSign = false; if (workingString.StartsWith("@")) { startsWithAtSign = true; workingString = workingString.TrimStart('@'); } - string[] parts = workingString.Split('@'); + var parts = workingString.Split('@'); if (parts.Length != 2) { return false; } - string at = startsWithAtSign ? "@" : string.Empty; - string name = $"{at}{parts[0]}"; + var at = startsWithAtSign ? "@" : string.Empty; + var name = $"{at}{parts[0]}"; output = new Tuple(name, parts[1]); return true; diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs index 80831f96d..4668d2674 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs @@ -2,7 +2,7 @@ { public class YarnDependency { - public string LookupKey => $"{Name}@{Version}"; + public string LookupKey => $"{this.Name}@{this.Version}"; public string Name { get; set; } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs index 8984525ea..2fb8a187e 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs @@ -4,7 +4,7 @@ namespace Microsoft.ComponentDetection.Detectors.Yarn { public class YarnEntry { - public string LookupKey => $"{Name}@{Version}"; + public string LookupKey => $"{this.Name}@{this.Version}"; /// /// Gets or sets the non-version qualified name of the entry. diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs index cb9ae9bdf..9652e3c73 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs @@ -35,30 +35,30 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - string skippedFolder = SkippedFolders.FirstOrDefault(folder => file.Location.Contains(folder)); + var skippedFolder = this.SkippedFolders.FirstOrDefault(folder => file.Location.Contains(folder)); if (!string.IsNullOrEmpty(skippedFolder)) { - Logger.LogInfo($"Yarn.Lock file {file.Location} was found in a {skippedFolder} folder and will be skipped."); + this.Logger.LogInfo($"Yarn.Lock file {file.Location} was found in a {skippedFolder} folder and will be skipped."); return; } - Logger.LogInfo($"Processing file {file.Location}"); + this.Logger.LogInfo($"Processing file {file.Location}"); try { - var parsed = await YarnLockFileFactory.ParseYarnLockFileAsync(file.Stream, Logger); - DetectComponents(parsed, file.Location, singleFileComponentRecorder); + var parsed = await YarnLockFileFactory.ParseYarnLockFileAsync(file.Stream, this.Logger); + this.DetectComponents(parsed, file.Location, singleFileComponentRecorder); } catch (Exception ex) { - Logger.LogBuildWarning($"Could not read components from file {file.Location}."); - Logger.LogFailedReadingFile(file.Location, ex); + this.Logger.LogBuildWarning($"Could not read components from file {file.Location}."); + this.Logger.LogFailedReadingFile(file.Location, ex); } } private void DetectComponents(YarnLockFile file, string location, ISingleFileComponentRecorder singleFileComponentRecorder) { - Dictionary yarnPackages = new Dictionary(); + var yarnPackages = new Dictionary(); // Iterate once and build our provider lookup for all possible yarn packages requests // Each entry can satisfy more than one request in a Yarn.Lock file @@ -73,12 +73,12 @@ private void DetectComponents(YarnLockFile file, string location, ISingleFileCom var addSuccessful = yarnPackages.TryAdd(key, entry); if (!addSuccessful) { - Logger.LogWarning($"Found duplicate entry {key} in {location}"); + this.Logger.LogWarning($"Found duplicate entry {key} in {location}"); } } } - if (yarnPackages.Count == 0 || !TryReadPeerPackageJsonRequestsAsYarnEntries(location, yarnPackages, out List yarnRoots)) + if (yarnPackages.Count == 0 || !this.TryReadPeerPackageJsonRequestsAsYarnEntries(location, yarnPackages, out var yarnRoots)) { return; } @@ -86,15 +86,15 @@ private void DetectComponents(YarnLockFile file, string location, ISingleFileCom foreach (var dependency in yarnRoots) { var root = new DetectedComponent(new NpmComponent(dependency.Name, dependency.Version)); - AddDetectedComponentToGraph(root, null, singleFileComponentRecorder, isRootComponent: true); + this.AddDetectedComponentToGraph(root, null, singleFileComponentRecorder, isRootComponent: true); } // It's important that all of the root dependencies get registered *before* we start processing any non-root // dependencies; otherwise, we would miss root dependency links for root dependencies that are also indirect - // transitive dependencies. + // transitive dependencies. foreach (var dependency in yarnRoots) { - ParseTreeWithAssignedRoot(dependency, yarnPackages, singleFileComponentRecorder); + this.ParseTreeWithAssignedRoot(dependency, yarnPackages, singleFileComponentRecorder); } // Catch straggler top level packages in the yarn.lock file that aren't in the package.lock file for whatever reason @@ -103,7 +103,7 @@ private void DetectComponents(YarnLockFile file, string location, ISingleFileCom var component = new DetectedComponent(new NpmComponent(entry.Name, entry.Version)); if (singleFileComponentRecorder.GetComponent(component.Component.Id) == null) { - AddDetectedComponentToGraph(component, parentComponent: null, singleFileComponentRecorder); + this.AddDetectedComponentToGraph(component, parentComponent: null, singleFileComponentRecorder); } } } @@ -116,26 +116,26 @@ private void DetectComponents(YarnLockFile file, string location, ISingleFileCom /// The component recorder for file that is been processed. private void ParseTreeWithAssignedRoot(YarnEntry root, Dictionary providerTable, ISingleFileComponentRecorder singleFileComponentRecorder) { - Queue<(YarnEntry, YarnEntry)> queue = new Queue<(YarnEntry, YarnEntry)>(); + var queue = new Queue<(YarnEntry, YarnEntry)>(); queue.Enqueue((root, null)); - HashSet processed = new HashSet(); + var processed = new HashSet(); while (queue.Count > 0) { var (currentEntry, parentEntry) = queue.Dequeue(); - DetectedComponent currentComponent = singleFileComponentRecorder.GetComponent(YarnEntryToComponentId(currentEntry)); - DetectedComponent parentComponent = parentEntry != null ? singleFileComponentRecorder.GetComponent(YarnEntryToComponentId(parentEntry)) : null; + var currentComponent = singleFileComponentRecorder.GetComponent(this.YarnEntryToComponentId(currentEntry)); + var parentComponent = parentEntry != null ? singleFileComponentRecorder.GetComponent(this.YarnEntryToComponentId(parentEntry)) : null; if (currentComponent != null) { - AddDetectedComponentToGraph(currentComponent, parentComponent, singleFileComponentRecorder, isDevDependency: root.DevDependency); + this.AddDetectedComponentToGraph(currentComponent, parentComponent, singleFileComponentRecorder, isDevDependency: root.DevDependency); } else { // If this is the first time we've seen a component... var detectedComponent = new DetectedComponent(new NpmComponent(currentEntry.Name, currentEntry.Version)); - AddDetectedComponentToGraph(detectedComponent, parentComponent, singleFileComponentRecorder, isDevDependency: root.DevDependency); + this.AddDetectedComponentToGraph(detectedComponent, parentComponent, singleFileComponentRecorder, isDevDependency: root.DevDependency); } // Ensure that we continue to parse the tree for dependencies @@ -156,7 +156,7 @@ private void ParseTreeWithAssignedRoot(YarnEntry root, Dictionary(); - var pkgJsons = ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(location).Directory, new List { "package.json" }, (name, directoryName) => false, recursivelyScanDirectories: false); + var pkgJsons = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(location).Directory, new List { "package.json" }, (name, directoryName) => false, recursivelyScanDirectories: false); IDictionary> combinedDependencies = new Dictionary>(); - int pkgJsonCount = 0; + var pkgJsonCount = 0; IList yarnWorkspaces = new List(); foreach (var pkgJson in pkgJsons) @@ -190,26 +190,26 @@ private bool TryReadPeerPackageJsonRequestsAsYarnEntries(string location, Dictio if (pkgJsonCount != 1) { - Logger.LogWarning($"No package.json was found for file at {location}. It will not be registered."); + this.Logger.LogWarning($"No package.json was found for file at {location}. It will not be registered."); return false; } if (yarnWorkspaces.Count > 0) { - GetWorkspaceDependencies(yarnWorkspaces, new FileInfo(location).Directory, combinedDependencies); + this.GetWorkspaceDependencies(yarnWorkspaces, new FileInfo(location).Directory, combinedDependencies); } // Convert all of the dependencies we retrieved from package.json // into the appropriate yarn package foreach (var dependency in combinedDependencies) { - string name = dependency.Key; + var name = dependency.Key; foreach (var version in dependency.Value) { var entryKey = $"{name}@npm:{version.Key}"; if (!yarnEntries.ContainsKey(entryKey)) { - Logger.LogWarning($"A package was requested in the package.json file that was a peer of {location} but was not contained in the lockfile. {name} - {version.Key}"); + this.Logger.LogWarning($"A package was requested in the package.json file that was a peer of {location} but was not contained in the lockfile. {name} - {version.Key}"); continue; } @@ -240,16 +240,16 @@ private void GetWorkspaceDependencies(IList yarnWorkspaces, DirectoryInf { var glob = Glob.Parse($"{root.FullName.Replace('\\', '/')}/{workspacePattern}/package.json", globOptions); - var componentStreams = ComponentStreamEnumerableFactory.GetComponentStreams(root, (file) => glob.IsMatch(file.FullName.Replace('\\', '/')), null, true); + var componentStreams = this.ComponentStreamEnumerableFactory.GetComponentStreams(root, (file) => glob.IsMatch(file.FullName.Replace('\\', '/')), null, true); foreach (var stream in componentStreams) { - Logger.LogInfo($"{stream.Location} found for workspace {workspacePattern}"); + this.Logger.LogInfo($"{stream.Location} found for workspace {workspacePattern}"); var combinedDependencies = NpmComponentUtilities.TryGetAllPackageJsonDependencies(stream.Stream, out _); foreach (var dependency in combinedDependencies) { - ProcessWorkspaceDependency(dependencies, dependency); + this.ProcessWorkspaceDependency(dependencies, dependency); } } } @@ -265,7 +265,7 @@ private void ProcessWorkspaceDependency(IDictionary ParseYarnLockFileAsync(Stream file, ILogger logger) { - YarnBlockFile blockFile = await YarnBlockFile.CreateBlockFileAsync(file); + var blockFile = await YarnBlockFile.CreateBlockFileAsync(file); foreach (var parser in Parsers) { diff --git a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentHelper.cs b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentHelper.cs index 05323b4d1..e09ea92ba 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentHelper.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentHelper.cs @@ -14,17 +14,17 @@ public class ArgumentHelper : IArgumentHelper public ArgumentHelper() { - ArgumentSets = Enumerable.Empty(); + this.ArgumentSets = Enumerable.Empty(); } public ParserResult ParseArguments(string[] args) { - return Parser.Default.ParseArguments(args, ArgumentSets.Select(x => x.GetType()).ToArray()); + return Parser.Default.ParseArguments(args, this.ArgumentSets.Select(x => x.GetType()).ToArray()); } public ParserResult ParseArguments(string[] args, bool ignoreInvalidArgs = false) { - Parser p = new Parser(x => + var p = new Parser(x => { x.IgnoreUnknownArguments = ignoreInvalidArgs; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BaseArguments.cs b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BaseArguments.cs index 9633eed60..ffb057e7e 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BaseArguments.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BaseArguments.cs @@ -20,7 +20,7 @@ public class BaseArguments : IScanArguments [Option("AdditionalPluginDirectories", Separator = ';', Required = false, Hidden = true, HelpText = "Semi-colon delimited list of directories to search for plugins")] public IEnumerable AdditionalPluginDirectories { get; set; } - public IEnumerable AdditionalPluginDirectoriesSerialized => AdditionalPluginDirectories?.Select(x => x.ToString()) ?? new List(); + public IEnumerable AdditionalPluginDirectoriesSerialized => this.AdditionalPluginDirectories?.Select(x => x.ToString()) ?? new List(); [Option("CorrelationId", Required = false, HelpText = "Identifier used to correlate all telemetry for a given execution. If not provided, a new GUID will be generated.")] public Guid CorrelationId { get; set; } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BcdeArguments.cs b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BcdeArguments.cs index 0e985c6a8..0d6609d86 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BcdeArguments.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BcdeArguments.cs @@ -20,13 +20,13 @@ public class BcdeArguments : BaseArguments, IDetectionArguments [Option("SourceDirectory", Required = true, HelpText = "Directory to operate on.")] public DirectoryInfo SourceDirectory { get; set; } - public string SourceDirectorySerialized => SourceDirectory?.ToString(); + public string SourceDirectorySerialized => this.SourceDirectory?.ToString(); [JsonIgnore] [Option("SourceFileRoot", Required = false, HelpText = "Directory where source files can be found.")] public DirectoryInfo SourceFileRoot { get; set; } - public string SourceFileRootSerialized => SourceFileRoot?.ToString(); + public string SourceFileRootSerialized => this.SourceFileRoot?.ToString(); [Option("DetectorArgs", Separator = ',', Required = false, HelpText = "Comma separated list of properties that can affect the detectors execution, like EnableIfDefaultOff that allows a specific detector that is in beta to run, the format for this property is " + "DetectorId=EnableIfDefaultOff, for example Pip=EnableIfDefaultOff.")] @@ -43,7 +43,7 @@ public class BcdeArguments : BaseArguments, IDetectionArguments [Option("ManifestFile", Required = false, HelpText = "The file to write scan results to.")] public FileInfo ManifestFile { get; set; } - public string ManifestFileSerialized => ManifestFile?.ToString(); + public string ManifestFileSerialized => this.ManifestFile?.ToString(); [Option("DockerImagesToScan", Required = false, Separator = ',', HelpText = "Comma separated list of docker image names or hashes to execute container scanning on, ex: ubuntu:16.04, 56bab49eef2ef07505f6a1b0d5bd3a601dfc3c76ad4460f24c91d6fa298369ab")] public IEnumerable DockerImagesToScan { get; set; } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/CommandLineArgumentsExporter.cs b/src/Microsoft.ComponentDetection.Orchestrator/CommandLineArgumentsExporter.cs index 795bf9def..f7ec65808 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/CommandLineArgumentsExporter.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/CommandLineArgumentsExporter.cs @@ -9,7 +9,7 @@ public class CommandLineArgumentsExporter { public CommandLineArgumentsExporter() { - DelayedInjectionLazy = new Lazy(() => ArgumentsForDelayedInjection); + this.DelayedInjectionLazy = new Lazy(() => ArgumentsForDelayedInjection); } [Export("InjectableDetectionArguments")] diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Orchestrator.cs b/src/Microsoft.ComponentDetection.Orchestrator/Orchestrator.cs index 54d0976c3..e40b35d95 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Orchestrator.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Orchestrator.cs @@ -29,7 +29,7 @@ public class Orchestrator public ScanResult Load(string[] args) { - ArgumentHelper argumentHelper = new ArgumentHelper { ArgumentSets = new[] { new BaseArguments() } }; + var argumentHelper = new ArgumentHelper { ArgumentSets = new[] { new BaseArguments() } }; BaseArguments baseArguments = null; var parserResult = argumentHelper.ParseArguments(args, true); parserResult.WithParsed(x => baseArguments = x); @@ -39,7 +39,7 @@ public ScanResult Load(string[] args) baseArguments = new BaseArguments(); } - IEnumerable additionalDITargets = baseArguments.AdditionalDITargets ?? Enumerable.Empty(); + var additionalDITargets = baseArguments.AdditionalDITargets ?? Enumerable.Empty(); // Load all types from Common (where Logger lives) and our executing assembly. var configuration = new ContainerConfiguration() @@ -62,14 +62,14 @@ public ScanResult Load(string[] args) TelemetryRelay.Instance.SetTelemetryMode(baseArguments.DebugTelemetry ? TelemetryMode.Debug : TelemetryMode.Production); - bool shouldFailureBeSuppressed = false; + var shouldFailureBeSuppressed = false; // Don't use the using pattern here so we can take care not to clobber the stack var returnResult = BcdeExecutionTelemetryRecord.Track( (record) => { - var executionResult = HandleCommand(args, record); - if (executionResult.ResultCode == ProcessingResultCode.PartialSuccess) + var executionResult = this.HandleCommand(args, record); + if (executionResult.ResultCode == ProcessingResultCode.PartialSuccess) { shouldFailureBeSuppressed = true; record.HiddenExitCode = (int)executionResult.ResultCode; @@ -127,7 +127,7 @@ private static void AddAssembliesWithType(Assembly assembly, ContainerConfigu public ScanResult HandleCommand(string[] args, BcdeExecutionTelemetryRecord telemetryRecord) { - var scanResult = new ScanResult() + var scanResult = new ScanResult() { ResultCode = ProcessingResultCode.Error, }; @@ -139,22 +139,22 @@ public ScanResult HandleCommand(string[] args, BcdeExecutionTelemetryRecord tele // Don't set production telemetry if we are running the build task in DevFabric. 0.36.0 is set in the task.json for the build task in development, but is calculated during deployment for production. TelemetryConstants.CorrelationId = argumentSet.CorrelationId; - telemetryRecord.Command = GetVerb(argumentSet); + telemetryRecord.Command = this.GetVerb(argumentSet); - scanResult = SafelyExecute(telemetryRecord, () => + scanResult = this.SafelyExecute(telemetryRecord, () => { - GenerateEnvironmentSpecificTelemetry(telemetryRecord); + this.GenerateEnvironmentSpecificTelemetry(telemetryRecord); telemetryRecord.Arguments = JsonConvert.SerializeObject(argumentSet); FileWritingService.Init(argumentSet.Output); Logger.Init(argumentSet.Verbosity); Logger.LogInfo($"Run correlation id: {TelemetryConstants.CorrelationId.ToString()}"); - return Dispatch(argumentSet, CancellationToken.None).GetAwaiter().GetResult(); + return this.Dispatch(argumentSet, CancellationToken.None).GetAwaiter().GetResult(); }); }) - .WithNotParsed(errors => - { + .WithNotParsed(errors => + { if (errors.Any(e => e is HelpVerbRequestedError)) { telemetryRecord.Command = "help"; @@ -188,7 +188,7 @@ private void GenerateEnvironmentSpecificTelemetry(BcdeExecutionTelemetryRecord t var getLibSslPackages = Task.Run(() => { var startInfo = new ProcessStartInfo("apt", "list --installed") { RedirectStandardOutput = true }; - Process process = new Process { StartInfo = startInfo }; + var process = new Process { StartInfo = startInfo }; process.Start(); string aptListResult = null; var task = Task.Run(() => aptListResult = process.StandardOutput.ReadToEnd()); @@ -223,7 +223,7 @@ private string GetVerb(IScanArguments argumentSet) } private async Task Dispatch(IScanArguments arguments, CancellationToken cancellation) - { + { var scanResult = new ScanResult() { ResultCode = ProcessingResultCode.Error, @@ -266,7 +266,7 @@ private ScanResult SafelyExecute(BcdeExecutionTelemetryRecord record, Func Handle(IScanArguments arguments) { - // Run BCDE with the given arguments + // Run BCDE with the given arguments var detectionArguments = arguments as BcdeArguments; - var result = await BcdeScanExecutionService.ExecuteScanAsync(detectionArguments); + var result = await this.BcdeScanExecutionService.ExecuteScanAsync(detectionArguments); var detectedComponents = result.ComponentsFound.ToList(); foreach (var detectedComponent in detectedComponents) { Console.WriteLine(detectedComponent.Component.Id); } - // TODO: Get vulnerabilities from GH Advisories + // TODO: Get vulnerabilities from GH Advisories return result; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanCommandService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanCommandService.cs index 8e19b0a78..a04d3321f 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanCommandService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanCommandService.cs @@ -26,9 +26,9 @@ public bool CanHandle(IScanArguments arguments) public async Task Handle(IScanArguments arguments) { - BcdeArguments bcdeArguments = (BcdeArguments)arguments; - var result = await BcdeScanExecutionService.ExecuteScanAsync(bcdeArguments); - WriteComponentManifest(bcdeArguments, result); + var bcdeArguments = (BcdeArguments)arguments; + var result = await this.BcdeScanExecutionService.ExecuteScanAsync(bcdeArguments); + this.WriteComponentManifest(bcdeArguments, result); return result; } @@ -38,21 +38,21 @@ private void WriteComponentManifest(IDetectionArguments detectionArguments, Scan if (detectionArguments.ManifestFile != null) { - Logger.LogInfo($"Scan Manifest file: {detectionArguments.ManifestFile.FullName}"); + this.Logger.LogInfo($"Scan Manifest file: {detectionArguments.ManifestFile.FullName}"); userRequestedManifestPath = detectionArguments.ManifestFile; } else { - Logger.LogInfo($"Scan Manifest file: {FileWritingService.ResolveFilePath(ManifestRelativePath)}"); + this.Logger.LogInfo($"Scan Manifest file: {this.FileWritingService.ResolveFilePath(ManifestRelativePath)}"); } if (userRequestedManifestPath == null) { - FileWritingService.AppendToFile(ManifestRelativePath, JsonConvert.SerializeObject(scanResult, Formatting.Indented)); + this.FileWritingService.AppendToFile(ManifestRelativePath, JsonConvert.SerializeObject(scanResult, Formatting.Indented)); } else { - FileWritingService.WriteFile(userRequestedManifestPath, JsonConvert.SerializeObject(scanResult, Formatting.Indented)); + this.FileWritingService.WriteFile(userRequestedManifestPath, JsonConvert.SerializeObject(scanResult, Formatting.Indented)); } } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanExecutionService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanExecutionService.cs index 0fbb0fc14..e4c1f58d8 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanExecutionService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanExecutionService.cs @@ -47,23 +47,23 @@ private DetectorRestrictions GetDetectorRestrictions(IDetectionArguments detecti public async Task ExecuteScanAsync(IDetectionArguments detectionArguments) { - Logger.LogCreateLoggingGroup(); - var initialDetectors = DetectorRegistryService.GetDetectors(detectionArguments.AdditionalPluginDirectories, detectionArguments.AdditionalDITargets).ToImmutableList(); + this.Logger.LogCreateLoggingGroup(); + var initialDetectors = this.DetectorRegistryService.GetDetectors(detectionArguments.AdditionalPluginDirectories, detectionArguments.AdditionalDITargets).ToImmutableList(); if (!initialDetectors.Any()) { throw new NoDetectorsFoundException(); } - DetectorRestrictions detectorRestrictions = GetDetectorRestrictions(detectionArguments); - var detectors = DetectorRestrictionService.ApplyRestrictions(detectorRestrictions, initialDetectors).ToImmutableList(); + var detectorRestrictions = this.GetDetectorRestrictions(detectionArguments); + var detectors = this.DetectorRestrictionService.ApplyRestrictions(detectorRestrictions, initialDetectors).ToImmutableList(); - Logger.LogVerbose($"Finished applying restrictions to detectors."); - Logger.LogCreateLoggingGroup(); + this.Logger.LogVerbose($"Finished applying restrictions to detectors."); + this.Logger.LogCreateLoggingGroup(); - var processingResult = await DetectorProcessingService.ProcessDetectorsAsync(detectionArguments, detectors, detectorRestrictions); + var processingResult = await this.DetectorProcessingService.ProcessDetectorsAsync(detectionArguments, detectors, detectorRestrictions); - var graphTranslationService = GraphTranslationServices.OrderBy(gts => gts.Metadata.Priority).Last().Value; + var graphTranslationService = this.GraphTranslationServices.OrderBy(gts => gts.Metadata.Priority).Last().Value; var scanResult = graphTranslationService.GenerateScanResultFromProcessingResult(processingResult, detectionArguments); diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorListingCommandService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorListingCommandService.cs index 01fdae645..d6a1db6b3 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorListingCommandService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorListingCommandService.cs @@ -20,8 +20,8 @@ public bool CanHandle(IScanArguments arguments) public async Task Handle(IScanArguments arguments) { - await ListDetectorsAsync(arguments as IListDetectionArgs); - return new ScanResult() + await this.ListDetectorsAsync(arguments as IListDetectionArgs); + return new ScanResult() { ResultCode = ProcessingResultCode.Success, }; @@ -29,12 +29,12 @@ public async Task Handle(IScanArguments arguments) private async Task ListDetectorsAsync(IScanArguments listArguments) { - var detectors = DetectorRegistryService.GetDetectors(listArguments.AdditionalPluginDirectories, listArguments.AdditionalDITargets); + var detectors = this.DetectorRegistryService.GetDetectors(listArguments.AdditionalPluginDirectories, listArguments.AdditionalDITargets); if (detectors.Any()) { foreach (var detector in detectors) { - Logger.LogInfo($"{detector.Id}"); + this.Logger.LogInfo($"{detector.Id}"); } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs index 7b34809d9..e81c60a2c 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs @@ -35,27 +35,27 @@ public class DetectorProcessingService : ServiceBase, IDetectorProcessingService public async Task ProcessDetectorsAsync(IDetectionArguments detectionArguments, IEnumerable detectors, DetectorRestrictions detectorRestrictions) { - Logger.LogCreateLoggingGroup(); - Logger.LogInfo($"Finding components..."); + this.Logger.LogCreateLoggingGroup(); + this.Logger.LogInfo($"Finding components..."); - Stopwatch stopwatch = Stopwatch.StartNew(); + var stopwatch = Stopwatch.StartNew(); var exitCode = ProcessingResultCode.Success; // Run the scan on all protocol scanners and union the results - ConcurrentDictionary providerElapsedTime = new ConcurrentDictionary(); + var providerElapsedTime = new ConcurrentDictionary(); var detectorArguments = GetDetectorArgs(detectionArguments.DetectorArgs); - ExcludeDirectoryPredicate exclusionPredicate = IsOSLinuxOrMac() - ? GenerateDirectoryExclusionPredicate(detectionArguments.SourceDirectory.ToString(), detectionArguments.DirectoryExclusionList, detectionArguments.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: false) - : GenerateDirectoryExclusionPredicate(detectionArguments.SourceDirectory.ToString(), detectionArguments.DirectoryExclusionList, detectionArguments.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); + var exclusionPredicate = this.IsOSLinuxOrMac() + ? this.GenerateDirectoryExclusionPredicate(detectionArguments.SourceDirectory.ToString(), detectionArguments.DirectoryExclusionList, detectionArguments.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: false) + : this.GenerateDirectoryExclusionPredicate(detectionArguments.SourceDirectory.ToString(), detectionArguments.DirectoryExclusionList, detectionArguments.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); IEnumerable> scanTasks = detectors .Select(async detector => { - Stopwatch providerStopwatch = new Stopwatch(); + var providerStopwatch = new Stopwatch(); providerStopwatch.Start(); - var componentRecorder = new ComponentRecorder(Logger, !detector.NeedsAutomaticRootDependencyCalculation); + var componentRecorder = new ComponentRecorder(this.Logger, !detector.NeedsAutomaticRootDependencyCalculation); var isExperimentalDetector = detector is IExperimentalDetector && !(detectorRestrictions.ExplicitlyEnabledDetectorIds?.Contains(detector.Id)).GetValueOrDefault(); @@ -65,13 +65,13 @@ public async Task ProcessDetectorsAsync(IDetectionArgu IndividualDetectorScanResult result; using (var record = new DetectorExecutionTelemetryRecord()) { - result = await WithExperimentalScanGuards( - () => detector.ExecuteDetectorAsync(new ScanRequest(detectionArguments.SourceDirectory, exclusionPredicate, Logger, detectorArguments, detectionArguments.DockerImagesToScan, componentRecorder)), + result = await this.WithExperimentalScanGuards( + () => detector.ExecuteDetectorAsync(new ScanRequest(detectionArguments.SourceDirectory, exclusionPredicate, this.Logger, detectorArguments, detectionArguments.DockerImagesToScan, componentRecorder)), isExperimentalDetector, record); // Make sure top level enumerables are at least empty and not null. - result = CoalesceResult(result); + result = this.CoalesceResult(result); detectedComponents = componentRecorder.GetDetectedComponents(); resultCode = result.ResultCode; @@ -118,13 +118,13 @@ public async Task ProcessDetectorsAsync(IDetectionArgu var results = await Task.WhenAll(scanTasks); - DetectorProcessingResult detectorProcessingResult = ConvertDetectorResultsIntoResult(results, exitCode); + var detectorProcessingResult = this.ConvertDetectorResultsIntoResult(results, exitCode); var totalElapsedTime = stopwatch.Elapsed.TotalSeconds; - LogTabularOutput(Logger, providerElapsedTime, totalElapsedTime); + this.LogTabularOutput(this.Logger, providerElapsedTime, totalElapsedTime); - Logger.LogCreateLoggingGroup(); - Logger.LogInfo($"Detection time: {totalElapsedTime} seconds."); + this.Logger.LogCreateLoggingGroup(); + this.Logger.LogInfo($"Detection time: {totalElapsedTime} seconds."); return detectorProcessingResult; } @@ -164,7 +164,7 @@ private async Task WithExperimentalScanGuards(Func try { - return await AsyncExecution.ExecuteWithTimeoutAsync(detectionTaskGenerator, TimeSpan.FromMinutes(2), CancellationToken.None); + return await AsyncExecution.ExecuteWithTimeoutAsync(detectionTaskGenerator, TimeSpan.FromMinutes(4), CancellationToken.None); } catch (TimeoutException) { @@ -190,7 +190,7 @@ private bool IsOSLinuxOrMac() private void LogTabularOutput(ILogger logger, ConcurrentDictionary providerElapsedTime, double totalElapsedTime) { - TabularStringFormat tsf = new TabularStringFormat(new Column[] + var tsf = new TabularStringFormat(new Column[] { new Column { Header = "Component Detector Id", Width = 30 }, new Column { Header = "Detection Time", Width = 30, Format = "{0:g2} seconds" }, @@ -219,9 +219,9 @@ private void LogTabularOutput(ILogger logger, ConcurrentDictionary nameOfDirectoryToConsiderSpan, ReadOnlySpan pathOfParentOfDirectoryToConsiderSpan) => { - string pathOfParentOfDirectoryToConsider = pathOfParentOfDirectoryToConsiderSpan.ToString(); - string nameOfDirectoryToConsider = nameOfDirectoryToConsiderSpan.ToString(); + var pathOfParentOfDirectoryToConsider = pathOfParentOfDirectoryToConsiderSpan.ToString(); + var nameOfDirectoryToConsider = nameOfDirectoryToConsiderSpan.ToString(); foreach (var valueTuple in directories) { @@ -283,7 +283,7 @@ public ExcludeDirectoryPredicate GenerateDirectoryExclusionPredicate(string orig && (pathOfParentOfDirectoryToConsider.Equals(pathOfParentOfDirectoryToExclude, StringComparison.Ordinal) || pathOfParentOfDirectoryToConsider.ToString().Equals(valueTuple.rootedLinuxSymlinkCompatibleRelativePathToExclude, StringComparison.Ordinal))) { - Logger.LogVerbose($"Excluding folder {Path.Combine(pathOfParentOfDirectoryToConsider.ToString(), nameOfDirectoryToConsider.ToString())}."); + this.Logger.LogVerbose($"Excluding folder {Path.Combine(pathOfParentOfDirectoryToConsider.ToString(), nameOfDirectoryToConsider.ToString())}."); return true; } } @@ -292,7 +292,7 @@ public ExcludeDirectoryPredicate GenerateDirectoryExclusionPredicate(string orig }; } - Dictionary minimatchers = new Dictionary(); + var minimatchers = new Dictionary(); var globOptions = new GlobOptions() { @@ -315,7 +315,7 @@ public ExcludeDirectoryPredicate GenerateDirectoryExclusionPredicate(string orig { if (minimatcherKeyValue.Value.IsMatch(path)) { - Logger.LogVerbose($"Excluding folder {path} because it matched glob {minimatcherKeyValue.Key}."); + this.Logger.LogVerbose($"Excluding folder {path} because it matched glob {minimatcherKeyValue.Key}."); return true; } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRegistryService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRegistryService.cs index 954a87518..6e64ce120 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRegistryService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRegistryService.cs @@ -27,49 +27,49 @@ public IEnumerable GetDetectors(IEnumerable a var executableLocation = Assembly.GetEntryAssembly().Location; var searchPath = Path.Combine(Path.GetDirectoryName(executableLocation), "Plugins"); - List directoriesToSearch = new List { new DirectoryInfo(searchPath) }; + var directoriesToSearch = new List { new DirectoryInfo(searchPath) }; if (additionalSearchDirectories != null) { directoriesToSearch.AddRange(additionalSearchDirectories); } - ComponentDetectors = GetComponentDetectors(directoriesToSearch, extraDetectorAssemblies); + this.ComponentDetectors = this.GetComponentDetectors(directoriesToSearch, extraDetectorAssemblies); - if (!ComponentDetectors.Any()) + if (!this.ComponentDetectors.Any()) { - Logger.LogError($"No component detectors were found in {searchPath} or other provided search paths."); + this.Logger.LogError($"No component detectors were found in {searchPath} or other provided search paths."); } - return ComponentDetectors; + return this.ComponentDetectors; } public IEnumerable GetDetectors(Assembly assemblyToSearch, IEnumerable extraDetectorAssemblies) { - Logger.LogInfo($"Attempting to load component detectors from {assemblyToSearch.FullName}"); + this.Logger.LogInfo($"Attempting to load component detectors from {assemblyToSearch.FullName}"); - var loadedDetectors = LoadComponentDetectorsFromAssemblies(new List { assemblyToSearch }, extraDetectorAssemblies); + var loadedDetectors = this.LoadComponentDetectorsFromAssemblies(new List { assemblyToSearch }, extraDetectorAssemblies); var pluralPhrase = loadedDetectors.Count == 1 ? "detector was" : "detectors were"; - Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {assemblyToSearch.FullName}\n"); + this.Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {assemblyToSearch.FullName}\n"); return loadedDetectors; } private IList GetComponentDetectors(IEnumerable searchPaths, IEnumerable extraDetectorAssemblies) { - List detectors = new List(); + var detectors = new List(); using (var record = new LoadComponentDetectorsTelemetryRecord()) { - Logger.LogInfo($"Attempting to load default detectors"); + this.Logger.LogInfo($"Attempting to load default detectors"); var assembly = Assembly.GetAssembly(typeof(IComponentGovernanceOwnedDetectors)); - var loadedDetectors = LoadComponentDetectorsFromAssemblies(new[] { assembly }, extraDetectorAssemblies); + var loadedDetectors = this.LoadComponentDetectorsFromAssemblies(new[] { assembly }, extraDetectorAssemblies); var pluralPhrase = loadedDetectors.Count == 1 ? "detector was" : "detectors were"; - Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {assembly.GetName().Name}\n"); + this.Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {assembly.GetName().Name}\n"); detectors.AddRange(loadedDetectors); @@ -80,20 +80,20 @@ private IList GetComponentDetectors(IEnumerable x.FullName)); + var assemblies = this.SafeLoadAssemblies(searchPath.GetFiles("*.dll", SearchOption.AllDirectories).Select(x => x.FullName)); - var loadedDetectors = LoadComponentDetectorsFromAssemblies(assemblies, extraDetectorAssemblies); + var loadedDetectors = this.LoadComponentDetectorsFromAssemblies(assemblies, extraDetectorAssemblies); var pluralPhrase = loadedDetectors.Count == 1 ? "detector was" : "detectors were"; - Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {searchPath}\n"); + this.Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {searchPath}\n"); detectors.AddRange(loadedDetectors); @@ -105,7 +105,7 @@ private IList GetComponentDetectors(IEnumerable LoadComponentDetectorsFromAssemblies(IEnumerable assemblies, IEnumerable extraDetectorAssemblies) { - new InjectionParameters(DetectorDependencies); + new InjectionParameters(this.DetectorDependencies); var configuration = new ContainerConfiguration() .WithAssemblies(assemblies); @@ -130,7 +130,7 @@ private IList LoadComponentDetectorsFromAssemblies(IEnumerab // Plugin producers may include files we have already loaded private IList SafeLoadAssemblies(IEnumerable files) { - List assemblyList = new List(); + var assemblyList = new List(); foreach (var file in files) { diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs index bd74f56ba..1e3601320 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs @@ -25,12 +25,13 @@ public IEnumerable ApplyRestrictions(DetectorRestrictions ar // If someone specifies an "allow list", use it, otherwise assume everything is allowed if (argSpecifiedRestrictions.AllowedDetectorIds != null && argSpecifiedRestrictions.AllowedDetectorIds.Any()) { - IEnumerable allowedIds = argSpecifiedRestrictions.AllowedDetectorIds; + var allowedIds = argSpecifiedRestrictions.AllowedDetectorIds; // If we have retired detectors in the arg specified list and don't have the new detector, add the new detector - if (allowedIds.Where(a => oldDetectorIds.Contains(a, StringComparer.OrdinalIgnoreCase)).Any() && !allowedIds.Contains(newDetectorId, StringComparer.OrdinalIgnoreCase)) + if (allowedIds.Where(a => this.oldDetectorIds.Contains(a, StringComparer.OrdinalIgnoreCase)).Any() && !allowedIds.Contains(this.newDetectorId, StringComparer.OrdinalIgnoreCase)) { - allowedIds = allowedIds.Concat(new string[] { newDetectorId }); + allowedIds = allowedIds.Concat(new string[] { + this.newDetectorId }); } detectors = detectors.Where(d => allowedIds.Contains(d.Id, StringComparer.OrdinalIgnoreCase)).ToList(); @@ -39,13 +40,13 @@ public IEnumerable ApplyRestrictions(DetectorRestrictions ar { if (!detectors.Select(d => d.Id).Contains(id, StringComparer.OrdinalIgnoreCase)) { - if (!oldDetectorIds.Contains(id, StringComparer.OrdinalIgnoreCase)) + if (!this.oldDetectorIds.Contains(id, StringComparer.OrdinalIgnoreCase)) { throw new InvalidDetectorFilterException($"Detector '{id}' was not found"); } else { - Logger.LogWarning($"The detector '{id}' has been phased out, we will run the '{newDetectorId}' detector which replaced its functionality."); + this.Logger.LogWarning($"The detector '{id}' has been phased out, we will run the '{this.newDetectorId}' detector which replaced its functionality."); } } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs index ebd160b04..783f86705 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs @@ -22,15 +22,15 @@ public ScanResult GenerateScanResultFromProcessingResult(DetectorProcessingResul { var recorderDetectorPairs = detectorProcessingResult.ComponentRecorders; - var unmergedComponents = GatherSetOfDetectedComponentsUnmerged(recorderDetectorPairs, detectionArguments.SourceDirectory); + var unmergedComponents = this.GatherSetOfDetectedComponentsUnmerged(recorderDetectorPairs, detectionArguments.SourceDirectory); - var mergedComponents = FlattenAndMergeComponents(unmergedComponents); + var mergedComponents = this.FlattenAndMergeComponents(unmergedComponents); - LogComponentScopeTelemetry(mergedComponents); + this.LogComponentScopeTelemetry(mergedComponents); return new DefaultGraphScanResult { - ComponentsFound = mergedComponents.Select(x => ConvertToContract(x)).ToList(), + ComponentsFound = mergedComponents.Select(x => this.ConvertToContract(x)).ToList(), ContainerDetailsMap = detectorProcessingResult.ContainersDetailsMap, DependencyGraphs = GraphTranslationUtility.AccumulateAndConvertToContract(recorderDetectorPairs .Select(tuple => tuple.recorder) @@ -79,8 +79,8 @@ private IEnumerable GatherSetOfDetectedComponentsUnmerged(IEn var dependencyGraph = graphKvp.Value; // Calculate roots of the component - AddRootsToDetectedComponent(component, dependencyGraph, componentRecorder); - component.DevelopmentDependency = MergeDevDependency(component.DevelopmentDependency, dependencyGraph.IsDevelopmentDependency(component.Component.Id)); + this.AddRootsToDetectedComponent(component, dependencyGraph, componentRecorder); + component.DevelopmentDependency = this.MergeDevDependency(component.DevelopmentDependency, dependencyGraph.IsDevelopmentDependency(component.Component.Id)); component.DependencyScope = DependencyScopeComparer.GetMergedDependencyScope(component.DependencyScope, dependencyGraph.GetDependencyScope(component.Component.Id)); component.DetectedBy = detector; @@ -88,7 +88,7 @@ private IEnumerable GatherSetOfDetectedComponentsUnmerged(IEn var locations = dependencyGraph.GetAdditionalRelatedFiles(); locations.Add(location); - var relativePaths = MakeFilePathsRelative(Logger, rootDirectory, locations); + var relativePaths = this.MakeFilePathsRelative(this.Logger, rootDirectory, locations); foreach (var additionalRelatedFile in relativePaths ?? Enumerable.Empty()) { @@ -103,10 +103,10 @@ private IEnumerable GatherSetOfDetectedComponentsUnmerged(IEn private List FlattenAndMergeComponents(IEnumerable components) { - List flattenedAndMergedComponents = new List(); + var flattenedAndMergedComponents = new List(); foreach (var grouping in components.GroupBy(x => x.Component.Id + x.DetectedBy.Id)) { - flattenedAndMergedComponents.Add(MergeComponents(grouping)); + flattenedAndMergedComponents.Add(this.MergeComponents(grouping)); } return flattenedAndMergedComponents; @@ -149,7 +149,7 @@ private DetectedComponent MergeComponents(IEnumerable enumera firstComponent.DependencyRoots.Add(root); } - firstComponent.DevelopmentDependency = MergeDevDependency(firstComponent.DevelopmentDependency, nextComponent.DevelopmentDependency); + firstComponent.DevelopmentDependency = this.MergeDevDependency(firstComponent.DevelopmentDependency, nextComponent.DevelopmentDependency); firstComponent.DependencyScope = DependencyScopeComparer.GetMergedDependencyScope(firstComponent.DependencyScope, nextComponent.DependencyScope); if (nextComponent.ContainerDetailIds.Count > 0) @@ -189,7 +189,7 @@ private HashSet MakeFilePathsRelative(ILogger logger, DirectoryInfo root } // Make relative Uri needs a trailing separator to ensure that we turn "directory we are scanning" into "/" - string rootDirectoryFullName = rootDirectory.FullName; + var rootDirectoryFullName = rootDirectory.FullName; if (!rootDirectory.FullName.EndsWith(Path.DirectorySeparatorChar.ToString()) && !rootDirectory.FullName.EndsWith(Path.AltDirectorySeparatorChar.ToString())) { rootDirectoryFullName += Path.DirectorySeparatorChar; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/GraphTranslationUtility.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/GraphTranslationUtility.cs index aa950f2df..26a3daef5 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/GraphTranslationUtility.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/GraphTranslationUtility.cs @@ -35,7 +35,7 @@ public static DependencyGraphCollection AccumulateAndConvertToContract(IEnumerab var componentDependencies = graphByLocation.Value.GetDependenciesForComponent(componentId); // We set dependencies to null basically to make the serialized output look more consistent (instead of empty arrays). If another location gets merged that has dependencies, it needs to create and set the key to non-null. - if (!graphWithMetadata.Graph.TryGetValue(componentId, out HashSet dependencies)) + if (!graphWithMetadata.Graph.TryGetValue(componentId, out var dependencies)) { dependencies = componentDependencies != null && componentDependencies.Any() ? new HashSet() : null; graphWithMetadata.Graph[componentId] = dependencies; diff --git a/src/Microsoft.ComponentDetection/Program.cs b/src/Microsoft.ComponentDetection/Program.cs index f4facb028..143549ea8 100644 --- a/src/Microsoft.ComponentDetection/Program.cs +++ b/src/Microsoft.ComponentDetection/Program.cs @@ -30,12 +30,12 @@ public static void Main(string[] args) var result = orchestrator.Load(args); - int exitCode = (int)result.ResultCode; + var exitCode = (int)result.ResultCode; if (result.ResultCode == ProcessingResultCode.Error || result.ResultCode == ProcessingResultCode.InputError) { exitCode = -1; } - + Console.WriteLine($"Execution finished, status: {exitCode}."); // force an exit, not letting any lingering threads not responding. diff --git a/stylecop.json b/stylecop.json deleted file mode 100644 index 705ef6e0c..000000000 --- a/stylecop.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$schema": - "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", - "settings": { - "orderingRules": { - "usingDirectivesPlacement": "outsideNamespace", - "systemUsingDirectivesFirst": false, - "blankLinesBetweenUsingGroups": "require" - }, - "documentationRules": { - "companyName": "Microsoft Corporation", - "copyrightText": "Copyright (c) {companyName}. All rights reserved.\n\nLicensed under the MIT license.", - "xmlHeader": false - } - } -} \ No newline at end of file diff --git a/test/.editorconfig b/test/.editorconfig new file mode 100644 index 000000000..8a58ab540 --- /dev/null +++ b/test/.editorconfig @@ -0,0 +1,40 @@ +########################################## +# StyleCop +########################################## + +[*] +# SA0001: XML comment analysis is disabled due to project configuration +# Justification: Comments turned off +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA0001.md +dotnet_diagnostic.SA0001.severity = none + +[*.cs] +# SA1600: A C# code element is missing a documentation header. +# Justification: Comments turned off +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1600.md +dotnet_diagnostic.SA1600.severity = none + +# SA1601: A C# partial element is missing a documentation header. +# Justification: Comments turned off +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1601.md +dotnet_diagnostic.SA1601.severity = none + +# SA1602: An item within a C# enumeration is missing an XML documentation header. +# Justification: Comments turned off +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1602.md +dotnet_diagnostic.SA1602.severity = none + +########################################## +# Custom +########################################## + +[*.cs] +# CA1062: Validate arguments of public methods +# Justification: xUnit Theory method parameters don't need to be validated +# https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1062 +dotnet_diagnostic.CA1062.severity = none + +# CA1707: Identifiers should not contain underscores +# Justification: Test method names contain underscores +# https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1707 +dotnet_diagnostic.CA1707.severity = none diff --git a/test/Directory.Build.props b/test/Directory.Build.props index faa16343d..eba374172 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -1,19 +1,18 @@ - + - - - - - - - - + + true + - - $(MSBuildThisFileDirectory)../analyzers.ruleset - true - NU1608,NU5119,NU5100 - - \ No newline at end of file + + + + + + + + + + diff --git a/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs index f3d0d3a22..36a5ce76d 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs @@ -20,7 +20,7 @@ public class BaseDetectionTelemetryRecordTests public void Initialize() { // this only discovers types in a single assembly, since that's the current situation! - recordTypes = typeof(BaseDetectionTelemetryRecord).Assembly.GetTypes() + this.recordTypes = typeof(BaseDetectionTelemetryRecord).Assembly.GetTypes() .Where(type => typeof(BaseDetectionTelemetryRecord).IsAssignableFrom(type)) .Where(type => !type.IsAbstract) .ToArray(); @@ -31,7 +31,7 @@ public void UniqueRecordNames() { var dic = new Dictionary(); - foreach (var type in recordTypes) + foreach (var type in this.recordTypes) { var inst = Activator.CreateInstance(type) as IDetectionTelemetryRecord; Assert.IsNotNull(inst); @@ -65,7 +65,7 @@ public void SerializableProperties() typeof(HttpStatusCode), }); - foreach (var type in recordTypes) + foreach (var type in this.recordTypes) { foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { diff --git a/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs index ed1eaff7a..e616b37c3 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs @@ -18,50 +18,50 @@ public class CommandLineInvocationServiceTests [TestInitialize] public void TestInitialize() { - commandLineService = new CommandLineInvocationService(); + this.commandLineService = new CommandLineInvocationService(); } [SkipTestIfNotWindows] public async Task ShowsCmdExeAsExecutable() { - Assert.IsTrue(await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C")); + Assert.IsTrue(await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C")); } [SkipTestIfNotWindows] public async Task FallbackWorksIfBadCommandsAreFirst() { - Assert.IsTrue(await commandLineService.CanCommandBeLocated("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe", "cmd.exe" }, "/C")); + Assert.IsTrue(await this.commandLineService.CanCommandBeLocated("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe", "cmd.exe" }, "/C")); } [SkipTestIfNotWindows] public async Task ReturnsFalseIfNoValidCommandIsFound() { - Assert.IsFalse(await commandLineService.CanCommandBeLocated("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe" }, "/C")); + Assert.IsFalse(await this.commandLineService.CanCommandBeLocated("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe" }, "/C")); } [SkipTestIfNotWindows] public async Task ReturnsStandardOutput() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); - var taskResult = await commandLineService.ExecuteCommand("cmd.exe", default, "/C echo Expected Output"); + var taskResult = await this.commandLineService.ExecuteCommand("cmd.exe", default, "/C echo Expected Output"); Assert.AreEqual(0, taskResult.ExitCode); Assert.AreEqual(string.Empty, taskResult.StdErr); - Assert.AreEqual("Expected Output", taskResult.StdOut.Replace(System.Environment.NewLine, string.Empty)); + Assert.AreEqual("Expected Output", taskResult.StdOut.Replace(Environment.NewLine, string.Empty)); } [SkipTestIfNotWindows] public async Task ExecutesCommandEvenWithLargeStdOut() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); - StringBuilder largeStringBuilder = new StringBuilder(); + var largeStringBuilder = new StringBuilder(); while (largeStringBuilder.Length < 8100) // Cmd.exe command limit is in the 8100s { largeStringBuilder.Append("Some sample text"); } - var taskResult = await commandLineService.ExecuteCommand("cmd.exe", default, $"/C echo {largeStringBuilder.ToString()}"); + var taskResult = await this.commandLineService.ExecuteCommand("cmd.exe", default, $"/C echo {largeStringBuilder.ToString()}"); Assert.AreEqual(0, taskResult.ExitCode); Assert.AreEqual(string.Empty, taskResult.StdErr); Assert.IsTrue(taskResult.StdOut.Length > 8099, taskResult.StdOut.Length < 100 ? $"Stdout was '{taskResult.StdOut}', which is shorter than 8100 chars" : $"Length was {taskResult.StdOut.Length}, which is less than 8100"); @@ -70,15 +70,15 @@ public async Task ExecutesCommandEvenWithLargeStdOut() [SkipTestIfNotWindows] public async Task ExecutesCommandCapturingErrorOutput() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); - StringBuilder largeStringBuilder = new StringBuilder(); + var largeStringBuilder = new StringBuilder(); while (largeStringBuilder.Length < 9000) // Pick a command that is "too big" for cmd. { largeStringBuilder.Append("Some sample text"); } - var taskResult = await commandLineService.ExecuteCommand("cmd.exe", default, $"/C echo {largeStringBuilder.ToString()}"); + var taskResult = await this.commandLineService.ExecuteCommand("cmd.exe", default, $"/C echo {largeStringBuilder.ToString()}"); Assert.AreEqual(1, taskResult.ExitCode); Assert.IsTrue(taskResult.StdErr.Contains("too long"), $"Expected '{taskResult.StdErr}' to contain 'too long'"); Assert.AreEqual(string.Empty, taskResult.StdOut); @@ -87,12 +87,12 @@ public async Task ExecutesCommandCapturingErrorOutput() [SkipTestIfNotWindows] public async Task ExecutesInAWorkingDirectory() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); - string tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + var tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var tempDirectory = Directory.CreateDirectory(tempDirectoryPath); - var taskResult = await commandLineService.ExecuteCommand("cmd.exe", default, workingDirectory: tempDirectory, "/C cd"); + var taskResult = await this.commandLineService.ExecuteCommand("cmd.exe", default, workingDirectory: tempDirectory, "/C cd"); taskResult.ExitCode.Should().Be(0); taskResult.StdOut.Should().Contain(tempDirectoryPath); } @@ -100,12 +100,12 @@ public async Task ExecutesInAWorkingDirectory() [SkipTestIfNotWindows] public async Task ThrowsIfWorkingDirectoryDoesNotExist() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); var tempDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); - Func action = async () => await commandLineService.ExecuteCommand("cmd.exe", default, workingDirectory: tempDirectory, "/C cd"); + Func action = async () => await this.commandLineService.ExecuteCommand("cmd.exe", default, workingDirectory: tempDirectory, "/C cd"); await action.Should() .ThrowAsync() diff --git a/test/Microsoft.ComponentDetection.Common.Tests/ComponentRecorderTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/ComponentRecorderTests.cs index 91e72947e..c66aa1a22 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/ComponentRecorderTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/ComponentRecorderTests.cs @@ -17,7 +17,7 @@ public class ComponentRecorderTests [TestInitialize] public void TestInitialize() { - componentRecorder = new ComponentRecorder(); + this.componentRecorder = new ComponentRecorder(); } [TestMethod] @@ -25,13 +25,13 @@ public void RegisterUsage_RegisterNewDetectedComponent_NodeInTheGraphIsCreated() { var location = "location"; - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(location); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(location); var detectedComponent = new DetectedComponent(new NpmComponent("test", "1.0.0")); singleFileComponentRecorder.RegisterUsage(detectedComponent); singleFileComponentRecorder.GetComponent(detectedComponent.Component.Id).Should().NotBeNull(); - var dependencyGraph = componentRecorder.GetDependencyGraphForLocation(location); + var dependencyGraph = this.componentRecorder.GetDependencyGraphForLocation(location); dependencyGraph.GetDependenciesForComponent(detectedComponent.Component.Id).Should().NotBeNull(); } @@ -41,7 +41,7 @@ public void RegisterUsage_NewDetectedComponentHasParent_NewRelationshipIsInserte { var location = "location"; - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(location); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(location); var detectedComponent = new DetectedComponent(new NpmComponent("test", "1.0.0")); var parentComponent = new DetectedComponent(new NpmComponent("test2", "2.0.0")); @@ -49,7 +49,7 @@ public void RegisterUsage_NewDetectedComponentHasParent_NewRelationshipIsInserte singleFileComponentRecorder.RegisterUsage(parentComponent); singleFileComponentRecorder.RegisterUsage(detectedComponent, parentComponentId: parentComponent.Component.Id); - var dependencyGraph = componentRecorder.GetDependencyGraphForLocation(location); + var dependencyGraph = this.componentRecorder.GetDependencyGraphForLocation(location); dependencyGraph.GetDependenciesForComponent(parentComponent.Component.Id).Should().Contain(detectedComponent.Component.Id); } @@ -57,7 +57,7 @@ public void RegisterUsage_NewDetectedComponentHasParent_NewRelationshipIsInserte [TestMethod] public void RegisterUsage_DetectedComponentIsNull_ArgumentNullExceptionIsThrown() { - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("location"); Action action = () => singleFileComponentRecorder.RegisterUsage(null); @@ -68,11 +68,11 @@ public void RegisterUsage_DetectedComponentIsNull_ArgumentNullExceptionIsThrown( public void RegisterUsage_DevelopmentDependencyHasValue_componentNodeHasDependencyScope() { var location = "location"; - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(location); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(location); var detectedComponent = new DetectedComponent(new MavenComponent("org.apache.maven", "maven-artifact", "3.6.1")); singleFileComponentRecorder.RegisterUsage(detectedComponent, dependencyScope: DependencyScope.MavenProvided); - var dependencyGraph = componentRecorder.GetDependencyGraphForLocation(location); + var dependencyGraph = this.componentRecorder.GetDependencyGraphForLocation(location); dependencyGraph.GetDependencyScope(detectedComponent.Component.Id).Should().NotBeNull(); dependencyGraph.GetDependencyScope(detectedComponent.Component.Id).Should().Be(DependencyScope.MavenProvided); @@ -81,7 +81,7 @@ public void RegisterUsage_DevelopmentDependencyHasValue_componentNodeHasDependen [TestMethod] public void RegisterUsage_DetectedComponentWithNullComponent_ArgumentExceptionIsThrown() { - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("location"); var detectedComponent = new DetectedComponent(null); Action action = () => singleFileComponentRecorder.RegisterUsage(detectedComponent); @@ -92,7 +92,7 @@ public void RegisterUsage_DetectedComponentWithNullComponent_ArgumentExceptionIs [TestMethod] public void RegisterUsage_DetectedComponentExistAndUpdateFunctionIsNull_NotExceptionIsThrown() { - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("location"); var detectedComponent = new DetectedComponent(new NpmComponent("test", "1.0.0")); singleFileComponentRecorder.RegisterUsage(detectedComponent); @@ -104,33 +104,33 @@ public void RegisterUsage_DetectedComponentExistAndUpdateFunctionIsNull_NotExcep [TestMethod] public void CreateComponentsingleFileComponentRecorderForLocation_LocationIsNull_ArgumentNullExceptionIsThrown() { - Action action = () => componentRecorder.CreateSingleFileComponentRecorder(null); + Action action = () => this.componentRecorder.CreateSingleFileComponentRecorder(null); action.Should().Throw(); - action = () => componentRecorder.CreateSingleFileComponentRecorder(string.Empty); + action = () => this.componentRecorder.CreateSingleFileComponentRecorder(string.Empty); action.Should().Throw(); - action = () => componentRecorder.CreateSingleFileComponentRecorder(" "); + action = () => this.componentRecorder.CreateSingleFileComponentRecorder(" "); action.Should().Throw(); } [TestMethod] public void GetComponent_ComponentNotExist_NullIsReturned() { - componentRecorder.CreateSingleFileComponentRecorder("someMockLocation").GetComponent("nonexistedcomponentId").Should().BeNull(); + this.componentRecorder.CreateSingleFileComponentRecorder("someMockLocation").GetComponent("nonexistedcomponentId").Should().BeNull(); } [TestMethod] public void GetDetectedComponents_AreComponentsRegistered_ComponentsAreReturned() { - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("location"); var detectedComponent1 = new DetectedComponent(new NpmComponent("test", "1.0.0")); var detectedComponent2 = new DetectedComponent(new NpmComponent("test", "2.0.0")); singleFileComponentRecorder.RegisterUsage(detectedComponent1); singleFileComponentRecorder.RegisterUsage(detectedComponent2); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); detectedComponents.Should().HaveCount(2); detectedComponents.Should().Contain(detectedComponent1); @@ -140,7 +140,7 @@ public void GetDetectedComponents_AreComponentsRegistered_ComponentsAreReturned( [TestMethod] public void GetDetectedComponents_NoComponentsAreRegistered_EmptyCollectionIsReturned() { - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); detectedComponents.Should().NotBeNull(); detectedComponents.Should().BeEmpty(); @@ -150,7 +150,7 @@ public void GetDetectedComponents_NoComponentsAreRegistered_EmptyCollectionIsRet public void GetAllDependencyGraphs_ReturnsImmutableDictionaryWithContents() { // Setup an initial, simple graph. - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/some/location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("/some/location"); // We want to take a look at how the class is used by it's friends var internalsView = (ComponentRecorder.SingleFileComponentRecorder)singleFileComponentRecorder; @@ -164,7 +164,7 @@ public void GetAllDependencyGraphs_ReturnsImmutableDictionaryWithContents() component1.DependencyIds.Add(component2.Id); // Get readonly content from graph - var allGraphs = componentRecorder.GetDependencyGraphsByLocation(); + var allGraphs = this.componentRecorder.GetDependencyGraphsByLocation(); var expectedGraph = allGraphs["/some/location"]; // Verify content looks correct @@ -193,7 +193,7 @@ public void GetAllDependencyGraphs_ReturnsImmutableDictionaryWithContents() public void GetAllDependencyGraphs_ReturnedGraphsAreImmutable() { // Setup an initial, simple graph. - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/some/location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("/some/location"); // We want to take a look at how the class is used by it's friends var internalsView = (ComponentRecorder.SingleFileComponentRecorder)singleFileComponentRecorder; @@ -208,7 +208,7 @@ public void GetAllDependencyGraphs_ReturnedGraphsAreImmutable() component1.DependencyIds.Add(component2.Id); // Get readonly content from graph - var allGraphs = componentRecorder.GetDependencyGraphsByLocation(); + var allGraphs = this.componentRecorder.GetDependencyGraphsByLocation(); var expectedGraph = allGraphs["/some/location"]; // Verify content looks correct diff --git a/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs index 80df72875..fdb15abac 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs @@ -17,7 +17,7 @@ public class ComponentStreamEnumerableTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); + this.loggerMock = new Mock(); } [TestMethod] @@ -38,7 +38,7 @@ public void GetEnumerator_WorksOverExpectedFiles() File = new FileInfo(tempFileTwo), Pattern = "Some Pattern", }, - }, loggerMock.Object); + }, this.loggerMock.Object); enumerable.Count() .Should().Be(2); @@ -60,7 +60,7 @@ public void GetEnumerator_LogsAndBreaksEnumerationWhenFileIsMissing() var tempFileTwo = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var tempFileThree = Path.GetTempFileName(); File.Delete(tempFileTwo); - loggerMock.Setup(x => x.LogWarning(Match.Create(message => message.Contains("not exist")))); + this.loggerMock.Setup(x => x.LogWarning(Match.Create(message => message.Contains("not exist")))); var enumerable = new ComponentStreamEnumerable( new[] { @@ -74,12 +74,12 @@ public void GetEnumerator_LogsAndBreaksEnumerationWhenFileIsMissing() File = new FileInfo(tempFileTwo), Pattern = "Some Pattern", }, - }, loggerMock.Object).ToList(); + }, this.loggerMock.Object).ToList(); enumerable.Count .Should().Be(1); - loggerMock.VerifyAll(); + this.loggerMock.VerifyAll(); } } } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/CreateDirectoryTraversalStructure.ps1 b/test/Microsoft.ComponentDetection.Common.Tests/CreateDirectoryTraversalStructure.ps1 index 305d6b8c8..6d043a789 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/CreateDirectoryTraversalStructure.ps1 +++ b/test/Microsoft.ComponentDetection.Common.Tests/CreateDirectoryTraversalStructure.ps1 @@ -54,16 +54,16 @@ if ([System.Environment]::OSVersion.Platform -eq "Win32NT") { New-Item -ItemType Directory -Path ./root/junctions New-Item -ItemType Junction -Path ./root/junctions/unknown-files-junction -Target ./outside-root-two New-Item -ItemType Junction -Path ./root/junctions/known-files-junction -Target ./outside-root - + New-Item -ItemType Directory -Path ./outside-junction-cycles-a CreateValidFileTree ./outside-junction-cycles-a - + New-Item -ItemType Directory -Path ./outside-junction-cycles-b CreateValidFileTree ./outside-junction-cycles-b - + New-Item -ItemType Directory -Path ./root/junction-cycles CreateValidFileTree ./root/junction-cycles - + New-Item -ItemType Junction -Path ./root/junction-cycles/a/b/c/d/e/f/junction-to-outside-q -Target ./outside-junction-cycles-a New-Item -ItemType Junction -Path ./root/junction-cycles/a/b/c/d/e/f/junction-to-outside-r -Target ./outside-junction-cycles-b New-Item -ItemType Junction -Path ./root/junction-cycles/a/b/c/d/e/f/junction-to-outside-s -Target ./outside-junction-cycles-a @@ -74,4 +74,4 @@ if ([System.Environment]::OSVersion.Platform -eq "Win32NT") { } Write-Host "##vso[task.setvariable variable=COMPONENT_DETECTION_SYMLINK_TEST]$testTreeRootName" -Pop-Location \ No newline at end of file +Pop-Location diff --git a/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs index ec7018d53..6110a1804 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs @@ -14,7 +14,7 @@ public class DependencyGraphTests public void TestInitializer() { // Default value of true -- some tests will create their own, though. - dependencyGraph = new DependencyGraph.DependencyGraph(true); + this.dependencyGraph = new DependencyGraph.DependencyGraph(true); } [TestMethod] @@ -25,25 +25,25 @@ public void AddComponent_ParentComponentIdIsPresent_DependencyRelationIsAdded() var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; var componentD = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentD" }; - dependencyGraph.AddComponent(componentD); - dependencyGraph.AddComponent(componentB, parentComponentId: componentD.Id); - dependencyGraph.AddComponent(componentC, parentComponentId: componentB.Id); - dependencyGraph.AddComponent(componentA, parentComponentId: componentB.Id); - dependencyGraph.AddComponent(componentA, parentComponentId: componentC.Id); + this.dependencyGraph.AddComponent(componentD); + this.dependencyGraph.AddComponent(componentB, parentComponentId: componentD.Id); + this.dependencyGraph.AddComponent(componentC, parentComponentId: componentB.Id); + this.dependencyGraph.AddComponent(componentA, parentComponentId: componentB.Id); + this.dependencyGraph.AddComponent(componentA, parentComponentId: componentC.Id); - var componentAChildren = dependencyGraph.GetDependenciesForComponent(componentA.Id); + var componentAChildren = this.dependencyGraph.GetDependenciesForComponent(componentA.Id); componentAChildren.Should().HaveCount(0); - var componentBChildren = dependencyGraph.GetDependenciesForComponent(componentB.Id); + var componentBChildren = this.dependencyGraph.GetDependenciesForComponent(componentB.Id); componentBChildren.Should().HaveCount(2); componentBChildren.Should().Contain(componentA.Id); componentBChildren.Should().Contain(componentC.Id); - var componentCChildren = dependencyGraph.GetDependenciesForComponent(componentC.Id); + var componentCChildren = this.dependencyGraph.GetDependenciesForComponent(componentC.Id); componentCChildren.Should().HaveCount(1); componentCChildren.Should().Contain(componentA.Id); - var componentDChildren = dependencyGraph.GetDependenciesForComponent(componentD.Id); + var componentDChildren = this.dependencyGraph.GetDependenciesForComponent(componentD.Id); componentDChildren.Should().HaveCount(1); componentDChildren.Should().Contain(componentB.Id); } @@ -53,16 +53,16 @@ public void AddComponent_parentComponentIdIsNotPresent_AdditionTakePlaceWithoutT { var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA", IsExplicitReferencedDependency = true }; - Action action = () => dependencyGraph.AddComponent(componentA); + Action action = () => this.dependencyGraph.AddComponent(componentA); action.Should().NotThrow(); - dependencyGraph.Contains(componentA.Id).Should().BeTrue(); + this.dependencyGraph.Contains(componentA.Id).Should().BeTrue(); } [TestMethod] public void AddComponent_ComponentIsNull_ArgumentNullExceptionIsThrow() { - Action action = () => dependencyGraph.AddComponent(null); + Action action = () => this.dependencyGraph.AddComponent(null); action.Should().Throw(); } @@ -71,15 +71,15 @@ public void AddComponent_ComponentIsNull_ArgumentNullExceptionIsThrow() public void AddComponent_ComponentHasNoId_ArgumentNullExceptionIsThrow() { var component = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = null }; - Action action = () => dependencyGraph.AddComponent(component); + Action action = () => this.dependencyGraph.AddComponent(component); action.Should().Throw(); component = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = string.Empty }; - action = () => dependencyGraph.AddComponent(component); + action = () => this.dependencyGraph.AddComponent(component); action.Should().Throw(); component = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = " " }; - action = () => dependencyGraph.AddComponent(component); + action = () => this.dependencyGraph.AddComponent(component); action.Should().Throw(); } @@ -88,7 +88,7 @@ public void AddComponent_ParentComponentWasNotAddedPreviously_ArgumentExceptionI { var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA" }; - Action action = () => dependencyGraph.AddComponent(componentA, parentComponentId: "nonexistingComponent"); + Action action = () => this.dependencyGraph.AddComponent(componentA, parentComponentId: "nonexistingComponent"); action.Should().Throw(); } @@ -103,34 +103,34 @@ public void GetExplicitReferencedDependencyIds_ComponentsWereAddedSpecifyingRoot var componentE = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentE", IsExplicitReferencedDependency = true }; var componentF = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentF" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC, componentB.Id); - dependencyGraph.AddComponent(componentE); - dependencyGraph.AddComponent(componentD, componentE.Id); - dependencyGraph.AddComponent(componentC, componentD.Id); - dependencyGraph.AddComponent(componentF, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC, componentB.Id); + this.dependencyGraph.AddComponent(componentE); + this.dependencyGraph.AddComponent(componentD, componentE.Id); + this.dependencyGraph.AddComponent(componentC, componentD.Id); + this.dependencyGraph.AddComponent(componentF, componentC.Id); - var rootsForComponentA = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var rootsForComponentA = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); rootsForComponentA.Should().HaveCount(1); - var rootsForComponentE = dependencyGraph.GetExplicitReferencedDependencyIds(componentE.Id); + var rootsForComponentE = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentE.Id); rootsForComponentE.Should().HaveCount(1); - var rootsForComponentB = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var rootsForComponentB = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); rootsForComponentB.Should().HaveCount(1); rootsForComponentB.Should().Contain(componentA.Id); - var rootsForComponentD = dependencyGraph.GetExplicitReferencedDependencyIds(componentD.Id); + var rootsForComponentD = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentD.Id); rootsForComponentD.Should().HaveCount(1); rootsForComponentD.Should().Contain(componentE.Id); - var rootsForComponentC = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var rootsForComponentC = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); rootsForComponentC.Should().HaveCount(2); rootsForComponentC.Should().Contain(componentA.Id); rootsForComponentC.Should().Contain(componentE.Id); - var rootsForComponentF = dependencyGraph.GetExplicitReferencedDependencyIds(componentF.Id); + var rootsForComponentF = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentF.Id); rootsForComponentF.Should().HaveCount(2); rootsForComponentF.Should().Contain(componentA.Id); rootsForComponentF.Should().Contain(componentE.Id); @@ -142,13 +142,13 @@ public void GetExplicitReferencedDependencyIds_ComponentsWereAddedWithoutSpecify var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA" }; var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); - var rootsForComponentA = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var rootsForComponentA = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); rootsForComponentA.Should().HaveCount(0); - var rootsForComponentB = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var rootsForComponentB = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); rootsForComponentB.Should().HaveCount(0); } @@ -156,9 +156,9 @@ public void GetExplicitReferencedDependencyIds_ComponentsWereAddedWithoutSpecify public void GetExplicitReferencedDependencyIds_ComponentIsRoot_ARootIsRootOfItSelf() { var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentA); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(1); aRoots.Should().Contain(componentA.Id); } @@ -170,20 +170,20 @@ public void GetExplicitReferencedDependencyIds_RootHasParent_ReturnItselfAndItsP var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsExplicitReferencedDependency = true }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC, componentB.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC, componentB.Id); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(1); aRoots.Should().Contain(componentA.Id); - var bRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); bRoots.Should().HaveCount(2); bRoots.Should().Contain(componentA.Id); bRoots.Should().Contain(componentB.Id); - var cRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); cRoots.Should().HaveCount(3); cRoots.Should().Contain(componentA.Id); cRoots.Should().Contain(componentB.Id); @@ -197,26 +197,26 @@ public void GetExplicitReferencedDependencyIds_InsertionOrderNotAffectedRoots() var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB" }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentB); + this.dependencyGraph.AddComponent(componentB); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(2); aRoots.Should().Contain(componentA.Id); aRoots.Should().Contain(componentC.Id); - var bRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); bRoots.Should().HaveCount(3); bRoots.Should().Contain(componentA.Id); bRoots.Should().Contain(componentB.Id); bRoots.Should().Contain(componentC.Id); - var cRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); cRoots.Should().HaveCount(1); cRoots.Should().Contain(componentC.Id); } @@ -224,78 +224,78 @@ public void GetExplicitReferencedDependencyIds_InsertionOrderNotAffectedRoots() [TestMethod] public void GetExplicitReferencedDependencyIds_UseManualSelectionTurnedOff_ComponentsWithNoParentsAreSelectedAsExplicitReferencedDependencies() { - dependencyGraph = new DependencyGraph.DependencyGraph(false); + this.dependencyGraph = new DependencyGraph.DependencyGraph(false); var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA" }; var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB" }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(1); aRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse(); - var bRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); bRoots.Should().HaveCount(1); bRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse(); - var cRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); cRoots.Should().HaveCount(1); cRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue(); } [TestMethod] public void GetExplicitReferencedDependencyIds_UseManualSelectionTurnedOff_PropertyIsExplicitReferencedDependencyIsIgnored() { - dependencyGraph = new DependencyGraph.DependencyGraph(false); + this.dependencyGraph = new DependencyGraph.DependencyGraph(false); var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA", IsExplicitReferencedDependency = true }; var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsExplicitReferencedDependency = true }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(1); aRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse(); - var bRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); bRoots.Should().HaveCount(1); bRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse(); - var cRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); cRoots.Should().HaveCount(1); cRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue(); } [TestMethod] public void GetExplicitReferencedDependencyIds_NullComponentId_ArgumentNullExceptionIsThrown() { - Action action = () => dependencyGraph.GetExplicitReferencedDependencyIds(null); + Action action = () => this.dependencyGraph.GetExplicitReferencedDependencyIds(null); action.Should().Throw(); - action = () => dependencyGraph.GetExplicitReferencedDependencyIds(string.Empty); + action = () => this.dependencyGraph.GetExplicitReferencedDependencyIds(string.Empty); action.Should().Throw(); - action = () => dependencyGraph.GetExplicitReferencedDependencyIds(" "); + action = () => this.dependencyGraph.GetExplicitReferencedDependencyIds(" "); action.Should().Throw(); } [TestMethod] public void GetExplicitReferencedDependencyIds_ComponentIdIsNotRegisteredInGraph_ArgumentExceptionIsThrown() { - Action action = () => dependencyGraph.GetExplicitReferencedDependencyIds("nonExistingId"); + Action action = () => this.dependencyGraph.GetExplicitReferencedDependencyIds("nonExistingId"); action.Should().Throw(); } @@ -306,14 +306,14 @@ public void IsDevelopmentDependency_ReturnsAsExpected() var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsDevelopmentDependency = false }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); - dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(true); - dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(null); + this.dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(true); + this.dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(null); } [TestMethod] @@ -323,32 +323,32 @@ public void IsDevelopmentDependency_ReturnsAsExpected_AfterMerge() var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsDevelopmentDependency = false }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); var componentANewValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA", IsDevelopmentDependency = false }; var componentBNewValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsDevelopmentDependency = true }; var componentCNewValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC", IsDevelopmentDependency = true }; - dependencyGraph.AddComponent(componentANewValue); - dependencyGraph.AddComponent(componentBNewValue); - dependencyGraph.AddComponent(componentCNewValue); + this.dependencyGraph.AddComponent(componentANewValue); + this.dependencyGraph.AddComponent(componentBNewValue); + this.dependencyGraph.AddComponent(componentCNewValue); - dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(true); + this.dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(true); var componentANullValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA" }; var componentBNullValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB" }; var componentCNullValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; - dependencyGraph.AddComponent(componentANullValue); - dependencyGraph.AddComponent(componentBNullValue); - dependencyGraph.AddComponent(componentCNullValue); + this.dependencyGraph.AddComponent(componentANullValue); + this.dependencyGraph.AddComponent(componentBNullValue); + this.dependencyGraph.AddComponent(componentCNullValue); - dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(true); + this.dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(true); } } } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/DependencyScopeComparerTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/DependencyScopeComparerTests.cs index 0bc7f0205..5b963fbca 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/DependencyScopeComparerTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/DependencyScopeComparerTests.cs @@ -1,11 +1,7 @@ using FluentAssertions; -using FluentAssertions.Primitives; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using Faker; using static Microsoft.ComponentDetection.Common.DependencyScopeComparer; -using System.Linq; namespace Microsoft.ComponentDetection.Common.Tests { @@ -23,7 +19,7 @@ public void GetMergedDependencyScope_returnNull_IfBothNull() [TestMethod] public void GetMergedDependencyScope_returnSecondIfFirstNulll() { - DependencyScope randomDependencyScope = Faker.Enum.Random(); + var randomDependencyScope = Faker.Enum.Random(); GetMergedDependencyScope(null, randomDependencyScope) .Should() .Be(randomDependencyScope); @@ -32,7 +28,7 @@ public void GetMergedDependencyScope_returnSecondIfFirstNulll() [TestMethod] public void GetMergedDependencyScope_returnFirstIfSecondNulll() { - DependencyScope randomDependencyScope = Faker.Enum.Random(); + var randomDependencyScope = Faker.Enum.Random(); GetMergedDependencyScope(randomDependencyScope, null) .Should() .Be(randomDependencyScope); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs index 172eef47e..4c2ed79a6 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs @@ -15,41 +15,41 @@ public class DockerServiceTests private DockerService dockerService; private const string TestImage = "governancecontainerregistry.azurecr.io/testcontainers/hello-world:latest"; - + private const string TestImageWithBaseDetails = "governancecontainerregistry.azurecr.io/testcontainers/dockertags_test:testtag"; - + [TestInitialize] public void TestInitialize() { - dockerService = new DockerService(); + this.dockerService = new DockerService(); } - + [TestMethod] public async Task DockerService_CanPingDocker() { - var canPingDocker = await dockerService.CanPingDockerAsync(); + var canPingDocker = await this.dockerService.CanPingDockerAsync(); Assert.IsTrue(canPingDocker); } [SkipTestOnWindows] public async Task DockerService_CanRunLinuxContainersAsync() { - var isLinuxContainerModeEnabled = await dockerService.CanRunLinuxContainersAsync(); + var isLinuxContainerModeEnabled = await this.dockerService.CanRunLinuxContainersAsync(); Assert.IsTrue(isLinuxContainerModeEnabled); } - + [SkipTestOnWindows] public async Task DockerService_CanPullImage() { - Func action = async () => await dockerService.TryPullImageAsync(TestImage); + Func action = async () => await this.dockerService.TryPullImageAsync(TestImage); await action.Should().NotThrowAsync(); } - + [SkipTestOnWindows] public async Task DockerService_CanInspectImage() { - await dockerService.TryPullImageAsync(TestImage); - var details = await dockerService.InspectImageAsync(TestImage); + await this.dockerService.TryPullImageAsync(TestImage); + var details = await this.dockerService.InspectImageAsync(TestImage); details.Should().NotBeNull(); details.Tags.Should().Contain("governancecontainerregistry.azurecr.io/testcontainers/hello-world:latest"); } @@ -57,8 +57,8 @@ public async Task DockerService_CanInspectImage() [SkipTestOnWindows] public async Task DockerService_PopulatesBaseImageAndLayerDetails() { - await dockerService.TryPullImageAsync(TestImageWithBaseDetails); - var details = await dockerService.InspectImageAsync(TestImageWithBaseDetails); + await this.dockerService.TryPullImageAsync(TestImageWithBaseDetails); + var details = await this.dockerService.InspectImageAsync(TestImageWithBaseDetails); details.Should().NotBeNull(); details.Tags.Should().Contain("governancecontainerregistry.azurecr.io/testcontainers/dockertags_test:testtag"); @@ -73,13 +73,13 @@ public async Task DockerService_PopulatesBaseImageAndLayerDetails() details.BaseImageRef.Should().Be("docker.io/library/hello-world:latest"); details.Layers.Should().HaveCount(1); } - + [SkipTestOnWindows] public async Task DockerService_CanCreateAndRunImage() { - var (stdout, stderr) = await dockerService.CreateAndRunContainerAsync(TestImage, new List()); + var (stdout, stderr) = await this.dockerService.CreateAndRunContainerAsync(TestImage, new List()); stdout.Should().StartWith("\nHello from Docker!"); stderr.Should().BeEmpty(); } } -} \ No newline at end of file +} diff --git a/test/Microsoft.ComponentDetection.Common.Tests/EnvironmentVariableServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/EnvironmentVariableServiceTests.cs index 7e8fd2ffd..854e5d072 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/EnvironmentVariableServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/EnvironmentVariableServiceTests.cs @@ -1,5 +1,4 @@ -using Microsoft.ComponentDetection.Common; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting; using System; @@ -14,30 +13,30 @@ public class EnvironmentVariableServiceTests [TestInitialize] public void TestInitialize() { - testSubject = new EnvironmentVariableService(); - Environment.SetEnvironmentVariable(EnvironmentVariableServiceTests.MyEnvVar, "true"); + this.testSubject = new EnvironmentVariableService(); + Environment.SetEnvironmentVariable(MyEnvVar, "true"); } [TestCleanup] public void TestCleanup() { - Environment.SetEnvironmentVariable(EnvironmentVariableServiceTests.MyEnvVar, null); + Environment.SetEnvironmentVariable(MyEnvVar, null); } [TestMethod] public void DoesEnvironmentVariableExist_ChecksAreCaseInsensitive() - { - Assert.IsFalse(testSubject.DoesEnvironmentVariableExist("THIS_ENVIRONMENT_VARIABLE_DOES_NOT_EXIST")); + { + Assert.IsFalse(this.testSubject.DoesEnvironmentVariableExist("THIS_ENVIRONMENT_VARIABLE_DOES_NOT_EXIST")); - Assert.IsTrue(testSubject.DoesEnvironmentVariableExist(MyEnvVar)); - Assert.IsTrue(testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToLower())); - Assert.IsTrue(testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToUpper())); + Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar)); + Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToLower())); + Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToUpper())); } - + [TestMethod] public void GetEnvironmentVariable_returnNullIfVariableDoesNotExist() { - Assert.IsNull(testSubject.GetEnvironmentVariable("NonExistentVar")); + Assert.IsNull(this.testSubject.GetEnvironmentVariable("NonExistentVar")); } [TestMethod] @@ -46,7 +45,7 @@ public void GetEnvironmentVariable_returnCorrectValue() string envVariableKey = nameof(envVariableKey); string envVariableValue = nameof(envVariableValue); Environment.SetEnvironmentVariable(envVariableKey, envVariableValue); - var result = testSubject.GetEnvironmentVariable(envVariableKey); + var result = this.testSubject.GetEnvironmentVariable(envVariableKey); Assert.IsNotNull(result); Assert.AreEqual(envVariableValue, result); Environment.SetEnvironmentVariable(envVariableKey, null); @@ -59,8 +58,8 @@ public void IsEnvironmentVariableValueTrue_returnsTrueForValidKey_caseInsensitiv string envVariableKey2 = nameof(envVariableKey2); Environment.SetEnvironmentVariable(envVariableKey1, "True"); Environment.SetEnvironmentVariable(envVariableKey2, "tRuE"); - var result1 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); - var result2 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result2 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); Assert.IsTrue(result1); Assert.IsTrue(result2); Environment.SetEnvironmentVariable(envVariableKey1, null); @@ -74,8 +73,8 @@ public void IsEnvironmentVariableValueTrue_returnsFalseForValidKey_caseInsensiti string envVariableKey2 = nameof(envVariableKey2); Environment.SetEnvironmentVariable(envVariableKey1, "False"); Environment.SetEnvironmentVariable(envVariableKey2, "fAlSe"); - var result1 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); - var result2 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result2 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); Assert.IsFalse(result1); Assert.IsFalse(result2); Environment.SetEnvironmentVariable(envVariableKey1, null); @@ -88,8 +87,8 @@ public void IsEnvironmentVariableValueTrue_returnsFalseForInvalidAndNull() string envVariableKey1 = nameof(envVariableKey1); string nonExistentKey = nameof(nonExistentKey); Environment.SetEnvironmentVariable(envVariableKey1, "notABoolean"); - var result1 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); - var result2 = testSubject.IsEnvironmentVariableValueTrue(nonExistentKey); + var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result2 = this.testSubject.IsEnvironmentVariableValueTrue(nonExistentKey); Assert.IsFalse(result1); Assert.IsFalse(result2); Environment.SetEnvironmentVariable(envVariableKey1, null); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs index 2ee9dfc25..5a612a3e7 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs @@ -18,31 +18,31 @@ public class FileWritingServiceTests [TestInitialize] public void TestInitialize() { - serviceUnderTest = new FileWritingService(); + this.serviceUnderTest = new FileWritingService(); // Get a temp file and repurpose it as a temp folder var tempFile = Path.GetTempFileName(); File.Delete(tempFile); Directory.CreateDirectory(tempFile); - tempFolder = tempFile; + this.tempFolder = tempFile; - serviceUnderTest.Init(tempFolder); + this.serviceUnderTest.Init(this.tempFolder); } [TestCleanup] public void TestCleanup() { - Directory.Delete(tempFolder, true); + Directory.Delete(this.tempFolder, true); } [TestMethod] public void AppendToFile_AppendsToFiles() { var relativeDir = "someOtherFileName.txt"; - var fileLocation = Path.Combine(tempFolder, relativeDir); + var fileLocation = Path.Combine(this.tempFolder, relativeDir); File.Create(fileLocation).Dispose(); - serviceUnderTest.AppendToFile(relativeDir, "someSampleText"); - var text = File.ReadAllText(Path.Combine(tempFolder, relativeDir)); + this.serviceUnderTest.AppendToFile(relativeDir, "someSampleText"); + var text = File.ReadAllText(Path.Combine(this.tempFolder, relativeDir)); text .Should().Be("someSampleText"); } @@ -51,8 +51,8 @@ public void AppendToFile_AppendsToFiles() public void WriteFile_CreatesAFile() { var relativeDir = "someFileName.txt"; - serviceUnderTest.WriteFile(relativeDir, "sampleText"); - var text = File.ReadAllText(Path.Combine(tempFolder, relativeDir)); + this.serviceUnderTest.WriteFile(relativeDir, "sampleText"); + var text = File.ReadAllText(Path.Combine(this.tempFolder, relativeDir)); text .Should().Be("sampleText"); } @@ -61,23 +61,23 @@ public void WriteFile_CreatesAFile() public void WriteFile_AppendToFile_WorkWithTemplatizedPaths() { var relativeDir = "somefile_{timestamp}.txt"; - serviceUnderTest.WriteFile(relativeDir, "sampleText"); - serviceUnderTest.AppendToFile(relativeDir, "sampleText2"); - var files = Directory.GetFiles(tempFolder); + this.serviceUnderTest.WriteFile(relativeDir, "sampleText"); + this.serviceUnderTest.AppendToFile(relativeDir, "sampleText2"); + var files = Directory.GetFiles(this.tempFolder); files .Should().NotBeEmpty(); File.ReadAllText(files[0]) .Should().Contain($"sampleTextsampleText2"); - VerifyTimestamp(files[0], "somefile_", ".txt"); + this.VerifyTimestamp(files[0], "somefile_", ".txt"); } [TestMethod] public void ResolveFilePath_ResolvedTemplatizedPaths() { var relativeDir = "someOtherFile_{timestamp}.txt"; - serviceUnderTest.WriteFile(relativeDir, string.Empty); - var fullPath = serviceUnderTest.ResolveFilePath(relativeDir); - VerifyTimestamp(fullPath, "someOtherFile_", ".txt"); + this.serviceUnderTest.WriteFile(relativeDir, string.Empty); + var fullPath = this.serviceUnderTest.ResolveFilePath(relativeDir); + this.VerifyTimestamp(fullPath, "someOtherFile_", ".txt"); } [TestMethod] @@ -85,7 +85,7 @@ public void InitLogger_FailsOnDirectoryThatDoesNotExist() { var relativeDir = Guid.NewGuid(); var actualServiceUnderTest = new FileWritingService(); - Action action = () => actualServiceUnderTest.Init(Path.Combine(serviceUnderTest.BasePath, relativeDir.ToString())); + Action action = () => actualServiceUnderTest.Init(Path.Combine(this.serviceUnderTest.BasePath, relativeDir.ToString())); action.Should().Throw(); } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/LoggerTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/LoggerTests.cs index e167a4bc2..2e2dd71c2 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/LoggerTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/LoggerTests.cs @@ -15,30 +15,30 @@ public class LoggerTests [TestInitialize] public void TestInitialize() { - consoleWritingServiceMock = new Mock(); - fileWritingServiceMock = new Mock(); + this.consoleWritingServiceMock = new Mock(); + this.fileWritingServiceMock = new Mock(); } [TestCleanup] public void TestCleanup() { - consoleWritingServiceMock.VerifyAll(); - fileWritingServiceMock.VerifyAll(); + this.consoleWritingServiceMock.VerifyAll(); + this.fileWritingServiceMock.VerifyAll(); } private Logger CreateLogger(VerbosityMode verbosityMode) { var serviceUnderTest = new Logger { - ConsoleWriter = consoleWritingServiceMock.Object, - FileWritingService = fileWritingServiceMock.Object, + ConsoleWriter = this.consoleWritingServiceMock.Object, + FileWritingService = this.fileWritingServiceMock.Object, }; serviceUnderTest.Init(verbosityMode); // We're not explicitly testing init behavior here, so we reset mock expecations. Another test should verify these. - consoleWritingServiceMock.Invocations.Clear(); - fileWritingServiceMock.Invocations.Clear(); + this.consoleWritingServiceMock.Invocations.Clear(); + this.fileWritingServiceMock.Invocations.Clear(); return serviceUnderTest; } @@ -47,15 +47,15 @@ public void LogCreateLoggingGroup_HandlesFailedInit() { var logger = new Logger { - ConsoleWriter = consoleWritingServiceMock.Object, + ConsoleWriter = this.consoleWritingServiceMock.Object, FileWritingService = null, }; // This should throw an exception while setting up the file writing service, but handle it logger.Init(VerbosityMode.Normal); - consoleWritingServiceMock.Invocations.Clear(); - consoleWritingServiceMock.Setup(x => x.Write(Environment.NewLine)); + this.consoleWritingServiceMock.Invocations.Clear(); + this.consoleWritingServiceMock.Setup(x => x.Write(Environment.NewLine)); // This should not fail, despite not initializing the file writing service logger.LogCreateLoggingGroup(); @@ -63,7 +63,7 @@ public void LogCreateLoggingGroup_HandlesFailedInit() // As a result of handling the file writing service failure, the verbosity should now be Verbose var verboseMessage = "verboseMessage"; var expectedMessage = $"[VERBOSE] {verboseMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); logger.LogVerbose(verboseMessage); } @@ -71,113 +71,113 @@ public void LogCreateLoggingGroup_HandlesFailedInit() [TestMethod] public void LogCreateLoggingGroup_WritesOnNormal() { - var logger = CreateLogger(VerbosityMode.Normal); - consoleWritingServiceMock.Setup(x => x.Write(Environment.NewLine)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, Environment.NewLine)); + var logger = this.CreateLogger(VerbosityMode.Normal); + this.consoleWritingServiceMock.Setup(x => x.Write(Environment.NewLine)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, Environment.NewLine)); logger.LogCreateLoggingGroup(); } [TestMethod] public void LogCreateLoggingGroup_SkipsConsoleOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, Environment.NewLine)); + var logger = this.CreateLogger(VerbosityMode.Quiet); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, Environment.NewLine)); logger.LogCreateLoggingGroup(); } [TestMethod] public void LogWarning_WritesOnNormal() { - var logger = CreateLogger(VerbosityMode.Normal); + var logger = this.CreateLogger(VerbosityMode.Normal); var warningMessage = "warningMessage"; var expectedMessage = $"[WARN] {warningMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogWarning(warningMessage); } [TestMethod] public void LogWarning_SkipsConsoleOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var warningMessage = "warningMessage"; var expectedMessage = $"[WARN] {warningMessage} {Environment.NewLine}"; - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogWarning(warningMessage); } [TestMethod] public void LogInfo_WritesOnNormal() { - var logger = CreateLogger(VerbosityMode.Normal); + var logger = this.CreateLogger(VerbosityMode.Normal); var infoMessage = "informationalMessage"; var expectedMessage = $"[INFO] {infoMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogInfo(infoMessage); } [TestMethod] public void LogInfo_SkipsConsoleOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var infoMessage = "informationalMessage"; var expectedMessage = $"[INFO] {infoMessage} {Environment.NewLine}"; - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogInfo(infoMessage); } [TestMethod] public void LogVerbose_WritesOnVerbose() { - var logger = CreateLogger(VerbosityMode.Verbose); + var logger = this.CreateLogger(VerbosityMode.Verbose); var verboseMessage = "verboseMessage"; var expectedMessage = $"[VERBOSE] {verboseMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogVerbose(verboseMessage); } [TestMethod] public void LogVerbose_SkipsConsoleOnNormal() { - var logger = CreateLogger(VerbosityMode.Normal); + var logger = this.CreateLogger(VerbosityMode.Normal); var verboseMessage = "verboseMessage"; var expectedMessage = $"[VERBOSE] {verboseMessage} {Environment.NewLine}"; - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogVerbose(verboseMessage); } [TestMethod] public void LogError_WritesOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var errorMessage = "errorMessage"; var expectedMessage = $"[ERROR] {errorMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogError(errorMessage); } [TestMethod] public void LogFailedReadingFile_WritesOnVerbose() { - var logger = CreateLogger(VerbosityMode.Verbose); + var logger = this.CreateLogger(VerbosityMode.Verbose); var filePath = "some/bad/file/path"; var error = new UnauthorizedAccessException("Some unauthorized access error"); var consoleSequence = new MockSequence(); - consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write(Environment.NewLine)); - consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write( + this.consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write(Environment.NewLine)); + this.consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write( Match.Create(message => message.StartsWith("[VERBOSE]") && message.Contains(filePath)))); - consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write( + this.consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write( Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); var fileSequence = new MockSequence(); - fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( + this.fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[VERBOSE]") && message.Contains(filePath)))); - fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( + this.fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); @@ -187,15 +187,15 @@ public void LogFailedReadingFile_WritesOnVerbose() [TestMethod] public void LogFailedReadingFile_SkipsConsoleOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var filePath = "some/bad/file/path"; var error = new UnauthorizedAccessException("Some unauthorized access error"); var fileSequence = new MockSequence(); - fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( + this.fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[VERBOSE]") && message.Contains(filePath)))); - fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( + this.fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); @@ -205,13 +205,13 @@ public void LogFailedReadingFile_SkipsConsoleOnQuiet() [TestMethod] public void LogException_WritesOnQuietIfError() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var error = new UnauthorizedAccessException("Some unauthorized access error"); - consoleWritingServiceMock.Setup(x => x.Write( + this.consoleWritingServiceMock.Setup(x => x.Write( Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.Message)))); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.ToString())))); @@ -221,13 +221,13 @@ public void LogException_WritesOnQuietIfError() [TestMethod] public void LogException_DoesNotLogFullExceptionByDefault() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var error = new UnauthorizedAccessException("Some unauthorized access error"); - consoleWritingServiceMock.Setup(x => x.Write( + this.consoleWritingServiceMock.Setup(x => x.Write( Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.Message) && !message.Contains(error.ToString())))); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.ToString())))); @@ -237,13 +237,13 @@ public void LogException_DoesNotLogFullExceptionByDefault() [TestMethod] public void LogException_LogsFullExceptionOnRequest() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var error = new UnauthorizedAccessException("Some unauthorized access error"); - consoleWritingServiceMock.Setup(x => x.Write( + this.consoleWritingServiceMock.Setup(x => x.Write( Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.ToString())))); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.ToString())))); @@ -253,10 +253,10 @@ public void LogException_LogsFullExceptionOnRequest() [TestMethod] public void LogException_SkipsConsoleIfNotErrorAndNormalLogging() { - var logger = CreateLogger(VerbosityMode.Normal); + var logger = this.CreateLogger(VerbosityMode.Normal); var error = new UnauthorizedAccessException("Some unauthorized access error"); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.ToString())))); @@ -266,13 +266,13 @@ public void LogException_SkipsConsoleIfNotErrorAndNormalLogging() [TestMethod] public void LogException_WritesEverythingIfNotErrorAndVerboseLogging() { - var logger = CreateLogger(VerbosityMode.Verbose); + var logger = this.CreateLogger(VerbosityMode.Verbose); var error = new UnauthorizedAccessException("Some unauthorized access error"); - consoleWritingServiceMock.Setup(x => x.Write( + this.consoleWritingServiceMock.Setup(x => x.Write( Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/Microsoft.ComponentDetection.Common.Tests.csproj b/test/Microsoft.ComponentDetection.Common.Tests/Microsoft.ComponentDetection.Common.Tests.csproj index f0417b056..78539e8eb 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/Microsoft.ComponentDetection.Common.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Common.Tests/Microsoft.ComponentDetection.Common.Tests.csproj @@ -1,11 +1,7 @@  - - AnyCPU - - - AnyCPU - - - - + + + + + diff --git a/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs index 35b4fff30..b50fab059 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs @@ -22,37 +22,37 @@ public class SafeFileEnumerableTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - pathUtilityServiceMock = new Mock(); - temporaryDirectory = GetTemporaryDirectory(); + this.loggerMock = new Mock(); + this.pathUtilityServiceMock = new Mock(); + this.temporaryDirectory = this.GetTemporaryDirectory(); } [TestCleanup] public void TestCleanup() { - CleanupTemporaryDirectory(temporaryDirectory); + this.CleanupTemporaryDirectory(this.temporaryDirectory); } [TestMethod] public void GetEnumerator_WorksOverExpectedFiles() { - var subDir = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "SubDir")); - string name = string.Format("{0}.txt", Guid.NewGuid()); + var subDir = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "SubDir")); + var name = string.Format("{0}.txt", Guid.NewGuid()); - var file0 = Path.Combine(temporaryDirectory, name); - var subFile0 = Path.Combine(temporaryDirectory, "SubDir", name); + var file0 = Path.Combine(this.temporaryDirectory, name); + var subFile0 = Path.Combine(this.temporaryDirectory, "SubDir", name); File.Create(file0).Close(); File.Create(subFile0).Close(); IEnumerable searchPatterns = new List { name }; - pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(It.IsAny())).Returns((s) => s); - pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); + this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(It.IsAny())).Returns((s) => s); + this.pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); - var enumerable = new SafeFileEnumerable(new DirectoryInfo(temporaryDirectory), searchPatterns, loggerMock.Object, pathUtilityServiceMock.Object, (directoryName, span) => false, true); + var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, true); - int filesFound = 0; + var filesFound = 0; foreach (var file in enumerable) { file.File.FullName.Should().BeOneOf(file0, subFile0); @@ -65,21 +65,21 @@ public void GetEnumerator_WorksOverExpectedFiles() [TestMethod] public void GetEnumerator_IgnoresSubDirectories() { - var subDir = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "SubDir")); - string name = string.Format("{0}.txt", Guid.NewGuid()); + var subDir = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "SubDir")); + var name = string.Format("{0}.txt", Guid.NewGuid()); - var file0 = Path.Combine(temporaryDirectory, name); + var file0 = Path.Combine(this.temporaryDirectory, name); File.Create(file0).Close(); - File.Create(Path.Combine(temporaryDirectory, "SubDir", name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, "SubDir", name)).Close(); IEnumerable searchPatterns = new List { name }; - pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); + this.pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); - var enumerable = new SafeFileEnumerable(new DirectoryInfo(temporaryDirectory), searchPatterns, loggerMock.Object, pathUtilityServiceMock.Object, (directoryName, span) => false, false); + var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, false); - int filesFound = 0; + var filesFound = 0; foreach (var file in enumerable) { file.File.FullName.Should().BeOneOf(file0); @@ -93,20 +93,20 @@ public void GetEnumerator_IgnoresSubDirectories() public void GetEnumerator_CallsSymlinkCode() { Assert.Inconclusive("Need actual symlinks to accurately test this"); - var subDir = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "SubDir")); - string name = string.Format("{0}.txt", Guid.NewGuid()); - File.Create(Path.Combine(temporaryDirectory, name)).Close(); - File.Create(Path.Combine(temporaryDirectory, "SubDir", name)).Close(); + var subDir = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "SubDir")); + var name = string.Format("{0}.txt", Guid.NewGuid()); + File.Create(Path.Combine(this.temporaryDirectory, name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, "SubDir", name)).Close(); IEnumerable searchPatterns = new List { name }; - var enumerable = new SafeFileEnumerable(new DirectoryInfo(temporaryDirectory), searchPatterns, loggerMock.Object, pathUtilityServiceMock.Object, (directoryName, span) => false, true); + var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, true); foreach (var file in enumerable) { } - pathUtilityServiceMock.Verify(x => x.ResolvePhysicalPath(temporaryDirectory), Times.AtLeastOnce); + this.pathUtilityServiceMock.Verify(x => x.ResolvePhysicalPath(this.temporaryDirectory), Times.AtLeastOnce); } [TestMethod] @@ -115,33 +115,33 @@ public void GetEnumerator_DuplicatePathIgnored() Assert.Inconclusive("Need actual symlinks to accurately test this"); Environment.SetEnvironmentVariable("GovernanceSymlinkAwareMode", bool.TrueString, EnvironmentVariableTarget.Process); - var subDir = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "SubDir")); - var fakeSymlink = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "FakeSymlink")); - string name = string.Format("{0}.txt", Guid.NewGuid()); - string canary = string.Format("{0}.txt", Guid.NewGuid()); - File.Create(Path.Combine(temporaryDirectory, name)).Close(); - File.Create(Path.Combine(temporaryDirectory, "SubDir", name)).Close(); - File.Create(Path.Combine(temporaryDirectory, "FakeSymlink", canary)).Close(); + var subDir = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "SubDir")); + var fakeSymlink = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "FakeSymlink")); + var name = string.Format("{0}.txt", Guid.NewGuid()); + var canary = string.Format("{0}.txt", Guid.NewGuid()); + File.Create(Path.Combine(this.temporaryDirectory, name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, "SubDir", name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, "FakeSymlink", canary)).Close(); - pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(temporaryDirectory)).Returns(temporaryDirectory); - pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(subDir.FullName)).Returns(subDir.FullName); - pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(fakeSymlink.FullName)).Returns(subDir.FullName); + this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(this.temporaryDirectory)).Returns(this.temporaryDirectory); + this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(subDir.FullName)).Returns(subDir.FullName); + this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(fakeSymlink.FullName)).Returns(subDir.FullName); IEnumerable searchPatterns = new List { name }; - var enumerable = new SafeFileEnumerable(new DirectoryInfo(temporaryDirectory), searchPatterns, loggerMock.Object, pathUtilityServiceMock.Object, (directoryName, span) => false, true); + var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, true); foreach (var file in enumerable) { - file.File.FullName.Should().NotBe(Path.Combine(temporaryDirectory, "FakeSymlink", canary)); + file.File.FullName.Should().NotBe(Path.Combine(this.temporaryDirectory, "FakeSymlink", canary)); } - pathUtilityServiceMock.Verify(x => x.ResolvePhysicalPath(temporaryDirectory), Times.AtLeastOnce); + this.pathUtilityServiceMock.Verify(x => x.ResolvePhysicalPath(this.temporaryDirectory), Times.AtLeastOnce); } private string GetTemporaryDirectory() { - string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs index 2b3b18b6e..29ab56a72 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs @@ -17,29 +17,29 @@ public class TabularStringFormatTests [TestInitialize] public void TestInitialize() { - columns = new Column[] + this.columns = new Column[] { new Column { Header = "ColumnA", Width = 50, Format = null }, new Column { Header = "ColumnB", Width = 60, Format = "prefix{0}suffix" }, new Column { Header = "ColumnC", Width = 30, Format = null }, }; - rows = new[] + this.rows = new[] { // One row new[] { "a", "b", "c" }, }; - tsf = new TabularStringFormat(columns); + this.tsf = new TabularStringFormat(this.columns); } [TestMethod] public void GenerateString_AllRowsObeyHeaderLength() { - var generatedString = tsf.GenerateString(rows); + var generatedString = this.tsf.GenerateString(this.rows); // Column width + border characters, one per column + one to 'close' the table. - var lineLength = columns.Sum(x => x.Width) + columns.Length + 1; + var lineLength = this.columns.Sum(x => x.Width) + this.columns.Length + 1; var splitStrings = generatedString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in splitStrings) { @@ -50,31 +50,31 @@ public void GenerateString_AllRowsObeyHeaderLength() [TestMethod] public void GenerateString_ColumnHeadersAreWritten() { - var generatedString = tsf.GenerateString(rows); + var generatedString = this.tsf.GenerateString(this.rows); var splitStrings = generatedString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Second row has the headers var headerCells = splitStrings[1].Split(new[] { TabularStringFormat.DefaultVerticalLineChar }, StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < columns.Length; i++) + for (var i = 0; i < this.columns.Length; i++) { headerCells[i] - .Should().Contain(columns[i].Header); + .Should().Contain(this.columns[i].Header); } } [TestMethod] public void GenerateString_RowContentsAreWritten() { - var generatedString = tsf.GenerateString(rows); + var generatedString = this.tsf.GenerateString(this.rows); var splitStrings = generatedString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Fourth row should have some info var rowCells = splitStrings[3].Split(new[] { TabularStringFormat.DefaultVerticalLineChar }, StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < columns.Length; i++) + for (var i = 0; i < this.columns.Length; i++) { rowCells[i] - .Should().Contain(rows[0][i].ToString()); + .Should().Contain(this.rows[0][i].ToString()); } } } diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/DetectedComponentTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/DetectedComponentTests.cs index f1bec9631..1e9252434 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/DetectedComponentTests.cs +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/DetectedComponentTests.cs @@ -11,11 +11,11 @@ public class DetectedComponentTests [TestMethod] public void AddComponentFilePath_AddsPathsCorrectly() { - string componentName = "express"; - string componentVersion = "1.0.0"; - string filePathToAdd = @"C:\some\fake\file\path.txt"; + var componentName = "express"; + var componentVersion = "1.0.0"; + var filePathToAdd = @"C:\some\fake\file\path.txt"; - DetectedComponent component = new DetectedComponent(new NpmComponent(componentName, componentVersion)); + var component = new DetectedComponent(new NpmComponent(componentName, componentVersion)); Assert.IsNotNull(component.FilePaths); Assert.AreEqual(0, component.FilePaths.Count); diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/Microsoft.ComponentDetection.Contracts.Tests.csproj b/test/Microsoft.ComponentDetection.Contracts.Tests/Microsoft.ComponentDetection.Contracts.Tests.csproj index 7731d4580..37bf889e7 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/Microsoft.ComponentDetection.Contracts.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/Microsoft.ComponentDetection.Contracts.Tests.csproj @@ -1,15 +1,7 @@ - - AnyCPU - - - - AnyCPU - - - + diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/ScanResultSerializationTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/ScanResultSerializationTests.cs index ddb338c3a..d714633d0 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/ScanResultSerializationTests.cs +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/ScanResultSerializationTests.cs @@ -18,7 +18,7 @@ public class ScanResultSerializationTests [TestInitialize] public void TestInitialize() { - scanResultUnderTest = new ScanResult + this.scanResultUnderTest = new ScanResult { ResultCode = ProcessingResultCode.PartialSuccess, ComponentsFound = new[] @@ -59,7 +59,7 @@ public void TestInitialize() [TestMethod] public void ScanResultSerialization_HappyPath() { - var serializedResult = JsonConvert.SerializeObject(scanResultUnderTest); + var serializedResult = JsonConvert.SerializeObject(this.scanResultUnderTest); var actual = JsonConvert.DeserializeObject(serializedResult); actual.ResultCode.Should().Be(ProcessingResultCode.PartialSuccess); @@ -91,8 +91,8 @@ public void ScanResultSerialization_HappyPath() [TestMethod] public void ScanResultSerialization_ExpectedJsonFormat() { - var serializedResult = JsonConvert.SerializeObject(scanResultUnderTest); - JObject json = JObject.Parse(serializedResult); + var serializedResult = JsonConvert.SerializeObject(this.scanResultUnderTest); + var json = JObject.Parse(serializedResult); json.Value("resultCode").Should().Be("PartialSuccess"); json.Value("sourceDirectory").Should().Be("D:\\test\\directory"); diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/TypedComponentSerializationTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/TypedComponentSerializationTests.cs index a1039a638..72958a176 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/TypedComponentSerializationTests.cs +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/TypedComponentSerializationTests.cs @@ -29,8 +29,8 @@ public void TypedComponent_Serialization_Other() [TestMethod] public void TypedComponent_Serialization_NuGet() { - string testComponentName = "SomeNuGetComponent"; - string testVersion = "1.2.3"; + var testComponentName = "SomeNuGetComponent"; + var testVersion = "1.2.3"; string[] testAuthors = { "John Doe", "Jane Doe" }; TypedComponent.TypedComponent tc = new NuGetComponent(testComponentName, testVersion, testAuthors); var result = JsonConvert.SerializeObject(tc); @@ -45,7 +45,7 @@ public void TypedComponent_Serialization_NuGet() [TestMethod] public void TypedComponent_Serialization_Npm() { - NpmAuthor npmAuthor = new Internal.NpmAuthor("someAuthorName", "someAuthorEmail"); + var npmAuthor = new NpmAuthor("someAuthorName", "someAuthorEmail"); var npmCompObj = new NpmComponent("SomeNpmComponent", "1.2.3") { Author = npmAuthor, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs index 5ac54b820..0b69c4fef 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs @@ -28,31 +28,31 @@ public class GoComponentDetectorTests [TestInitialize] public void TestInitialize() { - commandLineMock = new Mock(); - envVarService = new Mock(); + this.commandLineMock = new Mock(); + this.envVarService = new Mock(); var loggerMock = new Mock(); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(true); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(true); var detector = new GoComponentDetector { - CommandLineInvocationService = commandLineMock.Object, + CommandLineInvocationService = this.commandLineMock.Object, Logger = loggerMock.Object, - EnvVarService = envVarService.Object, + EnvVarService = this.envVarService.Object, }; var tempPath = Path.GetTempPath(); var detectionPath = Path.Combine(tempPath, Guid.NewGuid().ToString()); Directory.CreateDirectory(detectionPath); - scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); + this.scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); - detectorTestUtility = DetectorTestUtilityCreator.Create() - .WithScanRequest(scanRequest) + this.detectorTestUtility = DetectorTestUtilityCreator.Create() + .WithScanRequest(this.scanRequest) .WithDetector(detector); - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(false); } @@ -68,7 +68,7 @@ public async Task TestGoModDetectorWithValidFile_ReturnsSuccessfully() gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 github.com/dgrijalva/jwt-go v3.2.0+incompatible )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", goMod) .ExecuteDetector(); @@ -99,7 +99,7 @@ public async Task TestGoSumDetectorWithValidFile_ReturnsSuccessfully() github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.sum", goSum) .ExecuteDetector(); @@ -107,7 +107,7 @@ public async Task TestGoSumDetectorWithValidFile_ReturnsSuccessfully() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(6, detectedComponents.Count()); - List typedComponents = detectedComponents.Select(d => d.Component).ToList(); + var typedComponents = detectedComponents.Select(d => d.Component).ToList(); Assert.IsTrue(typedComponents.Contains( new GoComponent("github.com/golang/mock", "v1.1.1", "h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A="))); Assert.IsTrue(typedComponents.Contains( @@ -135,7 +135,7 @@ public async Task TestGoModDetector_MultipleSpaces_ReturnsSuccessfully() github.com/dgrijalva/jwt-go v3.2.0+incompatible )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", goMod) .ExecuteDetector(); @@ -173,7 +173,7 @@ public async Task TestGoModDetector_ComponentsWithMultipleLocations_ReturnsSucce github.com/Azure/go-autorest v10.15.2+incompatible )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", goMod1) .WithFile("go.mod", goMod2, fileLocation: Path.Join(Path.GetTempPath(), "another-location", "go.mod")) .ExecuteDetector(); @@ -193,13 +193,13 @@ public async Task TestGoModDetector_ComponentsWithMultipleLocations_ReturnsSucce [TestMethod] public async Task TestGoModDetectorInvalidFiles_DoesNotFail() { - string invalidGoMod = + var invalidGoMod = @" #/bin/sh lorem ipsum four score and seven bugs ago $#26^#25%4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", invalidGoMod) .ExecuteDetector(); @@ -216,7 +216,7 @@ public async Task TestGoSumDetection_TwoEntriesForTheSameComponent_ReturnsSucces github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d/go.mod h1:ZZMPRZwes7CROmyNKgQzC3XPs6L/G2EJLHddWejkmf4= )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.sum", goSum) .ExecuteDetector(); @@ -241,7 +241,7 @@ public async Task TestGoModDetector_DetectorOnlyDetectInsideRequireSection() github.com/docker/distribution => github.com/docker/distribution v0.0.0-20191216044856-a8371794149d ) "; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", goMod) .ExecuteDetector(); @@ -258,54 +258,54 @@ public async Task TestGoModDetector_DetectorOnlyDetectInsideRequireSection() [TestMethod] public async Task TestGoDetector_GoCommandNotFound() { - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(false); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); } [TestMethod] public async Task TestGoDetector_GoCommandThrows() { - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(() => throw new Exception("Some horrible error occured")); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); } [TestMethod] public async Task TestGoDetector_GoGraphCommandFails() { - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - commandLineMock.Setup(x => x.ExecuteCommand("go mod graph", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.ExecuteCommand("go mod graph", null, It.IsAny(), It.IsAny())) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 1, }); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); } [TestMethod] public async Task TestGoDetector_GoGraphCommandThrows() { - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - commandLineMock.Setup(x => x.ExecuteCommand("go mod graph", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.ExecuteCommand("go mod graph", null, It.IsAny(), It.IsAny())) .ReturnsAsync(() => throw new Exception("Some horrible error occured")); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); } [TestMethod] @@ -342,26 +342,26 @@ public async Task TestGoDetector_GoGraphHappyPath() }"; var goGraph = "example.com/mainModule some-package@v1.2.3\nsome-package@v1.2.3 other@v1.0.0\nsome-package@v1.2.3 other@v1.2.0\ntest@v2.0.0 a@v1.5.0"; - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "list", "-m", "-json", "all" })) + this.commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "list", "-m", "-json", "all" })) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "mod", "graph" })) + this.commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "mod", "graph" })) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = goGraph, }); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", string.Empty) .ExecuteDetector(); @@ -404,26 +404,26 @@ public async Task TestGoDetector_GoGraphCyclicDependencies() var goGraph = @" github.com/prometheus/common@v0.32.1 github.com/prometheus/client_golang@v1.11.0 github.com/prometheus/client_golang@v1.12.1 github.com/prometheus/common@v0.32.1"; - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "list", "-m", "-json", "all" })) + this.commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "list", "-m", "-json", "all" })) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "mod", "graph" })) + this.commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "mod", "graph" })) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = goGraph, }); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", string.Empty) .ExecuteDetector(); @@ -436,9 +436,9 @@ public async Task TestGoDetector_GoGraphCyclicDependencies() [TestMethod] public async Task TestGoDetector_GoCliRequiresEnvVarToRun() { - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); - commandLineMock.Verify(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny()), Times.Never); + this.commandLineMock.Verify(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny()), Times.Never); } } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentTests.cs index 3042d3a56..3e7ae990e 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentTests.cs @@ -21,7 +21,7 @@ public void TestInitialize() [TestMethod] public void ConstructorTest_NameVersion() { - GoComponent goComponent = new GoComponent(TestName, TestVersion); + var goComponent = new GoComponent(TestName, TestVersion); Assert.AreEqual(TestName, goComponent.Name); Assert.AreEqual(TestVersion, goComponent.Version); Assert.AreEqual(string.Empty, goComponent.Hash); @@ -32,20 +32,20 @@ public void ConstructorTest_NameVersion() [ExpectedException(typeof(ArgumentNullException))] public void ConstructorTest_NameVersion_NullVersion() { - GoComponent goComponent = new GoComponent(TestName, null); + var goComponent = new GoComponent(TestName, null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void ConstructorTest_NameVersion_NullName() { - GoComponent goComponent = new GoComponent(null, TestVersion); + var goComponent = new GoComponent(null, TestVersion); } [TestMethod] public void ConstructorTest_NameVersionHash() { - GoComponent goComponent = new GoComponent(TestName, TestVersion, TestHash); + var goComponent = new GoComponent(TestName, TestVersion, TestHash); Assert.AreEqual(TestName, goComponent.Name); Assert.AreEqual(TestVersion, goComponent.Version); Assert.AreEqual(TestHash, goComponent.Hash); @@ -56,29 +56,29 @@ public void ConstructorTest_NameVersionHash() [ExpectedException(typeof(ArgumentNullException))] public void ConstructorTest_NameVersionHash_NullVersion() { - GoComponent goComponent = new GoComponent(TestName, null, TestHash); + var goComponent = new GoComponent(TestName, null, TestHash); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void ConstructorTest_NameVersionHash_NullName() { - GoComponent goComponent = new GoComponent(null, TestVersion, TestHash); + var goComponent = new GoComponent(null, TestVersion, TestHash); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void ConstructorTest_NameVersionHash_NullHash() { - GoComponent goComponent = new GoComponent(TestName, TestVersion, null); + var goComponent = new GoComponent(TestName, TestVersion, null); } [TestMethod] public void TestEquals() { - GoComponent goComponent1 = new GoComponent(TestName, TestVersion, TestHash); - GoComponent goComponent2 = new GoComponent(TestName, TestVersion, TestHash); - GoComponent goComponent3 = new GoComponent(TestName, TestVersion, Guid.NewGuid().ToString()); + var goComponent1 = new GoComponent(TestName, TestVersion, TestHash); + var goComponent2 = new GoComponent(TestName, TestVersion, TestHash); + var goComponent3 = new GoComponent(TestName, TestVersion, Guid.NewGuid().ToString()); Assert.IsTrue(goComponent1.Equals(goComponent2)); Assert.IsTrue(((object)goComponent1).Equals(goComponent2)); @@ -89,8 +89,8 @@ public void TestEquals() [TestMethod] public void TestGetHashCode() { - GoComponent goComponent1 = new GoComponent(TestName, TestVersion, TestHash); - GoComponent goComponent2 = new GoComponent(TestName, TestVersion, TestHash); + var goComponent1 = new GoComponent(TestName, TestVersion, TestHash); + var goComponent2 = new GoComponent(TestName, TestVersion, TestHash); Assert.IsTrue(goComponent1.GetHashCode() == goComponent2.GetHashCode()); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs index 33428084f..3ccd5efcb 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs @@ -21,13 +21,13 @@ public class GradleComponentDetectorTests [TestInitialize] public void TestInitialize() { - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] public async Task TestGradleDetectorWithNoFiles_ReturnsSuccessfully() { - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -37,12 +37,12 @@ public async Task TestGradleDetectorWithNoFiles_ReturnsSuccessfully() [TestMethod] public async Task TestGradleDetectorWithValidFile_DetectsComponentsSuccessfully() { - string validFileOne = + var validFileOne = @"org.springframework:spring-beans:5.0.5.RELEASE org.springframework:spring-core:5.0.5.RELEASE org.springframework:spring-jcl:5.0.5.RELEASE"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", validFileOne) .ExecuteDetector(); @@ -68,12 +68,12 @@ public async Task TestGradleDetectorWithValidFile_DetectsComponentsSuccessfully( [TestMethod] public async Task TestGradleDetectorWithValidSingleLockfilePerProject_DetectsComponentsSuccessfully() { - string validFileOne = + var validFileOne = @"org.springframework:spring-beans:5.0.5.RELEASE=lintClassPath org.springframework:spring-core:5.0.5.RELEASE=debugCompile,releaseCompile org.springframework:spring-jcl:5.0.5.RELEASE=lintClassPath,debugCompile,releaseCompile"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", validFileOne) .ExecuteDetector(); @@ -100,19 +100,19 @@ public async Task TestGradleDetectorWithValidSingleLockfilePerProject_DetectsCom [TestMethod] public async Task TestGradleDetectorWithValidFiles_ReturnsSuccessfully() { - string validFileOne = + var validFileOne = @"org.springframework:spring-beans:5.0.5.RELEASE org.springframework:spring-core:5.0.5.RELEASE org.springframework:spring-jcl:5.0.5.RELEASE"; - string validFileTwo = + var validFileTwo = @"com.fasterxml.jackson.core:jackson-annotations:2.8.0 com.fasterxml.jackson.core:jackson-core:2.8.10 com.fasterxml.jackson.core:jackson-databind:2.8.11.3 org.msgpack:msgpack-core:0.8.16 org.springframework:spring-jcl:5.0.5.RELEASE"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", validFileOne) .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetector(); @@ -151,13 +151,13 @@ public async Task TestGradleDetectorWithValidFiles_ReturnsSuccessfully() [TestMethod] public async Task TestGradleDetector_SameComponentDifferentLocations_DifferentLocationsAreSaved() { - string validFileOne = + var validFileOne = @"org.springframework:spring-beans:5.0.5.RELEASE"; - string validFileTwo = + var validFileTwo = "org.springframework:spring-beans:5.0.5.RELEASE"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", validFileOne) .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetector(); @@ -182,20 +182,20 @@ public async Task TestGradleDetector_SameComponentDifferentLocations_DifferentLo [TestMethod] public async Task TestGradleDetectorWithInvalidAndValidFiles_ReturnsSuccessfully() { - string validFileTwo = + var validFileTwo = @"com.fasterxml.jackson.core:jackson-annotations:2.8.0 com.fasterxml.jackson.core:jackson-core:2.8.10 com.fasterxml.jackson.core:jackson-databind:2.8.11.3 org.msgpack:msgpack-core:0.8.16 org.springframework:spring-jcl:5.0.5.RELEASE"; - string invalidFileOne = + var invalidFileOne = @" #/bin/sh lorem ipsum four score and seven bugs ago $#26^#25%4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", invalidFileOne) .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs index 3d3eac1be..339c965ce 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs @@ -26,12 +26,12 @@ public class IvyDetectorTests [TestInitialize] public void InitializeTests() { - commandLineMock = new Mock(); + this.commandLineMock = new Mock(); var loggerMock = new Mock(); var detector = new IvyDetector { - CommandLineInvocationService = commandLineMock.Object, + CommandLineInvocationService = this.commandLineMock.Object, Logger = loggerMock.Object, }; @@ -39,26 +39,26 @@ public void InitializeTests() var detectionPath = Path.Combine(tempPath, Guid.NewGuid().ToString()); Directory.CreateDirectory(detectionPath); - scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); + this.scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); - detectorTestUtility = DetectorTestUtilityCreator.Create() - .WithScanRequest(scanRequest) + this.detectorTestUtility = DetectorTestUtilityCreator.Create() + .WithScanRequest(this.scanRequest) .WithDetector(detector); } [TestCleanup] public void TestCleanup() { - scanRequest.SourceDirectory.Delete(recursive: true); + this.scanRequest.SourceDirectory.Delete(recursive: true); } [TestMethod] public async Task IfAntIsNotAvailableThenExitDetectorGracefully() { - commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) + this.commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) .ReturnsAsync(false); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 0); Assert.AreEqual(detectorResult.ResultCode, ProcessingResultCode.Success); @@ -75,9 +75,9 @@ public async Task AntAvailableHappyPath() "{ \"gav\": { \"g\": \"d3g\", \"a\": \"d3a\", \"v\": \"3.3.3\"}, \"DevelopmentDependency\": false, \"resolved\": true, \"parent_gav\": { \"g\": \"d2g\", \"a\": \"d2a\", \"v\": \"2.2.2\"}},\n" + "]}"; - IvyHappyPath(content: registerUsageContent); + this.IvyHappyPath(content: registerUsageContent); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); // IsDevelopmentDependency = true in componentRecorder but null in detectedComponents... why? Assert.AreEqual(3, detectedComponents.Count()); @@ -102,10 +102,10 @@ public async Task AntAvailableHappyPath() [TestMethod] public async Task IvyDetector_FileObservableIsNotPresent_DetectionShouldNotFail() { - commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) + this.commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) .ReturnsAsync(true); - Func action = async () => await detectorTestUtility.ExecuteDetector(); + Func action = async () => await this.detectorTestUtility.ExecuteDetector(); await action.Should().NotThrowAsync(); } @@ -125,9 +125,9 @@ public async Task IvyDependencyGraph() var d2Id = "d2g d2a 2.2.2 - Maven"; var d3Id = "d3g d3a 3.3.3 - Maven"; - IvyHappyPath(content: registerUsageContent); + this.IvyHappyPath(content: registerUsageContent); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); // IsDevelopmentDependency = true in componentRecorder but null in detectedComponents... why? Assert.AreEqual(3, detectedComponents.Count()); @@ -152,17 +152,17 @@ public async Task IvyDependencyGraph() private void IvyHappyPath(string content) { - commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) + this.commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) .ReturnsAsync(true); - var expectedIvyXmlLocation = scanRequest.SourceDirectory.FullName; + var expectedIvyXmlLocation = this.scanRequest.SourceDirectory.FullName; File.WriteAllText(Path.Combine(expectedIvyXmlLocation, "ivy.xml"), "(dummy content)"); File.WriteAllText(Path.Combine(expectedIvyXmlLocation, "ivysettings.xml"), "(dummy content)"); - detectorTestUtility + this.detectorTestUtility .WithFile("ivy.xml", "(dummy content)", fileLocation: Path.Combine(expectedIvyXmlLocation, "ivy.xml")); - commandLineMock.Setup( + this.commandLineMock.Setup( x => x.ExecuteCommand( IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs index 677ee82a6..da596cfb3 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs @@ -39,18 +39,18 @@ public class LinuxContainerDetectorTests [TestInitialize] public void TestInitialize() { - mockDockerService = new Mock(); - mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) + this.mockDockerService = new Mock(); + this.mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) .ReturnsAsync(true); - mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())) + this.mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(true); - mockDockerService.Setup(service => service.InspectImageAsync(It.IsAny(), It.IsAny())) + this.mockDockerService.Setup(service => service.InspectImageAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(new ContainerDetails { Id = 1, ImageId = NodeLatestDigest, Layers = Enumerable.Empty() }); - mockLogger = new Mock(); + this.mockLogger = new Mock(); - mockSyftLinuxScanner = new Mock(); - mockSyftLinuxScanner.Setup(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) + this.mockSyftLinuxScanner = new Mock(); + this.mockSyftLinuxScanner.Setup(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(LinuxComponents); } @@ -59,14 +59,14 @@ public async Task TestLinuxContainerDetector() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage }, componentRecorder); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -87,17 +87,17 @@ public async Task TestLinuxContainerDetector_CantRunLinuxContainers() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, null, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage }, componentRecorder); - mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) + this.mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) .ReturnsAsync(false); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -107,7 +107,7 @@ public async Task TestLinuxContainerDetector_CantRunLinuxContainers() scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); detectedComponents.Should().HaveCount(0); scanResult.ContainerDetails.Should().HaveCount(0); - mockLogger.Verify(logger => logger.LogInfo(It.IsAny())); + this.mockLogger.Verify(logger => logger.LogInfo(It.IsAny())); } [TestMethod] @@ -115,14 +115,14 @@ public async Task TestLinuxContainerDetector_TestNull() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, null, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, null, componentRecorder); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -132,7 +132,7 @@ public async Task TestLinuxContainerDetector_TestNull() scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); detectedComponents.Should().HaveCount(0); scanResult.ContainerDetails.Should().HaveCount(0); - mockLogger.Verify(logger => logger.LogInfo(It.IsAny())); + this.mockLogger.Verify(logger => logger.LogInfo(It.IsAny())); } [TestMethod] @@ -140,14 +140,14 @@ public async Task TestLinuxContainerDetector_VerifyLowerCase() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, null, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { "UPPERCASE" }, componentRecorder); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -166,14 +166,14 @@ public async Task TestLinuxContainerDetector_SameImagePassedMultipleTimes() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, null, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage, NodeLatestDigest }, componentRecorder); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -185,25 +185,38 @@ public async Task TestLinuxContainerDetector_SameImagePassedMultipleTimes() detectedComponents.Should().HaveCount(1); detectedComponents.First().Component.Id.Should().Be(BashPackageId); detectedComponents.All(dc => dc.ContainerDetailIds.Contains(scanResult.ContainerDetails.First().Id)).Should().BeTrue(); - mockSyftLinuxScanner.Verify(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Once); + this.mockSyftLinuxScanner.Verify(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Once); } [TestMethod] public async Task TestLinuxContainerDetector_TimeoutParameterSpecified() { var detectorArgs = new Dictionary { { "Linux.ScanningTimeoutSec", "2" } }; - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, detectorArgs, new List { NodeLatestImage }, new ComponentRecorder()); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; Func action = async () => await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); await action.Should().NotThrowAsync(); } + + [TestMethod] + public async Task TestLinuxContainerDetector_HandlesScratchBase() { + // Setup docker service to throw an exception on scratch + // then specify that the base image is scratch, to test this + // is coped with. + this.mockDockerService.Setup(service => service.TryPullImageAsync("scratch", It.IsAny())) + .Throws(new IOException()); + this.mockDockerService.Setup(service => service.InspectImageAsync(It.IsAny(), It.IsAny())) + // Specify BaseImageRef = scratch to verify that cope + .ReturnsAsync(new ContainerDetails { Id = 1, ImageId = NodeLatestDigest, Layers = Enumerable.Empty(), BaseImageRef = "scratch"}); + await this.TestLinuxContainerDetector(); + } } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs index 35e453350..a0452f579 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs @@ -35,27 +35,27 @@ public class LinuxScannerTests } ] }"; - + private LinuxScanner linuxScanner; private Mock mockDockerService; [TestInitialize] public void TestInitialize() { - mockDockerService = new Mock(); - mockDockerService.Setup(service => service.CanPingDockerAsync(It.IsAny())) + this.mockDockerService = new Mock(); + this.mockDockerService.Setup(service => service.CanPingDockerAsync(It.IsAny())) .ReturnsAsync(true); - mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())); - mockDockerService.Setup(service => service.CreateAndRunContainerAsync(It.IsAny(), It.IsAny>(), It.IsAny())) + this.mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())); + this.mockDockerService.Setup(service => service.CreateAndRunContainerAsync(It.IsAny(), It.IsAny>(), It.IsAny())) .ReturnsAsync((SyftOutput, string.Empty)); - linuxScanner = new LinuxScanner { DockerService = mockDockerService.Object }; + this.linuxScanner = new LinuxScanner { DockerService = this.mockDockerService.Object }; } [TestMethod] public async Task TestLinuxScanner() { - var result = (await linuxScanner.ScanLinuxAsync("fake_hash", new[] { new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" } }, 0)).First().LinuxComponents; + var result = (await this.linuxScanner.ScanLinuxAsync("fake_hash", new[] { new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" } }, 0)).First().LinuxComponents; result.Should().HaveCount(1); var package = result.First(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs index b0debcd7c..55cb4e00b 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs @@ -25,15 +25,15 @@ public class MavenCommandServiceTests [TestInitialize] public void InitializeTests() { - commandLineMock = new Mock(); + this.commandLineMock = new Mock(); var loggerMock = new Mock(); - parserServiceMock = new Mock(); + this.parserServiceMock = new Mock(); - mavenCommandService = new MavenCommandService + this.mavenCommandService = new MavenCommandService { - CommandLineInvocationService = commandLineMock.Object, - ParserService = parserServiceMock.Object, + CommandLineInvocationService = this.commandLineMock.Object, + ParserService = this.parserServiceMock.Object, Logger = loggerMock.Object, }; } @@ -41,12 +41,12 @@ public void InitializeTests() [TestMethod] public async Task MavenCLIExists_ExpectedArguments_ReturnTrue() { - commandLineMock.Setup(x => x.CanCommandBeLocated( + this.commandLineMock.Setup(x => x.CanCommandBeLocated( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(true); - var result = await mavenCommandService.MavenCLIExists(); + var result = await this.mavenCommandService.MavenCLIExists(); result.Should().BeTrue(); } @@ -54,12 +54,12 @@ public async Task MavenCLIExists_ExpectedArguments_ReturnTrue() [TestMethod] public async Task MavenCLIExists_ExpectedArguments_ReturnFalse() { - commandLineMock.Setup(x => x.CanCommandBeLocated( + this.commandLineMock.Setup(x => x.CanCommandBeLocated( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(false); - var result = await mavenCommandService.MavenCLIExists(); + var result = await this.mavenCommandService.MavenCLIExists(); result.Should().BeFalse(); } @@ -79,26 +79,26 @@ public async Task GenerateDependenciesFile_Success() var bcdeMvnFileName = "bcde.mvndeps"; var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={bcdeMvnFileName}", "-DoutputType=text", $"-f{pomLocation}" }; - commandLineMock.Setup(x => x.ExecuteCommand( + this.commandLineMock.Setup(x => x.ExecuteCommand( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, - It.Is(y => ShouldBeEquivalentTo(y, cliParameters)))) + It.Is(y => this.ShouldBeEquivalentTo(y, cliParameters)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, }) .Verifiable(); - await mavenCommandService.GenerateDependenciesFile(processRequest); + await this.mavenCommandService.GenerateDependenciesFile(processRequest); - Mock.Verify(commandLineMock); + Mock.Verify(this.commandLineMock); } [TestMethod] public void ParseDependenciesFile_Success() { const string componentString = "org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT"; - string content = $@"com.bcde.test:top-level:jar:1.0.0{Environment.NewLine}\- {componentString}{Environment.NewLine}"; + var content = $@"com.bcde.test:top-level:jar:1.0.0{Environment.NewLine}\- {componentString}{Environment.NewLine}"; var pomLocation = "Test/location"; var processRequest = new ProcessRequest @@ -111,11 +111,11 @@ public void ParseDependenciesFile_Success() }; var lines = new[] { "com.bcde.test:top-level:jar:1.0.0", $"\\- {componentString}" }; - parserServiceMock.Setup(x => x.Parse(lines, It.IsAny())).Verifiable(); + this.parserServiceMock.Setup(x => x.Parse(lines, It.IsAny())).Verifiable(); - mavenCommandService.ParseDependenciesFile(processRequest); + this.mavenCommandService.ParseDependenciesFile(processRequest); - Mock.Verify(parserServiceMock); + Mock.Verify(this.parserServiceMock); } protected bool ShouldBeEquivalentTo(IEnumerable result, IEnumerable expected) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs index 1574e3e06..5692d9fde 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs @@ -1,13 +1,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Microsoft.ComponentDetection.Detectors.Maven; using System; -using System.Collections.Generic; -using System.Text; using static Microsoft.ComponentDetection.Detectors.Maven.MavenParsingUtilities; using Microsoft.ComponentDetection.Contracts.TypedComponent; -using FluentAssertions.Collections; using Microsoft.ComponentDetection.Contracts.BcdeModels; -using Microsoft.ComponentDetection.Contracts; namespace Microsoft.ComponentDetection.Detectors.Tests { @@ -26,12 +21,12 @@ public void GenerateDetectedComponentAndIsDeveDependencyAndDependencyScope_Happy Assert.IsNotNull(componentAndMetaData.Component); Assert.IsNotNull(componentAndMetaData.IsDevelopmentDependency); Assert.IsNotNull(componentAndMetaData.dependencyScope); - + var actualComponent = (MavenComponent)componentAndMetaData.Component.Component; Assert.IsInstanceOfType(actualComponent, typeof(MavenComponent)); var expectedComponent = new MavenComponent("org.apache.maven", "maven-artifact", "3.6.1-SNAPSHOT"); - + Assert.AreEqual(expectedComponent.ArtifactId, actualComponent.ArtifactId); Assert.AreEqual(expectedComponent.GroupId, actualComponent.GroupId); Assert.AreEqual(expectedComponent.Version, actualComponent.Version); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs index eb2a7786c..0b8fc45a1 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs @@ -17,9 +17,9 @@ public class MavenStyleDependencyGraphParserTests [TestMethod] public void MavenFormat_ExpectedParse() { - var sampleMavenDependencyTree = File.ReadAllLines(sampleMavenDependencyTreePath); + var sampleMavenDependencyTree = File.ReadAllLines(this.sampleMavenDependencyTreePath); - MavenStyleDependencyGraphParser parser = new MavenStyleDependencyGraphParser(); + var parser = new MavenStyleDependencyGraphParser(); var parsedGraph = parser.Parse(sampleMavenDependencyTree); Assert.AreEqual(parsedGraph.Children.Count, 20); Assert.AreEqual(parsedGraph.Value, "org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT"); @@ -45,9 +45,9 @@ public void MavenFormat_ExpectedParse() [TestMethod] public void MavenFormat_WithSingleFileComponentRecorder_ExpectedParse() { - var sampleMavenDependencyTree = File.ReadAllLines(sampleMavenDependencyTreePath); + var sampleMavenDependencyTree = File.ReadAllLines(this.sampleMavenDependencyTreePath); - MavenStyleDependencyGraphParser parser = new MavenStyleDependencyGraphParser(); + var parser = new MavenStyleDependencyGraphParser(); var componentRecorder = new ComponentRecorder(); var pomfileLocation = "location"; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenTestUtilities.cs index e99709043..4d23161d7 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenTestUtilities.cs @@ -4,7 +4,7 @@ public static class MavenTestUtilities { public static string GetMalformedPomFile() { - string pomFile = @" + var pomFile = @" "; return pomFile; @@ -12,7 +12,7 @@ public static string GetMalformedPomFile() public static string GetPomFileNoDependencies() { - string pomFile = @" + var pomFile = @" 4.0.0 @@ -21,7 +21,7 @@ public static string GetPomFileNoDependencies() - + "; return pomFile; @@ -29,7 +29,7 @@ public static string GetPomFileNoDependencies() public static string GetPomFileWithDependencyToResolveAsProperty(string groupId, string artifactId, string version) { - string pomFile = @" + var pomFile = @" 4.0.0 @@ -40,10 +40,10 @@ public static string GetPomFileWithDependencyToResolveAsProperty(string groupId, {0} {1} - ${{myproperty.version}} + ${{myproperty.version}} - + "; var pomFileTemplate = string.Format(pomFile, groupId, artifactId, version); return pomFileTemplate; @@ -51,17 +51,17 @@ public static string GetPomFileWithDependencyToResolveAsProperty(string groupId, public static string GetPomFileWithDependencyToResolveAsProjectVar(string groupId, string artifactId, string version) { - string pomFile = @" + var pomFile = @" {2} {0} {1} - ${{myproperty.version}} + ${{myproperty.version}} - + "; var pomFileTemplate = string.Format(pomFile, groupId, artifactId, version); return pomFileTemplate; @@ -69,7 +69,7 @@ public static string GetPomFileWithDependencyToResolveAsProjectVar(string groupI public static string GetPomFileWithDependencyFailToResolve(string groupId, string artifactId, string version) { - string pomFile = @" + var pomFile = @" 4.0.0 @@ -80,10 +80,10 @@ public static string GetPomFileWithDependencyFailToResolve(string groupId, strin {0} {1} - ${{unknown.version}} + ${{unknown.version}} - + "; var pomFileTemplate = string.Format(pomFile, groupId, artifactId, version); @@ -92,7 +92,7 @@ public static string GetPomFileWithDependencyFailToResolve(string groupId, strin public static string GetPomFileWithDependency(string groupId, string artifactId, string version) { - string pomFile = @" + var pomFile = @" 4.0.0 @@ -100,10 +100,10 @@ public static string GetPomFileWithDependency(string groupId, string artifactId, {0} {1} - {2} + {2} - + "; var pomFileTemplate = string.Format(pomFile, groupId, artifactId, version); return pomFileTemplate; @@ -111,17 +111,17 @@ public static string GetPomFileWithDependency(string groupId, string artifactId, public static string GetPomFileWithDependencyNoVersion(string groupId, string artifactId) { - string pomFile = @" + var pomFile = @" 4.0.0 {0} - {1} + {1} - + "; var pomFileTemplate = string.Format(pomFile, groupId, artifactId); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj b/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj index f033d2347..1b66f8b71 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj @@ -4,18 +4,10 @@ - - AnyCPU - - - - AnyCPU - - - - - + + + diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/Mocks/TestResources.Designer.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/Mocks/TestResources.Designer.cs index 7083add65..dc3c690ed 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/Mocks/TestResources.Designer.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/Mocks/TestResources.Designer.cs @@ -1,182 +1,183 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.ComponentDetection.Detectors.Tests.Mocks { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class TestResources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal TestResources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.ComponentDetection.Detectors.Tests.Mocks.TestResources", typeof(TestResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to integrationTestCompileClasspath - Compile classpath for source set 'integration test'. - ///+--- commons-io:commons-io:2.5 - ///+--- org.kohsuke:github-api:1.94 - ///| +--- org.apache.commons:commons-lang3:3.7 - ///| +--- commons-codec:commons-codec:1.7 - ///| +--- com.fasterxml.jackson.core:jackson-databind:2.9.2 - ///| | +--- com.fasterxml.jackson.core:jackson-annotations:2.9.0 - ///| | \--- com.fasterxml.jackson.core:jackson-core:2.9.2 - ///| \--- commons-io:commons-io:1.4 -> 2.5 - ///+--- org.zeroturnaround:zt-zip: [rest of string was truncated]";. - /// - internal static string GradlewDependencyOutput { - get { - return ResourceManager.GetString("GradlewDependencyOutput", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT - ///+- org.apache.maven:maven-model:jar:3.6.1-SNAPSHOT:compile - ///+- org.apache.maven:maven-model-builder:jar:3.6.1-SNAPSHOT:compile - ///| \- org.apache.maven:maven-builder-support:jar:3.6.1-SNAPSHOT:compile - ///+- org.apache.maven:maven-settings:jar:3.6.1-SNAPSHOT:compile - ///+- org.apache.maven:maven-settings-builder:jar:3.6.1-SNAPSHOT:compile - ///| \- org.sonatype.plexus:plexus-sec-dispatcher:jar:1.4:compile - ///| \- org.sonatype.plexus:plexus-cipher:jar:1.7:compile - ///+- [rest of string was truncated]";. - /// - internal static string MvnCliDependencyOutput { - get { - return ResourceManager.GetString("MvnCliDependencyOutput", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to { - /// "version": 3, - /// "targets": { - /// ".NETCoreApp,Version=v2.2": { - /// "CommandLineParser/2.8.0": { - /// "type": "package", - /// "compile": { - /// "lib/netstandard2.0/_._": {} - /// }, - /// "runtime": { - /// "lib/netstandard2.0/CommandLine.dll": {} - /// } - /// }, - /// "coverlet.msbuild/2.5.1": { - /// "type": "package", - /// "build": { - /// "build/netstandard2.0/coverlet.msbuild.props": {}, - /// "build/netstandard2.0/coverlet.msbuild.targets": {} - /// } - /// }, - /// "DotNet.Glob/2.1.1": { - /// "type": "package [rest of string was truncated]";. - /// - internal static string project_assets_2_2 { - get { - return ResourceManager.GetString("project_assets_2_2", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to { - /// "version": 3, - /// "targets": { - /// ".NETCoreApp,Version=v2.2": { - /// "coverlet.msbuild/2.5.1": { - /// "type": "package", - /// "build": { - /// "build/netstandard2.0/coverlet.msbuild.props": {}, - /// "build/netstandard2.0/coverlet.msbuild.targets": {} - /// } - /// }, - /// "DotNet.Glob/2.1.1": { - /// "type": "package", - /// "dependencies": { - /// "NETStandard.Library": "1.6.1" - /// }, - /// "compile": { - /// "lib/netstandard1.1/DotNet.Glob.dll": {} - /// }, - /// "runtime": { - /// "lib/netstandard1.1/DotNet.Glob.dll": {} /// [rest of string was truncated]";. - /// - internal static string project_assets_2_2_additional { - get { - return ResourceManager.GetString("project_assets_2_2_additional", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to { - /// "version": 3, - /// "targets": { - /// ".NETCoreApp,Version=v3.1": { - /// "Microsoft.Extensions.DependencyModel/3.0.0": { - /// "type": "package", - /// "dependencies": { - /// "System.Text.Json": "4.6.0" - /// }, - /// "compile": { - /// "lib/netstandard2.0/Microsoft.Extensions.DependencyModel.dll": {} - /// }, - /// "runtime": { - /// "lib/netstandard2.0/Microsoft.Extensions.DependencyModel.dll": {} - /// } - /// }, - /// "Microsoft. [rest of string was truncated]";. - /// - internal static string project_assets_3_1 { - get { - return ResourceManager.GetString("project_assets_3_1", resourceCulture); - } - } - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.ComponentDetection.Detectors.Tests.Mocks { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class TestResources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal TestResources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.ComponentDetection.Detectors.Tests.Mocks.TestResources", typeof(TestResources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to integrationTestCompileClasspath - Compile classpath for source set 'integration test'. + ///+--- commons-io:commons-io:2.5 + ///+--- org.kohsuke:github-api:1.94 + ///| +--- org.apache.commons:commons-lang3:3.7 + ///| +--- commons-codec:commons-codec:1.7 + ///| +--- com.fasterxml.jackson.core:jackson-databind:2.9.2 + ///| | +--- com.fasterxml.jackson.core:jackson-annotations:2.9.0 + ///| | \--- com.fasterxml.jackson.core:jackson-core:2.9.2 + ///| \--- commons-io:commons-io:1.4 -> 2.5 + ///+--- org.zeroturnaround:zt-zip: [rest of string was truncated]";. + /// + internal static string GradlewDependencyOutput { + get { + return ResourceManager.GetString("GradlewDependencyOutput", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT + ///+- org.apache.maven:maven-model:jar:3.6.1-SNAPSHOT:compile + ///+- org.apache.maven:maven-model-builder:jar:3.6.1-SNAPSHOT:compile + ///| \- org.apache.maven:maven-builder-support:jar:3.6.1-SNAPSHOT:compile + ///+- org.apache.maven:maven-settings:jar:3.6.1-SNAPSHOT:compile + ///+- org.apache.maven:maven-settings-builder:jar:3.6.1-SNAPSHOT:compile + ///| \- org.sonatype.plexus:plexus-sec-dispatcher:jar:1.4:compile + ///| \- org.sonatype.plexus:plexus-cipher:jar:1.7:compile + ///+- [rest of string was truncated]";. + /// + internal static string MvnCliDependencyOutput { + get { + return ResourceManager.GetString("MvnCliDependencyOutput", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to { + /// "version": 3, + /// "targets": { + /// ".NETCoreApp,Version=v2.2": { + /// "CommandLineParser/2.8.0": { + /// "type": "package", + /// "compile": { + /// "lib/netstandard2.0/_._": {} + /// }, + /// "runtime": { + /// "lib/netstandard2.0/CommandLine.dll": {} + /// } + /// }, + /// "coverlet.msbuild/2.5.1": { + /// "type": "package", + /// "build": { + /// "build/netstandard2.0/coverlet.msbuild.props": {}, + /// "build/netstandard2.0/coverlet.msbuild.targets": {} + /// } + /// }, + /// "DotNet.Glob/2.1.1": { + /// "type": "package [rest of string was truncated]";. + /// + internal static string project_assets_2_2 { + get { + return ResourceManager.GetString("project_assets_2_2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to { + /// "version": 3, + /// "targets": { + /// ".NETCoreApp,Version=v2.2": { + /// "coverlet.msbuild/2.5.1": { + /// "type": "package", + /// "build": { + /// "build/netstandard2.0/coverlet.msbuild.props": {}, + /// "build/netstandard2.0/coverlet.msbuild.targets": {} + /// } + /// }, + /// "DotNet.Glob/2.1.1": { + /// "type": "package", + /// "dependencies": { + /// "NETStandard.Library": "1.6.1" + /// }, + /// "compile": { + /// "lib/netstandard1.1/DotNet.Glob.dll": {} + /// }, + /// "runtime": { + /// "lib/netstandard1.1/DotNet.Glob.dll": {} + /// [rest of string was truncated]";. + /// + internal static string project_assets_2_2_additional { + get { + return ResourceManager.GetString("project_assets_2_2_additional", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to { + /// "version": 3, + /// "targets": { + /// ".NETCoreApp,Version=v3.1": { + /// "Microsoft.Extensions.DependencyModel/3.0.0": { + /// "type": "package", + /// "dependencies": { + /// "System.Text.Json": "4.6.0" + /// }, + /// "compile": { + /// "lib/netstandard2.0/Microsoft.Extensions.DependencyModel.dll": {} + /// }, + /// "runtime": { + /// "lib/netstandard2.0/Microsoft.Extensions.DependencyModel.dll": {} + /// } + /// }, + /// "Microsoft. [rest of string was truncated]";. + /// + internal static string project_assets_3_1 { + get { + return ResourceManager.GetString("project_assets_3_1", resourceCulture); + } + } + } +} diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs index 0481b9679..2c19a3f50 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs @@ -28,10 +28,10 @@ public class MvnCliDetectorTests [TestInitialize] public void InitializeTests() { - commandLineMock = new Mock(); - mavenCommandService = new MavenCommandService + this.commandLineMock = new Mock(); + this.mavenCommandService = new MavenCommandService { - CommandLineInvocationService = commandLineMock.Object, + CommandLineInvocationService = this.commandLineMock.Object, ParserService = new MavenStyleDependencyGraphParserService(), }; @@ -39,7 +39,7 @@ public void InitializeTests() var detector = new MvnCliComponentDetector { - MavenCommandService = mavenCommandService, + MavenCommandService = this.mavenCommandService, Logger = loggerMock.Object, }; @@ -47,28 +47,28 @@ public void InitializeTests() var detectionPath = Path.Combine(tempPath, Guid.NewGuid().ToString()); Directory.CreateDirectory(detectionPath); - scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); + this.scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); - detectorTestUtility = DetectorTestUtilityCreator.Create() - .WithScanRequest(scanRequest) + this.detectorTestUtility = DetectorTestUtilityCreator.Create() + .WithScanRequest(this.scanRequest) .WithDetector(detector); } [TestCleanup] public void TestCleanup() { - scanRequest.SourceDirectory.Delete(); + this.scanRequest.SourceDirectory.Delete(); } [TestMethod] public async Task IfMavenIsNotAvailableThenExitDetectorGracefully() { - commandLineMock.Setup(x => x.CanCommandBeLocated( + this.commandLineMock.Setup(x => x.CanCommandBeLocated( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(false); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 0); Assert.AreEqual(detectorResult.ResultCode, ProcessingResultCode.Success); @@ -79,9 +79,9 @@ public async Task MavenAvailableHappyPath() { const string componentString = "org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT"; - MvnCliHappyPath(content: componentString); + this.MvnCliHappyPath(content: componentString); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(detectedComponents.Count(), 1); @@ -98,12 +98,12 @@ public async Task MavenAvailableHappyPath() [TestMethod] public async Task MavenCli_FileObservableIsNotPresent_DetectionShouldNotFail() { - commandLineMock.Setup(x => x.CanCommandBeLocated( + this.commandLineMock.Setup(x => x.CanCommandBeLocated( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(true); - Func action = async () => await detectorTestUtility.ExecuteDetector(); + Func action = async () => await this.detectorTestUtility.ExecuteDetector(); await action.Should().NotThrowAsync(); } @@ -114,11 +114,11 @@ public async Task MavenRoots() const string componentString = "org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT"; const string childComponentString = "org.apache.maven:maven-compat-child:jar:3.6.1-SNAPSHOT"; - string content = $@"com.bcde.test:top-level:jar:1.0.0{Environment.NewLine}\- {componentString}{Environment.NewLine} \- {childComponentString}"; + var content = $@"com.bcde.test:top-level:jar:1.0.0{Environment.NewLine}\- {componentString}{Environment.NewLine} \- {childComponentString}"; - MvnCliHappyPath(content); + this.MvnCliHappyPath(content); - var (detectorResult, componentRecorder) = await detectorTestUtility + var (detectorResult, componentRecorder) = await this.detectorTestUtility .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -145,7 +145,7 @@ public async Task MavenDependencyGraph() const string leafComponentString = "org.apache.maven:maven-compat-child:jar:3.6.1-SNAPSHOT"; - string content = $@"com.bcde.test:top-level:jar:1.0.0 + var content = $@"com.bcde.test:top-level:jar:1.0.0 \- {explicitReferencedComponent} \- {intermediateParentComponent} \-{leafComponentString}"; @@ -154,9 +154,9 @@ public async Task MavenDependencyGraph() const string intermediateParentComponentId = "org.apache.maven maven-compat-parent 3.6.1-SNAPSHOT - Maven"; const string leafComponentId = "org.apache.maven maven-compat-child 3.6.1-SNAPSHOT - Maven"; - MvnCliHappyPath(content); + this.MvnCliHappyPath(content); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); componentRecorder.GetDetectedComponents().Should().HaveCount(4); detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -178,20 +178,20 @@ public async Task MavenDependencyGraph() private void MvnCliHappyPath(string content) { - commandLineMock.Setup(x => x.CanCommandBeLocated(MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(true); + this.commandLineMock.Setup(x => x.CanCommandBeLocated(MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(true); - var expectedPomLocation = scanRequest.SourceDirectory.FullName; + var expectedPomLocation = this.scanRequest.SourceDirectory.FullName; var bcdeMvnFileName = "bcde.mvndeps"; - detectorTestUtility.WithFile("pom.xml", content, fileLocation: expectedPomLocation) + this.detectorTestUtility.WithFile("pom.xml", content, fileLocation: expectedPomLocation) .WithFile("pom.xml", content, searchPatterns: new[] { bcdeMvnFileName }, fileLocation: Path.Combine(expectedPomLocation, "pom.xml")); var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={bcdeMvnFileName}", "-DoutputType=text", $"-f{expectedPomLocation}" }; - commandLineMock.Setup(x => x.ExecuteCommand( + this.commandLineMock.Setup(x => x.ExecuteCommand( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, - It.Is(y => ShouldBeEquivalentTo(y, cliParameters)))) + It.Is(y => this.ShouldBeEquivalentTo(y, cliParameters)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs index 98f21f874..4e8be6fe1 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs @@ -28,24 +28,24 @@ public class NpmDetectorTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - pathUtilityService = new Mock(); - pathUtilityService.Setup(x => x.GetParentDirectory(It.IsAny())).Returns((string path) => Path.GetDirectoryName(path)); - componentRecorder = new ComponentRecorder(); + this.loggerMock = new Mock(); + this.pathUtilityService = new Mock(); + this.pathUtilityService.Setup(x => x.GetParentDirectory(It.IsAny())).Returns((string path) => Path.GetDirectoryName(path)); + this.componentRecorder = new ComponentRecorder(); } [TestMethod] public async Task TestNpmDetector_NameAndVersionDetected() { - string componentName = GetRandomString(); - string version = NewRandomVersion(); - var (packageJsonName, packageJsonContents, packageJsonPath) = + var componentName = GetRandomString(); + var version = NewRandomVersion(); + var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForNameAndVersion(componentName, version); var detector = new NpmComponentDetector(); - - var (scanResult, componentRecorder) = await detectorTestUtility + + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -58,14 +58,14 @@ public async Task TestNpmDetector_NameAndVersionDetected() [TestMethod] public async Task TestNpmDetector_AuthorNameAndEmailDetected_AuthorInJsonFormat() { - string authorName = GetRandomString(); - string authorEmail = GetRandomString(); + var authorName = GetRandomString(); + var authorEmail = GetRandomString(); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailInJsonFormat(authorName, authorEmail); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -78,36 +78,36 @@ public async Task TestNpmDetector_AuthorNameAndEmailDetected_AuthorInJsonFormat( [TestMethod] public async Task TestNpmDetector_AuthorNameDetectedWhenEmailIsNotPresent_AuthorInJsonFormat() { - string authorName = GetRandomString(); - var (packageJsonName, packageJsonContents, packageJsonPath) = + var authorName = GetRandomString(); + var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailInJsonFormat(authorName, null); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); Assert.AreEqual(authorName, ((NpmComponent)detectedComponents.First().Component).Author.Name); - Assert.IsNull(((NpmComponent)detectedComponents.First().Component).Author.Email); + Assert.IsNull(((NpmComponent)detectedComponents.First().Component).Author.Email); } [TestMethod] public async Task TestNpmDetector_AuthorNameAndAuthorEmailDetected_WhenAuthorNameAndEmailAndUrlIsPresent_AuthorAsSingleString() { - string authorName = GetRandomString(); - string authorEmail = GetRandomString(); - string authroUrl = GetRandomString(); - var (packageJsonName, packageJsonContents, packageJsonPath) = + var authorName = GetRandomString(); + var authorEmail = GetRandomString(); + var authroUrl = GetRandomString(); + var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName, authorEmail, authroUrl); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -120,15 +120,15 @@ public async Task TestNpmDetector_AuthorNameAndAuthorEmailDetected_WhenAuthorNam [TestMethod] public async Task TestNpmDetector_AuthorNameDetected_WhenEmailNotPresentAndUrlIsPresent_AuthorAsSingleString() { - string authorName = GetRandomString(); - string authroUrl = GetRandomString(); - var (packageJsonName, packageJsonContents, packageJsonPath) = + var authorName = GetRandomString(); + var authroUrl = GetRandomString(); + var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName, null, authroUrl); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -141,16 +141,16 @@ public async Task TestNpmDetector_AuthorNameDetected_WhenEmailNotPresentAndUrlIs [TestMethod] public async Task TestNpmDetector_AuthorNull_WhenAuthorMalformed_AuthorAsSingleString() { - string authorName = GetRandomString(); - string authroUrl = GetRandomString(); - string authorEmail = GetRandomString(); + var authorName = GetRandomString(); + var authroUrl = GetRandomString(); + var authorEmail = GetRandomString(); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesMalformedAuthorAsSingleString(authorName, authorEmail, authroUrl); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -162,15 +162,15 @@ public async Task TestNpmDetector_AuthorNull_WhenAuthorMalformed_AuthorAsSingleS [TestMethod] public async Task TestNpmDetector_AuthorNameDetected_WhenEmailNotPresentAndUrlNotPresent_AuthorAsSingleString() { - string authorName = GetRandomString(); - string authroUrl = GetRandomString(); + var authorName = GetRandomString(); + var authroUrl = GetRandomString(); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -183,15 +183,15 @@ public async Task TestNpmDetector_AuthorNameDetected_WhenEmailNotPresentAndUrlNo [TestMethod] public async Task TestNpmDetector_AuthorNameAndAuthorEmailDetected_WhenUrlNotPresent_AuthorAsSingleString() { - string authorName = GetRandomString(); - string authorEmail = GetRandomString(); + var authorName = GetRandomString(); + var authorEmail = GetRandomString(); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName, authorEmail); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -205,15 +205,15 @@ public async Task TestNpmDetector_AuthorNameAndAuthorEmailDetected_WhenUrlNotPre [TestMethod] public async Task TestNpmDetector_NullAuthor_WhenAuthorNameIsNullOrEmpty_AuthorAsJson() { - string authorName = string.Empty; - string authorEmail = GetRandomString(); + var authorName = string.Empty; + var authorEmail = GetRandomString(); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailInJsonFormat(authorName, authorEmail); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -226,15 +226,15 @@ public async Task TestNpmDetector_NullAuthor_WhenAuthorNameIsNullOrEmpty_AuthorA [TestMethod] public async Task TestNpmDetector_NullAuthor_WhenAuthorNameIsNullOrEmpty_AuthorAsSingleString() { - string authorName = string.Empty; - string authorEmail = GetRandomString(); + var authorName = string.Empty; + var authorEmail = GetRandomString(); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName, authorEmail); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs index c6e7fbd06..b543b5a89 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs @@ -33,30 +33,30 @@ public class NpmDetectorWithRootsTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - pathUtilityService = new Mock(); - pathUtilityService.Setup(x => x.GetParentDirectory(It.IsAny())).Returns((string path) => Path.GetDirectoryName(path)); - componentRecorder = new ComponentRecorder(); + this.loggerMock = new Mock(); + this.pathUtilityService = new Mock(); + this.pathUtilityService.Setup(x => x.GetParentDirectory(It.IsAny())).Returns((string path) => Path.GetDirectoryName(path)); + this.componentRecorder = new ComponentRecorder(); } [TestMethod] public async Task TestNpmDetector_PackageLockReturnsValid() { - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName0, version0); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName0, version0); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, version0); var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -74,21 +74,21 @@ public async Task TestNpmDetector_PackageLockReturnsValid() [TestMethod] public async Task TestNpmDetector_MismatchedFilesReturnsEmpty() { - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, version0); var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -98,14 +98,14 @@ public async Task TestNpmDetector_MismatchedFilesReturnsEmpty() [TestMethod] public async Task TestNpmDetector_MissingPackageJsonReturnsEmpty() { - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName); var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) .ExecuteDetector(); @@ -117,16 +117,16 @@ public async Task TestNpmDetector_MissingPackageJsonReturnsEmpty() [TestMethod] public async Task TestNpmDetector_PackageLockMultiRoot() { - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); - string componentName1 = Guid.NewGuid().ToString("N"); - string componentName2 = Guid.NewGuid().ToString("N"); - string version2 = NewRandomVersion(); - string componentName3 = Guid.NewGuid().ToString("N"); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); + var componentName1 = Guid.NewGuid().ToString("N"); + var componentName2 = Guid.NewGuid().ToString("N"); + var version2 = NewRandomVersion(); + var componentName3 = Guid.NewGuid().ToString("N"); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName0, version0, componentName2, version2, packageName1: componentName1, packageName3: componentName3); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName0, version0, componentName2, version2, packageName1: componentName1, packageName3: componentName3); - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -139,13 +139,13 @@ public async Task TestNpmDetector_PackageLockMultiRoot() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -181,14 +181,14 @@ public async Task TestNpmDetector_PackageLockMultiRoot() [TestMethod] public async Task TestNpmDetector_VerifyMultiRoot_DependencyGraph() { - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); - string componentName2 = Guid.NewGuid().ToString("N"); - string version2 = NewRandomVersion(); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); + var componentName2 = Guid.NewGuid().ToString("N"); + var version2 = NewRandomVersion(); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName0, version0, componentName2, version2); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName0, version0, componentName2, version2); - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -201,13 +201,13 @@ public async Task TestNpmDetector_VerifyMultiRoot_DependencyGraph() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); var graphsByLocation = componentRecorder.GetDependencyGraphsByLocation(); @@ -228,12 +228,12 @@ public async Task TestNpmDetector_VerifyMultiRoot_DependencyGraph() [TestMethod] public async Task TestNpmDetector_EmptyVersionSkipped() { - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); - string componentName2 = Guid.NewGuid().ToString("N"); - string version2 = NewRandomVersion(); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); + var componentName2 = Guid.NewGuid().ToString("N"); + var version2 = NewRandomVersion(); - string packageLockJson = @"{{ + var packageLockJson = @"{{ ""name"": ""test"", ""version"": """", ""dependencies"": {{ @@ -258,7 +258,7 @@ public async Task TestNpmDetector_EmptyVersionSkipped() var packageLockTemplate = string.Format(packageLockJson, componentName0, version0, componentName2, version2, componentName2, version2, componentName0, version0); - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -271,13 +271,13 @@ public async Task TestNpmDetector_EmptyVersionSkipped() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -287,12 +287,12 @@ public async Task TestNpmDetector_EmptyVersionSkipped() [TestMethod] public async Task TestNpmDetector_InvalidNameSkipped() { - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); - string componentName2 = Guid.NewGuid().ToString("N"); - string version2 = NewRandomVersion(); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); + var componentName2 = Guid.NewGuid().ToString("N"); + var version2 = NewRandomVersion(); - string packageLockJson = @"{{ + var packageLockJson = @"{{ ""name"": """", ""version"": ""1.0.0"", ""dependencies"": {{ @@ -317,7 +317,7 @@ public async Task TestNpmDetector_InvalidNameSkipped() var packageLockTemplate = string.Format(packageLockJson, componentName0, version0, componentName2, version2, componentName2, version2, componentName0, version0); - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -330,13 +330,13 @@ public async Task TestNpmDetector_InvalidNameSkipped() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -346,18 +346,18 @@ public async Task TestNpmDetector_InvalidNameSkipped() [TestMethod] public async Task TestNpmDetector_LernaDirectory() { - string lockFileLocation = Path.Combine(Path.GetTempPath(), Path.Combine("belowLerna", packageLockJsonFileName)); - string packageJsonFileLocation = Path.Combine(Path.GetTempPath(), Path.Combine("belowLerna", packageJsonFileName)); - string lernaFileLocation = Path.Combine(Path.GetTempPath(), "lerna.json"); - - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); - string componentName1 = Guid.NewGuid().ToString("N"); - string version1 = NewRandomVersion(); - string componentName2 = Guid.NewGuid().ToString("N"); - string version2 = NewRandomVersion(); - - string packageLockJson = @"{{ + var lockFileLocation = Path.Combine(Path.GetTempPath(), Path.Combine("belowLerna", this.packageLockJsonFileName)); + var packageJsonFileLocation = Path.Combine(Path.GetTempPath(), Path.Combine("belowLerna", this.packageJsonFileName)); + var lernaFileLocation = Path.Combine(Path.GetTempPath(), "lerna.json"); + + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); + var componentName1 = Guid.NewGuid().ToString("N"); + var version1 = NewRandomVersion(); + var componentName2 = Guid.NewGuid().ToString("N"); + var version2 = NewRandomVersion(); + + var packageLockJson = @"{{ ""name"": """", ""version"": """", ""dependencies"": {{ @@ -382,7 +382,7 @@ public async Task TestNpmDetector_LernaDirectory() var packageLockTemplate = string.Format(packageLockJson, componentName0, version0, componentName2, version2, componentName2, version2, componentName0, version0); - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -395,14 +395,14 @@ public async Task TestNpmDetector_LernaDirectory() var packageJsonTemplate = string.Format(packagejson, componentName0, version0, componentName1, version1, componentName2, version2); var detector = new NpmComponentDetectorWithRoots(); - pathUtilityService.Setup(x => x.IsFileBelowAnother(It.IsAny(), It.IsAny())).Returns(true); - detector.PathUtilityService = pathUtilityService.Object; + this.pathUtilityService.Setup(x => x.IsFileBelowAnother(It.IsAny(), It.IsAny())).Returns(true); + detector.PathUtilityService = this.pathUtilityService.Object; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile("lerna.json", "unused string", detector.SearchPatterns, fileLocation: lernaFileLocation) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns, fileLocation: lockFileLocation) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern, fileLocation: packageJsonFileLocation) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns, fileLocation: lockFileLocation) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern, fileLocation: packageJsonFileLocation) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -412,14 +412,14 @@ public async Task TestNpmDetector_LernaDirectory() [TestMethod] public async Task TestNpmDetector_CircularRequirementsResolve() { - string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), packageLockJsonFileName); + var packageJsonComponentPath = Path.Combine(Path.GetTempPath(), this.packageLockJsonFileName); - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); - string componentName2 = Guid.NewGuid().ToString("N"); - string version2 = NewRandomVersion(); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); + var componentName2 = Guid.NewGuid().ToString("N"); + var version2 = NewRandomVersion(); - string packageLockJson = @"{{ + var packageLockJson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -444,7 +444,7 @@ public async Task TestNpmDetector_CircularRequirementsResolve() var packageLockTemplate = string.Format(packageLockJson, componentName0, version0, componentName2, version2, componentName2, version2, componentName0, version0); - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -457,13 +457,13 @@ public async Task TestNpmDetector_CircularRequirementsResolve() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -483,24 +483,24 @@ public async Task TestNpmDetector_CircularRequirementsResolve() [TestMethod] public async Task TestNpmDetector_ShrinkwrapLockReturnsValid() { - string lockFileName = "npm-shrinkwrap.json"; - string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), packageJsonFileName); + var lockFileName = "npm-shrinkwrap.json"; + var packageJsonComponentPath = Path.Combine(Path.GetTempPath(), this.packageJsonFileName); - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(lockFileName, componentName0, version0); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, version0); var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonFileName, packageJsonContents, packageJsonSearchPattern) + .WithFile(this.packageJsonFileName, packageJsonContents, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -518,20 +518,20 @@ public async Task TestNpmDetector_ShrinkwrapLockReturnsValid() [TestMethod] public async Task TestNpmDetector_IgnoresPackageLocksInSubFolders() { - string pathRoot = Path.GetTempPath(); + var pathRoot = Path.GetTempPath(); - string packageLockUnderNodeModules = Path.Combine(pathRoot, Path.Combine("node_modules", packageLockJsonFileName)); - string packageJsonUnderNodeModules = Path.Combine(pathRoot, Path.Combine("node_modules", packageJsonFileName)); + var packageLockUnderNodeModules = Path.Combine(pathRoot, Path.Combine("node_modules", this.packageLockJsonFileName)); + var packageJsonUnderNodeModules = Path.Combine(pathRoot, Path.Combine("node_modules", this.packageJsonFileName)); - string componentName0 = Guid.NewGuid().ToString("N"); - string version0 = NewRandomVersion(); - string componentName2 = Guid.NewGuid().ToString("N"); - string version2 = NewRandomVersion(); + var componentName0 = Guid.NewGuid().ToString("N"); + var version0 = NewRandomVersion(); + var componentName2 = Guid.NewGuid().ToString("N"); + var version2 = NewRandomVersion(); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName0, version0); - var (packageLockName2, packageLockContents2, packageLockPath2) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName2, version2, packageName0: "test2"); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName0, version0); + var (packageLockName2, packageLockContents2, packageLockPath2) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName2, version2, packageName0: "test2"); - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""{2}"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -545,17 +545,17 @@ public async Task TestNpmDetector_IgnoresPackageLocksInSubFolders() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) /* Top level */ .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) /* Under node_modules */ .WithFile(packageLockName2, packageLockContents2, detector.SearchPatterns, fileLocation: packageLockUnderNodeModules) - .WithFile(packageJsonFileName, packageJsonTemplate2, packageJsonSearchPattern, fileLocation: packageJsonUnderNodeModules) + .WithFile(this.packageJsonFileName, packageJsonTemplate2, this.packageJsonSearchPattern, fileLocation: packageJsonUnderNodeModules) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -573,13 +573,13 @@ public async Task TestNpmDetector_IgnoresPackageLocksInSubFolders() [TestMethod] public async Task TestNpmDetector_DependencyGraphIsCreated() { - string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), packageLockJsonFileName); + var packageJsonComponentPath = Path.Combine(Path.GetTempPath(), this.packageLockJsonFileName); var componentA = (Name: "componentA", Version: "1.0.0"); var componentB = (Name: "componentB", Version: "1.0.0"); var componentC = (Name: "componentC", Version: "1.0.0"); - string packageLockJson = @"{{ + var packageLockJson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -613,7 +613,7 @@ public async Task TestNpmDetector_DependencyGraphIsCreated() componentB.Name, componentB.Version, componentC.Name, componentC.Version); - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -626,13 +626,13 @@ public async Task TestNpmDetector_DependencyGraphIsCreated() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmTestUtilities.cs index 5f3b3a9ad..2e4bc8677 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmTestUtilities.cs @@ -17,7 +17,7 @@ public static class NpmTestUtilities { public static string GetPackageJsonNoDependencies() { - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"" }}"; @@ -27,7 +27,7 @@ public static string GetPackageJsonNoDependencies() public static IComponentStream GetPackageJsonOneRootComponentStream(string componentName0, string version0) { - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -79,7 +79,7 @@ public static Mock GetMockDirectoryWalker(IEn public static (string, string, string) GetPackageJsonOneRoot(string componentName0, string version0) { - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""test"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -94,7 +94,7 @@ public static (string, string, string) GetPackageJsonOneRoot(string componentNam public static (string, string, string) GetPackageJsonNoDependenciesForNameAndVersion(string packageName, string packageVersion) { - string packagejson = @"{{ + var packagejson = @"{{ ""name"": ""{0}"", ""version"": ""{1}"" }}"; @@ -126,7 +126,7 @@ public static (string, string, string) GetPackageJsonNoDependenciesForAuthorAndE }} }}"; } - + var packageJsonTemplate = string.Format(packagejson, authorName, authorEmail); return ("package.json", packageJsonTemplate, Path.Combine(Path.GetTempPath(), "package.json")); } @@ -134,7 +134,7 @@ public static (string, string, string) GetPackageJsonNoDependenciesForAuthorAndE public static (string, string, string) GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString( string authorName, string authorEmail = null, string authorUrl = null) { - string packagejson = @"{{{{ + var packagejson = @"{{{{ ""name"": ""test"", ""version"": ""0.0.0"", ""author"": {0} @@ -162,7 +162,7 @@ public static (string, string, string) GetPackageJsonNoDependenciesForAuthorAndE public static (string, string, string) GetPackageJsonNoDependenciesMalformedAuthorAsSingleString( string authorName, string authorEmail = null, string authorUrl = null) { - string packagejson = @"{{{{ + var packagejson = @"{{{{ ""name"": ""test"", ""version"": ""0.0.0"", ""author"": {0} @@ -192,7 +192,7 @@ public static (string, string, string) GetPackageJsonNoDependenciesMalformedAuth public static (string, string, string) GetWellFormedPackageLock2(string lockFileName, string rootName0 = null, string rootVersion0 = null, string rootName2 = null, string rootVersion2 = null, string packageName0 = "test", string packageName1 = null, string packageName3 = null) { - string packageLockJson = @"{{ + var packageLockJson = @"{{ ""name"": ""{10}"", ""version"": ""0.0.0"", ""dependencies"": {{ @@ -225,14 +225,14 @@ public static (string, string, string) GetWellFormedPackageLock2(string lockFile }} }} }}"; - string componentName0 = rootName0 ?? Guid.NewGuid().ToString("N"); - string version0 = rootVersion0 ?? NewRandomVersion(); - string componentName1 = packageName1 ?? Guid.NewGuid().ToString("N"); - string version1 = NewRandomVersion(); - string componentName2 = rootName2 ?? Guid.NewGuid().ToString("N"); - string version2 = rootVersion2 ?? NewRandomVersion(); - string componentName3 = packageName3 ?? Guid.NewGuid().ToString("N"); - string version3 = NewRandomVersion(); + var componentName0 = rootName0 ?? Guid.NewGuid().ToString("N"); + var version0 = rootVersion0 ?? NewRandomVersion(); + var componentName1 = packageName1 ?? Guid.NewGuid().ToString("N"); + var version1 = NewRandomVersion(); + var componentName2 = rootName2 ?? Guid.NewGuid().ToString("N"); + var version2 = rootVersion2 ?? NewRandomVersion(); + var componentName3 = packageName3 ?? Guid.NewGuid().ToString("N"); + var version3 = NewRandomVersion(); var packageLockTemplate = string.Format(packageLockJson, componentName0, version0, componentName1, version1, componentName2, version2, componentName2, version2, componentName3, version3, packageName0); return (lockFileName, packageLockTemplate, Path.Combine(Path.GetTempPath(), lockFileName)); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs index e2640c9d6..55d6c3cc1 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs @@ -22,13 +22,13 @@ public class NpmUtilitiesTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); + this.loggerMock = new Mock(); } [TestMethod] public void TestGetTypedComponent() { - string json = @"{ + var json = @"{ ""async"": { ""version"": ""2.3.0"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -36,14 +36,14 @@ public void TestGetTypedComponent() }, }"; - JObject j = JObject.Parse(json); + var j = JObject.Parse(json); - var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNotNull(componentFromJProperty); Assert.AreEqual(componentFromJProperty.Type, ComponentType.Npm); - NpmComponent npmComponent = (NpmComponent)componentFromJProperty; + var npmComponent = (NpmComponent)componentFromJProperty; Assert.AreEqual(npmComponent.Name, "async"); Assert.AreEqual(npmComponent.Version, "2.3.0"); } @@ -51,7 +51,7 @@ public void TestGetTypedComponent() [TestMethod] public void TestGetTypedComponent_FailsOnMalformed() { - string json = @"{ + var json = @"{ ""async"": { ""version"": ""NOTAVERSION"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -59,9 +59,9 @@ public void TestGetTypedComponent_FailsOnMalformed() }, }"; - JObject j = JObject.Parse(json); + var j = JObject.Parse(json); - var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); } @@ -69,7 +69,7 @@ public void TestGetTypedComponent_FailsOnMalformed() [TestMethod] public void TestGetTypedComponent_FailsOnInvalidPackageName() { - string jsonInvalidCharacter = @"{ + var jsonInvalidCharacter = @"{ ""async<"": { ""version"": ""1.0.0"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -77,11 +77,11 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }, }"; - JObject j = JObject.Parse(jsonInvalidCharacter); - var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + var j = JObject.Parse(jsonInvalidCharacter); + var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); - string jsonUrlName = @"{ + var jsonUrlName = @"{ ""http://thisis/my/packagename"": { ""version"": ""1.0.0"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -90,10 +90,10 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }"; j = JObject.Parse(jsonUrlName); - componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); - string jsonInvalidInitialCharacter1 = @"{ + var jsonInvalidInitialCharacter1 = @"{ ""_async"": { ""version"": ""1.0.0"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -102,10 +102,10 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }"; j = JObject.Parse(jsonInvalidInitialCharacter1); - componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); - string jsonInvalidInitialCharacter2 = @"{ + var jsonInvalidInitialCharacter2 = @"{ "".async"": { ""version"": ""1.0.0"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -114,11 +114,11 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }"; j = JObject.Parse(jsonInvalidInitialCharacter2); - componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); var longPackageName = new string('a', 214); - string jsonLongName = $@"{{ + var jsonLongName = $@"{{ ""{longPackageName}"": {{ ""version"": ""1.0.0"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -127,14 +127,14 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }}"; j = JObject.Parse(jsonLongName); - componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); } [TestMethod] public void TestTryParseNpmVersion() { - var parsed = NpmComponentUtilities.TryParseNpmVersion("registry.npmjs.org", "archiver", "https://registry.npmjs.org/archiver-2.1.1.tgz", out SemanticVersion parsedVersion); + var parsed = NpmComponentUtilities.TryParseNpmVersion("registry.npmjs.org", "archiver", "https://registry.npmjs.org/archiver-2.1.1.tgz", out var parsedVersion); Assert.IsTrue(parsed); Assert.AreEqual(parsedVersion.ToString(), "2.1.1"); @@ -145,7 +145,7 @@ public void TestTryParseNpmVersion() [TestMethod] public void TestTraverseAndGetRequirementsAndDependencies() { - string json = @"{ + var json = @"{ ""archiver"": { ""version"": ""2.3.0"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -164,8 +164,8 @@ public void TestTraverseAndGetRequirementsAndDependencies() var currentDependency = jsonChildren.Single(); var dependencyLookup = jsonChildren.ToDictionary(dependency => dependency.Name); - var typedComponent = NpmComponentUtilities.GetTypedComponent(currentDependency, "registry.npmjs.org", loggerMock.Object); - ComponentRecorder componentRecorder = new ComponentRecorder(); + var typedComponent = NpmComponentUtilities.GetTypedComponent(currentDependency, "registry.npmjs.org", this.loggerMock.Object); + var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder1 = componentRecorder.CreateSingleFileComponentRecorder("/this/is/a/test/path/"); var singleFileComponentRecorder2 = componentRecorder.CreateSingleFileComponentRecorder("/this/is/a/different/path/"); @@ -183,7 +183,7 @@ public void TestTraverseAndGetRequirementsAndDependencies() Assert.IsTrue(graph2.GetExplicitReferencedDependencyIds(typedComponent.Id).Contains(typedComponent.Id)); Assert.IsFalse(componentRecorder.GetEffectiveDevDependencyValue(typedComponent.Id).GetValueOrDefault(true)); - string json1 = @"{ + var json1 = @"{ ""test"": { ""version"": ""2.0.0"", ""resolved"": ""https://mseng.pkgs.visualstudio.com/_packaging/VsoMicrosoftExternals/npm/registry/async/-/async-2.3.0.tgz"", @@ -196,7 +196,7 @@ public void TestTraverseAndGetRequirementsAndDependencies() var currentDependency1 = jsonChildren1.Single(); var dependencyLookup1 = jsonChildren1.ToDictionary(dependency => dependency.Name); - var typedComponent1 = NpmComponentUtilities.GetTypedComponent(currentDependency1, "registry.npmjs.org", loggerMock.Object); + var typedComponent1 = NpmComponentUtilities.GetTypedComponent(currentDependency1, "registry.npmjs.org", this.loggerMock.Object); NpmComponentUtilities.TraverseAndRecordComponents(currentDependency1, singleFileComponentRecorder2, typedComponent1, typedComponent1); @@ -220,7 +220,7 @@ public void AddOrUpdateDetectedComponent_NewComponent_ComponentAdded() var expectedDetectedComponent = new DetectedComponent(new NpmComponent("test", "1.0.0")); var expectedDetectedDevComponent = new DetectedComponent(new NpmComponent("test2", "1.0.0")); - ComponentRecorder componentRecorder = new ComponentRecorder(); + var componentRecorder = new ComponentRecorder(); var addedComponent1 = NpmComponentUtilities.AddOrUpdateDetectedComponent( componentRecorder.CreateSingleFileComponentRecorder("path1"), diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs index a88b0238f..213058f9f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs @@ -15,6 +15,8 @@ namespace Microsoft.ComponentDetection.Detectors.Tests { + using FluentAssertions; + [TestClass] [TestCategory("Governance/All")] [TestCategory("Governance/ComponentDetection")] @@ -26,14 +28,14 @@ public class NuGetComponentDetectorTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.loggerMock = new Mock(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] public async Task TestNuGetDetectorWithNoFiles_ReturnsSuccessfully() { - var (scanResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (scanResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); @@ -47,14 +49,14 @@ public async Task TestNugetDetector_ReturnsValidNuspecComponent() var testAuthors = new string[] { "author 1", "author 2" }; var nuspec = NugetTestUtilities.GetValidNuspec(testComponentName, testVersion, testAuthors); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("*.nuspec", nuspec) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode, "Result code does Not match."); Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count(), "Componet count does not match"); var detectedComponent = componentRecorder.GetDetectedComponents().First().Component; - Assert.AreEqual(Contracts.TypedComponent.ComponentType.NuGet, detectedComponent.Type); + Assert.AreEqual(ComponentType.NuGet, detectedComponent.Type); var nuGetComponent = (NuGetComponent)detectedComponent; Assert.AreEqual(testComponentName, nuGetComponent.Name, "Component name does not match."); Assert.AreEqual(testVersion, nuGetComponent.Version, "Component version does not match."); @@ -69,14 +71,14 @@ public async Task TestNugetDetector_ReturnsValidNuspecComponent_SingleAuthor() var testAuthors = new string[] { "author 1" }; var nuspec = NugetTestUtilities.GetValidNuspec(testComponentName, testVersion, testAuthors); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("*.nuspec", nuspec) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode, "Result code does Not match."); Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count(), "Componet count does not match"); var detectedComponent = componentRecorder.GetDetectedComponents().First().Component; - Assert.AreEqual(Contracts.TypedComponent.ComponentType.NuGet, detectedComponent.Type); + Assert.AreEqual(ComponentType.NuGet, detectedComponent.Type); var nuGetComponent = (NuGetComponent)detectedComponent; Assert.AreEqual(testComponentName, nuGetComponent.Name, "Component name does not match."); Assert.AreEqual(testVersion, nuGetComponent.Version, "Component version does not match."); @@ -88,7 +90,7 @@ public async Task TestNugetDetector_ReturnsValidNupkgComponent() { var nupkg = await NugetTestUtilities.ZipNupkgComponent("test.nupkg", NugetTestUtilities.GetRandomValidNuspec()); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("test.nupkg", nupkg) .ExecuteDetector(); @@ -102,7 +104,7 @@ public async Task TestNugetDetector_ReturnsValidMixedComponent() var nuspec = NugetTestUtilities.GetRandomValidNuSpecComponent(); var nupkg = await NugetTestUtilities.ZipNupkgComponent("test.nupkg", NugetTestUtilities.GetRandomValidNuspec()); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("test.nuspec", nuspec) .WithFile("test.nupkg", nupkg) .ExecuteDetector(); @@ -118,14 +120,14 @@ public async Task TestNugetDetector_HandlesMalformedComponentsInComponentList() var malformedNupkg = await NugetTestUtilities.ZipNupkgComponent("malformed.nupkg", NugetTestUtilities.GetRandomMalformedNuPkgComponent()); var nuspec = NugetTestUtilities.GetRandomValidNuSpecComponent(); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithLogger(loggerMock) + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithLogger(this.loggerMock) .WithFile("test.nuspec", nuspec) .WithFile("test.nupkg", validNupkg) .WithFile("malformed.nupkg", malformedNupkg) .ExecuteDetector(); - loggerMock.Verify(x => x.LogFailedReadingFile(Path.Join(Path.GetTempPath(), "malformed.nupkg"), It.IsAny())); + this.loggerMock.Verify(x => x.LogFailedReadingFile(Path.Join(Path.GetTempPath(), "malformed.nupkg"), It.IsAny())); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); Assert.AreEqual(2, componentRecorder.GetDetectedComponents().Count()); @@ -137,15 +139,15 @@ public async Task TestNugetDetector_AdditionalDirectories() var component1 = NugetTestUtilities.GetRandomValidNuSpecComponentStream(); var streamsDetectedInNormalPass = new List { component1 }; - var additionalDirectory = CreateTemporaryDirectory(); + var additionalDirectory = this.CreateTemporaryDirectory(); var nugetConfigComponent = NugetTestUtilities.GetValidNuGetConfig(additionalDirectory); var streamsDetectedInAdditionalDirectoryPass = new List { nugetConfigComponent }; var componentRecorder = new ComponentRecorder(); var detector = new NuGetComponentDetector(); - var sourceDirectoryPath = CreateTemporaryDirectory(); + var sourceDirectoryPath = this.CreateTemporaryDirectory(); - detector.Logger = loggerMock.Object; + detector.Logger = this.loggerMock.Object; // Use strict mock evaluation because we're doing some "fun" stuff with this mock. var componentStreamEnumerableFactoryMock = new Mock(MockBehavior.Strict); @@ -207,6 +209,20 @@ public async Task TestNugetDetector_AdditionalDirectories() Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count()); } + [TestMethod] + public async Task TestNugetDetector_LowConfidencePackages() + { + var nupkg = await NugetTestUtilities.ZipNupkgComponent("Newtonsoft.Json.nupkg", NugetTestUtilities.GetValidNuspec("Newtonsoft.Json", "9.0.1", new []{ "JamesNK"})); + + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile("Newtonsoft.Json.nupkg", nupkg) + .ExecuteDetector(); + + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Should().BeEmpty() + .And.HaveCount(0); + } + private string CreateTemporaryDirectory() { string path; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs index 3cdb9cead..dbc1a222d 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs @@ -30,7 +30,7 @@ public async Task GetNuspecBytes_FailsOnTooSmallStream() { using var stream = new MemoryStream(); - for (int i = 0; i < NuGetNuspecUtilities.MinimumLengthForZipArchive - 1; i++) + for (var i = 0; i < NuGetNuspecUtilities.MinimumLengthForZipArchive - 1; i++) { stream.WriteByte(0); } @@ -50,7 +50,7 @@ public async Task GetNuspecBytes_FailsIfNuspecNotPresent() { using var stream = new MemoryStream(); - using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, true)) + using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true)) { archive.CreateEntry("test.txt"); } @@ -73,7 +73,7 @@ public async Task GetNuspecBytes_ReadsNuspecBytes() using var stream = new MemoryStream(); - using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, true)) + using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true)) { var entry = archive.CreateEntry("test.nuspec"); @@ -88,7 +88,7 @@ public async Task GetNuspecBytes_ReadsNuspecBytes() Assert.AreEqual(randomBytes.Length, bytes.Length); - for (int i = 0; i < randomBytes.Length; i++) + for (var i = 0; i < randomBytes.Length; i++) { Assert.AreEqual(randomBytes[i], bytes[i]); } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs index 213d41578..1e3e19f83 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs @@ -28,7 +28,7 @@ public class NuGetProjectModelProjectCentricComponentDetectorTests public void TestInitialize() { var detector = new NuGetProjectModelProjectCentricComponentDetector(); - + var loggerMock = new Mock(); loggerMock.Setup(x => x.LogWarning(It.IsAny())).Callback(message => Console.WriteLine(message)); loggerMock.Setup(x => x.LogFailedReadingFile(It.IsAny(), It.IsAny())).Callback((message, exception) => @@ -43,16 +43,16 @@ public void TestInitialize() .Returns(true); detector.FileUtilityService = fileUtilityServiceMock.Object; - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithDetector(detector); } [TestMethod] public async Task ScanDirectoryAsync_Base_2_2_Verification() { - string osAgnostic = Convert22SampleToOSAgnostic(TestResources.project_assets_2_2); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var osAgnostic = this.Convert22SampleToOSAgnostic(TestResources.project_assets_2_2); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -73,9 +73,9 @@ public async Task ScanDirectoryAsync_Base_2_2_Verification() [TestMethod] public async Task ScanDirectoryAsync_Base_2_2_additional_Verification() { - string osAgnostic = Convert22SampleToOSAgnostic(TestResources.project_assets_2_2_additional); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var osAgnostic = this.Convert22SampleToOSAgnostic(TestResources.project_assets_2_2_additional); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -99,9 +99,9 @@ public async Task ScanDirectoryAsync_Base_2_2_additional_Verification() [TestMethod] public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_2_2_Verification() { - string osAgnostic = Convert22SampleToOSAgnostic(TestResources.project_assets_2_2); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var osAgnostic = this.Convert22SampleToOSAgnostic(TestResources.project_assets_2_2); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var ommittedComponentInformationJson = scanResult.AdditionalTelemetryDetails[NuGetProjectModelProjectCentricComponentDetector.OmittedFrameworkComponentsTelemetryKey]; @@ -114,9 +114,9 @@ public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_2_2_Verification [TestMethod] public async Task ScanDirectoryAsync_DependencyGraph_2_2_additional_Verification() { - string osAgnostic = Convert22SampleToOSAgnostic(TestResources.project_assets_2_2_additional); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var osAgnostic = this.Convert22SampleToOSAgnostic(TestResources.project_assets_2_2_additional); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var graphsByLocation = componentRecorder.GetDependencyGraphsByLocation(); var graph = graphsByLocation.Values.First(); @@ -140,7 +140,7 @@ public async Task ScanDirectoryAsync_DependencyGraph_2_2_additional_Verification // Top level dependencies look like this: // (we expect all non-proj and non-framework to show up as explicit refs, so those will be absent from the check) - // + // // "DotNet.Glob >= 2.1.1", // "Microsoft.NETCore.App >= 2.2.8", // "Microsoft.VisualStudio.Services.Governance.ComponentDetection.Common >= 1.0.0", @@ -186,7 +186,7 @@ public async Task ScanDirectoryAsync_DependencyGraph_2_2_additional_Verification foreach (var componentId in graph.GetComponents()) { var component = detectedComponents.First(x => x.Component.Id == componentId); - bool expectedExplicitRefValue = expectedExplicitRefs.Contains(((NuGetComponent)component.Component).Name); + var expectedExplicitRefValue = expectedExplicitRefs.Contains(((NuGetComponent)component.Component).Name); Assert.AreEqual(expectedExplicitRefValue, graph.IsComponentExplicitlyReferenced(componentId)); } } @@ -194,9 +194,9 @@ public async Task ScanDirectoryAsync_DependencyGraph_2_2_additional_Verification [TestMethod] public async Task ScanDirectoryAsync_Base_3_1_Verification() { - string osAgnostic = Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var osAgnostic = this.Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); // Number of unique nodes in ProjectAssetsJson @@ -216,9 +216,9 @@ public async Task ScanDirectoryAsync_Base_3_1_Verification() [TestMethod] public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_3_1_Verification() { - string osAgnostic = Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var osAgnostic = this.Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var ommittedComponentInformationJson = scanResult.AdditionalTelemetryDetails[NuGetProjectModelProjectCentricComponentDetector.OmittedFrameworkComponentsTelemetryKey]; @@ -232,9 +232,9 @@ public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_3_1_Verification [TestMethod] public async Task ScanDirectoryAsync_DependencyGraph_3_1_Verification() { - string osAgnostic = Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var osAgnostic = this.Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var graphsByLocation = componentRecorder.GetDependencyGraphsByLocation(); @@ -246,7 +246,7 @@ public async Task ScanDirectoryAsync_DependencyGraph_3_1_Verification() }; var detectedComponents = componentRecorder.GetDetectedComponents(); - + var componentDetectionCommon = detectedComponents.First(x => x.Component.Id.Contains("Microsoft.Extensions.DependencyModel")); var dependencies = graph.GetDependenciesForComponent(componentDetectionCommon.Component.Id); foreach (var expectedId in expectedDependencyIdsForExtensionsDependencyModel) @@ -258,7 +258,7 @@ public async Task ScanDirectoryAsync_DependencyGraph_3_1_Verification() // Top level dependencies look like this: // (we expect all non-proj and non-framework to show up as explicit refs, so those will be absent from the check) - // + // // "ExtCore.Infrastructure >= 5.1.0", // "Microsoft.Extensions.DependencyModel >= 3.0.0", // "System.Runtime.Loader >= 4.3.0" @@ -270,7 +270,7 @@ public async Task ScanDirectoryAsync_DependencyGraph_3_1_Verification() foreach (var componentId in graph.GetComponents()) { var component = detectedComponents.First(x => x.Component.Id == componentId); - bool expectedExplicitRefValue = expectedExplicitRefs.Contains(((NuGetComponent)component.Component).Name); + var expectedExplicitRefValue = expectedExplicitRefs.Contains(((NuGetComponent)component.Component).Name); Assert.AreEqual(expectedExplicitRefValue, graph.IsComponentExplicitlyReferenced(componentId)); } } @@ -278,7 +278,7 @@ public async Task ScanDirectoryAsync_DependencyGraph_3_1_Verification() [TestMethod] public async Task ScanDirectory_NoPackageSpec() { - string osAgnostic = + var osAgnostic = @"{ ""version"": 3, ""targets"": { @@ -286,12 +286,12 @@ public async Task ScanDirectory_NoPackageSpec() }, ""packageFolders"": {} }"; - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - + var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); dependencyGraphs.Count.Should().Be(0); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NugetTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NugetTestUtilities.cs index beced56f4..fd50f550e 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NugetTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NugetTestUtilities.cs @@ -16,9 +16,9 @@ public static class NugetTestUtilities { public static string GetRandomValidNuSpecComponent() { - string componentName = GetRandomString(); - string componentSpecFileName = $"{componentName}.nuspec"; - string componentSpecPath = Path.Combine(Path.GetTempPath(), componentSpecFileName); + var componentName = GetRandomString(); + var componentSpecFileName = $"{componentName}.nuspec"; + var componentSpecPath = Path.Combine(Path.GetTempPath(), componentSpecFileName); var template = GetTemplatedNuspec(componentName, NewRandomVersion(), new string[] { GetRandomString(), GetRandomString() }); return template; @@ -26,9 +26,9 @@ public static string GetRandomValidNuSpecComponent() public static IComponentStream GetRandomValidNuSpecComponentStream() { - string componentName = GetRandomString(); - string componentSpecFileName = $"{componentName}.nuspec"; - string componentSpecPath = Path.Combine(Path.GetTempPath(), componentSpecFileName); + var componentName = GetRandomString(); + var componentSpecFileName = $"{componentName}.nuspec"; + var componentSpecPath = Path.Combine(Path.GetTempPath(), componentSpecFileName); var template = GetTemplatedNuspec(componentName, NewRandomVersion(), new string[] { GetRandomString(), GetRandomString() }); var mock = new Mock(); @@ -53,7 +53,7 @@ public static IComponentStream GetValidNuGetConfig(string repositoryPath) public static string GetRandomValidNuspec() { - string componentName = GetRandomString(); + var componentName = GetRandomString(); var template = GetTemplatedNuspec(componentName, NewRandomVersion(), new string[] { GetRandomString(), GetRandomString() }); return template; } @@ -67,7 +67,7 @@ public static async Task ZipNupkgComponent(string filename, string conte { var stream = new MemoryStream(); - using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, true)) + using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true)) { var entry = archive.CreateEntry($"{filename}.nuspec"); @@ -83,7 +83,7 @@ public static async Task ZipNupkgComponent(string filename, string conte public static string GetRandomMalformedNuPkgComponent() { - string componentName = GetRandomString(); + var componentName = GetRandomString(); var template = GetTemplatedNuspec(componentName, NewRandomVersion(), new string[] { GetRandomString(), GetRandomString() }); template = template.Replace("", ""); return template; @@ -91,7 +91,7 @@ public static string GetRandomMalformedNuPkgComponent() private static string GetTemplatedNuspec(string id, string version, string[] authors) { - string nuspec = @" + var nuspec = @" @@ -111,7 +111,7 @@ private static string GetTemplatedNuspec(string id, string version, string[] aut private static string GetTemplatedNuGetConfig(string repositoryPath) { - string nugetConfig = + var nugetConfig = @" @@ -123,7 +123,7 @@ private static string GetTemplatedNuGetConfig(string repositoryPath) private static string GetTemplatedProjectAsset(IDictionary>> packages) { - string individualPackageJson = + var individualPackageJson = @"""{packageName}"": { ""type"": ""package"", ""dependencies"": { @@ -140,7 +140,7 @@ private static string GetTemplatedProjectAsset(IDictionary(); - pythonResolver = new Mock(); - loggerMock = new Mock(); + this.pythonCommandService = new Mock(); + this.pythonResolver = new Mock(); + this.loggerMock = new Mock(); var detector = new PipComponentDetector { - PythonCommandService = pythonCommandService.Object, - PythonResolver = pythonResolver.Object, - Logger = loggerMock.Object, + PythonCommandService = this.pythonCommandService.Object, + PythonResolver = this.pythonResolver.Object, + Logger = this.loggerMock.Object, }; - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithDetector(detector); } [TestMethod] public async Task TestPipDetector_PythonNotInstalled() { - pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(false); + this.pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(false); - loggerMock.Setup(x => x.LogInfo(It.Is(l => l.Contains("No python found")))); + this.loggerMock.Setup(x => x.LogInfo(It.Is(l => l.Contains("No python found")))); - var (result, componentRecorder) = await detectorTestUtility + var (result, componentRecorder) = await this.detectorTestUtility .WithFile("setup.py", string.Empty) - .WithLogger(loggerMock) + .WithLogger(this.loggerMock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - loggerMock.VerifyAll(); + this.loggerMock.VerifyAll(); } [TestMethod] public async Task TestPipDetector_PythonInstalledNoFiles() { - var (result, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (result, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); } @@ -69,14 +69,14 @@ public async Task TestPipDetector_PythonInstalledNoFiles() [TestMethod] public async Task TestPipDetector_SetupPyAndRequirementsTxt() { - pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); + this.pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); - var baseSetupPyDependencies = ToGitTuple(new List { "a==1.0", "b>=2.0,!=2.1", "c!=1.1" }); - var baseRequirementsTextDependencies = ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1" }); + var baseSetupPyDependencies = this.ToGitTuple(new List { "a==1.0", "b>=2.0,!=2.1", "c!=1.1" }); + var baseRequirementsTextDependencies = this.ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1" }); baseRequirementsTextDependencies.Add((null, new GitComponent(new Uri("https://github.com/example/example"), "deadbee"))); - pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); - pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); + this.pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); + this.pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); var setupPyRoots = new List { @@ -94,10 +94,10 @@ public async Task TestPipDetector_SetupPyAndRequirementsTxt() new PipGraphNode(new PipComponent("f", "1.1")), }; - pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "b")))).ReturnsAsync(setupPyRoots); - pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "d")))).ReturnsAsync(requirementsTxtRoots); + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "b")))).ReturnsAsync(setupPyRoots); + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "d")))).ReturnsAsync(requirementsTxtRoots); - var (result, componentRecorder) = await detectorTestUtility + var (result, componentRecorder) = await this.detectorTestUtility .WithFile("setup.py", string.Empty) .WithFile("requirements.txt", string.Empty) .ExecuteDetector(); @@ -128,12 +128,12 @@ public async Task TestPipDetector_SetupPyAndRequirementsTxt() [TestMethod] public async Task TestPipDetector_ComponentsDedupedAcrossFiles() { - pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); + this.pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); - var baseRequirementsTextDependencies = ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1", "h==1.3" }); - var baseRequirementsTextDependencies2 = ToGitTuple(new List { "D~=1.0", "E<=2.0", "F===1.1", "g==2" }); - pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); - pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "TEST", "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies2); + var baseRequirementsTextDependencies = this.ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1", "h==1.3" }); + var baseRequirementsTextDependencies2 = this.ToGitTuple(new List { "D~=1.0", "E<=2.0", "F===1.1", "g==2" }); + this.pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); + this.pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "TEST", "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies2); var requirementsTxtRoots = new List { @@ -150,10 +150,10 @@ public async Task TestPipDetector_ComponentsDedupedAcrossFiles() new PipGraphNode(new PipComponent("g", "1.2")), }; - pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "h")))).ReturnsAsync(requirementsTxtRoots); - pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "g")))).ReturnsAsync(requirementsTxtRoots2); + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "h")))).ReturnsAsync(requirementsTxtRoots); + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "g")))).ReturnsAsync(requirementsTxtRoots2); - var (result, componentRecorder) = await detectorTestUtility + var (result, componentRecorder) = await this.detectorTestUtility .WithFile("requirements.txt", string.Empty) .WithFile("requirements.txt", string.Empty, fileLocation: Path.Join(Path.GetTempPath(), "TEST", "requirements.txt")) .ExecuteDetector(); @@ -165,15 +165,15 @@ public async Task TestPipDetector_ComponentsDedupedAcrossFiles() [TestMethod] public async Task TestPipDetector_ComponentRecorder() { - pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); + this.pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); const string file1 = "c:\\repo\\setup.py"; const string file2 = "c:\\repo\\lib\\requirements.txt"; - var baseReqs = ToGitTuple(new List { "a~=1.0", "b<=2.0", }); - var altReqs = ToGitTuple(new List { "c~=1.0", "d<=2.0", "e===1.1" }); - pythonCommandService.Setup(x => x.ParseFile(file1, null)).ReturnsAsync(baseReqs); - pythonCommandService.Setup(x => x.ParseFile(file2, null)).ReturnsAsync(altReqs); + var baseReqs = this.ToGitTuple(new List { "a~=1.0", "b<=2.0", }); + var altReqs = this.ToGitTuple(new List { "c~=1.0", "d<=2.0", "e===1.1" }); + this.pythonCommandService.Setup(x => x.ParseFile(file1, null)).ReturnsAsync(baseReqs); + this.pythonCommandService.Setup(x => x.ParseFile(file2, null)).ReturnsAsync(altReqs); var rootA = new PipGraphNode(new PipComponent("a", "1.0")); var rootB = new PipGraphNode(new PipComponent("b", "2.1")); @@ -198,15 +198,15 @@ public async Task TestPipDetector_ComponentRecorder() blue.Children.Add(cat); blue.Children.Add(dog); - pythonResolver.Setup(x => + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "a")))) .ReturnsAsync(new List { rootA, rootB, }); - pythonResolver.Setup(x => + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "c")))) .ReturnsAsync(new List { rootC, rootD, rootE, }); - var (result, componentRecorder) = await detectorTestUtility + var (result, componentRecorder) = await this.detectorTestUtility .WithFile("setup.py", string.Empty, fileLocation: file1) .WithFile("setup.py", string.Empty, fileLocation: file2) .ExecuteDetector(); @@ -232,12 +232,12 @@ public async Task TestPipDetector_ComponentRecorder() x => x.Id == rootId); } - CheckChild(componentRecorder, "red 0.2 - pip", new[] { "a 1.0 - pip", "c 1.0 - pip", }); - CheckChild(componentRecorder, "green 1.3 - pip", new[] { "b 2.1 - pip", }); - CheckChild(componentRecorder, "blue 0.4 - pip", new[] { "c 1.0 - pip", }); - CheckChild(componentRecorder, "cat 1.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); - CheckChild(componentRecorder, "lion 3.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); - CheckChild(componentRecorder, "dog 2.1 - pip", new[] { "c 1.0 - pip", }); + this.CheckChild(componentRecorder, "red 0.2 - pip", new[] { "a 1.0 - pip", "c 1.0 - pip", }); + this.CheckChild(componentRecorder, "green 1.3 - pip", new[] { "b 2.1 - pip", }); + this.CheckChild(componentRecorder, "blue 0.4 - pip", new[] { "c 1.0 - pip", }); + this.CheckChild(componentRecorder, "cat 1.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); + this.CheckChild(componentRecorder, "lion 3.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); + this.CheckChild(componentRecorder, "dog 2.1 - pip", new[] { "c 1.0 - pip", }); var graphsByLocations = componentRecorder.GetDependencyGraphsByLocation(); Assert.AreEqual(2, graphsByLocations.Count); @@ -255,7 +255,7 @@ public async Task TestPipDetector_ComponentRecorder() var graph1 = graphsByLocations[file1]; Assert.IsTrue(graph1ComponentsWithDeps.Keys.Take(2).All(graph1.IsComponentExplicitlyReferenced)); Assert.IsTrue(graph1ComponentsWithDeps.Keys.Skip(2).All(a => !graph1.IsComponentExplicitlyReferenced(a))); - CheckGraphStructure(graph1, graph1ComponentsWithDeps); + this.CheckGraphStructure(graph1, graph1ComponentsWithDeps); var graph2ComponentsWithDeps = new Dictionary { @@ -272,7 +272,7 @@ public async Task TestPipDetector_ComponentRecorder() var graph2 = graphsByLocations[file2]; Assert.IsTrue(graph2ComponentsWithDeps.Keys.Take(3).All(graph2.IsComponentExplicitlyReferenced)); Assert.IsTrue(graph2ComponentsWithDeps.Keys.Skip(3).All(a => !graph2.IsComponentExplicitlyReferenced(a))); - CheckGraphStructure(graph2, graph2ComponentsWithDeps); + this.CheckGraphStructure(graph2, graph2ComponentsWithDeps); } private void CheckGraphStructure(IDependencyGraph graph, Dictionary graphComponentsWithDeps) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs index ec05f80a2..3090705d2 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs @@ -10,7 +10,7 @@ public class PipDependencySpecifierTests [TestMethod] public void TestPipDependencySpecifierConstruction() { - List<(string, PipDependencySpecification)> specs = new List<(string, PipDependencySpecification)> + var specs = new List<(string, PipDependencySpecification)> { ("TestPackage==1.0", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { "==1.0" } }), ("TestPackage>=1.0,!=1.1", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=1.0", "!=1.1" } }), @@ -24,7 +24,7 @@ public void TestPipDependencySpecifierConstruction() Assert.AreEqual(referenceDependencySpecification.Name, dependencySpecifier.Name); - for (int i = 0; i < referenceDependencySpecification.DependencySpecifiers.Count; i++) + for (var i = 0; i < referenceDependencySpecification.DependencySpecifiers.Count; i++) { Assert.AreEqual(referenceDependencySpecification.DependencySpecifiers[i], dependencySpecifier.DependencySpecifiers[i]); } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs index 3f4a4a77b..e7c7e31eb 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs @@ -21,8 +21,8 @@ public class PipResolverTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - pyPiClient = new Mock(); + this.loggerMock = new Mock(); + this.pyPiClient = new Mock(); } [TestMethod] @@ -34,21 +34,21 @@ public async Task TestPipResolverSimpleGraph() var versions = new List { "1.0" }; - var aReleases = CreateReleasesDictionary(versions); - var bReleases = CreateReleasesDictionary(versions); - var cReleases = CreateReleasesDictionary(versions); + var aReleases = this.CreateReleasesDictionary(versions); + var bReleases = this.CreateReleasesDictionary(versions); + var cReleases = this.CreateReleasesDictionary(versions); - pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); - pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); - pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); + this.pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); + this.pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); + this.pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); - pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); - pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); var dependencies = new List { a }; - var resolver = new PythonResolver() { PypiClient = pyPiClient.Object, Logger = loggerMock.Object, }; + var resolver = new PythonResolver() { PypiClient = this.pyPiClient.Object, Logger = this.loggerMock.Object, }; var resolveResult = await resolver.ResolveRoots(dependencies); @@ -63,7 +63,7 @@ public async Task TestPipResolverSimpleGraph() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(CompareGraphs(resolveResult.First(), expectedA)); + Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); } [TestMethod] @@ -76,22 +76,22 @@ public async Task TestPipResolverNonExistantRoot() var versions = new List { "1.0" }; - var aReleases = CreateReleasesDictionary(versions); - var bReleases = CreateReleasesDictionary(versions); - var cReleases = CreateReleasesDictionary(versions); + var aReleases = this.CreateReleasesDictionary(versions); + var bReleases = this.CreateReleasesDictionary(versions); + var cReleases = this.CreateReleasesDictionary(versions); - pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); - pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); - pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); - pyPiClient.Setup(x => x.GetReleases(doesNotExist)).ReturnsAsync(CreateReleasesDictionary(new List())); + this.pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); + this.pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); + this.pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); + this.pyPiClient.Setup(x => x.GetReleases(doesNotExist)).ReturnsAsync(this.CreateReleasesDictionary(new List())); - pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); - pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); var dependencies = new List { a, doesNotExist }; - var resolver = new PythonResolver() { PypiClient = pyPiClient.Object, Logger = loggerMock.Object, }; + var resolver = new PythonResolver() { PypiClient = this.pyPiClient.Object, Logger = this.loggerMock.Object, }; var resolveResult = await resolver.ResolveRoots(dependencies); @@ -106,7 +106,7 @@ public async Task TestPipResolverNonExistantRoot() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(CompareGraphs(resolveResult.First(), expectedA)); + Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); } [TestMethod] @@ -118,20 +118,20 @@ public async Task TestPipResolverNonExistantLeaf() var versions = new List { "1.0" }; - var aReleases = CreateReleasesDictionary(versions); - var bReleases = CreateReleasesDictionary(versions); - var cReleases = CreateReleasesDictionary(versions); + var aReleases = this.CreateReleasesDictionary(versions); + var bReleases = this.CreateReleasesDictionary(versions); + var cReleases = this.CreateReleasesDictionary(versions); - pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); - pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); - pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(CreateReleasesDictionary(new List())); + this.pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); + this.pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); + this.pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(this.CreateReleasesDictionary(new List())); - pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); var dependencies = new List { a }; - var resolver = new PythonResolver() { PypiClient = pyPiClient.Object, Logger = loggerMock.Object, }; + var resolver = new PythonResolver() { PypiClient = this.pyPiClient.Object, Logger = this.loggerMock.Object, }; var resolveResult = await resolver.ResolveRoots(dependencies); @@ -143,8 +143,8 @@ public async Task TestPipResolverNonExistantLeaf() expectedA.Children.Add(expectedB); expectedB.Parents.Add(expectedA); - Assert.IsTrue(CompareGraphs(resolveResult.First(), expectedA)); - pyPiClient.Verify(x => x.FetchPackageDependencies(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.pyPiClient.Verify(x => x.FetchPackageDependencies(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); } [TestMethod] @@ -159,22 +159,22 @@ public async Task TestPipResolverBacktrack() var otherVersions = new List { "1.0", "1.1" }; - var aReleases = CreateReleasesDictionary(versions); - var bReleases = CreateReleasesDictionary(versions); - var cReleases = CreateReleasesDictionary(otherVersions); + var aReleases = this.CreateReleasesDictionary(versions); + var bReleases = this.CreateReleasesDictionary(versions); + var cReleases = this.CreateReleasesDictionary(otherVersions); - pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); - pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); - pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); + this.pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); + this.pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); + this.pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); - pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b, c }); - pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { cAlt }); - pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.1", cReleases["1.1"].First())).ReturnsAsync(new List { }); - pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b, c }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { cAlt }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.1", cReleases["1.1"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); var dependencies = new List { a }; - var resolver = new PythonResolver() { PypiClient = pyPiClient.Object, Logger = loggerMock.Object, }; + var resolver = new PythonResolver() { PypiClient = this.pyPiClient.Object, Logger = this.loggerMock.Object, }; var resolveResult = await resolver.ResolveRoots(dependencies); @@ -191,8 +191,8 @@ public async Task TestPipResolverBacktrack() expectedC.Parents.Add(expectedA); expectedC.Parents.Add(expectedB); - Assert.IsTrue(CompareGraphs(resolveResult.First(), expectedA)); - pyPiClient.Verify(x => x.FetchPackageDependencies(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(4)); + Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.pyPiClient.Verify(x => x.FetchPackageDependencies(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(4)); } private bool CompareGraphs(PipGraphNode a, PipGraphNode b) @@ -211,11 +211,11 @@ private bool CompareGraphs(PipGraphNode a, PipGraphNode b) return false; } - bool valid = true; + var valid = true; - for (int i = 0; i < a.Children.Count; i++) + for (var i = 0; i < a.Children.Count; i++) { - valid = CompareGraphs(a.Children[i], b.Children[i]); + valid = this.CompareGraphs(a.Children[i], b.Children[i]); } return valid; @@ -227,7 +227,8 @@ private SortedDictionary> CreateReleasesDict foreach (var version in versions) { - toReturn.Add(version, new List { CreatePythonProjectRelease() }); + toReturn.Add(version, new List { + this.CreatePythonProjectRelease() }); } return toReturn; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs index 464d6aba4..561dcb5b0 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs @@ -24,7 +24,7 @@ public class PnpmDetectorTests public void TestInitialize() { var componentRecorder = new ComponentRecorder(enableManualTrackingOfExplicitReferences: false); - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithScanRequest(new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder)); } @@ -70,7 +70,7 @@ public async Task TestPnpmDetector_SingleFileLocatesExpectedInput() shrinkwrapMinorVersion: 7 shrinkwrapVersion: 3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile) .ExecuteDetector(); @@ -171,7 +171,7 @@ public async Task TestPnpmDetector_SameComponentMergesRootsAndLocationsAcrossMul shrinkwrapMinorVersion: 7 shrinkwrapVersion: 3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .WithFile("shrinkwrap2.yaml", yamlFile2) .ExecuteDetector(); @@ -216,7 +216,7 @@ public async Task TestPnpmDetector_SpecialDependencyVersionStringDoesntBlowUsUp( shrinkwrapMinorVersion: 7 shrinkwrapVersion: 3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetector(); @@ -245,7 +245,7 @@ public async Task TestPnpmDetector_DetectorRecognizeDevDependenciesValues() /strict-uri-encode/1.1.0: dev: true"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetector(); @@ -276,7 +276,7 @@ public async Task TestPnpmDetector_DetectorRecognizeDevDependenciesValues_InWeir shared-non-dev-dep: 0.1.2 dev: true"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetector(); @@ -291,7 +291,7 @@ public async Task TestPnpmDetector_HandlesMalformedYaml() // This is a clearly malformed Yaml. We expect parsing it to "succeed" but find no components var yamlFile1 = @"dependencies"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetector(); @@ -321,7 +321,7 @@ public async Task TestPnpmDetector_DependencyGraphIsCreated() /test/1.0.0: dev: true"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile) .ExecuteDetector(); @@ -361,7 +361,7 @@ public async Task TestPnpmDetector_DependenciesRefeToLocalPaths_DependenciesAreI packages: file:projects/file-annotation-bar.tgz_node-sass@4.14.1: - resolution: {integrity: sha1-G7T22scAcvwxPoyc0UF7UHTAoSU=} + resolution: {integrity: sha1-G7T22scAcvwxPoyc0UF7UHTAoSU=} /query-string/4.3.4: dependencies: '@learningclient/common': link:../common @@ -369,7 +369,7 @@ public async Task TestPnpmDetector_DependenciesRefeToLocalPaths_DependenciesAreI /nth-check/2.0.0: resolution: {integrity: sha1-G7T22scAcvwxPoyc0UF7UHTAoSU=} "; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs index b188ee5fa..25443497f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs @@ -38,7 +38,7 @@ public async Task DeserializePnpmYamlFile() shrinkwrapMinorVersion: 7 shrinkwrapVersion: 3"; - var parsedYaml = await PnpmParsingUtilities.DeserializePnpmYamlFile(CreateComponentStreamForShrinkwrap(yamlFile)); + var parsedYaml = await PnpmParsingUtilities.DeserializePnpmYamlFile(this.CreateComponentStreamForShrinkwrap(yamlFile)); parsedYaml.packages.Should().HaveCount(2); parsedYaml.packages.Should().ContainKey("/query-string/4.3.4"); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs index 4c00ddcc7..c6cec4a44 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs @@ -22,7 +22,7 @@ public class PodDetectorTest [TestInitialize] public void TestInitialize() { - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] @@ -32,7 +32,7 @@ public async Task TestPodDetector_EmptyPodfileLock() COCOAPODS: 1.4.0.beta.1"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -68,7 +68,7 @@ public async Task TestPodDetector_DetectorRecognizePodComponents() COCOAPODS: 0.39.0"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -77,12 +77,12 @@ public async Task TestPodDetector_DetectorRecognizePodComponents() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(6, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); - AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); - AssertPodComponentNameAndVersion(detectedComponents, "Auth", "1.44.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Auth", "1.44.1"); } [TestMethod] @@ -110,7 +110,7 @@ public async Task TestPodDetector_DetectorRecognizeSubspecsAsSinglePodComponent( COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -119,8 +119,8 @@ public async Task TestPodDetector_DetectorRecognizeSubspecsAsSinglePodComponent( var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(2, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "MSAL", "1.0.7"); - AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "MSAL", "1.0.7"); + this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); } [TestMethod] @@ -154,7 +154,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponents() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -163,7 +163,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponents() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertGitComponentHashAndUrl(detectedComponents, "da7223e3c455fe558de361c611df36c6dcc4229d", "https://github.com/microsoftgraph/msgraph-sdk-objc.git"); + this.AssertGitComponentHashAndUrl(detectedComponents, "da7223e3c455fe558de361c611df36c6dcc4229d", "https://github.com/microsoftgraph/msgraph-sdk-objc.git"); } [TestMethod] @@ -197,7 +197,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -206,7 +206,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); } [TestMethod] @@ -240,7 +240,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -249,7 +249,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); } [TestMethod] @@ -277,7 +277,7 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromExternalPods COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -286,8 +286,8 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromExternalPods var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(2, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); - AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); } [TestMethod] @@ -310,7 +310,7 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromLocalPath() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -319,7 +319,7 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromLocalPath() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "Keys", "1.0.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Keys", "1.0.1"); } [TestMethod] @@ -375,7 +375,7 @@ public async Task TestPodDetector_MultiplePodfileLocks() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetector(); @@ -385,14 +385,14 @@ public async Task TestPodDetector_MultiplePodfileLocks() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(8, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); - AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); - AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); - AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); } [TestMethod] @@ -459,7 +459,7 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetector(); @@ -469,27 +469,27 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(8, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); - AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); - AssertGitComponentHashAndUrl(detectedComponents, "0d4db53890c664fb8605666e6fbccd14912ff821", "https://github.com/SVGKit/SVGKit.git"); - AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); - - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureMobile", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); - AssertGitComponentHasGitComponentDependencyRoot(componentRecorder, component: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); - - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); - AssertPodComponentHasGitComponentDependencyRoot(componentRecorder, component: (name: "CocoaLumberjack", version: "3.6.0"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); + this.AssertGitComponentHashAndUrl(detectedComponents, "0d4db53890c664fb8605666e6fbccd14912ff821", "https://github.com/SVGKit/SVGKit.git"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); + + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureMobile", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); + this.AssertGitComponentHasGitComponentDependencyRoot(componentRecorder, component: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); + + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); + this.AssertPodComponentHasGitComponentDependencyRoot(componentRecorder, component: (name: "CocoaLumberjack", version: "3.6.0"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureData", version: "0.5.0")); } [TestMethod] @@ -556,7 +556,7 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots_GitUri() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetector(); @@ -566,27 +566,27 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots_GitUri() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(8, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); - AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); - AssertGitComponentHashAndUrl(detectedComponents, "0d4db53890c664fb8605666e6fbccd14912ff821", "https://github.com/SVGKit/SVGKit.git"); - AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); - - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureMobile", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); - AssertGitComponentHasGitComponentDependencyRoot(componentRecorder, component: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); - - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); - AssertPodComponentHasGitComponentDependencyRoot(componentRecorder, component: (name: "CocoaLumberjack", version: "3.6.0"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); + this.AssertGitComponentHashAndUrl(detectedComponents, "0d4db53890c664fb8605666e6fbccd14912ff821", "https://github.com/SVGKit/SVGKit.git"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); + + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureMobile", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); + this.AssertGitComponentHasGitComponentDependencyRoot(componentRecorder, component: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); + + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); + this.AssertPodComponentHasGitComponentDependencyRoot(componentRecorder, component: (name: "CocoaLumberjack", version: "3.6.0"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureData", version: "0.5.0")); } [TestMethod] @@ -637,7 +637,7 @@ public async Task TestPodDetector_DetectorHandlesMainSpecRepoDifferences() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2) .WithFile("Podfile.lock", podfileLockContent3) @@ -648,7 +648,7 @@ public async Task TestPodDetector_DetectorHandlesMainSpecRepoDifferences() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); } [TestMethod] @@ -684,7 +684,7 @@ public async Task TestPodDetector_DetectorRecognizeComponentsSpecRepo() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2, fileLocation: Path.Join(Path.GetTempPath(), "sub-folder", "Podfile.lock")) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs index 7f8dc7ad2..8561d77ed 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs @@ -20,7 +20,7 @@ public class PoetryComponentDetectorTests [TestInitialize] public void TestInitialize() { - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] @@ -40,7 +40,7 @@ public async Task TestPoetryDetector_TestCustomSource() reference = ""custom"" "; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("poetry.lock", poetryLockContent) .ExecuteDetector(); @@ -49,7 +49,7 @@ public async Task TestPoetryDetector_TestCustomSource() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); + this.AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); var queryString = detectedComponents.Single(component => ((PipComponent)component.Component).Name.Contains("certifi")); Assert.IsFalse(componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false)); } @@ -66,7 +66,7 @@ public async Task TestPoetryDetector_TestDevDependency() python-versions = ""*"" "; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("poetry.lock", poetryLockContent) .ExecuteDetector(); @@ -75,7 +75,7 @@ public async Task TestPoetryDetector_TestDevDependency() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); + this.AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); var queryString = detectedComponents.Single(component => ((PipComponent)component.Component).Name.Contains("certifi")); Assert.IsTrue(componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false)); @@ -117,7 +117,7 @@ public async Task TestPoetryDetector_TestGitDependency() reference = ""master"" resolved_reference = ""232a5596424c98d11c3cf2e29b2f6a6c591c2ff3"""; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("poetry.lock", poetryLockContent) .ExecuteDetector(); @@ -126,7 +126,7 @@ public async Task TestPoetryDetector_TestGitDependency() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(2, detectedComponents.Count()); - AssertGitComponentHashAndUrl(detectedComponents, "232a5596424c98d11c3cf2e29b2f6a6c591c2ff3", "https://github.com/requests/requests.git"); + this.AssertGitComponentHashAndUrl(detectedComponents, "232a5596424c98d11c3cf2e29b2f6a6c591c2ff3", "https://github.com/requests/requests.git"); } private void AssertPipComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs index f64df081c..ce264c97b 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs @@ -24,7 +24,7 @@ public class PyPiClientTests [TestInitialize] public void Initialize() { - pypiClient = new PyPiClient() + this.pypiClient = new PyPiClient() { EnvironmentVariableService = new EnvironmentVariableService(), Logger = new Mock().Object, @@ -44,10 +44,10 @@ public async Task GetReleases_InvalidSpecVersion_NotThrow() }, }; - var mockHandler = MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); + var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); - Func action = async () => await pypiClient.GetReleases(pythonSpecs); + Func action = async () => await this.pypiClient.GetReleases(pythonSpecs); await action.Should().NotThrowAsync(); } @@ -64,10 +64,10 @@ public async Task GetReleases_DuplicateEntries_CallsGetAsync_Once() }, }; - var mockHandler = MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); + var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); - Func action = async () => await pypiClient.GetReleases(pythonSpecs); + Func action = async () => await this.pypiClient.GetReleases(pythonSpecs); await action.Should().NotThrowAsync(); await action.Should().NotThrowAsync(); @@ -92,13 +92,13 @@ public async Task GetReleases_DifferentEntries_CallsGetAsync_Once() }, }; - var mockHandler = MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); + var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); Func action = async () => { pythonSpecs.Name = Guid.NewGuid().ToString(); - await pypiClient.GetReleases(pythonSpecs); + await this.pypiClient.GetReleases(pythonSpecs); }; await action.Should().NotThrowAsync(); @@ -115,10 +115,10 @@ public async Task GetReleases_DifferentEntries_CallsGetAsync_Once() [TestMethod] public async Task FetchPackageDependencies_DuplicateEntries_CallsGetAsync_Once() { - var mockHandler = MockHttpMessageHandler("invalid ZIP"); + var mockHandler = this.MockHttpMessageHandler("invalid ZIP"); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); - Func action = async () => await pypiClient.FetchPackageDependencies("a", "1.0.0", new PythonProjectRelease { PackageType = "bdist_wheel", PythonVersion = "3.5.2", Size = 1000, Url = new Uri($"https://testurl") }); + Func action = async () => await this.pypiClient.FetchPackageDependencies("a", "1.0.0", new PythonProjectRelease { PackageType = "bdist_wheel", PythonVersion = "3.5.2", Size = 1000, Url = new Uri($"https://testurl") }); await action.Should().ThrowAsync(); await action.Should().ThrowAsync(); @@ -134,10 +134,10 @@ public async Task FetchPackageDependencies_DuplicateEntries_CallsGetAsync_Once() [TestMethod] public async Task FetchPackageDependencies_DifferentEntries_CallsGetAsync_Once() { - var mockHandler = MockHttpMessageHandler("invalid ZIP"); + var mockHandler = this.MockHttpMessageHandler("invalid ZIP"); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); - Func action = async () => await pypiClient.FetchPackageDependencies("a", "1.0.0", new PythonProjectRelease { PackageType = "bdist_wheel", PythonVersion = "3.5.2", Size = 1000, Url = new Uri($"https://{Guid.NewGuid()}") }); + Func action = async () => await this.pypiClient.FetchPackageDependencies("a", "1.0.0", new PythonProjectRelease { PackageType = "bdist_wheel", PythonVersion = "3.5.2", Size = 1000, Url = new Uri($"https://{Guid.NewGuid()}") }); await action.Should().ThrowAsync(); await action.Should().ThrowAsync(); @@ -162,7 +162,7 @@ public async Task GetReleases_MaxEntriesVariable_CreatesNewCache() }, }; - var mockHandler = MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); + var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); var mockLogger = new Mock(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs index bf8f5b644..c54c4f282 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs @@ -22,15 +22,15 @@ public class PythonCommandServiceTests [TestInitialize] public void TestInitialize() { - commandLineInvokationService = new Mock(); + this.commandLineInvokationService = new Mock(); } [TestMethod] public async Task PythonCommandService_ReturnsTrueWhenPythonExists() { - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; Assert.IsTrue(await service.PythonExists()); } @@ -38,9 +38,9 @@ public async Task PythonCommandService_ReturnsTrueWhenPythonExists() [TestMethod] public async Task PythonCommandService_ReturnsFalseWhenPythonExists() { - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(false); + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(false); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; Assert.IsFalse(await service.PythonExists()); } @@ -48,9 +48,9 @@ public async Task PythonCommandService_ReturnsFalseWhenPythonExists() [TestMethod] public async Task PythonCommandService_ReturnsTrueWhenPythonExistsForAPath() { - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("test", It.IsAny>(), "--version")).ReturnsAsync(true); + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("test", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; Assert.IsTrue(await service.PythonExists("test")); } @@ -58,9 +58,9 @@ public async Task PythonCommandService_ReturnsTrueWhenPythonExistsForAPath() [TestMethod] public async Task PythonCommandService_ReturnsFalseWhenPythonExistsForAPath() { - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("test", It.IsAny>(), "--version")).ReturnsAsync(false); + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("test", It.IsAny>(), "--version")).ReturnsAsync(false); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; Assert.IsFalse(await service.PythonExists("test")); } @@ -71,11 +71,11 @@ public async Task PythonCommandService_ParsesEmptySetupPyOutputCorrectly() var fakePath = @"c:\the\fake\path.py"; var fakePathAsPassedToPython = fakePath.Replace("\\", "/"); - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - commandLineInvokationService.Setup(x => x.ExecuteCommand("python", It.IsAny>(), It.Is(c => c.Contains(fakePathAsPassedToPython)))) + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + this.commandLineInvokationService.Setup(x => x.ExecuteCommand("python", It.IsAny>(), It.Is(c => c.Contains(fakePathAsPassedToPython)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = "[]", StdErr = string.Empty }); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; var result = await service.ParseFile(fakePath); @@ -88,18 +88,18 @@ public async Task PythonCommandService_ParsesRegularSetupPyOutputCorrectly() var fakePath = @"c:\the\fake\path.py"; var fakePathAsPassedToPython = fakePath.Replace("\\", "/"); - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - commandLineInvokationService.Setup(x => x.ExecuteCommand("python", It.IsAny>(), It.Is(c => c.Contains(fakePathAsPassedToPython)))) + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + this.commandLineInvokationService.Setup(x => x.ExecuteCommand("python", It.IsAny>(), It.Is(c => c.Contains(fakePathAsPassedToPython)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = "['knack==0.4.1', 'setuptools>=1.0,!=1.1', 'vsts-cli-common==0.1.3', 'vsts-cli-admin==0.1.3', 'vsts-cli-build==0.1.3', 'vsts-cli-code==0.1.3', 'vsts-cli-team==0.1.3', 'vsts-cli-package==0.1.3', 'vsts-cli-work==0.1.3']", StdErr = string.Empty }); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; var result = await service.ParseFile(fakePath); var expected = new string[] { "knack==0.4.1", "setuptools>=1.0,!=1.1", "vsts-cli-common==0.1.3", "vsts-cli-admin==0.1.3", "vsts-cli-build==0.1.3", "vsts-cli-code==0.1.3", "vsts-cli-team==0.1.3", "vsts-cli-package==0.1.3", "vsts-cli-work==0.1.3" }.Select(dep => (dep, null)).ToArray(); Assert.AreEqual(9, result.Count); - for (int i = 0; i < 9; i++) + for (var i = 0; i < 9; i++) { Assert.AreEqual(expected[i], result[i]); } @@ -110,12 +110,12 @@ public async Task PythonCommandService_ParsesRequirementsTxtCorrectly() { var testPath = Path.Join(Directory.GetCurrentDirectory(), string.Join(Guid.NewGuid().ToString(), ".txt")); - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; try { - using (StreamWriter writer = File.CreateText(testPath)) + using (var writer = File.CreateText(testPath)) { writer.WriteLine("knack==0.4.1"); writer.WriteLine("vsts-cli-common==0.1.3 \\ "); @@ -128,7 +128,7 @@ public async Task PythonCommandService_ParsesRequirementsTxtCorrectly() Assert.AreEqual(expected.Length, result.Count); - for (int i = 0; i < expected.Length; i++) + for (var i = 0; i < expected.Length; i++) { Assert.AreEqual(expected[i], result[i]); } @@ -147,12 +147,12 @@ public async Task ParseFile_RequirementTxtHasComment_CommentAreIgnored() { var testPath = Path.Join(Directory.GetCurrentDirectory(), string.Join(Guid.NewGuid().ToString(), ".txt")); - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; try { - using (StreamWriter writer = File.CreateText(testPath)) + using (var writer = File.CreateText(testPath)) { writer.WriteLine("#this is a comment"); writer.WriteLine("knack==0.4.1 #this is another comment"); @@ -177,10 +177,10 @@ public async Task ParseFile_RequirementTxtHasComment_CommentAreIgnored() [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentsSupported() { - await SetupAndParseReqsTxt(requirementstxtBasicGitComponent, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtBasicGitComponent, parseResult => { parseResult.Count.Should().Be(1); - + var tuple = parseResult.Single(); tuple.Item1.Should().BeNull(); tuple.Item2.Should().NotBeNull(); @@ -194,7 +194,7 @@ await SetupAndParseReqsTxt(requirementstxtBasicGitComponent, parseResult => [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentAndEnvironmentMarker() { - await SetupAndParseReqsTxt(requirementstxtGitComponentAndEnvironmentMarker, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentAndEnvironmentMarker, parseResult => { parseResult.Count.Should().Be(1); @@ -211,7 +211,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentAndEnvironmentMarker, pars [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentAndComment() { - await SetupAndParseReqsTxt(requirementstxtGitComponentAndComment, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentAndComment, parseResult => { parseResult.Count.Should().Be(1); @@ -228,7 +228,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentAndComment, parseResult => [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentAndCommentAndEnvironmentMarker() { - await SetupAndParseReqsTxt(requirementstxtGitComponentAndCommentAndEnvironmentMarker, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentAndCommentAndEnvironmentMarker, parseResult => { parseResult.Count.Should().Be(1); @@ -245,7 +245,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentAndCommentAndEnvironmentMa [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenGivenBranch() { - await SetupAndParseReqsTxt(requirementstxtGitComponentBranchInsteadOfCommitId, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentBranchInsteadOfCommitId, parseResult => { parseResult.Count.Should().Be(0); }); @@ -254,7 +254,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentBranchInsteadOfCommitId, p [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenGivenRelease() { - await SetupAndParseReqsTxt(requirementstxtGitComponentReleaseInsteadOfCommitId, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentReleaseInsteadOfCommitId, parseResult => { parseResult.Count.Should().Be(0); }); @@ -263,7 +263,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentReleaseInsteadOfCommitId, [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenGivenMalformedCommitHash() { - await SetupAndParseReqsTxt(requirementstxtGitComponentCommitIdWrongLength, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentCommitIdWrongLength, parseResult => { parseResult.Count.Should().Be(0); }); @@ -272,7 +272,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentCommitIdWrongLength, parse [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentsMultiple() { - await SetupAndParseReqsTxt(requirementstxtDoubleGitComponents, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtDoubleGitComponents, parseResult => { parseResult.Count.Should().Be(2); @@ -297,7 +297,7 @@ await SetupAndParseReqsTxt(requirementstxtDoubleGitComponents, parseResult => [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentWrappedInRegularComponent() { - await SetupAndParseReqsTxt(requirementstxtGitComponentWrappedinRegularComponents, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentWrappedinRegularComponents, parseResult => { parseResult.Count.Should().Be(3); @@ -329,10 +329,10 @@ private async Task SetupAndParseReqsTxt(string fileToParse, Action x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + var service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; - using (StreamWriter writer = File.CreateText(testPath)) + using (var writer = File.CreateText(testPath)) { writer.WriteLine(fileToParse); writer.Flush(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs index b407eb240..7c1f36b60 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs @@ -66,7 +66,7 @@ public void TestPythonVersionComplexComparisons() "1.1", }.Select(x => new PythonVersion(x)).ToList(); - for (int i = 1; i < versions.Count; i++) + for (var i = 1; i < versions.Count; i++) { Assert.IsTrue(versions[i - 1] < versions[i]); } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs index 2592d620c..f73694662 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs @@ -26,15 +26,15 @@ public class RubyDetectorTest [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - rubyDetector = new RubyComponentDetector + this.loggerMock = new Mock(); + this.rubyDetector = new RubyComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithScanRequest(new ScanRequest( new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, - new ComponentRecorder(enableManualTrackingOfExplicitReferences: !rubyDetector.NeedsAutomaticRootDependencyCalculation))); + new ComponentRecorder(enableManualTrackingOfExplicitReferences: !this.rubyDetector.NeedsAutomaticRootDependencyCalculation))); } [TestMethod] @@ -71,7 +71,7 @@ BUNDLED WITH BUNDLED WITH 1.17.3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .WithFile("2Gemfile.lock", gemFileLockContent2) .ExecuteDetector(); @@ -81,13 +81,13 @@ BUNDLED WITH var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(7, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.2"); - AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.3"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.2"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.3"); } [TestMethod] @@ -97,11 +97,11 @@ public async Task TestRubyDetector_TestGemsWithUppercase_LockFile() remote: https://rubygems.org/ specs: CFPropertyList (3.0.4) - rexml + rexml BUNDLED WITH 2.2.28"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -111,8 +111,8 @@ BUNDLED WITH Assert.AreEqual(2, detectedComponents.Count()); // we do not record invalid/unknown versions - AssertRubyComponentNameAndVersion(detectedComponents, "CFPropertyList", "3.0.4"); - AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "2.2.28"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "CFPropertyList", "3.0.4"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "2.2.28"); } [TestMethod] @@ -134,7 +134,7 @@ public async Task TestRubyDetector_DetectorParseWithBundlerVersion() BUNDLED WITH 1.17.3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -143,12 +143,12 @@ BUNDLED WITH var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(6, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.3"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.3"); } [TestMethod] @@ -168,7 +168,7 @@ public async Task TestRubyDetector_DetectorRecognizeGemComponents() nokogiri (~> 1.8.2) websocket-driver (0.6.1)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -177,11 +177,11 @@ public async Task TestRubyDetector_DetectorRecognizeGemComponents() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(5, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); } [TestMethod] @@ -198,7 +198,7 @@ public async Task TestRubyDetector_ParentWithTildeInVersion_IsExcluded() mini_portile2 (~> 2.3.0) mini_portile2 (2.3.0)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -207,9 +207,9 @@ public async Task TestRubyDetector_ParentWithTildeInVersion_IsExcluded() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(3, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "mini_portile2", "2.3.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "mini_portile2", "2.3.0"); } [TestMethod] @@ -235,7 +235,7 @@ public async Task TestRubyDetector_DetectorCreatesADependencyGraph() nio4r (5.2.1) websocket-driver (0.6.1)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -287,7 +287,7 @@ public async Task TestRubyDetector_ComponentsRootsAreFilledCorrectly() nio4r (5.2.1) websocket-driver (0.6.1)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -342,15 +342,15 @@ public async Task TestRubyDetector_DetectorRecognizeGitComponents() specs: mini_mime (2.0.0)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(3, detectedComponents.Count()); - AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-1", repositoryUrl: "https://github.com/test/abc.git"); - AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-2", repositoryUrl: "https://github.com/mikel/mail.git"); - AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); + this.AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-1", repositoryUrl: "https://github.com/test/abc.git"); + this.AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-2", repositoryUrl: "https://github.com/mikel/mail.git"); + this.AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); } [TestMethod] @@ -371,11 +371,11 @@ public async Task TestRubyDetector_DetectorRecognizeParentChildRelationshipInGit specs: mail (2.7.2.edge)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); - AssertGitComponentAsRootAndGitComponentAsSubDependency(componentRecorder, rootHash: "commit-hash-1", subDependencyHash: "commit-hash-2"); + this.AssertGitComponentAsRootAndGitComponentAsSubDependency(componentRecorder, rootHash: "commit-hash-1", subDependencyHash: "commit-hash-2"); } [TestMethod] @@ -396,16 +396,16 @@ public async Task TestRubyDetector_DetectorRecognizeLocalDependencies() specs: test2 (1.0.0)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(3, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, name: "test", version: "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, name: "test2", version: "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, name: "test", version: "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, name: "test2", version: "1.0.0"); } private void AssertRubyComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs index 7e79e95d4..61cb5d793 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs @@ -25,16 +25,16 @@ public class RustCrateDetectorTests [TestInitialize] public void TestInitialize() { - detectorTestUtility = DetectorTestUtilityCreator.Create(); - detectorV2TestUtility = DetectorTestUtilityCreator.Create(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.detectorV2TestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] public async Task TestGraphIsCorrect() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -77,8 +77,8 @@ public async Task TestRequirePairForComponents() { var cargoDefinitionPairsMatrix = new List<(string, string)> { - (null, testCargoTomlString), - (testCargoLockString, null), + (null, this.testCargoTomlString), + (this.testCargoLockString, null), (null, null), }; @@ -86,15 +86,15 @@ public async Task TestRequirePairForComponents() { if (cargoDefinitionPairs.Item1 != null) { - detectorTestUtility.WithFile("Cargo.lock", cargoDefinitionPairs.Item1); + this.detectorTestUtility.WithFile("Cargo.lock", cargoDefinitionPairs.Item1); } if (cargoDefinitionPairs.Item2 != null) { - detectorTestUtility.WithFile("Cargo.toml", cargoDefinitionPairs.Item2, new List { "Cargo.toml" }); + this.detectorTestUtility.WithFile("Cargo.toml", cargoDefinitionPairs.Item2, new List { "Cargo.toml" }); } - var (result, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (result, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -106,26 +106,26 @@ public async Task TestRequirePairForComponents() public async Task TestSupportsCargoV1AndV2DefinitionPairs() { var componentRecorder = new ComponentRecorder(); - ScanRequest request = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder); + var request = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder); - var (result1, _) = await detectorTestUtility + var (result1, _) = await this.detectorTestUtility /* v1 files */ - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) /* v2 files */ - .WithFile("Cargo.lock", testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.lock")) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.toml")) + .WithFile("Cargo.lock", this.testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.lock")) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.toml")) /* so we can reuse the component recorder */ .WithScanRequest(request) .ExecuteDetector(); - var (result2, _) = await detectorV2TestUtility + var (result2, _) = await this.detectorV2TestUtility /* v1 files */ - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) /* v2 files */ - .WithFile("Cargo.lock", testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.lock")) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.toml")) + .WithFile("Cargo.lock", this.testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.lock")) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.toml")) /* so we can reuse the component recorder */ .WithScanRequest(request) .ExecuteDetector(); @@ -141,11 +141,11 @@ public async Task TestSupportsCargoV1AndV2DefinitionPairs() [TestMethod] public async Task TestSupportsMultipleCargoV1DefinitionPairs() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.lock", testCargoLockString, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.lock", this.testCargoLockString, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -166,11 +166,11 @@ public async Task TestSupportsMultipleCargoV1DefinitionPairs() [TestMethod] public async Task TestSupportsMultipleCargoV2DefinitionPairs() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testCargoLockV2String) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.lock", testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testCargoLockV2String) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.lock", this.testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -191,9 +191,9 @@ public async Task TestSupportsMultipleCargoV2DefinitionPairs() [TestMethod] public async Task TestRustDetector() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -261,15 +261,15 @@ public async Task TestRustDetector() [TestMethod] public async Task TestRustV2Detector() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testCargoLockV2String) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testCargoLockV2String) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); Assert.AreEqual(7, componentRecorder.GetDetectedComponents().Count()); - List packageVersions = new List() + var packageVersions = new List() { "my_dependency 1.0.0", "other_dependency 0.4.0", @@ -332,9 +332,9 @@ public async Task TestRustV2Detector() [TestMethod] public async Task TestRustV2Detector_DoesNotRunV1Format() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -344,9 +344,9 @@ public async Task TestRustV2Detector_DoesNotRunV1Format() [TestMethod] public async Task TestRustV1Detector_DoesNotRunV2Format() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testCargoLockV2String) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testCargoLockV2String) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -356,7 +356,7 @@ public async Task TestRustV1Detector_DoesNotRunV2Format() [TestMethod] public async Task TestRustV2Detector_DuplicatePackage() { - string testCargoLock = @" + var testCargoLock = @" [[package]] name = ""my_dependency"" version = ""1.0.0"" @@ -425,9 +425,9 @@ public async Task TestRustV2Detector_DuplicatePackage() source = ""registry+https://github.com/rust-lang/crates.io-index"" "; - var (result, componentRecorder) = await detectorV2TestUtility + var (result, componentRecorder) = await this.detectorV2TestUtility .WithFile("Cargo.lock", testCargoLock) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -493,7 +493,7 @@ public async Task TestRustDetector_SupportEmptySource() version = ""0.1.12-alpha.6"" source = ""registry+https://github.com/rust-lang/crates.io-index"" "; - var (result, componentRecorder) = await detectorV2TestUtility + var (result, componentRecorder) = await this.detectorV2TestUtility .WithFile("Cargo.lock", testLockString) .WithFile("Cargo.toml", testTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); @@ -516,17 +516,17 @@ public async Task TestRustDetector_SupportEmptySource() [TestMethod] public async Task TestRustV1Detector_WorkspacesWithTopLevelDependencies() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", string.Concat(testWorkspaceLockBaseDependency, testWorkspaceLockV1NoBaseString)) - .WithFile("Cargo.toml", string.Concat(testWorkspaceTomlBaseDependency, testWorkspacesBaseTomlString), new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", string.Concat(this.testWorkspaceLockBaseDependency, this.testWorkspaceLockV1NoBaseString)) + .WithFile("Cargo.toml", string.Concat(this.testWorkspaceTomlBaseDependency, this.testWorkspacesBaseTomlString), new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); Assert.AreEqual(7, componentRecorder.GetDetectedComponents().Count()); - List packageVersions = new List() + var packageVersions = new List() { "dev_dependency_dependency 0.2.23", "one_more_dev_dep 1.0.0", @@ -589,17 +589,17 @@ public async Task TestRustV1Detector_WorkspacesWithTopLevelDependencies() [TestMethod] public async Task TestRustV2Detector_WorkspacesWithTopLevelDependencies() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", string.Concat(testWorkspaceLockBaseDependency, testWorkspaceLockV2NoBaseString)) - .WithFile("Cargo.toml", string.Concat(testWorkspaceTomlBaseDependency, testWorkspacesBaseTomlString), new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", string.Concat(this.testWorkspaceLockBaseDependency, this.testWorkspaceLockV2NoBaseString)) + .WithFile("Cargo.toml", string.Concat(this.testWorkspaceTomlBaseDependency, this.testWorkspacesBaseTomlString), new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); Assert.AreEqual(7, componentRecorder.GetDetectedComponents().Count()); - List packageVersions = new List() + var packageVersions = new List() { "dev_dependency_dependency 0.2.23", "one_more_dev_dep 1.0.0", @@ -662,11 +662,11 @@ public async Task TestRustV2Detector_WorkspacesWithTopLevelDependencies() [TestMethod] public async Task TestRustV1Detector_WorkspacesNoTopLevelDependencies() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testWorkspaceLockV1NoBaseString) - .WithFile("Cargo.toml", testWorkspacesBaseTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testWorkspaceLockV1NoBaseString) + .WithFile("Cargo.toml", this.testWorkspacesBaseTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -676,11 +676,11 @@ public async Task TestRustV1Detector_WorkspacesNoTopLevelDependencies() [TestMethod] public async Task TestRustV2Detector_WorkspacesNoTopLevelDependencies() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testWorkspaceLockV2NoBaseString) - .WithFile("Cargo.toml", testWorkspacesBaseTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testWorkspaceLockV2NoBaseString) + .WithFile("Cargo.toml", this.testWorkspacesBaseTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -690,11 +690,11 @@ public async Task TestRustV2Detector_WorkspacesNoTopLevelDependencies() [TestMethod] public async Task TestRustV1Detector_WorkspacesWithSubDirectories() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testWorkspaceLockV1NoBaseString) - .WithFile("Cargo.toml", testWorkspacesSubdirectoryTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub//test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub2//test//test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testWorkspaceLockV1NoBaseString) + .WithFile("Cargo.toml", this.testWorkspacesSubdirectoryTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub//test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub2//test//test-work2", "Cargo.toml")) .ExecuteDetector(); var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); @@ -711,11 +711,11 @@ public async Task TestRustV1Detector_WorkspacesWithSubDirectories() [TestMethod] public async Task TestRustV2Detector_WorkspacesWithSubDirectories() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testWorkspaceLockV2NoBaseString) - .WithFile("Cargo.toml", testWorkspacesSubdirectoryTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub//test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub2//test//test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testWorkspaceLockV2NoBaseString) + .WithFile("Cargo.toml", this.testWorkspacesSubdirectoryTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub//test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub2//test//test-work2", "Cargo.toml")) .ExecuteDetector(); var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); @@ -764,7 +764,7 @@ public async Task TestRustDetector_UnequalButSemverCompatibleRoot() ""c-ares"", ] "; - var (result, componentRecorder) = await detectorV2TestUtility + var (result, componentRecorder) = await this.detectorV2TestUtility .WithFile("Cargo.lock", testLockString) .WithFile("Cargo.toml", testTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); @@ -805,7 +805,7 @@ public async Task TestRustDetector_RenamedDependency() version = ""1.0.0"" source = ""registry+https://github.com/rust-lang/crates.io-index"" "; - var (result, componentRecorder) = await detectorV2TestUtility + var (result, componentRecorder) = await this.detectorV2TestUtility .WithFile("Cargo.lock", testLockString) .WithFile("Cargo.toml", testTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); @@ -829,9 +829,9 @@ public async Task TestRustDetector_RenamedDependency() [TestMethod] public async Task TestRustDetector_TargetSpecificDependencies() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testTargetSpecificDependenciesLockString) - .WithFile("Cargo.toml", testTargetSpecificDependenciesTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testTargetSpecificDependenciesLockString) + .WithFile("Cargo.toml", this.testTargetSpecificDependenciesTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs index c1abdb44b..1b163236e 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs @@ -36,14 +36,14 @@ public void DoesntMatch_WhenNoDependencyAdded() (true, "Matches_-", "some-cargo-package", "1.2.0 - 1.2.5"), (false, "DoesntMatch_-", "some-cargo-package", "1.1.0 - 1.1.5"), }; - DoAllTheTests(testCases); + this.DoAllTheTests(testCases); } public void DoAllTheTests(IEnumerable<(bool shouldMatch, string caseName, string specifierName, string specifierRange)> testCases) { foreach (var testCase in testCases) { - DependencySpecification di = new DependencySpecification(); + var di = new DependencySpecification(); if (testCase.specifierName != null) { di.Add(testCase.specifierName, testCase.specifierRange); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs index 44704c37c..9b37d10ef 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs @@ -26,8 +26,8 @@ public class Spdx22ComponentDetectorTests public void TestInitialize() { var componentRecorder = new ComponentRecorder(enableManualTrackingOfExplicitReferences: false); - detectorTestUtility = DetectorTestUtilityCreator.Create() - .WithScanRequest(new ScanRequest(new DirectoryInfo(tempPath), null, null, new Dictionary(), null, componentRecorder)); + this.detectorTestUtility = DetectorTestUtilityCreator.Create() + .WithScanRequest(new ScanRequest(new DirectoryInfo(this.tempPath), null, null, new Dictionary(), null, componentRecorder)); } [TestMethod] @@ -98,7 +98,7 @@ public async Task TestSbomDetector_SimpleSbom() }"; var spdxFileName = "manifest.spdx.json"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile(spdxFileName, spdxFile) .ExecuteDetector(); @@ -124,15 +124,15 @@ public async Task TestSbomDetector_SimpleSbom() Assert.AreEqual(sbomComponent.DocumentNamespace, new Uri("https://sbom.microsoft/Test/1.0.0/61de1a5-57cc-4732-9af5-edb321b4a7ee")); Assert.AreEqual(sbomComponent.SpdxVersion, "SPDX-2.2"); Assert.AreEqual(sbomComponent.Checksum, checksum); - Assert.AreEqual(sbomComponent.Path, Path.Combine(tempPath, spdxFileName)); + Assert.AreEqual(sbomComponent.Path, Path.Combine(this.tempPath, spdxFileName)); } [TestMethod] public async Task TestSbomDetector_BlankJson() { var spdxFile = "{}"; - - var (scanResult, componentRecorder) = await detectorTestUtility + + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("manifest.spdx.json", spdxFile) .ExecuteDetector(); @@ -147,8 +147,8 @@ public async Task TestSbomDetector_BlankJson() public async Task TestSbomDetector_InvalidFile() { var spdxFile = "invalidspdxfile"; - - var (scanResult, componentRecorder) = await detectorTestUtility + + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("manifest.spdx.json", spdxFile) .ExecuteDetector(); @@ -156,7 +156,7 @@ public async Task TestSbomDetector_InvalidFile() var detectedComponents = componentRecorder.GetDetectedComponents(); var components = detectedComponents.ToList(); - Assert.IsFalse(components.Any()); + Assert.IsFalse(components.Any()); } } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/ComponentRecorderTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/ComponentRecorderTestUtilities.cs index bc7ee33e8..8608045e2 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/ComponentRecorderTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/ComponentRecorderTestUtilities.cs @@ -15,7 +15,7 @@ public static void ForAllComponents(this IComponentRecorder recorder, Action> graphsAndLocationsByComponentId = GroupByComponentId(graphs); + var graphsAndLocationsByComponentId = GroupByComponentId(graphs); foreach (var item in graphsAndLocationsByComponentId) { @@ -30,7 +30,7 @@ public static void ForOneComponent(this IComponentRecorder recorder, string comp // This magic grouping is a flattening of "occurrences" of components across single file recorders. This allows aggregate operations // per component id, which is logical for most tests. - List> graphsAndLocationsByComponentId = GroupByComponentId(graphs); + var graphsAndLocationsByComponentId = GroupByComponentId(graphs); forOneComponent(TupleToObject(graphsAndLocationsByComponentId.First(x => x.Key == componentId))); } @@ -62,7 +62,7 @@ public static bool IsDependencyOfExplicitlyReferencedComponents string componentIdToValidate, params Func[] locatingPredicatesForParentExplicitReference) { - bool isDependency = false; + var isDependency = false; recorder.ForOneComponent(componentIdToValidate, grouping => { isDependency = true; @@ -84,8 +84,8 @@ public static void AssertAllExplicitlyReferencedComponents( { recorder.ForOneComponent(componentIdToValidate, grouping => { - HashSet explicitReferrers = new HashSet(grouping.ParentComponentIdsThatAreExplicitReferences); - int assertionIndex = 0; + var explicitReferrers = new HashSet(grouping.ParentComponentIdsThatAreExplicitReferences); + var assertionIndex = 0; foreach (var predicate in locatingPredicatesForParentExplicitReference) { var dependencyModel = recorder.GetDetectedComponents().Select(x => x.Component).OfType() diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs index 70b6cb8ad..5f674c5f3 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs @@ -22,7 +22,7 @@ public class VcpkgComponentDetectorTests public void TestInitialize() { var componentRecorder = new ComponentRecorder(enableManualTrackingOfExplicitReferences: false); - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithScanRequest(new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder)); } @@ -38,7 +38,7 @@ public async Task TestNlohmann() { ""name"": ""nlohmann-json"", ""SPDXID"": ""SPDXRef-port"", - ""versionInfo"": ""3.10.4"", + ""versionInfo"": ""3.10.4#5"", ""downloadLocation"": ""git+https://github.com/Microsoft/vcpkg#ports/nlohmann-json"", ""homepage"": ""https://github.com/nlohmann/json"", ""licenseConcluded"": ""NOASSERTION"", @@ -49,7 +49,7 @@ public async Task TestNlohmann() } ] }"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetector(); @@ -67,10 +67,10 @@ public async Task TestNlohmann() Assert.AreEqual(1, components.Count()); Assert.AreEqual("nlohmann-json", sbomComponent.Name); Assert.AreEqual("3.10.4", sbomComponent.Version); - Assert.AreEqual("0", sbomComponent.PortVersion); + Assert.AreEqual(5, sbomComponent.PortVersion); Assert.AreEqual("SPDXRef-port", sbomComponent.SPDXID); Assert.AreEqual("git+https://github.com/Microsoft/vcpkg#ports/nlohmann-json", sbomComponent.DownloadLocation); - Assert.AreEqual("pkg:vcpkg/nlohmann-json@3.10.4?port_version=0", sbomComponent.PackageUrl.ToString()); + Assert.AreEqual("pkg:vcpkg/nlohmann-json@3.10.4?port_version=5", sbomComponent.PackageUrl.ToString()); } [TestMethod] @@ -108,7 +108,7 @@ public async Task TestTinyxmlAndResource() } ] }"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetector(); @@ -137,7 +137,7 @@ public async Task TestBlankJson() { var spdxFile = "{}"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetector(); @@ -153,7 +153,7 @@ public async Task TestInvalidFile() { var spdxFile = "invalidspdxfile"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnBlockFileTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnBlockFileTests.cs index c1b3a74db..e3cfa44dd 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnBlockFileTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnBlockFileTests.cs @@ -24,7 +24,7 @@ public async Task BlockFileParserWithNullStream_Fails() [TestMethod] public async Task BlockFileParserWithClosedStream_Fails() { - using MemoryStream stream = new MemoryStream(); + using var stream = new MemoryStream(); stream.Close(); @@ -50,7 +50,7 @@ public async Task BlockFileParserWithEmptyStream_ProducesEnumerableOfZero() [TestMethod] public async Task BlockFileParserV1WithVersionString_ProducesEnumerableOfZero() { - string yarnLockFileVersionString = "#yarn lockfile v1"; + var yarnLockFileVersionString = "#yarn lockfile v1"; using var stream = new MemoryStream(); @@ -70,7 +70,7 @@ public async Task BlockFileParserV1WithVersionString_ProducesEnumerableOfZero() [TestMethod] public async Task BlockFileParserV1WithSingleBlock_Parses() { - string yarnLockFileVersionString = "#yarn lockfile v1"; + var yarnLockFileVersionString = "#yarn lockfile v1"; using var stream = new MemoryStream(); @@ -101,7 +101,7 @@ public async Task BlockFileParserV1WithSingleBlock_Parses() [TestMethod] public async Task BlockFileParserV1WithSeveralBlocks_Parses() { - string yarnLockFileVersionString = "#yarn lockfile v1"; + var yarnLockFileVersionString = "#yarn lockfile v1"; using var stream = new MemoryStream(); @@ -145,7 +145,7 @@ public async Task BlockFileParserV1WithSeveralBlocks_Parses() [TestMethod] public async Task BlockFileParserV2WithMetadataBlock_Parses() { - string yarnLockFileVersionString = "__metadata:"; + var yarnLockFileVersionString = "__metadata:"; using var stream = new MemoryStream(); @@ -172,7 +172,7 @@ public async Task BlockFileParserV2WithMetadataBlock_Parses() [TestMethod] public async Task BlockFileParserV2WithSingleBlock_Parses() { - string yarnLockFileVersionString = "__metadata:"; + var yarnLockFileVersionString = "__metadata:"; using var stream = new MemoryStream(); @@ -210,7 +210,7 @@ public async Task BlockFileParserV2WithSingleBlock_Parses() [TestMethod] public async Task BlockFileParserV2WithSingleBlock_ParsesWithQuotes() { - string yarnLockFileVersionString = "__metadata:"; + var yarnLockFileVersionString = "__metadata:"; using var stream = new MemoryStream(); @@ -248,7 +248,7 @@ public async Task BlockFileParserV2WithSingleBlock_ParsesWithQuotes() [TestMethod] public async Task BlockFileParserV2WithMultipleBlocks_Parses() { - string yarnLockFileVersionString = "__metadata:"; + var yarnLockFileVersionString = "__metadata:"; using var stream = new MemoryStream(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs index ddd60b245..7dd39496c 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs @@ -34,9 +34,9 @@ public class YarnLockDetectorTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - componentRecorder = new ComponentRecorder(); - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.loggerMock = new Mock(); + this.componentRecorder = new ComponentRecorder(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] @@ -45,7 +45,7 @@ public async Task WellFormedYarnLockV1WithZeroComponents_FindsNothing() var yarnLock = YarnTestUtilities.GetWellFormedEmptyYarnV1LockFile(); var packageJson = NpmTestUtilities.GetPackageJsonNoDependencies(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJson, new List { "package.json" }) .ExecuteDetector(); @@ -60,7 +60,7 @@ public async Task WellFormedYarnLockV2WithZeroComponents_FindsNothing() var yarnLock = YarnTestUtilities.GetWellFormedEmptyYarnV2LockFile(); var packageJson = NpmTestUtilities.GetPackageJsonNoDependencies(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJson, new List { "package.json" }) .ExecuteDetector(); @@ -89,7 +89,7 @@ public async Task MalformedYarnLockV1WithOneComponent_FindsNoComponent() var yarnLock = builder.ToString(); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, providedVersion0); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -108,7 +108,7 @@ public async Task MalformedYarnLockV2WithOneComponent_FindsNoComponent() var builder = new StringBuilder(); - builder.AppendLine(CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); builder.AppendLine($"{componentName0}@{providedVersion0}"); builder.AppendLine($" version {version0}"); builder.AppendLine($" resolved {resolved0}"); @@ -116,7 +116,7 @@ public async Task MalformedYarnLockV2WithOneComponent_FindsNoComponent() var yarnLock = builder.ToString(); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, providedVersion0); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -137,10 +137,10 @@ public async Task WellFormedYarnLockV1WithOneComponent_FindsComponent() ResolvedVersion = "https://resolved0/a/resolved", }; - var yarnLock = CreateYarnLockV1FileContent(new List { componentA }); + var yarnLock = this.CreateYarnLockV1FileContent(new List { componentA }); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -169,10 +169,10 @@ public async Task WellFormedYarnLockV2WithOneComponent_FindsComponent() ResolvedVersion = "https://resolved0/a/resolved", }; - var yarnLock = CreateYarnLockV2FileContent(new List { componentA }); + var yarnLock = this.CreateYarnLockV2FileContent(new List { componentA }); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -203,7 +203,7 @@ public async Task WellFormedYarnLockV1WithWorkspace_FindsComponent() Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", CreateYarnLockV1FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent(new List { componentA })); var workspaceJson = new { @@ -219,7 +219,7 @@ public async Task WellFormedYarnLockV1WithWorkspace_FindsComponent() var detector = new YarnLockComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; var mock = new Mock(); @@ -233,21 +233,21 @@ public async Task WellFormedYarnLockV1WithWorkspace_FindsComponent() // The call to get the package.json that contains actual information mock.Setup(x => x.GetComponentStreams(It.IsAny(), It.IsAny>(), It.IsAny(), true)).Returns(new List { packageStream }); - var directoryWalkerMock = NpmTestUtilities.GetMockDirectoryWalker(new List { componentStream }, new List { packageStream }, directory.FullName, patterns: detector.SearchPatterns, componentRecorder: componentRecorder); + var directoryWalkerMock = NpmTestUtilities.GetMockDirectoryWalker(new List { componentStream }, new List { packageStream }, directory.FullName, patterns: detector.SearchPatterns, componentRecorder: this.componentRecorder); - var (scanResult, _) = await detectorTestUtility + var (scanResult, _) = await this.detectorTestUtility .WithObservableDirectoryWalkerFactory(directoryWalkerMock) .WithComponentStreamEnumerableFactory(mock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); - componentRecorder.AssertAllExplicitlyReferencedComponents( + this.componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, parentComponent => parentComponent.Name == componentA.Name && parentComponent.Version == version0); } @@ -266,7 +266,7 @@ public async Task WellFormedYarnLockV2WithWorkspace_FindsComponent() Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", CreateYarnLockV2FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV2FileContent(new List { componentA })); var workspaceJson = new { @@ -282,7 +282,7 @@ public async Task WellFormedYarnLockV2WithWorkspace_FindsComponent() var detector = new YarnLockComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; var mock = new Mock(); @@ -296,21 +296,21 @@ public async Task WellFormedYarnLockV2WithWorkspace_FindsComponent() // The call to get the package.json that contains actual information mock.Setup(x => x.GetComponentStreams(It.IsAny(), It.IsAny>(), It.IsAny(), true)).Returns(new List { packageStream }); - var directoryWalkerMock = NpmTestUtilities.GetMockDirectoryWalker(new List { componentStream }, new List { packageStream }, directory.FullName, patterns: detector.SearchPatterns, componentRecorder: componentRecorder); + var directoryWalkerMock = NpmTestUtilities.GetMockDirectoryWalker(new List { componentStream }, new List { packageStream }, directory.FullName, patterns: detector.SearchPatterns, componentRecorder: this.componentRecorder); - var (scanResult, _) = await detectorTestUtility + var (scanResult, _) = await this.detectorTestUtility .WithObservableDirectoryWalkerFactory(directoryWalkerMock) .WithComponentStreamEnumerableFactory(mock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); - componentRecorder.AssertAllExplicitlyReferencedComponents( + this.componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, parentComponent => parentComponent.Name == componentA.Name && parentComponent.Version == version0); } @@ -329,7 +329,7 @@ public async Task WellFormedYarnLockV1WithWorkspaceAltForm_FindsComponent() Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", CreateYarnLockV1FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent(new List { componentA })); var workspaceJson = new { @@ -345,7 +345,7 @@ public async Task WellFormedYarnLockV1WithWorkspaceAltForm_FindsComponent() var detector = new YarnLockComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; var mock = new Mock(); @@ -370,22 +370,22 @@ public async Task WellFormedYarnLockV1WithWorkspaceAltForm_FindsComponent() }.Select(cs => new ProcessRequest { ComponentStream = cs, - SingleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(cs.Location), + SingleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(cs.Location), }).ToObservable()); - var (scanResult, _) = await detectorTestUtility + var (scanResult, _) = await this.detectorTestUtility .WithObservableDirectoryWalkerFactory(directoryWalkerMock) .WithComponentStreamEnumerableFactory(mock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); - componentRecorder.AssertAllExplicitlyReferencedComponents( + this.componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, parentComponent => parentComponent.Name == componentA.Name && parentComponent.Version == version0); } @@ -404,7 +404,7 @@ public async Task WellFormedYarnLockV2WithWorkspaceAltForm_FindsComponent() Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", CreateYarnLockV2FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV2FileContent(new List { componentA })); var workspaceJson = new { @@ -420,7 +420,7 @@ public async Task WellFormedYarnLockV2WithWorkspaceAltForm_FindsComponent() var detector = new YarnLockComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; var mock = new Mock(); @@ -445,22 +445,22 @@ public async Task WellFormedYarnLockV2WithWorkspaceAltForm_FindsComponent() }.Select(cs => new ProcessRequest { ComponentStream = cs, - SingleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(cs.Location), + SingleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(cs.Location), }).ToObservable()); - var (scanResult, _) = await detectorTestUtility + var (scanResult, _) = await this.detectorTestUtility .WithObservableDirectoryWalkerFactory(directoryWalkerMock) .WithComponentStreamEnumerableFactory(mock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); - componentRecorder.AssertAllExplicitlyReferencedComponents( + this.componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, parentComponent => parentComponent.Name == componentA.Name && parentComponent.Version == version0); } @@ -488,10 +488,10 @@ public async Task WellFormedYarnLockV1WithMoreThanOneComponent_FindsComponents() componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; - var yarnLock = CreateYarnLockV1FileContent(new List { componentA, componentB }); + var yarnLock = this.CreateYarnLockV1FileContent(new List { componentA, componentB }); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -535,10 +535,10 @@ public async Task WellFormedYarnLockV2WithMoreThanOneComponent_FindsComponents() componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; - var yarnLock = CreateYarnLockV2FileContent(new List { componentA, componentB }); + var yarnLock = this.CreateYarnLockV2FileContent(new List { componentA, componentB }); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -611,7 +611,7 @@ public async Task WellFormedYarnLockV1WithMultiRootedComponent_FindsAllRoots() var yarnLock = builder.ToString(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -673,7 +673,7 @@ public async Task WellFormedYarnLockV2WithMultiRootedComponent_FindsAllRoots() var builder = new StringBuilder(); - builder.AppendLine(CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); builder.AppendLine($"{componentNameA}@{requestedVersionA}:"); builder.AppendLine($" version: {actualVersionA}"); builder.AppendLine($" resolved: {resolvedA}"); @@ -687,7 +687,7 @@ public async Task WellFormedYarnLockV2WithMultiRootedComponent_FindsAllRoots() var yarnLock = builder.ToString(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -743,10 +743,10 @@ public async Task DependencyGraphV1IsGeneratedCorrectly() componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; componentB.Dependencies = new List<(string, string)> { (componentC.Name, componentC.RequestedVersion) }; - var yarnLockFileContent = CreateYarnLockV1FileContent(new List { componentA, componentB, componentC }); - var packageJsonFileContent = CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); + var yarnLockFileContent = this.CreateYarnLockV1FileContent(new List { componentA, componentB, componentC }); + var packageJsonFileContent = this.CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) .ExecuteDetector(); @@ -799,10 +799,10 @@ public async Task DependencyGraphV2IsGeneratedCorrectly() componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; componentB.Dependencies = new List<(string, string)> { (componentC.Name, componentC.RequestedVersion) }; - var yarnLockFileContent = CreateYarnLockV2FileContent(new List { componentA, componentB, componentC }); - var packageJsonFileContent = CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); + var yarnLockFileContent = this.CreateYarnLockV2FileContent(new List { componentA, componentB, componentC }); + var packageJsonFileContent = this.CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) .ExecuteDetector(); @@ -833,24 +833,24 @@ public async Task MalformedYarnLockV1_Duplicate() const string componentNameB = "lodash"; const string requestedVersionB = "file:lodash-shim"; const string actualVersion = "2.4.2"; - + var builder = new StringBuilder(); - builder.AppendLine(CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); builder.AppendLine($"\"{componentNameA}@{requestedVersionA}\", \"{componentNameB}@{requestedVersionB}\":"); builder.AppendLine($" version: {actualVersion}"); builder.AppendLine(); var yarnLockFileContent = builder.ToString(); - var packageJsonFileContent = CreatePackageJsonFileContent(new List()); - - var (scanResult, componentRecorder) = await detectorTestUtility + var packageJsonFileContent = this.CreatePackageJsonFileContent(new List()); + + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) .ExecuteDetector(); - + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - + var detectedComponents = componentRecorder.GetDetectedComponents(); detectedComponents.Should().HaveCount(1); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs index e2dddc370..8ff04a60c 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs @@ -19,7 +19,7 @@ public class YarnParserTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); + this.loggerMock = new Mock(); } [TestMethod] @@ -27,7 +27,7 @@ public void YarnLockParserWithNullBlockFile_Fails() { var parser = new YarnLockParser(); - Action action = () => parser.Parse(null, loggerMock.Object); + Action action = () => parser.Parse(null, this.loggerMock.Object); Assert.ThrowsException(action); } @@ -70,7 +70,7 @@ public void YarnLockParser_ParsesEmptyFile() blockFile.Setup(x => x.YarnLockVersion).Returns(yarnLockFileVersion); blockFile.Setup(x => x.GetEnumerator()).Returns(blocks.GetEnumerator()); - var file = parser.Parse(blockFile.Object, loggerMock.Object); + var file = parser.Parse(blockFile.Object, this.loggerMock.Object); Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); Assert.AreEqual(0, file.Entries.Count()); @@ -85,25 +85,27 @@ public void YarnLockParser_ParsesBlocks() var blocks = new List { - CreateBlock("a@^1.0.0", "1.0.0", "https://a", new List { CreateDependencyBlock(new Dictionary { { "xyz", "2" } }) }), - CreateBlock("b@2.4.6", "2.4.6", "https://b", new List { CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }) }), - CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", Enumerable.Empty()), + this.CreateBlock("a@^1.0.0", "1.0.0", "https://a", new List { + this.CreateDependencyBlock(new Dictionary { { "xyz", "2" } }) }), + this.CreateBlock("b@2.4.6", "2.4.6", "https://b", new List { + this.CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }) }), + this.CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", Enumerable.Empty()), }; var blockFile = new Mock(); blockFile.Setup(x => x.YarnLockVersion).Returns(yarnLockFileVersion); blockFile.Setup(x => x.GetEnumerator()).Returns(blocks.GetEnumerator()); - var file = parser.Parse(blockFile.Object, loggerMock.Object); + var file = parser.Parse(blockFile.Object, this.loggerMock.Object); Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); Assert.AreEqual(3, file.Entries.Count()); foreach (var entry in file.Entries) { - YarnBlock block = blocks.Single(x => x.Values["resolved"] == entry.Resolved); + var block = blocks.Single(x => x.Values["resolved"] == entry.Resolved); - AssertBlockMatchesEntry(block, entry); + this.AssertBlockMatchesEntry(block, entry); } } @@ -116,15 +118,17 @@ public void YarnLockParser_ParsesNoVersionInTitleBlock() var blocks = new List { - CreateBlock("a", "1.0.0", "https://a", new List { CreateDependencyBlock(new Dictionary { { "xyz", "2" } }) }), - CreateBlock("b", "2.4.6", "https://b", new List { CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }) }), + this.CreateBlock("a", "1.0.0", "https://a", new List { + this.CreateDependencyBlock(new Dictionary { { "xyz", "2" } }) }), + this.CreateBlock("b", "2.4.6", "https://b", new List { + this.CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }) }), }; var blockFile = new Mock(); blockFile.Setup(x => x.YarnLockVersion).Returns(yarnLockFileVersion); blockFile.Setup(x => x.GetEnumerator()).Returns(blocks.GetEnumerator()); - var file = parser.Parse(blockFile.Object, loggerMock.Object); + var file = parser.Parse(blockFile.Object, this.loggerMock.Object); Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); Assert.AreEqual(2, file.Entries.Count()); @@ -148,7 +152,7 @@ private YarnBlock CreateDependencyBlock(IDictionary dependencies private YarnBlock CreateBlock(string title, string version, string resolved, IEnumerable dependencies) { - var block = new YarnBlock + var block = new YarnBlock { Title = title, Values = diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnTestUtilities.cs index 442405a35..3d4329fb9 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnTestUtilities.cs @@ -10,7 +10,7 @@ public static class YarnTestUtilities { public static string GetWellFormedEmptyYarnV1LockFile() { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); builder.AppendLine("# THIS IS A YARNFILE"); builder.AppendLine("# yarn lockfile v1"); @@ -21,7 +21,7 @@ public static string GetWellFormedEmptyYarnV1LockFile() public static string GetWellFormedEmptyYarnV2LockFile() { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); builder.AppendLine("# THIS IS A YARNFILE"); builder.AppendLine(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/nuget/NuGetPackagesConfigDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/nuget/NuGetPackagesConfigDetectorTests.cs new file mode 100644 index 000000000..9a375fc51 --- /dev/null +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/nuget/NuGetPackagesConfigDetectorTests.cs @@ -0,0 +1,45 @@ +namespace Microsoft.ComponentDetection.Detectors.Tests.NuGet +{ + using System.Threading.Tasks; + using Contracts; + using Contracts.TypedComponent; + using Detectors.NuGet; + using FluentAssertions; + using TestsUtilities; + using VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class NuGetPackagesConfigDetectorTests + { + private DetectorTestUtility detectorTestUtility; + + [TestInitialize] + public void TestInitialize() + { + var detector = new NuGetPackagesConfigDetector(); + this.detectorTestUtility = new DetectorTestUtility().WithDetector(detector); + } + + [TestMethod] + public async Task Should_Work() + { + var packagesConfig = + @" + + + + "; + + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile("packages.config", packagesConfig) + .ExecuteDetector() + .ConfigureAwait(true); + + var detectedComponents = componentRecorder.GetDetectedComponents(); + detectedComponents.Should().NotBeEmpty() + .And.HaveCount(2) + .And.ContainEquivalentOf(new DetectedComponent(new NuGetComponent("jQuery", "3.1.1"))) + .And.ContainEquivalentOf(new DetectedComponent(new NuGetComponent("NLog", "4.3.10"))); + } + } +} diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Microsoft.ComponentDetection.Orchestrator.Tests.csproj b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Microsoft.ComponentDetection.Orchestrator.Tests.csproj index 07f1cb5ff..4c8f8ca6e 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Microsoft.ComponentDetection.Orchestrator.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Microsoft.ComponentDetection.Orchestrator.Tests.csproj @@ -1,16 +1,8 @@ - - AnyCPU - - - - AnyCPU - - - - + + diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeDevCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeDevCommandServiceTests.cs index 4cead4c31..a9d29edb5 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeDevCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeDevCommandServiceTests.cs @@ -24,10 +24,10 @@ public class BcdeDevCommandServiceTests [TestInitialize] public void InitializeTest() { - scanExecutionServiceMock = new Mock(); - serviceUnderTest = new BcdeDevCommandService(); + this.scanExecutionServiceMock = new Mock(); + this.serviceUnderTest = new BcdeDevCommandService(); - scannedComponents = new ScannedComponent[] + this.scannedComponents = new ScannedComponent[] { new ScannedComponent { @@ -39,13 +39,13 @@ public void InitializeTest() var executeScanAsyncResult = new ScanResult { DetectorsInScan = new List(), - ComponentsFound = scannedComponents, + ComponentsFound = this.scannedComponents, ContainerDetailsMap = new Dictionary(), ResultCode = ProcessingResultCode.Success, SourceDirectory = "D:\\test\\directory", }; - scanExecutionServiceMock.Setup(x => x.ExecuteScanAsync(It.IsAny())) + this.scanExecutionServiceMock.Setup(x => x.ExecuteScanAsync(It.IsAny())) .ReturnsAsync(executeScanAsyncResult); } @@ -54,12 +54,12 @@ public void RunComponentDetection() { var args = new BcdeArguments(); - serviceUnderTest = new BcdeDevCommandService + this.serviceUnderTest = new BcdeDevCommandService { - BcdeScanExecutionService = scanExecutionServiceMock.Object, + BcdeScanExecutionService = this.scanExecutionServiceMock.Object, }; - var result = serviceUnderTest.Handle(args); + var result = this.serviceUnderTest.Handle(args); result.Result.ResultCode.Should().Be(ProcessingResultCode.Success); result.Result.SourceDirectory.Should().Be("D:\\test\\directory"); } diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs index fd45ee1df..572bf483a 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs @@ -41,54 +41,54 @@ public class BcdeScanExecutionServiceTests [TestInitialize] public void InitializeTest() { - loggerMock = new Mock(); - detectorProcessingServiceMock = new Mock(); - detectorRegistryServiceMock = new Mock(); - detectorRestrictionServiceMock = new Mock(); - componentDetector2Mock = new Mock(); - componentDetector3Mock = new Mock(); - versionedComponentDetector1Mock = new Mock(); - sampleContainerDetails = new ContainerDetails { Id = 1 }; + this.loggerMock = new Mock(); + this.detectorProcessingServiceMock = new Mock(); + this.detectorRegistryServiceMock = new Mock(); + this.detectorRestrictionServiceMock = new Mock(); + this.componentDetector2Mock = new Mock(); + this.componentDetector3Mock = new Mock(); + this.versionedComponentDetector1Mock = new Mock(); + this.sampleContainerDetails = new ContainerDetails { Id = 1 }; var defaultGraphTranslationService = new DefaultGraphTranslationService { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; - contentByFileInfo = new Dictionary(); + this.contentByFileInfo = new Dictionary(); - detectedComponents = new[] + this.detectedComponents = new[] { new DetectedComponent(new NpmComponent("some-npm-component", "1.2.3")), new DetectedComponent(new NuGetComponent("SomeNugetComponent", "1.2.3.4")), }; - serviceUnderTest = new BcdeScanExecutionService + this.serviceUnderTest = new BcdeScanExecutionService { - DetectorProcessingService = detectorProcessingServiceMock.Object, - DetectorRegistryService = detectorRegistryServiceMock.Object, - DetectorRestrictionService = detectorRestrictionServiceMock.Object, - Logger = loggerMock.Object, + DetectorProcessingService = this.detectorProcessingServiceMock.Object, + DetectorRegistryService = this.detectorRegistryServiceMock.Object, + DetectorRestrictionService = this.detectorRestrictionServiceMock.Object, + Logger = this.loggerMock.Object, GraphTranslationServices = new List> { new Lazy(() => defaultGraphTranslationService, new GraphTranslationServiceMetadata()), }, }; - sourceDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); + this.sourceDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); - sourceDirectory.Create(); + this.sourceDirectory.Create(); } [TestCleanup] public void CleanupTests() { - detectorProcessingServiceMock.VerifyAll(); - detectorRegistryServiceMock.VerifyAll(); - detectorRestrictionServiceMock.VerifyAll(); + this.detectorProcessingServiceMock.VerifyAll(); + this.detectorRegistryServiceMock.VerifyAll(); + this.detectorRestrictionServiceMock.VerifyAll(); try { - sourceDirectory.Delete(true); + this.sourceDirectory.Delete(true); } catch { @@ -99,36 +99,37 @@ public void CleanupTests() public void DetectComponents_HappyPath() { var componentRecorder = new ComponentRecorder(); - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(sourceDirectory.FullName, "/some/file/path")); + var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(this.sourceDirectory.FullName, "/some/file/path")); - componentDetector2Mock.SetupGet(x => x.Id).Returns("Detector2"); - componentDetector2Mock.SetupGet(x => x.Version).Returns(1); - componentDetector3Mock.SetupGet(x => x.Id).Returns("Detector3"); - componentDetector3Mock.SetupGet(x => x.Version).Returns(10); + this.componentDetector2Mock.SetupGet(x => x.Id).Returns("Detector2"); + this.componentDetector2Mock.SetupGet(x => x.Version).Returns(1); + this.componentDetector3Mock.SetupGet(x => x.Id).Returns("Detector3"); + this.componentDetector3Mock.SetupGet(x => x.Version).Returns(10); - detectedComponents[0].DevelopmentDependency = true; - detectedComponents[0].ContainerDetailIds = new HashSet { sampleContainerDetails.Id }; - singleFileComponentRecorder.RegisterUsage(detectedComponents[0], isDevelopmentDependency: true); + this.detectedComponents[0].DevelopmentDependency = true; + this.detectedComponents[0].ContainerDetailIds = new HashSet { + this.sampleContainerDetails.Id }; + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0], isDevelopmentDependency: true); var parentPipComponent = new PipComponent("sample-root", "1.0"); - detectedComponents[1].DependencyRoots = new HashSet(new[] { parentPipComponent }); - detectedComponents[1].DevelopmentDependency = null; + this.detectedComponents[1].DependencyRoots = new HashSet(new[] { parentPipComponent }); + this.detectedComponents[1].DevelopmentDependency = null; singleFileComponentRecorder.RegisterUsage(new DetectedComponent(parentPipComponent, detector: new PipComponentDetector()), isExplicitReferencedDependency: true); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1], parentComponentId: parentPipComponent.Id); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1], parentComponentId: parentPipComponent.Id); var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; - var result = DetectComponentsHappyPath(args, restrictions => + var result = this.DetectComponentsHappyPath(args, restrictions => { restrictions.AllowedDetectorCategories.Should().BeNull(); restrictions.AllowedDetectorIds.Should().BeNull(); }, new List { componentRecorder }); result.Result.Should().Be(ProcessingResultCode.Success); - ValidateDetectedComponents(result.DetectedComponents); + this.ValidateDetectedComponents(result.DetectedComponents); result.DetectorsInRun.Count().Should().Be(2); var detector2 = result.DetectorsInRun.Single(x => x.DetectorId == "Detector2"); detector2.Version.Should().Be(1); @@ -155,22 +156,22 @@ public void DetectComponents_DetectOnlyWithIdAndCategoryRestrictions() DetectorCategories = new[] { "Category1", "Category2" }, DetectorsFilter = new[] { "Detector1", "Detector2" }, AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/location"); - singleFileComponentRecorder.RegisterUsage(detectedComponents[0]); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1]); - var result = DetectComponentsHappyPath(args, restrictions => + var result = this.DetectComponentsHappyPath(args, restrictions => { restrictions.AllowedDetectorCategories.Should().Contain(args.DetectorCategories); restrictions.AllowedDetectorIds.Should().Contain(args.DetectorsFilter); }, new List { componentRecorder }); result.Result.Should().Be(ProcessingResultCode.Success); - ValidateDetectedComponents(result.DetectedComponents); + this.ValidateDetectedComponents(result.DetectedComponents); } [TestMethod] @@ -179,74 +180,76 @@ public void DetectComponents_DetectOnlyWithNoUrl() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/location"); - singleFileComponentRecorder.RegisterUsage(detectedComponents[0]); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1]); - var result = DetectComponentsHappyPath(args, restrictions => + var result = this.DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); result.Result.Should().Be(ProcessingResultCode.Success); - ValidateDetectedComponents(result.DetectedComponents); + this.ValidateDetectedComponents(result.DetectedComponents); } [TestMethod] public void DetectComponents_ReturnsExperimentalDetectorInformation() { - componentDetector2Mock.As(); - componentDetector3Mock.As(); + this.componentDetector2Mock.As(); + this.componentDetector3Mock.As(); var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/location"); - singleFileComponentRecorder.RegisterUsage(detectedComponents[0]); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1]); - var result = DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); + var result = this.DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); result.Result.Should().Be(ProcessingResultCode.Success); - ValidateDetectedComponents(result.DetectedComponents); + this.ValidateDetectedComponents(result.DetectedComponents); result.DetectorsInRun.All(x => x.IsExperimental).Should().BeTrue(); } [TestMethod] public void DetectComponents_Graph_Happy_Path() { - string mockGraphLocation = "/some/dependency/graph"; + var mockGraphLocation = "/some/dependency/graph"; var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(mockGraphLocation); - singleFileComponentRecorder.RegisterUsage(detectedComponents[0], isExplicitReferencedDependency: true, isDevelopmentDependency: true); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1], isDevelopmentDependency: false, parentComponentId: detectedComponents[0].Component.Id); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0], isExplicitReferencedDependency: true, isDevelopmentDependency: true); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1], isDevelopmentDependency: false, parentComponentId: this.detectedComponents[0].Component.Id); - Mock mockDependencyGraphA = new Mock(); - mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] { detectedComponents[0].Component.Id, detectedComponents[1].Component.Id }); - mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(detectedComponents[0].Component.Id)) - .Returns(new[] { detectedComponents[1].Component.Id }); - mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(detectedComponents[0].Component.Id)).Returns(true); - mockDependencyGraphA.Setup(x => x.IsDevelopmentDependency(detectedComponents[0].Component.Id)).Returns(true); - mockDependencyGraphA.Setup(x => x.IsDevelopmentDependency(detectedComponents[1].Component.Id)).Returns(false); + var mockDependencyGraphA = new Mock(); + mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] { + this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id }); + mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[0].Component.Id)) + .Returns(new[] { + this.detectedComponents[1].Component.Id }); + mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(this.detectedComponents[0].Component.Id)).Returns(true); + mockDependencyGraphA.Setup(x => x.IsDevelopmentDependency(this.detectedComponents[0].Component.Id)).Returns(true); + mockDependencyGraphA.Setup(x => x.IsDevelopmentDependency(this.detectedComponents[1].Component.Id)).Returns(false); - var result = DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); + var result = this.DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); result.SourceDirectory.Should().NotBeNull(); - result.SourceDirectory.Should().Be(sourceDirectory.ToString()); + result.SourceDirectory.Should().Be(this.sourceDirectory.ToString()); result.Result.Should().Be(ProcessingResultCode.Success); result.DependencyGraphs.Count.Should().Be(1); @@ -254,58 +257,62 @@ public void DetectComponents_Graph_Happy_Path() matchingGraph.Key.Should().Be(mockGraphLocation); var explicitlyReferencedComponents = matchingGraph.Value.ExplicitlyReferencedComponentIds; explicitlyReferencedComponents.Count.Should().Be(1); - explicitlyReferencedComponents.Should().Contain(detectedComponents[0].Component.Id); + explicitlyReferencedComponents.Should().Contain(this.detectedComponents[0].Component.Id); var actualGraph = matchingGraph.Value.Graph; actualGraph.Keys.Count.Should().Be(2); - actualGraph[detectedComponents[0].Component.Id].Count.Should().Be(1); - actualGraph[detectedComponents[0].Component.Id].Should().Contain(detectedComponents[1].Component.Id); - actualGraph[detectedComponents[1].Component.Id].Should().BeNull(); + actualGraph[this.detectedComponents[0].Component.Id].Count.Should().Be(1); + actualGraph[this.detectedComponents[0].Component.Id].Should().Contain(this.detectedComponents[1].Component.Id); + actualGraph[this.detectedComponents[1].Component.Id].Should().BeNull(); - matchingGraph.Value.DevelopmentDependencies.Should().Contain(detectedComponents[0].Component.Id); - matchingGraph.Value.DevelopmentDependencies.Should().NotContain(detectedComponents[1].Component.Id); + matchingGraph.Value.DevelopmentDependencies.Should().Contain(this.detectedComponents[0].Component.Id); + matchingGraph.Value.DevelopmentDependencies.Should().NotContain(this.detectedComponents[1].Component.Id); - matchingGraph.Value.Dependencies.Should().Contain(detectedComponents[1].Component.Id); - matchingGraph.Value.Dependencies.Should().NotContain(detectedComponents[0].Component.Id); + matchingGraph.Value.Dependencies.Should().Contain(this.detectedComponents[1].Component.Id); + matchingGraph.Value.Dependencies.Should().NotContain(this.detectedComponents[0].Component.Id); } [TestMethod] public void DetectComponents_Graph_AccumulatesGraphsOnSameLocation() { - string mockGraphLocation = "/some/dependency/graph"; + var mockGraphLocation = "/some/dependency/graph"; var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); - Mock mockDependencyGraphA = new Mock(); - mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] { detectedComponents[0].Component.Id, detectedComponents[1].Component.Id }); - mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(detectedComponents[0].Component.Id)) - .Returns(new[] { detectedComponents[1].Component.Id }); - mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(detectedComponents[0].Component.Id)).Returns(true); + var mockDependencyGraphA = new Mock(); + mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] { + this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id }); + mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[0].Component.Id)) + .Returns(new[] { + this.detectedComponents[1].Component.Id }); + mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(this.detectedComponents[0].Component.Id)).Returns(true); var singleFileComponentRecorderA = componentRecorder.CreateSingleFileComponentRecorder(mockGraphLocation); - singleFileComponentRecorderA.RegisterUsage(detectedComponents[0], isExplicitReferencedDependency: true); - singleFileComponentRecorderA.RegisterUsage(detectedComponents[1], parentComponentId: detectedComponents[0].Component.Id); + singleFileComponentRecorderA.RegisterUsage(this.detectedComponents[0], isExplicitReferencedDependency: true); + singleFileComponentRecorderA.RegisterUsage(this.detectedComponents[1], parentComponentId: this.detectedComponents[0].Component.Id); - Mock mockDependencyGraphB = new Mock(); - mockDependencyGraphB.Setup(x => x.GetComponents()).Returns(new[] { detectedComponents[0].Component.Id, detectedComponents[1].Component.Id }); - mockDependencyGraphB.Setup(x => x.GetDependenciesForComponent(detectedComponents[1].Component.Id)) - .Returns(new[] { detectedComponents[0].Component.Id }); - mockDependencyGraphB.Setup(x => x.IsComponentExplicitlyReferenced(detectedComponents[1].Component.Id)).Returns(true); + var mockDependencyGraphB = new Mock(); + mockDependencyGraphB.Setup(x => x.GetComponents()).Returns(new[] { + this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id }); + mockDependencyGraphB.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[1].Component.Id)) + .Returns(new[] { + this.detectedComponents[0].Component.Id }); + mockDependencyGraphB.Setup(x => x.IsComponentExplicitlyReferenced(this.detectedComponents[1].Component.Id)).Returns(true); var singleFileComponentRecorderB = componentRecorder.CreateSingleFileComponentRecorder(mockGraphLocation); - singleFileComponentRecorderB.RegisterUsage(detectedComponents[1], isExplicitReferencedDependency: true); - singleFileComponentRecorderB.RegisterUsage(detectedComponents[0], parentComponentId: detectedComponents[1].Component.Id); + singleFileComponentRecorderB.RegisterUsage(this.detectedComponents[1], isExplicitReferencedDependency: true); + singleFileComponentRecorderB.RegisterUsage(this.detectedComponents[0], parentComponentId: this.detectedComponents[1].Component.Id); - var result = DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); + var result = this.DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); result.SourceDirectory.Should().NotBeNull(); - result.SourceDirectory.Should().Be(sourceDirectory.ToString()); + result.SourceDirectory.Should().Be(this.sourceDirectory.ToString()); result.Result.Should().Be(ProcessingResultCode.Success); result.DependencyGraphs.Count.Should().Be(1); @@ -313,15 +320,15 @@ public void DetectComponents_Graph_AccumulatesGraphsOnSameLocation() matchingGraph.Key.Should().Be(mockGraphLocation); var explicitlyReferencedComponents = matchingGraph.Value.ExplicitlyReferencedComponentIds; explicitlyReferencedComponents.Count.Should().Be(2); - explicitlyReferencedComponents.Should().Contain(detectedComponents[0].Component.Id); - explicitlyReferencedComponents.Should().Contain(detectedComponents[1].Component.Id); + explicitlyReferencedComponents.Should().Contain(this.detectedComponents[0].Component.Id); + explicitlyReferencedComponents.Should().Contain(this.detectedComponents[1].Component.Id); var actualGraph = matchingGraph.Value.Graph; actualGraph.Keys.Count.Should().Be(2); - actualGraph[detectedComponents[0].Component.Id].Count.Should().Be(1); - actualGraph[detectedComponents[0].Component.Id].Should().Contain(detectedComponents[1].Component.Id); - actualGraph[detectedComponents[1].Component.Id].Count.Should().Be(1); - actualGraph[detectedComponents[1].Component.Id].Should().Contain(detectedComponents[0].Component.Id); + actualGraph[this.detectedComponents[0].Component.Id].Count.Should().Be(1); + actualGraph[this.detectedComponents[0].Component.Id].Should().Contain(this.detectedComponents[1].Component.Id); + actualGraph[this.detectedComponents[1].Component.Id].Count.Should().Be(1); + actualGraph[this.detectedComponents[1].Component.Id].Should().Contain(this.detectedComponents[0].Component.Id); } [TestMethod] @@ -332,7 +339,7 @@ public void VerifyTranslation_ComponentsAreReturnedWithDevDependencyInfo() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); @@ -344,7 +351,7 @@ public void VerifyTranslation_ComponentsAreReturnedWithDevDependencyInfo() singleFileComponentRecorder.RegisterUsage(detectedComponent2, isDevelopmentDependency: false); singleFileComponentRecorder.RegisterUsage(detectedComponent3); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var detectedComponents = results.ComponentsFound; @@ -366,7 +373,7 @@ public void VerifyTranslation_RootsFromMultipleLocationsAreAgregated() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location1"); @@ -380,7 +387,7 @@ public void VerifyTranslation_RootsFromMultipleLocationsAreAgregated() var detectedComponent2NewLocation = new DetectedComponent(new NpmComponent("test", "2.0.0"), detector: npmDetector); singleFileComponentRecorder.RegisterUsage(detectedComponent2NewLocation, isExplicitReferencedDependency: true); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var detectedComponents = results.ComponentsFound; @@ -402,7 +409,7 @@ public void VerifyTranslation_ComponentsAreReturnedWithRoots() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); @@ -412,7 +419,7 @@ public void VerifyTranslation_ComponentsAreReturnedWithRoots() singleFileComponentRecorder.RegisterUsage(detectedComponent1, isExplicitReferencedDependency: true); singleFileComponentRecorder.RegisterUsage(detectedComponent2, parentComponentId: detectedComponent1.Component.Id); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var detectedComponents = results.ComponentsFound; @@ -433,7 +440,7 @@ public void VerifyTranslation_DevDependenciesAreMergedWhenSameComponentInDiffere var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var firstRecorder = componentRecorder.CreateSingleFileComponentRecorder("FileA"); @@ -457,7 +464,7 @@ public void VerifyTranslation_DevDependenciesAreMergedWhenSameComponentInDiffere // The hint for reading this test is to know that each "column" you see visually is what's being merged, so componentAWithNoDevDep is being merged "down" into componentAWithDevDepTrue. #pragma warning disable format - foreach ((DetectedComponent component, bool? isDevDep) component in new[] + foreach ((DetectedComponent component, bool? isDevDep) component in new[] { (componentAWithNoDevDep, (bool?)null), (componentAWithDevDepTrue, true), (componentBWithNoDevDep, (bool?)null), (componentBWithDevDepFalse, false), @@ -469,7 +476,7 @@ public void VerifyTranslation_DevDependenciesAreMergedWhenSameComponentInDiffere firstRecorder.RegisterUsage(component.component, isDevelopmentDependency: component.isDevDep); } - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var components = results.ComponentsFound; @@ -487,13 +494,13 @@ public void VerifyTranslation_LocationsAreMergedWhenSameComponentInDifferentFile var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; - var firstRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(sourceDirectory.FullName, "/some/file/path")); - firstRecorder.AddAdditionalRelatedFile(Path.Join(sourceDirectory.FullName, "/some/related/file/1")); - var secondRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(sourceDirectory.FullName, "/some/other/file/path")); - secondRecorder.AddAdditionalRelatedFile(Path.Join(sourceDirectory.FullName, "/some/related/file/2")); + var firstRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(this.sourceDirectory.FullName, "/some/file/path")); + firstRecorder.AddAdditionalRelatedFile(Path.Join(this.sourceDirectory.FullName, "/some/related/file/1")); + var secondRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(this.sourceDirectory.FullName, "/some/other/file/path")); + secondRecorder.AddAdditionalRelatedFile(Path.Join(this.sourceDirectory.FullName, "/some/related/file/2")); var firstComponent = new DetectedComponent(new NpmComponent("test", "1.0.0"), detector: npmDetector); var secondComponent = new DetectedComponent(new NpmComponent("test", "1.0.0"), detector: npmDetector); @@ -501,7 +508,7 @@ public void VerifyTranslation_LocationsAreMergedWhenSameComponentInDifferentFile firstRecorder.RegisterUsage(firstComponent); secondRecorder.RegisterUsage(secondComponent); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var actualComponent = results.ComponentsFound.Single(); @@ -528,7 +535,7 @@ public void VerifyTranslation_RootsAreMergedWhenSameComponentInDifferentFiles() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var firstRecorder = componentRecorder.CreateSingleFileComponentRecorder("FileA"); @@ -546,7 +553,7 @@ public void VerifyTranslation_RootsAreMergedWhenSameComponentInDifferentFiles() secondRecorder.RegisterUsage(root2, isExplicitReferencedDependency: true); secondRecorder.RegisterUsage(secondComponent, parentComponentId: root2.Component.Id); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var actualComponent = results.ComponentsFound.First(c => c.Component.Id == firstComponent.Component.Id); actualComponent.TopLevelReferrers.Count().Should().Be(2); @@ -566,7 +573,7 @@ public void VerifyTranslation_DetectedComponentExist_UpdateFunctionIsApplied() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); @@ -574,12 +581,12 @@ public void VerifyTranslation_DetectedComponentExist_UpdateFunctionIsApplied() singleFileComponentRecorder.RegisterUsage(detectedComponent, isDevelopmentDependency: true); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); results.ComponentsFound.Where(component => component.Component.Id == detectedComponent.Component.Id).Single().IsDevelopmentDependency.Should().BeTrue(); singleFileComponentRecorder.RegisterUsage(detectedComponent, isDevelopmentDependency: false); - results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); results.ComponentsFound.Where(component => component.Component.Id == detectedComponent.Component.Id).Single().IsDevelopmentDependency.Should().BeFalse(); } @@ -588,11 +595,14 @@ private TestOutput DetectComponentsHappyPath( Action restrictionAsserter = null, IEnumerable componentRecorders = null) { - var registeredDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object, versionedComponentDetector1Mock.Object }; - var restrictedDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object }; - detectorRegistryServiceMock.Setup(x => x.GetDetectors(Enumerable.Empty(), It.IsAny>())) + var registeredDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, + this.versionedComponentDetector1Mock.Object }; + var restrictedDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object }; + this.detectorRegistryServiceMock.Setup(x => x.GetDetectors(Enumerable.Empty(), It.IsAny>())) .Returns(registeredDetectors); - detectorRestrictionServiceMock.Setup( + this.detectorRestrictionServiceMock.Setup( x => x.ApplyRestrictions( It.IsAny(), It.Is>(inputDetectors => registeredDetectors.Intersect(inputDetectors).Count() == registeredDetectors.Length))) @@ -601,27 +611,28 @@ private TestOutput DetectComponentsHappyPath( (restrictions, detectors) => restrictionAsserter?.Invoke(restrictions)); // We initialize detected component's DetectedBy here because of a Moq constraint -- certain operations (Adding interfaces) have to happen before .Object - detectedComponents[0].DetectedBy = componentDetector2Mock.Object; - detectedComponents[1].DetectedBy = componentDetector3Mock.Object; + this.detectedComponents[0].DetectedBy = this.componentDetector2Mock.Object; + this.detectedComponents[1].DetectedBy = this.componentDetector3Mock.Object; var processingResult = new DetectorProcessingResult { ResultCode = ProcessingResultCode.Success, ContainersDetailsMap = new Dictionary { - { sampleContainerDetails.Id, sampleContainerDetails }, + { + this.sampleContainerDetails.Id, this.sampleContainerDetails }, }, - ComponentRecorders = componentRecorders.Select(componentRecorder => (componentDetector2Mock.Object, componentRecorder)), + ComponentRecorders = componentRecorders.Select(componentRecorder => (this.componentDetector2Mock.Object, componentRecorder)), }; - detectorProcessingServiceMock.Setup(x => + this.detectorProcessingServiceMock.Setup(x => x.ProcessDetectorsAsync( args, It.Is>(inputDetectors => restrictedDetectors.Intersect(inputDetectors).Count() == restrictedDetectors.Length), Match.Create(restriction => true))) .ReturnsAsync(processingResult); - var result = serviceUnderTest.ExecuteScanAsync(args).Result; + var result = this.serviceUnderTest.ExecuteScanAsync(args).Result; result.ResultCode.Should().Be(ProcessingResultCode.Success); result.SourceDirectory.Should().NotBeNull(); result.SourceDirectory.Should().Be(args.SourceDirectorySerialized); @@ -635,38 +646,42 @@ private ScanResult SetupRecorderBasedScanning( BcdeArguments args, IEnumerable componentRecorders) { - var registeredDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object, versionedComponentDetector1Mock.Object }; - var restrictedDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object }; - detectorRegistryServiceMock.Setup(x => x.GetDetectors(Enumerable.Empty(), It.IsAny>())) + var registeredDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, + this.versionedComponentDetector1Mock.Object }; + var restrictedDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object }; + this.detectorRegistryServiceMock.Setup(x => x.GetDetectors(Enumerable.Empty(), It.IsAny>())) .Returns(registeredDetectors); - detectorRestrictionServiceMock.Setup( + this.detectorRestrictionServiceMock.Setup( x => x.ApplyRestrictions( It.IsAny(), It.Is>(inputDetectors => registeredDetectors.Intersect(inputDetectors).Count() == registeredDetectors.Length))) .Returns(restrictedDetectors); // We initialize detected component's DetectedBy here because of a Moq constraint -- certain operations (Adding interfaces) have to happen before .Object - detectedComponents[0].DetectedBy = componentDetector2Mock.Object; - detectedComponents[1].DetectedBy = componentDetector3Mock.Object; + this.detectedComponents[0].DetectedBy = this.componentDetector2Mock.Object; + this.detectedComponents[1].DetectedBy = this.componentDetector3Mock.Object; var processingResult = new DetectorProcessingResult { ResultCode = ProcessingResultCode.Success, ContainersDetailsMap = new Dictionary { - { sampleContainerDetails.Id, sampleContainerDetails }, + { + this.sampleContainerDetails.Id, this.sampleContainerDetails }, }, - ComponentRecorders = componentRecorders.Select(componentRecorder => (componentDetector2Mock.Object, componentRecorder)), + ComponentRecorders = componentRecorders.Select(componentRecorder => (this.componentDetector2Mock.Object, componentRecorder)), }; - detectorProcessingServiceMock.Setup(x => + this.detectorProcessingServiceMock.Setup(x => x.ProcessDetectorsAsync( args, It.Is>(inputDetectors => restrictedDetectors.Intersect(inputDetectors).Count() == restrictedDetectors.Length), Match.Create(restriction => true))) .ReturnsAsync(processingResult); - var result = serviceUnderTest.ExecuteScanAsync(args).Result; + var result = this.serviceUnderTest.ExecuteScanAsync(args).Result; result.ResultCode.Should().Be(ProcessingResultCode.Success); result.SourceDirectory.Should().NotBeNull(); result.SourceDirectory.Should().Be(args.SourceDirectorySerialized); @@ -678,21 +693,21 @@ private void ValidateDetectedComponents(IEnumerable scannedCom { var npmComponent = scannedComponents.Where(x => x.Component.Type == ComponentType.Npm).Select(x => x.Component as NpmComponent).FirstOrDefault(); npmComponent.Should().NotBeNull(); - npmComponent.Name.Should().Be(((NpmComponent)detectedComponents[0].Component).Name); + npmComponent.Name.Should().Be(((NpmComponent)this.detectedComponents[0].Component).Name); var nugetComponent = scannedComponents.Where(x => x.Component.Type == ComponentType.NuGet).Select(x => x.Component as NuGetComponent).FirstOrDefault(); nugetComponent.Should().NotBeNull(); - nugetComponent.Name.Should().Be(((NuGetComponent)detectedComponents[1].Component).Name); + nugetComponent.Name.Should().Be(((NuGetComponent)this.detectedComponents[1].Component).Name); } private class TestOutput { public TestOutput(DefaultGraphScanResult result) { - Result = result.ResultCode; - DetectedComponents = result.ComponentsFound; - DetectorsInRun = result.DetectorsInScan; - DependencyGraphs = result.DependencyGraphs; - SourceDirectory = result.SourceDirectory; + this.Result = result.ResultCode; + this.DetectedComponents = result.ComponentsFound; + this.DetectorsInRun = result.DetectorsInScan; + this.DependencyGraphs = result.DependencyGraphs; + this.SourceDirectory = result.SourceDirectory; } internal ProcessingResultCode Result { get; set; } diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorListingCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorListingCommandServiceTests.cs index c5e3958b6..d1d76c376 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorListingCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorListingCommandServiceTests.cs @@ -28,48 +28,50 @@ public class DetectorListingCommandServiceTests [TestInitialize] public void InitializeTest() { - loggerMock = new Mock(); - detectorRegistryServiceMock = new Mock(); - componentDetector2Mock = new Mock(); - componentDetector3Mock = new Mock(); - versionedComponentDetector1Mock = new Mock(); + this.loggerMock = new Mock(); + this.detectorRegistryServiceMock = new Mock(); + this.componentDetector2Mock = new Mock(); + this.componentDetector3Mock = new Mock(); + this.versionedComponentDetector1Mock = new Mock(); - serviceUnderTest = new DetectorListingCommandService + this.serviceUnderTest = new DetectorListingCommandService { - DetectorRegistryService = detectorRegistryServiceMock.Object, - Logger = loggerMock.Object, + DetectorRegistryService = this.detectorRegistryServiceMock.Object, + Logger = this.loggerMock.Object, }; - logOutput = new List(); - loggerMock.Setup(x => x.LogInfo(It.IsAny())).Callback(loggedString => + this.logOutput = new List(); + this.loggerMock.Setup(x => x.LogInfo(It.IsAny())).Callback(loggedString => { - logOutput.Add(loggedString); + this.logOutput.Add(loggedString); }); - componentDetector2Mock.SetupGet(x => x.Id).Returns("ComponentDetector2"); - componentDetector3Mock.SetupGet(x => x.Id).Returns("ComponentDetector3"); - versionedComponentDetector1Mock.SetupGet(x => x.Id).Returns("VersionedComponentDetector"); + this.componentDetector2Mock.SetupGet(x => x.Id).Returns("ComponentDetector2"); + this.componentDetector3Mock.SetupGet(x => x.Id).Returns("ComponentDetector3"); + this.versionedComponentDetector1Mock.SetupGet(x => x.Id).Returns("VersionedComponentDetector"); - var registeredDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object, versionedComponentDetector1Mock.Object }; - detectorRegistryServiceMock.Setup(x => x.GetDetectors(It.IsAny>(), It.IsAny>())) + var registeredDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, + this.versionedComponentDetector1Mock.Object }; + this.detectorRegistryServiceMock.Setup(x => x.GetDetectors(It.IsAny>(), It.IsAny>())) .Returns(registeredDetectors); } [TestCleanup] public void CleanupTests() { - detectorRegistryServiceMock.VerifyAll(); + this.detectorRegistryServiceMock.VerifyAll(); } [TestMethod] public async Task DetectorListingCommandService_ListsDetectors() { - var result = await serviceUnderTest.Handle(new ListDetectionArgs()); + var result = await this.serviceUnderTest.Handle(new ListDetectionArgs()); result.ResultCode.Should().Be(ProcessingResultCode.Success); - logOutput.Should().Contain("ComponentDetector2"); - logOutput.Should().Contain("ComponentDetector3"); - logOutput.Should().Contain("VersionedComponentDetector"); + this.logOutput.Should().Contain("ComponentDetector2"); + this.logOutput.Should().Contain("ComponentDetector3"); + this.logOutput.Should().Contain("VersionedComponentDetector"); } } } diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs index a433af0c5..31f07dd3e 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs @@ -58,29 +58,29 @@ private IndividualDetectorScanResult ExpectedResultForDetector(string detectorId [TestInitialize] public void TestInit() { - loggerMock = new Mock(); - serviceUnderTest = new DetectorProcessingService + this.loggerMock = new Mock(); + this.serviceUnderTest = new DetectorProcessingService { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; - directoryWalkerFactory = new FastDirectoryWalkerFactory() + this.directoryWalkerFactory = new FastDirectoryWalkerFactory() { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, PathUtilityService = new PathUtilityService(), }; - serviceUnderTest.Scanner = directoryWalkerFactory; + this.serviceUnderTest.Scanner = this.directoryWalkerFactory; - firstFileComponentDetectorMock = SetupFileDetectorMock("firstFileDetectorId"); - secondFileComponentDetectorMock = SetupFileDetectorMock("secondFileDetectorId"); - experimentalFileComponentDetectorMock = SetupFileDetectorMock("experimentalFileDetectorId"); - experimentalFileComponentDetectorMock.As(); + this.firstFileComponentDetectorMock = this.SetupFileDetectorMock("firstFileDetectorId"); + this.secondFileComponentDetectorMock = this.SetupFileDetectorMock("secondFileDetectorId"); + this.experimentalFileComponentDetectorMock = this.SetupFileDetectorMock("experimentalFileDetectorId"); + this.experimentalFileComponentDetectorMock.As(); - firstCommandComponentDetectorMock = SetupCommandDetectorMock("firstCommandDetectorId"); - secondCommandComponentDetectorMock = SetupCommandDetectorMock("secondCommandDetectorId"); + this.firstCommandComponentDetectorMock = this.SetupCommandDetectorMock("firstCommandDetectorId"); + this.secondCommandComponentDetectorMock = this.SetupCommandDetectorMock("secondCommandDetectorId"); - isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + this.isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } private Mock SetupFileDetectorMock(string id) @@ -90,9 +90,9 @@ private Mock SetupFileDetectorMock(string id) mockFileDetector.SetupGet(x => x.Id).Returns(id); var sourceDirectory = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "Some", "Source", "Directory")); - componentDictionary.Should().ContainKey(id, $"MockDetector id:{id}, should be in mock dictionary"); + this.componentDictionary.Should().ContainKey(id, $"MockDetector id:{id}, should be in mock dictionary"); - var expectedResult = ExpectedResultForDetector(id); + var expectedResult = this.ExpectedResultForDetector(id); mockFileDetector.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory && request.ComponentRecorder != null))).ReturnsAsync( (ScanRequest request) => @@ -102,8 +102,8 @@ private Mock SetupFileDetectorMock(string id) mockFileDetector.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory && request.ComponentRecorder != null))).ReturnsAsync( (ScanRequest request) => { - serviceUnderTest.Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1); - FillComponentRecorder(request.ComponentRecorder, id); + this.serviceUnderTest.Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1); + this.FillComponentRecorder(request.ComponentRecorder, id); return expectedResult; }).Verifiable(); @@ -121,14 +121,14 @@ private IEnumerable GetDiscoveredComponentsFromDetectorProces private void FillComponentRecorder(IComponentRecorder componentRecorder, string id) { var singleFileRecorder = componentRecorder.CreateSingleFileComponentRecorder("/mock/location"); - singleFileRecorder.RegisterUsage(componentDictionary[id], false); + singleFileRecorder.RegisterUsage(this.componentDictionary[id], false); } private void ValidateExpectedComponents(DetectorProcessingResult result, IEnumerable detectorsRan) { var shouldBePresent = detectorsRan.Where(detector => !(detector is IExperimentalDetector)) - .Select(detector => componentDictionary[detector.Id]); - var isPresent = GetDiscoveredComponentsFromDetectorProcessingResult(result); + .Select(detector => this.componentDictionary[detector.Id]); + var isPresent = this.GetDiscoveredComponentsFromDetectorProcessingResult(result); var check = isPresent.Select(i => i.GetType()); @@ -142,13 +142,13 @@ private Mock SetupCommandDetectorMock(string id) mockCommandDetector.SetupAllProperties(); mockCommandDetector.SetupGet(x => x.Id).Returns(id); - componentDictionary.Should().ContainKey(id, $"MockDetector id:{id}, should be in mock dictionary"); + this.componentDictionary.Should().ContainKey(id, $"MockDetector id:{id}, should be in mock dictionary"); mockCommandDetector.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory && !request.DetectorArgs.Any()))).ReturnsAsync( (ScanRequest request) => { - FillComponentRecorder(request.ComponentRecorder, id); - return ExpectedResultForDetector(id); + this.FillComponentRecorder(request.ComponentRecorder, id); + return this.ExpectedResultForDetector(id); }).Verifiable(); return mockCommandDetector; @@ -157,17 +157,18 @@ private Mock SetupCommandDetectorMock(string id) [TestMethod] public void ProcessDetectorsAsync_HappyPathReturnsDetectedComponents() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object }; - var results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object }; + var results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - ValidateExpectedComponents(results, detectorsToUse); - GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => x.Component?.Type == ComponentType.Npm).Component - .Should().Be(componentDictionary[firstFileComponentDetectorMock.Object.Id].Component); - GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => x.Component?.Type == ComponentType.NuGet).Component - .Should().Be(componentDictionary[secondFileComponentDetectorMock.Object.Id].Component); + this.ValidateExpectedComponents(results, this.detectorsToUse); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => x.Component?.Type == ComponentType.Npm).Component + .Should().Be(this.componentDictionary[this.firstFileComponentDetectorMock.Object.Id].Component); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => x.Component?.Type == ComponentType.NuGet).Component + .Should().Be(this.componentDictionary[this.secondFileComponentDetectorMock.Object.Id].Component); results.ResultCode.Should().Be(ProcessingResultCode.Success); } @@ -175,7 +176,7 @@ public void ProcessDetectorsAsync_HappyPathReturnsDetectedComponents() [TestMethod] public void ProcessDetectorsAsync_NullDetectedComponentsReturnIsCoalesced() { - Mock mockComponentDetector = new Mock(); + var mockComponentDetector = new Mock(); mockComponentDetector.Setup(d => d.Id).Returns("test"); mockComponentDetector.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) @@ -189,8 +190,8 @@ public void ProcessDetectorsAsync_NullDetectedComponentsReturnIsCoalesced() }; }); - detectorsToUse = new[] { mockComponentDetector.Object }; - var results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + this.detectorsToUse = new[] { mockComponentDetector.Object }; + var results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; results.ResultCode.Should().Be(ProcessingResultCode.Success); } @@ -198,16 +199,17 @@ public void ProcessDetectorsAsync_NullDetectedComponentsReturnIsCoalesced() [TestMethod] public void ProcessDetectorsAsync_HappyPathReturns_DependencyGraph() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object }; - var results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object }; + var results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - foreach (var discoveredComponent in GetDiscoveredComponentsFromDetectorProcessingResult(results)) + foreach (var discoveredComponent in this.GetDiscoveredComponentsFromDetectorProcessingResult(results)) { var componentId = discoveredComponent.Component.Id; - bool isMatched = false; + var isMatched = false; foreach (var graph in results.ComponentRecorders.Select(componentRecorder => componentRecorder.Item2.GetDependencyGraphsByLocation()).SelectMany(x => x.Values)) { isMatched |= graph.GetComponents().Contains(componentId); @@ -220,10 +222,11 @@ public void ProcessDetectorsAsync_HappyPathReturns_DependencyGraph() [TestMethod] public void ProcessDetectorsAsync_AdditionalTelemetryDetailsAreReturned() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object }; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Wait(); }); foreach (var record in records) @@ -236,16 +239,18 @@ public void ProcessDetectorsAsync_AdditionalTelemetryDetailsAreReturned() [TestMethod] public void ProcessDetectorsAsync_ExperimentalDetectorsDoNotReturnComponents() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object, experimentalFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, + this.experimentalFileComponentDetectorMock.Object }; DetectorProcessingResult results = null; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; }); - var experimentalDetectorRecord = records.FirstOrDefault(x => x.DetectorId == experimentalFileComponentDetectorMock.Object.Id); - var experimentalComponent = componentDictionary[experimentalFileComponentDetectorMock.Object.Id].Component as NuGetComponent; + var experimentalDetectorRecord = records.FirstOrDefault(x => x.DetectorId == this.experimentalFileComponentDetectorMock.Object.Id); + var experimentalComponent = this.componentDictionary[this.experimentalFileComponentDetectorMock.Object.Id].Component as NuGetComponent; // protect against test code changes. experimentalComponent.Name.Should().NotBeNullOrEmpty("Experimental component should be nuget and have a name"); @@ -255,54 +260,58 @@ public void ProcessDetectorsAsync_ExperimentalDetectorsDoNotReturnComponents() experimentalDetectorRecord.IsExperimental.Should().BeTrue(); // We should have all components except the ones that came from our experimental detector - GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount) - experimentalDetectorRecord.DetectedComponentCount); - GetDiscoveredComponentsFromDetectorProcessingResult(results).All(x => (x.Component as NuGetComponent)?.Name != experimentalComponent.Name) + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount) - experimentalDetectorRecord.DetectedComponentCount); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).All(x => (x.Component as NuGetComponent)?.Name != experimentalComponent.Name) .Should().BeTrue("Experimental component should not be in component list"); results.ResultCode.Should().Be(ProcessingResultCode.Success); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - experimentalFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.experimentalFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_ExperimentalDetectorsDoNormalStuffIfExplicitlyEnabled() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object, experimentalFileComponentDetectorMock.Object }; - var experimentalDetectorId = experimentalFileComponentDetectorMock.Object.Id; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, + this.experimentalFileComponentDetectorMock.Object }; + var experimentalDetectorId = this.experimentalFileComponentDetectorMock.Object.Id; DetectorProcessingResult results = null; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions { ExplicitlyEnabledDetectorIds = new[] { experimentalDetectorId } }).Result; + results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions { ExplicitlyEnabledDetectorIds = new[] { experimentalDetectorId } }).Result; }); // We should have all components except the ones that came from our experimental detector - GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount)); - GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => (x.Component as NuGetComponent)?.Name == (componentDictionary[experimentalDetectorId].Component as NuGetComponent).Name) + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount)); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => (x.Component as NuGetComponent)?.Name == (this.componentDictionary[experimentalDetectorId].Component as NuGetComponent).Name) .Should().NotBeNull(); results.ResultCode.Should().Be(ProcessingResultCode.Success); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - experimentalFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.experimentalFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_ExperimentalDetectorsThrowingDoesntKillDetection() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object, experimentalFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, + this.experimentalFileComponentDetectorMock.Object }; - experimentalFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))) + this.experimentalFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))) .Throws(new InvalidOperationException("Simulated experimental failure")); DetectorProcessingResult results = null; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; }); - var experimentalDetectorRecord = records.FirstOrDefault(x => x.DetectorId == experimentalFileComponentDetectorMock.Object.Id); + var experimentalDetectorRecord = records.FirstOrDefault(x => x.DetectorId == this.experimentalFileComponentDetectorMock.Object.Id); experimentalDetectorRecord.Should().NotBeNull(); experimentalDetectorRecord.DetectedComponentCount.Should().Be(0); experimentalDetectorRecord.IsExperimental.Should().BeTrue(); @@ -310,17 +319,18 @@ public void ProcessDetectorsAsync_ExperimentalDetectorsThrowingDoesntKillDetecti experimentalDetectorRecord.ExperimentalInformation.Contains("Simulated experimental failure"); // We should have all components except the ones that came from our experimental detector - GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount)); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount)); results.ResultCode.Should().Be(ProcessingResultCode.Success); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpected() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object }; if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Inconclusive("Test is platform specific and fails on non-windows"); @@ -330,13 +340,13 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpected() var d2 = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "shouldNotExclude", "stuff")); ScanRequest capturedRequest = null; - firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) - .ReturnsAsync(ExpectedResultForDetector(firstFileComponentDetectorMock.Object.Id)) + this.firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) + .ReturnsAsync(this.ExpectedResultForDetector(this.firstFileComponentDetectorMock.Object.Id)) .Callback(request => capturedRequest = request); - serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Wait(); - directoryWalkerFactory.Reset(); + this.directoryWalkerFactory.Reset(); // Base case should match all directories. capturedRequest.DirectoryExclusionPredicate(defaultArgs.SourceDirectory.Name, defaultArgs.SourceDirectory.Parent.Name).Should().BeFalse(); @@ -350,9 +360,9 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpected() }; // Now exercise the exclusion code - serviceUnderTest.ProcessDetectorsAsync(argsWithExclusion, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(argsWithExclusion, this.detectorsToUse, new DetectorRestrictions()).Wait(); - directoryWalkerFactory.Reset(); + this.directoryWalkerFactory.Reset(); // Previous two tests should now exclude capturedRequest.DirectoryExclusionPredicate(defaultArgs.SourceDirectory.Name, defaultArgs.SourceDirectory.Parent.FullName).Should().BeTrue(); @@ -385,46 +395,47 @@ public void GenerateDirectoryExclusionPredicate_IgnoreCaseAndAllowWindowsPathsWo // This unit test previously depended on defaultArgs. But the author assumed that \Source\ was in the default source path, which may not be true on all developers machines. // control this more explicitly. - BcdeArguments args = new BcdeArguments { SourceDirectory = new System.IO.DirectoryInfo(isWin ? @"C:\Some\Source\Directory" : "/c/Some/Source/Directory"), DetectorArgs = Enumerable.Empty() }; + var args = new BcdeArguments { SourceDirectory = new DirectoryInfo(this.isWin ? @"C:\Some\Source\Directory" : "/c/Some/Source/Directory"), DetectorArgs = Enumerable.Empty() }; var dn = args.SourceDirectory.Name.AsSpan(); var dp = args.SourceDirectory.Parent.FullName.AsSpan(); // Exclusion predicate is case sensitive and allow windows path, the exclusion list follow the windows path structure and has a case mismatch with the directory path, should not exclude args.DirectoryExclusionList = new[] { @"**\source\**" }; - var exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); + var exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); Assert.IsFalse(exclusionPredicate(dn, dp)); // Exclusion predicate is case sensitive and allow windows path, the exclusion list follow the windows path structure and match directory path case, should exclude args.DirectoryExclusionList = new[] { @"**\Source\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); Assert.IsTrue(exclusionPredicate(dn, dp)); // Exclusion predicate is not case sensitive and allow windows path, the exclusion list follow the windows path, should exclude args.DirectoryExclusionList = new[] { @"**\sOuRce\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); Assert.IsTrue(exclusionPredicate(dn, dp)); // Exclusion predicate does not support windows path and the exclusion list define the path as a windows path, should not exclude args.DirectoryExclusionList = new[] { @"**\Source\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: true); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: true); Assert.IsFalse(exclusionPredicate(dn, dp)); // Exclusion predicate support windows path and the exclusion list define the path as a windows path, should exclude args.DirectoryExclusionList = new[] { @"**\Source\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); Assert.IsTrue(exclusionPredicate(dn, dp)); // Exclusion predicate support windows path and the exclusion list does not define a windows path, should exclude args.DirectoryExclusionList = new[] { @"**/Source/**", @"**/Source\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); Assert.IsTrue(exclusionPredicate(dn, dp)); } [TestMethod] public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForObsolete() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object }; var sourceDirectory = defaultSourceDirectory; var args = defaultArgs; var d1 = new DirectoryInfo(Path.Combine(sourceDirectory.FullName, "Child")); @@ -442,13 +453,13 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForO Environment.CurrentDirectory = sourceDirectory.FullName; ScanRequest capturedRequest = null; - firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) - .ReturnsAsync(ExpectedResultForDetector(firstFileComponentDetectorMock.Object.Id)) + this.firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) + .ReturnsAsync(this.ExpectedResultForDetector(this.firstFileComponentDetectorMock.Object.Id)) .Callback(request => capturedRequest = request); - serviceUnderTest.ProcessDetectorsAsync(args, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(args, this.detectorsToUse, new DetectorRestrictions()).Wait(); - directoryWalkerFactory.Reset(); + this.directoryWalkerFactory.Reset(); // Base case should match all directories. capturedRequest.DirectoryExclusionPredicate(args.SourceDirectory.Name.AsSpan(), args.SourceDirectory.Parent.FullName.AsSpan()).Should().BeFalse(); @@ -456,9 +467,10 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForO // Now exercise the exclusion code args.DirectoryExclusionListObsolete = new[] { Path.Combine("Child"), Path.Combine("..", "bin") }; - serviceUnderTest.ProcessDetectorsAsync(args, new[] { firstFileComponentDetectorMock.Object }, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(args, new[] { + this.firstFileComponentDetectorMock.Object }, new DetectorRestrictions()).Wait(); - directoryWalkerFactory.Reset(); + this.directoryWalkerFactory.Reset(); // Previous two tests should now exclude capturedRequest.DirectoryExclusionPredicate(d1.Name.AsSpan(), d1.Parent.FullName.AsSpan()).Should().BeTrue(); @@ -471,37 +483,41 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForO [TestMethod] public void ProcessDetectorsAsync_CapturesTelemetry() { - BcdeArguments args = defaultArgs; - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object }; + var args = defaultArgs; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object }; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - serviceUnderTest.ProcessDetectorsAsync(args, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(args, this.detectorsToUse, new DetectorRestrictions()).Wait(); }); records.Should().Contain(x => x is DetectorExecutionTelemetryRecord); records.Count(x => x is DetectorExecutionTelemetryRecord) .Should().Be(2); - var firstDetectorRecord = records.FirstOrDefault(x => x.DetectorId == firstFileComponentDetectorMock.Object.Id); + var firstDetectorRecord = records.FirstOrDefault(x => x.DetectorId == this.firstFileComponentDetectorMock.Object.Id); firstDetectorRecord.Should().NotBeNull(); firstDetectorRecord.ExecutionTime.Should().BePositive(); - var secondDetectorRecord = records.FirstOrDefault(x => x.DetectorId == secondFileComponentDetectorMock.Object.Id); + var secondDetectorRecord = records.FirstOrDefault(x => x.DetectorId == this.secondFileComponentDetectorMock.Object.Id); secondDetectorRecord.Should().NotBeNull(); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_ExecutesMixedCommandAndFileDetectors() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object, firstCommandComponentDetectorMock.Object, secondCommandComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, + this.firstCommandComponentDetectorMock.Object, + this.secondCommandComponentDetectorMock.Object }; DetectorProcessingResult results = null; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; }); results.Should().NotBeNull("Detector processing failed"); @@ -511,26 +527,27 @@ public void ProcessDetectorsAsync_ExecutesMixedCommandAndFileDetectors() records.Count(x => x is DetectorExecutionTelemetryRecord) .Should().Be(4); - ValidateExpectedComponents(results, detectorsToUse); + this.ValidateExpectedComponents(results, this.detectorsToUse); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - firstCommandComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondCommandComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstCommandComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondCommandComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_HandlesDetectorArgs() { ScanRequest capturedRequest = null; - firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) - .ReturnsAsync(ExpectedResultForDetector(firstFileComponentDetectorMock.Object.Id)) + this.firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) + .ReturnsAsync(this.ExpectedResultForDetector(this.firstFileComponentDetectorMock.Object.Id)) .Callback(request => capturedRequest = request); var args = defaultArgs; args.DetectorArgs = new string[] { "arg1=val1", "arg2", "arg3=val3" }; - serviceUnderTest.ProcessDetectorsAsync(defaultArgs, new[] { firstFileComponentDetectorMock.Object }, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, new[] { + this.firstFileComponentDetectorMock.Object }, new DetectorRestrictions()).Wait(); capturedRequest.DetectorArgs .Should().Contain("arg1", "val1") diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs index ca6e99487..21a7541b1 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs @@ -40,34 +40,38 @@ private Mock GenerateDetector(string detectorName, string[] [TestInitialize] public void TestInitialize() { - logger = new Mock(); - firstDetectorMock = GenerateDetector("FirstDetector"); - secondDetectorMock = GenerateDetector("SecondDetector"); - thirdDetectorMock = GenerateDetector("ThirdDetector"); - retiredNpmDetector = GenerateDetector("MSLicenseDevNpm"); - newNpmDetector = GenerateDetector("NpmWithRoots"); - - detectors = new[] { firstDetectorMock.Object, secondDetectorMock.Object, thirdDetectorMock.Object, retiredNpmDetector.Object, newNpmDetector.Object }; - serviceUnderTest = new DetectorRestrictionService() { Logger = logger.Object }; + this.logger = new Mock(); + this.firstDetectorMock = this.GenerateDetector("FirstDetector"); + this.secondDetectorMock = this.GenerateDetector("SecondDetector"); + this.thirdDetectorMock = this.GenerateDetector("ThirdDetector"); + this.retiredNpmDetector = this.GenerateDetector("MSLicenseDevNpm"); + this.newNpmDetector = this.GenerateDetector("NpmWithRoots"); + + this.detectors = new[] { + this.firstDetectorMock.Object, this.secondDetectorMock.Object, + this.thirdDetectorMock.Object, + this.retiredNpmDetector.Object, + this.newNpmDetector.Object }; + this.serviceUnderTest = new DetectorRestrictionService() { Logger = this.logger.Object }; } [TestMethod] public void WithRestrictions_BaseCaseReturnsAll() { - DetectorRestrictions r = new DetectorRestrictions(); - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var r = new DetectorRestrictions(); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(detectors); + .Should().Contain(this.detectors); } [TestMethod] public void WithRestrictions_RemovesDefaultOff() { - DetectorRestrictions r = new DetectorRestrictions(); - var detectorMock = GenerateDetector("defaultOffDetector"); + var r = new DetectorRestrictions(); + var detectorMock = this.GenerateDetector("defaultOffDetector"); var defaultOffDetectorMock = detectorMock.As(); - detectors = detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + this.detectors = this.detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().NotContain(defaultOffDetectorMock.Object as IComponentDetector); } @@ -75,12 +79,12 @@ public void WithRestrictions_RemovesDefaultOff() [TestMethod] public void WithRestrictions_AllowsDefaultOffWithDetectorRestriction() { - DetectorRestrictions r = new DetectorRestrictions(); - var detectorMock = GenerateDetector("defaultOffDetector"); + var r = new DetectorRestrictions(); + var detectorMock = this.GenerateDetector("defaultOffDetector"); var defaultOffDetectorMock = detectorMock.As(); - detectors = detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); + this.detectors = this.detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); r.ExplicitlyEnabledDetectorIds = new[] { "defaultOffDetector" }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().Contain(defaultOffDetectorMock.Object as IComponentDetector); } @@ -92,13 +96,13 @@ public void WithRestrictions_FiltersBasedOnDetectorId() { AllowedDetectorIds = new[] { "FirstDetector", "SecondDetector" }, }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(firstDetectorMock.Object).And.Contain(secondDetectorMock.Object) - .And.NotContain(thirdDetectorMock.Object); + .Should().Contain(this.firstDetectorMock.Object).And.Contain(this.secondDetectorMock.Object) + .And.NotContain(this.thirdDetectorMock.Object); r.AllowedDetectorIds = new[] { "NotARealDetector" }; - Action shouldThrow = () => serviceUnderTest.ApplyRestrictions(r, detectors); + Action shouldThrow = () => this.serviceUnderTest.ApplyRestrictions(r, this.detectors); shouldThrow.Should().Throw(); } @@ -109,19 +113,19 @@ public void WithRestrictions_CorrectsRetiredDetector() { AllowedDetectorIds = new[] { "MSLicenseDevNpm" }, }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(newNpmDetector.Object); + .Should().Contain(this.newNpmDetector.Object); r.AllowedDetectorIds = new[] { "mslicensenpm" }; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(newNpmDetector.Object); + .Should().Contain(this.newNpmDetector.Object); r.AllowedDetectorIds = new[] { "mslicensenpm", "NpmWithRoots" }; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().OnlyContain(item => item == newNpmDetector.Object); + .Should().OnlyContain(item => item == this.newNpmDetector.Object); } [TestMethod] @@ -131,20 +135,20 @@ public void WithRestrictions_FiltersBasedOnCategory() { AllowedDetectorCategories = new[] { "FirstDetectorCategory", "ThirdDetectorCategory" }, }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(firstDetectorMock.Object).And.Contain(thirdDetectorMock.Object) - .And.NotContain(secondDetectorMock.Object); + .Should().Contain(this.firstDetectorMock.Object).And.Contain(this.thirdDetectorMock.Object) + .And.NotContain(this.secondDetectorMock.Object); r.AllowedDetectorCategories = new[] { "AllCategory" }; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(firstDetectorMock.Object) - .And.Contain(thirdDetectorMock.Object) - .And.Contain(secondDetectorMock.Object); + .Should().Contain(this.firstDetectorMock.Object) + .And.Contain(this.thirdDetectorMock.Object) + .And.Contain(this.secondDetectorMock.Object); r.AllowedDetectorCategories = new[] { "NoCategory" }; - Action shouldThrow = () => serviceUnderTest.ApplyRestrictions(r, detectors); + Action shouldThrow = () => this.serviceUnderTest.ApplyRestrictions(r, this.detectors); shouldThrow.Should().Throw(); } @@ -153,30 +157,30 @@ public void WithRestrictions_AlwaysIncludesDetectorsThatSpecifyAllCategory() { var detectors = new[] { - GenerateDetector("1", new[] { "Cat1" }).Object, - GenerateDetector("2", new[] { "Cat2" }).Object, - GenerateDetector("3", new[] { nameof(DetectorClass.All) }).Object, + this.GenerateDetector("1", new[] { "Cat1" }).Object, + this.GenerateDetector("2", new[] { "Cat2" }).Object, + this.GenerateDetector("3", new[] { nameof(DetectorClass.All) }).Object, }; var r = new DetectorRestrictions { AllowedDetectorCategories = new[] { "ACategoryWhichDoesntMatch" }, }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, detectors); restrictedDetectors .Should().Contain(detectors[2]) .And.NotContain(detectors[0]) .And.NotContain(detectors[1]); r.AllowedDetectorCategories = new[] { "Cat1" }; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, detectors); restrictedDetectors .Should().Contain(detectors[0]) .And.Contain(detectors[2]) .And.NotContain(detectors[1]); r.AllowedDetectorCategories = null; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, detectors); restrictedDetectors .Should().Contain(detectors[0]) .And.Contain(detectors[1]) diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/TelemetryHelper.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/TelemetryHelper.cs index ea8b2e45a..0cb81a9c9 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/TelemetryHelper.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/TelemetryHelper.cs @@ -13,8 +13,8 @@ public static class TelemetryHelper public static IEnumerable ExecuteWhileCapturingTelemetry(Action codeToExecute) where T : class, IDetectionTelemetryRecord { - Mock telemetryServiceMock = new Mock(); - ConcurrentBag records = new ConcurrentBag(); + var telemetryServiceMock = new Mock(); + var records = new ConcurrentBag(); telemetryServiceMock.Setup(x => x.PostRecord(It.IsAny())) .Callback(record => { diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs b/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs index aa68f9682..b2bf5bdc8 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs +++ b/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs @@ -30,23 +30,23 @@ public class DetectorTestUtility public async Task<(IndividualDetectorScanResult, IComponentRecorder)> ExecuteDetector() { - if (scanRequest == null) + if (this.scanRequest == null) { - scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder); + this.scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, this.componentRecorder); } else { - componentRecorder = scanRequest.ComponentRecorder; + this.componentRecorder = this.scanRequest.ComponentRecorder; } - InitializeFileRelatedMocksUsingDefaultImplementationIfNecessary(); + this.InitializeFileRelatedMocksUsingDefaultImplementationIfNecessary(); - detector.Scanner = mockObservableDirectoryWalkerFactory.Object; - detector.ComponentStreamEnumerableFactory = mockComponentStreamEnumerableFactory.Object; - detector.Logger = mockLogger.Object; + this.detector.Scanner = this.mockObservableDirectoryWalkerFactory.Object; + this.detector.ComponentStreamEnumerableFactory = this.mockComponentStreamEnumerableFactory.Object; + this.detector.Logger = this.mockLogger.Object; - var scanResult = await detector.ExecuteDetectorAsync(scanRequest); - return (scanResult, componentRecorder); + var scanResult = await this.detector.ExecuteDetectorAsync(this.scanRequest); + return (scanResult, this.componentRecorder); } /// @@ -75,7 +75,7 @@ public DetectorTestUtility WithScanRequest(ScanRequest scanRequest) public DetectorTestUtility WithFile(string fileName, string fileContents, IEnumerable searchPatterns = null, string fileLocation = null) { - return WithFile(fileName, fileContents.ToStream(), searchPatterns, fileLocation); + return this.WithFile(fileName, fileContents.ToStream(), searchPatterns, fileLocation); } public DetectorTestUtility WithFile(string fileName, Stream fileContents, IEnumerable searchPatterns = null, string fileLocation = null) @@ -87,23 +87,23 @@ public DetectorTestUtility WithFile(string fileName, Stream fileContents, IEn if (searchPatterns == null || !searchPatterns.Any()) { - searchPatterns = detector.SearchPatterns; + searchPatterns = this.detector.SearchPatterns; } - filesToAdd.Add((fileName, fileContents, fileLocation, searchPatterns)); + this.filesToAdd.Add((fileName, fileContents, fileLocation, searchPatterns)); return this; } public DetectorTestUtility WithComponentStreamEnumerableFactory(Mock mock) { - mockComponentStreamEnumerableFactory = mock; + this.mockComponentStreamEnumerableFactory = mock; return this; } public DetectorTestUtility WithObservableDirectoryWalkerFactory(Mock mock) { - mockObservableDirectoryWalkerFactory = mock; + this.mockObservableDirectoryWalkerFactory = mock; return this; } @@ -111,7 +111,7 @@ private ProcessRequest CreateProcessRequest(string pattern, string filePath, Str { return new ProcessRequest { - SingleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(filePath), + SingleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(filePath), ComponentStream = CreateComponentStreamForFile(pattern, filePath, content), }; } @@ -130,33 +130,33 @@ private void InitializeFileRelatedMocksUsingDefaultImplementationIfNecessary() { bool useDefaultObservableDirectoryWalkerFactory = false, useDefaultComponentStreamEnumerableFactory = false; - if (mockObservableDirectoryWalkerFactory == null) + if (this.mockObservableDirectoryWalkerFactory == null) { useDefaultObservableDirectoryWalkerFactory = true; - mockObservableDirectoryWalkerFactory = new Mock(); + this.mockObservableDirectoryWalkerFactory = new Mock(); } - if (mockComponentStreamEnumerableFactory == null) + if (this.mockComponentStreamEnumerableFactory == null) { useDefaultComponentStreamEnumerableFactory = true; - mockComponentStreamEnumerableFactory = new Mock(); + this.mockComponentStreamEnumerableFactory = new Mock(); } - if (!filesToAdd.Any() && useDefaultObservableDirectoryWalkerFactory) + if (!this.filesToAdd.Any() && useDefaultObservableDirectoryWalkerFactory) { - mockObservableDirectoryWalkerFactory.Setup(x => - x.GetFilteredComponentStreamObservable(It.IsAny(), detector.SearchPatterns, It.IsAny())) + this.mockObservableDirectoryWalkerFactory.Setup(x => + x.GetFilteredComponentStreamObservable(It.IsAny(), this.detector.SearchPatterns, It.IsAny())) .Returns(Enumerable.Empty().ToObservable()); } - if (!filesToAdd.Any() && useDefaultComponentStreamEnumerableFactory) + if (!this.filesToAdd.Any() && useDefaultComponentStreamEnumerableFactory) { - mockComponentStreamEnumerableFactory.Setup(x => - x.GetComponentStreams(It.IsAny(), detector.SearchPatterns, It.IsAny(), It.IsAny())) + this.mockComponentStreamEnumerableFactory.Setup(x => + x.GetComponentStreams(It.IsAny(), this.detector.SearchPatterns, It.IsAny(), It.IsAny())) .Returns(Enumerable.Empty()); } - var filesGroupedBySearchPattern = filesToAdd.GroupBy(filesToAdd => filesToAdd.searchPatterns, new EnumerableStringComparer()); + var filesGroupedBySearchPattern = this.filesToAdd.GroupBy(filesToAdd => filesToAdd.searchPatterns, new EnumerableStringComparer()); foreach (var group in filesGroupedBySearchPattern) { var searchPatterns = group.Key; @@ -164,48 +164,48 @@ private void InitializeFileRelatedMocksUsingDefaultImplementationIfNecessary() if (useDefaultObservableDirectoryWalkerFactory) { - mockObservableDirectoryWalkerFactory.Setup(x => + this.mockObservableDirectoryWalkerFactory.Setup(x => x.GetFilteredComponentStreamObservable(It.IsAny(), searchPatterns, It.IsAny())) .Returns, IComponentRecorder>((directoryInfo, searchPatterns, componentRecorder) => { return filesToSend - .Select(fileToSend => CreateProcessRequest(FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).ToObservable(); + .Select(fileToSend => this.CreateProcessRequest(this.FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).ToObservable(); }); } if (useDefaultComponentStreamEnumerableFactory) { - mockComponentStreamEnumerableFactory.Setup(x => + this.mockComponentStreamEnumerableFactory.Setup(x => x.GetComponentStreams(It.IsAny(), searchPatterns, It.IsAny(), It.IsAny())) .Returns, ExcludeDirectoryPredicate, bool>((directoryInfo, searchPatterns, excludeDirectoryPredicate, recurse) => { if (recurse) { return filesToSend - .Select(fileToSend => CreateProcessRequest(FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).Select(pr => pr.ComponentStream); + .Select(fileToSend => this.CreateProcessRequest(this.FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).Select(pr => pr.ComponentStream); } else { return filesToSend .Where(fileToSend => Directory.GetParent(fileToSend.Location).FullName == directoryInfo.FullName) - .Select(fileToSend => CreateProcessRequest(FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).Select(pr => pr.ComponentStream); - } + .Select(fileToSend => this.CreateProcessRequest(this.FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).Select(pr => pr.ComponentStream); + } }); } } - var providedDetectorSearchPatterns = filesGroupedBySearchPattern.Any(group => group.Key.SequenceEqual(detector.SearchPatterns)); + var providedDetectorSearchPatterns = filesGroupedBySearchPattern.Any(group => group.Key.SequenceEqual(this.detector.SearchPatterns)); if (!providedDetectorSearchPatterns && useDefaultObservableDirectoryWalkerFactory) { - mockObservableDirectoryWalkerFactory.Setup(x => - x.GetFilteredComponentStreamObservable(It.IsAny(), detector.SearchPatterns, It.IsAny())) + this.mockObservableDirectoryWalkerFactory.Setup(x => + x.GetFilteredComponentStreamObservable(It.IsAny(), this.detector.SearchPatterns, It.IsAny())) .Returns(new List().ToObservable()); } if (!providedDetectorSearchPatterns && useDefaultComponentStreamEnumerableFactory) { - mockComponentStreamEnumerableFactory.Setup(x => - x.GetComponentStreams(It.IsAny(), detector.SearchPatterns, It.IsAny(), It.IsAny())) + this.mockComponentStreamEnumerableFactory.Setup(x => + x.GetComponentStreams(It.IsAny(), this.detector.SearchPatterns, It.IsAny(), It.IsAny())) .Returns(new List()); } } diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/Microsoft.ComponentDetection.TestsUtilities.csproj b/test/Microsoft.ComponentDetection.TestsUtilities/Microsoft.ComponentDetection.TestsUtilities.csproj index b8312e018..56443f49d 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/Microsoft.ComponentDetection.TestsUtilities.csproj +++ b/test/Microsoft.ComponentDetection.TestsUtilities/Microsoft.ComponentDetection.TestsUtilities.csproj @@ -1,10 +1,10 @@  - + - - true - + + true + diff --git a/test/Microsoft.ComponentDetection.VerificationTests/resources/nuget/packages-config/packages.config b/test/Microsoft.ComponentDetection.VerificationTests/resources/nuget/packages-config/packages.config new file mode 100644 index 000000000..c9e20b2e5 --- /dev/null +++ b/test/Microsoft.ComponentDetection.VerificationTests/resources/nuget/packages-config/packages.config @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +