Пример #1
0
        ObjectDef IContainerModel.ToObjectDef(DiagnosticLevel diagnosticLevel)
        {
            var objectDef = toObjectDef(diagnosticLevel);
            objectDef.Name = UniqueId.ToString();

            return objectDef;
        }
Пример #2
0
        /// <summary>
        /// Writes a diagnostic.
        /// </summary>
        /// <param name="level"></param>
        /// <param name="message"></param>
        public void WriteDiagnostic(DiagnosticLevel level, String message)
        {
            Diagnostic diagnostic = new Diagnostic(this.BundleID);
            diagnostic.Level = level;
            diagnostic.Message = message;


        }
Пример #3
0
        public ObjectDef ToObjectDef(DiagnosticLevel level)
        {
            var objectDef = new ObjectDef(typeof (MediaWriter<>).MakeGenericType(_inputType));

            if (Links.Dependency != null) objectDef.Dependency(Links.Dependency);
            if (Projection.Dependency != null) objectDef.Dependency(Projection.Dependency);
            if (Document.Dependency != null) objectDef.Dependency(Document.Dependency);

            return objectDef;
        }
Пример #4
0
        protected ObjectDef toObjectDef(DiagnosticLevel diagnosticLevel)
        {
            var objectDef = buildObjectDef();

            if (_conditionalDef != null)
            {
                objectDef = buildConditionalInvokerDef(objectDef);
            }

            if (Next != null)
            {
                attachNextBehavior(objectDef, diagnosticLevel);
            }

            return diagnosticLevel == DiagnosticLevel.FullRequestTracing
                ? createTracerDef(objectDef)
                : objectDef;
        }
Пример #5
0
 private static DiagnosticSeverity ToDiagnosticSeverity(DiagnosticLevel level)
 => level switch
 {
Пример #6
0
 private void attachNextBehavior(ObjectDef objectDef, DiagnosticLevel diagnosticLevel)
 {
     var nextObjectDef = Next.As<IContainerModel>().ToObjectDef(diagnosticLevel);
     objectDef.DependencyByType<IActionBehavior>(nextObjectDef);
 }
        public void IncludesException_Returns_False_Given_Null_Exception(DiagnosticLevel level, string message)
        {
            var e = new DiagnosticGeneratedEventArgs(level, message);

            Assert.False(e.IncludesException);
        }
Пример #8
0
        public void Type_validation_runs_on_compilation_common_failures(TypeSymbolValidationFlags validationFlags, DiagnosticLevel expectedDiagnosticLevel)
        {
            var customTypes = new[] {
                TestTypeHelper.CreateCustomResourceTypeWithTopLevelProperties("My.Rp/myType", "2020-01-01", validationFlags,
                                                                              new [] { new TypeProperty("readOnlyTopLevelProp", LanguageConstants.String, TypePropertyFlags.ReadOnly) },
                                                                              new TypeProperty("readOnlyProp", LanguageConstants.String, TypePropertyFlags.ReadOnly),
                                                                              new TypeProperty("writeOnlyProp", LanguageConstants.String, TypePropertyFlags.WriteOnly | TypePropertyFlags.AllowImplicitNull),
                                                                              new TypeProperty("requiredProp", LanguageConstants.String, TypePropertyFlags.Required),
                                                                              new TypeProperty("additionalProps", new ObjectType(
                                                                                                   "additionalProps",
                                                                                                   validationFlags,
                                                                                                   new [] {
                    new TypeProperty("propA", LanguageConstants.String, TypePropertyFlags.Required),
                    new TypeProperty("propB", LanguageConstants.String, TypePropertyFlags.AllowImplicitNull),
                },
                                                                                                   LanguageConstants.Int
                                                                                                   )),
                                                                              new TypeProperty("nestedObj", new ObjectType(
                                                                                                   "nestedObj",
                                                                                                   validationFlags,
                                                                                                   new [] {
                    new TypeProperty("readOnlyNestedProp", LanguageConstants.String, TypePropertyFlags.ReadOnly),
                    new TypeProperty("writeOnlyNestedProp", LanguageConstants.String, TypePropertyFlags.WriteOnly | TypePropertyFlags.AllowImplicitNull),
                    new TypeProperty("requiredNestedProp", LanguageConstants.String, TypePropertyFlags.Required),
                },
                                                                                                   null
                                                                                                   ))),
            };
            var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  id: '/subscriptions/guid/resourceGroups/rg/My.Rp/myType/steve'
  type: 'My.Rp/myType'
  apiVersion: '2020-01-01'
  readOnlyTopLevelProp: 'abcd'
  properties: {
    readOnlyProp: 123
    writeOnlyProp: 456
    additionalProps: {
      propB: 123
    }
    nestedObj: {
      readOnlyNestedProp: 123
      writeOnlyNestedProp: 456
    }
  }
}

output writeOnlyOutput string = myRes.properties.writeOnlyProp
output writeOnlyOutput2 string = myRes.properties.nestedObj.writeOnlyProp
output missingOutput string = myRes.properties.missingOutput
output missingOutput2 string = myRes.properties.nestedObj.missingOutput
output incorrectTypeOutput int = myRes.properties.readOnlyProp
output incorrectTypeOutput2 int = myRes.properties.nestedObj.readOnlyProp
";

            var model = GetSemanticModelForTest(program, customTypes);

            model.GetAllDiagnostics().Should().SatisfyRespectively(
                x => x.Should().HaveCodeAndSeverity("BCP073", expectedDiagnosticLevel).And.HaveMessage("The property \"id\" is read-only. Expressions cannot be assigned to read-only properties."),
                x => x.Should().HaveCodeAndSeverity("BCP073", expectedDiagnosticLevel).And.HaveMessage("The property \"type\" is read-only. Expressions cannot be assigned to read-only properties."),
                x => x.Should().HaveCodeAndSeverity("BCP073", expectedDiagnosticLevel).And.HaveMessage("The property \"apiVersion\" is read-only. Expressions cannot be assigned to read-only properties."),
                x => x.Should().HaveCodeAndSeverity("BCP073", DiagnosticLevel.Warning).And.HaveMessage("The property \"readOnlyTopLevelProp\" is read-only. Expressions cannot be assigned to read-only properties. If this is an inaccuracy in the documentation, please report it to the Bicep Team."),
                x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified \"object\" declaration is missing the following required properties: \"requiredProp\"."),
                x => x.Should().HaveCodeAndSeverity("BCP073", DiagnosticLevel.Warning).And.HaveMessage("The property \"readOnlyProp\" is read-only. Expressions cannot be assigned to read-only properties. If this is an inaccuracy in the documentation, please report it to the Bicep Team."),
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property \"writeOnlyProp\" expected a value of type \"null | string\" but the provided value is of type \"int\"."),
                x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified \"object\" declaration is missing the following required properties: \"propA\"."),
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property \"propB\" expected a value of type \"null | string\" but the provided value is of type \"int\"."),
                x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified \"object\" declaration is missing the following required properties: \"requiredNestedProp\"."),
                x => x.Should().HaveCodeAndSeverity("BCP073", DiagnosticLevel.Warning).And.HaveMessage("The property \"readOnlyNestedProp\" is read-only. Expressions cannot be assigned to read-only properties. If this is an inaccuracy in the documentation, please report it to the Bicep Team."),
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property \"writeOnlyNestedProp\" expected a value of type \"null | string\" but the provided value is of type \"int\"."),
                x => x.Should().HaveCodeAndSeverity("BCP077", expectedDiagnosticLevel).And.HaveMessage("The property \"writeOnlyProp\" on type \"properties\" is write-only. Write-only properties cannot be accessed."),
                x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type \"nestedObj\" does not contain property \"writeOnlyProp\". Available properties include \"readOnlyNestedProp\", \"requiredNestedProp\"."),
                x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type \"properties\" does not contain property \"missingOutput\". Available properties include \"additionalProps\", \"nestedObj\", \"readOnlyProp\", \"requiredProp\"."),
                x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type \"nestedObj\" does not contain property \"missingOutput\". Available properties include \"readOnlyNestedProp\", \"requiredNestedProp\"."),
                x => x.Should().HaveCodeAndSeverity("BCP026", DiagnosticLevel.Error).And.HaveMessage("The output expects a value of type \"int\" but the provided value is of type \"string\"."),
                x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type \"nestedObj\" does not contain property \"readOnlyProp\". Available properties include \"readOnlyNestedProp\", \"requiredNestedProp\".")
                );
        }
Пример #9
0
        public void Type_validation_narrowing_on_discriminated_object_types(TypeSymbolValidationFlags validationFlags, DiagnosticLevel expectedDiagnosticLevel)
        {
            var customTypes = new[] {
                TestTypeHelper.CreateCustomResourceType("My.Rp/myType", "2020-01-01", validationFlags,
                                                        new TypeProperty("myDisc1", new DiscriminatedObjectType("myDisc1", validationFlags, "discKey", new [] {
                    new ObjectType("choiceA", validationFlags, new [] {
                        new TypeProperty("discKey", new StringLiteralType("choiceA"), TypePropertyFlags.Required),
                        new TypeProperty("valueA", LanguageConstants.String, TypePropertyFlags.Required),
                    }, null),
                    new ObjectType("choiceB", validationFlags, new [] {
                        new TypeProperty("discKey", new StringLiteralType("choiceB"), TypePropertyFlags.Required),
                        new TypeProperty("valueB", LanguageConstants.String, TypePropertyFlags.Required),
                    }, null),
                }
                                                                                                                ))),
            };

            {
                // missing discriminator key
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      valueA: 'abc'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP078", expectedDiagnosticLevel).And.HaveMessage("The property \"discKey\" requires a value of type \"'choiceA' | 'choiceB'\", but none was supplied.")
                    );
            }

            {
                // incorrect discriminator key case
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      DiscKey: 'choiceA'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP078", expectedDiagnosticLevel).And.HaveMessage("The property \"discKey\" requires a value of type \"'choiceA' | 'choiceB'\", but none was supplied."),
                    x => x.Should().HaveCodeAndSeverity("BCP089", expectedDiagnosticLevel).And.HaveMessage("The property \"DiscKey\" is not allowed on objects of type \"'choiceA' | 'choiceB'\". Did you mean \"discKey\"?")
                    );
            }

            {
                // incorrect discriminator key
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'foo'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property \"discKey\" expected a value of type \"'choiceA' | 'choiceB'\" but the provided value is of type \"'foo'\".")
                    );
            }

            {
                // incorrect discriminator key with suggestion
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'choiceC'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP088", expectedDiagnosticLevel).And.HaveMessage("The property \"discKey\" expected a value of type \"'choiceA' | 'choiceB'\" but the provided value is of type \"'choiceC'\". Did you mean \"'choiceA'\"?")
                    );
            }

            {
                // discriminator key supplied, required value omitted
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'choiceA'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified \"object\" declaration is missing the following required properties: \"valueA\".")
                    );
            }

            {
                // discriminator key supplied, case of required property is incorrect
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'choiceA'
      ValueA: 'hello'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified \"object\" declaration is missing the following required properties: \"valueA\"."),
                    x => x.Should().HaveCodeAndSeverity("BCP089", expectedDiagnosticLevel).And.HaveMessage("The property \"ValueA\" is not allowed on objects of type \"choiceA\". Did you mean \"valueA\"?")
                    );
            }

            {
                // all good, incorrect property access
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'choiceA'
      valueA: 'hello'
    }
  }
}

output valueA string = myRes.properties.myDisc1.valueA
output valueB string = myRes.properties.myDisc1.valuuuueB
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type \"choiceA\" does not contain property \"valuuuueB\". Available properties include \"discKey\", \"valueA\".")
                    );
            }

            {
                // all good, incorrect property access with suggestion
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'choiceA'
      valueA: 'hello'
    }
  }
}

output valueA string = myRes.properties.myDisc1.valueA
output valueB string = myRes.properties.myDisc1.valueB
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP083", expectedDiagnosticLevel).And.HaveMessage("The type \"choiceA\" does not contain property \"valueB\". Did you mean \"valueA\"?")
                    );
            }
        }
Пример #10
0
 ObjectDef IContainerModel.ToObjectDef(DiagnosticLevel diagnosticLevel)
 {
     return(buildObjectDef(diagnosticLevel));
 }
Пример #11
0
 public Diagnostic(int offset, int length, IProject project, string file, int line, string message, DiagnosticLevel level, DiagnosticCategory category)
 {
     StartOffset = offset;
     Length      = length;
     Project     = project;
     File        = file;
     Line        = line;
     Spelling    = message;
     Level       = level;
     Category    = category;
 }
Пример #12
0
 public AnalyzerDiagnostic(string analyzerName, TextSpan span, DiagnosticLevel level, string code, string message, Uri?documentationUri = null, DiagnosticStyling styling = DiagnosticStyling.Default)
     : base(span, level, code, message, documentationUri, styling, $"{LanguageConstants.LanguageId} {analyzerName}")
 {
 }
Пример #13
0
 public AnalyzerDiagnostic(string analyzerName, TextSpan span, DiagnosticLevel level, string code, string message, Uri?documentationUri = null, DiagnosticLabel?label = null)
     : base(span, level, code, message, documentationUri, label, $"{LanguageConstants.LanguageId} {analyzerName}")
 {
 }
Пример #14
0
 public FixableDiagnostic(Parsing.TextSpan span, DiagnosticLevel level, string code, string message, CodeFix fix, params CodeFix[] additionalFixes)
     : this(span, level, code, message, fix)
 {
     this.additionalFixes = additionalFixes;
 }
Пример #15
0
 public FixableDiagnostic(Parsing.TextSpan span, DiagnosticLevel level, string code, string message, CodeFix fix)
     : base(span, level, code, message)
 {
     this.fix             = fix;
     this.additionalFixes = null;
 }
Пример #16
0
        public void Type_validation_runs_on_compilation_common_failures(TypeSymbolValidationFlags validationFlags, DiagnosticLevel expectedDiagnosticLevel)
        {
            var customTypes = new [] {
                CreateCustomResourceType("My.Rp/myType", "2020-01-01", validationFlags,
                                         new TypeProperty("readOnlyProp", LanguageConstants.String, TypePropertyFlags.ReadOnly),
                                         new TypeProperty("writeOnlyProp", LanguageConstants.String, TypePropertyFlags.WriteOnly),
                                         new TypeProperty("requiredProp", LanguageConstants.String, TypePropertyFlags.Required),
                                         new TypeProperty("additionalProps", new NamedObjectType(
                                                              "additionalProps",
                                                              validationFlags,
                                                              new [] {
                    new TypeProperty("propA", LanguageConstants.String, TypePropertyFlags.Required),
                    new TypeProperty("propB", LanguageConstants.String),
                },
                                                              LanguageConstants.Int
                                                              )),
                                         new TypeProperty("nestedObj", new NamedObjectType(
                                                              "nestedObj",
                                                              validationFlags,
                                                              new [] {
                    new TypeProperty("readOnlyNestedProp", LanguageConstants.String, TypePropertyFlags.ReadOnly),
                    new TypeProperty("writeOnlyNestedProp", LanguageConstants.String, TypePropertyFlags.WriteOnly),
                    new TypeProperty("requiredNestedProp", LanguageConstants.String, TypePropertyFlags.Required),
                },
                                                              null
                                                              ))),
            };
            var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    readOnlyProp: 123
    writeOnlyProp: 456
    additionalProps: {
      propB: 123
    }
    nestedObj: {
      readOnlyNestedProp: 123
      writeOnlyNestedProp: 456
    }
  }
}

output writeOnlyOutput string = myRes.properties.writeOnlyProp
output writeOnlyOutput2 string = myRes.properties.nestedObj.writeOnlyProp
output missingOutput string = myRes.properties.missingOutput
output missingOutput2 string = myRes.properties.nestedObj.missingOutput
output incorrectTypeOutput int = myRes.properties.readOnlyProp
output incorrectTypeOutput2 int = myRes.properties.nestedObj.readOnlyProp
";

            var model = GetSemanticModelForTest(program, customTypes);

            model.GetAllDiagnostics().Should().SatisfyRespectively(
                x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified object is missing the following required properties: requiredProp."),
                x => x.Should().HaveCodeAndSeverity("BCP073", expectedDiagnosticLevel).And.HaveMessage("The property 'readOnlyProp' is read-only. Expressions cannot be assigned to read-only properties."),
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property 'readOnlyProp' expected a value of type string but the provided value is of type int."),
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property 'writeOnlyProp' expected a value of type string but the provided value is of type int."),
                x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified object is missing the following required properties: propA."),
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property 'propB' expected a value of type string but the provided value is of type int."),
                x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified object is missing the following required properties: requiredNestedProp."),
                x => x.Should().HaveCodeAndSeverity("BCP073", expectedDiagnosticLevel).And.HaveMessage("The property 'readOnlyNestedProp' is read-only. Expressions cannot be assigned to read-only properties."),
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property 'readOnlyNestedProp' expected a value of type string but the provided value is of type int."),
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property 'writeOnlyNestedProp' expected a value of type string but the provided value is of type int."),
                x => x.Should().HaveCodeAndSeverity("BCP077", expectedDiagnosticLevel).And.HaveMessage("The property 'writeOnlyProp' on type 'properties' is write-only. Write-only properties cannot be accessed."),
                x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type nestedObj does not contain property 'writeOnlyProp'. Available properties include 'readOnlyNestedProp', 'requiredNestedProp'."),
                x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type properties does not contain property 'missingOutput'. Available properties include 'additionalProps', 'nestedObj', 'readOnlyProp', 'requiredProp'."),
                x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type nestedObj does not contain property 'missingOutput'. Available properties include 'readOnlyNestedProp', 'requiredNestedProp'."),
                x => x.Should().HaveCodeAndSeverity("BCP026", DiagnosticLevel.Error).And.HaveMessage("The output expects a value of type int but the provided value is of type string."),
                x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type nestedObj does not contain property 'readOnlyProp'. Available properties include 'readOnlyNestedProp', 'requiredNestedProp'.")
                );
        }
Пример #17
0
        public void Type_validation_narrowing_on_discriminated_object_types(TypeSymbolValidationFlags validationFlags, DiagnosticLevel expectedDiagnosticLevel)
        {
            var customTypes = new [] {
                CreateCustomResourceType("My.Rp/myType", "2020-01-01", validationFlags,
                                         new TypeProperty("myDisc1", new DiscriminatedObjectType("myDisc1", validationFlags, "discKey", new [] {
                    new NamedObjectType("choiceA", validationFlags, new [] {
                        new TypeProperty("discKey", new StringLiteralType("choiceA"), TypePropertyFlags.Required),
                        new TypeProperty("valueA", LanguageConstants.String, TypePropertyFlags.Required),
                    }, null),
                    new NamedObjectType("choiceB", validationFlags, new [] {
                        new TypeProperty("discKey", new StringLiteralType("choiceB"), TypePropertyFlags.Required),
                        new TypeProperty("valueB", LanguageConstants.String, TypePropertyFlags.Required),
                    }, null),
                }
                                                                                                 ))),
            };

            {
                // missing discriminator key
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      valueA: 'abc'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP078", expectedDiagnosticLevel).And.HaveMessage("The property 'discKey' requires a value of type 'choiceA' | 'choiceB', but none was supplied.")
                    );
            }

            {
                // incorrect discriminator key
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'choiceC'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property 'discKey' expected a value of type 'choiceA' | 'choiceB' but the provided value is of type 'choiceC'.")
                    );
            }

            {
                // discriminator key supplied, required value omitted
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'choiceA'
    }
  }
}
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP035", expectedDiagnosticLevel).And.HaveMessage("The specified object is missing the following required properties: valueA.")
                    );
            }

            {
                // all good
                var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    myDisc1: {
      discKey: 'choiceA'
      valueA: 'hello'
    }
  }
}

output valueA string = myRes.properties.myDisc1.valueA
output valueB string = myRes.properties.myDisc1.valueB
";

                var model = GetSemanticModelForTest(program, customTypes);
                model.GetAllDiagnostics().Should().SatisfyRespectively(
                    x => x.Should().HaveCodeAndSeverity("BCP053", expectedDiagnosticLevel).And.HaveMessage("The type choiceA does not contain property 'valueB'. Available properties include 'discKey', 'valueA'.")
                    );
            }
        }
Пример #18
0
        public void Type_validation_narrowing_on_union_types(TypeSymbolValidationFlags validationFlags, DiagnosticLevel expectedDiagnosticLevel)
        {
            var customTypes = new [] {
                CreateCustomResourceType("My.Rp/myType", "2020-01-01", validationFlags,
                                         new TypeProperty("stringOrInt", UnionType.Create(LanguageConstants.String, LanguageConstants.Int)),
                                         new TypeProperty("unspecifiedStringOrInt", UnionType.Create(LanguageConstants.String, LanguageConstants.Int)),
                                         new TypeProperty("abcOrDef", UnionType.Create(new StringLiteralType("abc"), new StringLiteralType("def"))),
                                         new TypeProperty("unspecifiedAbcOrDef", UnionType.Create(new StringLiteralType("abc"), new StringLiteralType("def")))),
                CreateCustomResourceType("My.Rp/myDependentType", "2020-01-01", validationFlags,
                                         new TypeProperty("stringOnly", LanguageConstants.String),
                                         new TypeProperty("abcOnly", new StringLiteralType("abc")),
                                         new TypeProperty("abcOnlyUnNarrowed", new StringLiteralType("abc")),
                                         new TypeProperty("stringOrIntUnNarrowed", UnionType.Create(LanguageConstants.String, LanguageConstants.Int)),
                                         new TypeProperty("abcOrDefUnNarrowed", UnionType.Create(new StringLiteralType("abc"), new StringLiteralType("def"), new StringLiteralType("ghi")))),
            };
            var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    stringOrInt: 'abc'
    abcOrDef: 'abc'
  }
}

resource myDependentRes 'My.Rp/myDependentType@2020-01-01' = {
  name: 'steve'
  properties: {
    stringOnly: myRes.properties.stringOrInt // should be allowed
    abcOnly: myRes.properties.abcOrDef
    abcOnlyUnNarrowed: myRes.properties.unspecifiedAbcOrDef
    stringOrIntUnNarrowed: myRes.properties.unspecifiedStringOrInt
    abcOrDefUnNarrowed: myRes.properties.abcOrDef
  }
}
";

            var model = GetSemanticModelForTest(program, customTypes);

            model.GetAllDiagnostics().Should().SatisfyRespectively(
                x => x.Should().HaveCodeAndSeverity("BCP036", expectedDiagnosticLevel).And.HaveMessage("The property 'abcOnlyUnNarrowed' expected a value of type 'abc' but the provided value is of type 'abc' | 'def'.")
                );
        }
 public IDependencyViewModel CreateTargetViewModel(TargetFramework targetFramework, DiagnosticLevel maximumDiagnosticLevel)
 {
     return(new TargetDependencyViewModel(targetFramework, maximumDiagnosticLevel));
 }
        public (IDependencyViewModel?GroupNodeViewModel, ProjectTreeFlags?GroupNodeFlag) CreateGroupNodeViewModel(string providerType, DiagnosticLevel maximumDiagnosticLevel)
        {
            IProjectDependenciesSubTreeProvider?provider = GetProvider();

            IDependencyModel?dependencyModel = provider?.CreateRootDependencyNode();

            IDependencyViewModel?groupNodeViewModel = dependencyModel?.ToViewModel(maximumDiagnosticLevel);

            ProjectTreeFlags?groupNodeFlag = provider is IProjectDependenciesSubTreeProvider2 provider2
                ? provider2.GroupNodeFlag
                : null;

            return(groupNodeViewModel, groupNodeFlag);

            IProjectDependenciesSubTreeProvider?GetProvider()
            {
                return(SubTreeProviders
                       .FirstOrDefault((x, t) => StringComparers.DependencyProviderTypes.Equals(x.Value.ProviderType, t), providerType)
                       ?.Value);
            }
        }
Пример #21
0
        protected DependencyModel(
            string caption,
            string?path,
            string originalItemSpec,
            ProjectTreeFlags flags,
            bool isResolved,
            bool isImplicit,
            IImmutableDictionary <string, string>?properties,
            bool isVisible = true)
        {
            Requires.NotNullOrEmpty(caption, nameof(caption));

            // IDependencyModel allows original item spec to be null, but we can satisfy a
            // more strict requirement for the dependency types produced internally.
            // External providers may not have a meaningful value, but do not use this type.
            Requires.NotNullOrEmpty(originalItemSpec, nameof(originalItemSpec));

            Path             = path;
            OriginalItemSpec = originalItemSpec;
            Properties       = properties ?? ImmutableStringDictionary <string> .EmptyOrdinal;
            Caption          = caption;
            Flags            = flags;

            if (Properties.TryGetBoolProperty(ProjectItemMetadata.Visible, out bool visibleProperty))
            {
                isVisible = visibleProperty;
            }

            DiagnosticLevel diagnosticLevel = DiagnosticLevel.None;

            if (Properties.TryGetStringProperty(ProjectItemMetadata.DiagnosticLevel, out string?levelString))
            {
                diagnosticLevel = levelString switch
                {
                    "Warning" => DiagnosticLevel.Warning,
                    "Error" => DiagnosticLevel.Error,
                    _ => DiagnosticLevel.None
                };
            }

            if (diagnosticLevel == DiagnosticLevel.None && !isResolved)
            {
                // Treat unresolved state as a warning diagnostic
                diagnosticLevel = DiagnosticLevel.Warning;
            }

            DependencyFlags depFlags = 0;

            if (isResolved)
            {
                depFlags |= DependencyFlags.Resolved;
            }
            if (isVisible)
            {
                depFlags |= DependencyFlags.Visible;
            }
            if (isImplicit)
            {
                depFlags |= DependencyFlags.Implicit;
            }
            _flags = depFlags;

            DiagnosticLevel = diagnosticLevel;
        }
Пример #22
0
 public Diagnostic(DiagnosticLevel level, string message, CXSourceLocation location) : this(level, message, location.ToString())
 {
 }
        public void Instantiation(
            bool enableListener,
            bool enableDistributedNetwork,
            bool acceptDistributedChildren,
            int distributedChildLimit,
            bool enableUploadQueue,
            int maximumConcurrentUploads,
            int maximumUploadSpeed,
            int maximumConcurrentDownloads,
            int maximumDownloadSpeed,
            bool deduplicateSearchRequests,
            int messageTimeout,
            bool autoAcknowledgePrivateMessages,
            bool autoAcknowledgePrivilegeNotifications,
            bool acceptPrivateRoomInvitations,
            DiagnosticLevel minimumDiagnosticLevel,
            int startingToken)
        {
            var serverConnectionOptions      = new ConnectionOptions();
            var peerConnectionOptions        = new ConnectionOptions();
            var transferConnectionOptions    = new ConnectionOptions();
            var incomingConnectionOptions    = new ConnectionOptions();
            var distributedConnectionOptions = new ConnectionOptions();

            var userEndPointCache   = new Mock <IUserEndPointCache>();
            var searchResponseCache = new Mock <ISearchResponseCache>();

            var searchResponseResolver            = new Func <string, int, SearchQuery, Task <SearchResponse> >((s, i, q) => Task.FromResult <SearchResponse>(null));
            var browseResponseResolver            = new Func <string, IPEndPoint, Task <BrowseResponse> >((s, i) => Task.FromResult <BrowseResponse>(null));
            var directoryContentsResponseResolver = new Func <string, IPEndPoint, int, string, Task <Directory> >((s, i, ii, ss) => Task.FromResult <Directory>(null));
            var userInfoResponseResolver          = new Func <string, IPEndPoint, Task <UserInfo> >((s, i) => Task.FromResult <UserInfo>(null));
            var enqueueDownloadAction             = new Func <string, IPEndPoint, string, Task>((s, i, ss) => Task.CompletedTask);
            var placeInQueueResponseResolver      = new Func <string, IPEndPoint, string, Task <int?> >((s, i, ss) => Task.FromResult <int?>(0));

            var rnd        = new Random();
            var listenPort = rnd.Next(1024, 65535);

            var o = new SoulseekClientOptions(
                enableListener,
                listenPort,
                enableDistributedNetwork: enableDistributedNetwork,
                acceptDistributedChildren: acceptDistributedChildren,
                distributedChildLimit: distributedChildLimit,
                maximumConcurrentUploads: maximumConcurrentUploads,
                maximumUploadSpeed: maximumUploadSpeed,
                maximumConcurrentDownloads: maximumConcurrentDownloads,
                maximumDownloadSpeed: maximumDownloadSpeed,
                deduplicateSearchRequests: deduplicateSearchRequests,
                messageTimeout: messageTimeout,
                autoAcknowledgePrivateMessages: autoAcknowledgePrivateMessages,
                autoAcknowledgePrivilegeNotifications: autoAcknowledgePrivilegeNotifications,
                acceptPrivateRoomInvitations: acceptPrivateRoomInvitations,
                minimumDiagnosticLevel: minimumDiagnosticLevel,
                startingToken: startingToken,
                serverConnectionOptions: serverConnectionOptions,
                peerConnectionOptions: peerConnectionOptions,
                transferConnectionOptions: transferConnectionOptions,
                incomingConnectionOptions: incomingConnectionOptions,
                distributedConnectionOptions: distributedConnectionOptions,
                userEndPointCache: userEndPointCache.Object,
                searchResponseResolver: searchResponseResolver,
                searchResponseCache: searchResponseCache.Object,
                browseResponseResolver: browseResponseResolver,
                directoryContentsResolver: directoryContentsResponseResolver,
                userInfoResolver: userInfoResponseResolver,
                enqueueDownload: enqueueDownloadAction,
                placeInQueueResolver: placeInQueueResponseResolver);

            Assert.Equal(enableListener, o.EnableListener);
            Assert.Equal(listenPort, o.ListenPort);
            Assert.Equal(enableDistributedNetwork, o.EnableDistributedNetwork);
            Assert.Equal(acceptDistributedChildren, o.AcceptDistributedChildren);
            Assert.Equal(distributedChildLimit, o.DistributedChildLimit);
            Assert.Equal(enableUploadQueue, o.EnableDistributedNetwork);
            Assert.Equal(maximumConcurrentUploads, o.MaximumConcurrentUploads);
            Assert.Equal(maximumUploadSpeed, o.MaximumUploadSpeed);
            Assert.Equal(maximumConcurrentDownloads, o.MaximumConcurrentDownloads);
            Assert.Equal(maximumDownloadSpeed, o.MaximumDownloadSpeed);
            Assert.Equal(deduplicateSearchRequests, o.DeduplicateSearchRequests);
            Assert.Equal(messageTimeout, o.MessageTimeout);
            Assert.Equal(autoAcknowledgePrivateMessages, o.AutoAcknowledgePrivateMessages);
            Assert.Equal(autoAcknowledgePrivilegeNotifications, o.AutoAcknowledgePrivilegeNotifications);
            Assert.Equal(acceptPrivateRoomInvitations, o.AcceptPrivateRoomInvitations);
            Assert.Equal(minimumDiagnosticLevel, o.MinimumDiagnosticLevel);
            Assert.Equal(startingToken, o.StartingToken);
            Assert.Equal(peerConnectionOptions, o.PeerConnectionOptions);
            Assert.Equal(incomingConnectionOptions, o.IncomingConnectionOptions);
            Assert.Equal(distributedConnectionOptions, o.DistributedConnectionOptions);

            Assert.Equal(serverConnectionOptions.ReadBufferSize, o.ServerConnectionOptions.ReadBufferSize);
            Assert.Equal(serverConnectionOptions.WriteBufferSize, o.ServerConnectionOptions.WriteBufferSize);
            Assert.Equal(serverConnectionOptions.ConnectTimeout, o.ServerConnectionOptions.ConnectTimeout);
            Assert.Equal(-1, o.ServerConnectionOptions.InactivityTimeout);

            Assert.Equal(transferConnectionOptions.ReadBufferSize, o.TransferConnectionOptions.ReadBufferSize);
            Assert.Equal(transferConnectionOptions.WriteBufferSize, o.TransferConnectionOptions.WriteBufferSize);
            Assert.Equal(transferConnectionOptions.ConnectTimeout, o.TransferConnectionOptions.ConnectTimeout);
            Assert.Equal(-1, o.TransferConnectionOptions.InactivityTimeout);

            Assert.Equal(userEndPointCache.Object, o.UserEndPointCache);
            Assert.Equal(searchResponseResolver, o.SearchResponseResolver);
            Assert.Equal(searchResponseCache.Object, o.SearchResponseCache);
            Assert.Equal(browseResponseResolver, o.BrowseResponseResolver);
            Assert.Equal(directoryContentsResponseResolver, o.DirectoryContentsResolver);
            Assert.Equal(userInfoResponseResolver, o.UserInfoResolver);
            Assert.Equal(enqueueDownloadAction, o.EnqueueDownload);
            Assert.Equal(placeInQueueResponseResolver, o.PlaceInQueueResolver);

            Assert.Equal(1, o.MaximumConcurrentUploadsPerUser);
        }
Пример #24
0
 public AndConstraint <CompilationResultAssertions> OnlyContainDiagnostic(string code, DiagnosticLevel level, string message, string because = "", params object[] becauseArgs)
 => DoWithDiagnosticAnnotations(diags =>
 {
     diags.Should().ContainSingleDiagnostic(code, level, message, because, becauseArgs);
 });
Пример #25
0
        public AndConstraint <CompilationAssertions> ContainSingleDiagnostic(string code, DiagnosticLevel level, string message, string because = "", params object[] becauseArgs)
        {
            Subject.GetEntrypointSemanticModel().GetAllDiagnostics().Should().ContainSingleDiagnostic(code, level, message, because, becauseArgs);

            return(new AndConstraint <CompilationAssertions>(this));
        }
Пример #26
0
        public void Type_validation_runs_on_compilation_successfully(TypeSymbolValidationFlags validationFlags, DiagnosticLevel expectedDiagnosticLevel)
        {
            var customTypes = new[] {
                TestTypeHelper.CreateCustomResourceType("My.Rp/myType", "2020-01-01", validationFlags),
            };
            var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: { }
}
";

            var model = GetSemanticModelForTest(program, customTypes);

            model.GetAllDiagnostics().Should().BeEmpty();
        }
Пример #27
0
 private static LogLevel ToLogLevel(DiagnosticLevel level)
 => level switch
 {
 private ObjectDef toObjectDef(DiagnosticLevel level)
 {
     return theChain.As<IContainerModel>().ToObjectDef(level);
 }
Пример #29
0
 public override string toString(DiagnosticLevel minLevel = DiagnosticLevel.info)
 {
     return(toDiagnosticsNode(style: DiagnosticsTreeStyle.error).toStringDeep(minLevel: minLevel));
 }
Пример #30
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="SoulseekClientOptions"/> class.
        /// </summary>
        /// <param name="enableListener">A value indicating whether to listen for incoming connections.</param>
        /// <param name="listenPort">The port on which to listen for incoming connections.</param>
        /// <param name="enableDistributedNetwork">A value indicating whether to establish distributed network connections.</param>
        /// <param name="acceptDistributedChildren">A value indicating whether to accept distributed child connections.</param>
        /// <param name="distributedChildLimit">The number of allowed distributed children.</param>
        /// <param name="deduplicateSearchRequests">
        ///     A value indicating whether duplicated distributed search requests should be discarded.
        /// </param>
        /// <param name="messageTimeout">
        ///     The message timeout, in milliseconds, used when waiting for a response from the server.
        /// </param>
        /// <param name="autoAcknowledgePrivateMessages">
        ///     A value indicating whether to automatically send a private message acknowledgement upon receipt.
        /// </param>
        /// <param name="autoAcknowledgePrivilegeNotifications">
        ///     A value indicating whether to automatically send a privilege notification acknowledgement upon receipt.
        /// </param>
        /// <param name="acceptPrivateRoomInvitations">A value indicating whether to accept private room invitations.</param>
        /// <param name="minimumDiagnosticLevel">The minimum level of diagnostic messages to be generated by the client.</param>
        /// <param name="startingToken">The starting value for download and search tokens.</param>
        /// <param name="serverConnectionOptions">The options for the server message connection.</param>
        /// <param name="peerConnectionOptions">The options for peer message connections.</param>
        /// <param name="transferConnectionOptions">The options for peer transfer connections.</param>
        /// <param name="incomingConnectionOptions">The options for incoming connections.</param>
        /// <param name="distributedConnectionOptions">The options for distributed message connections.</param>
        /// <param name="userEndPointCache">The user endpoint cache to use when resolving user endpoints.</param>
        /// <param name="searchResponseResolver">
        ///     The delegate used to resolve the <see cref="SearchResponse"/> for an incoming <see cref="SearchRequest"/>.
        /// </param>
        /// <param name="browseResponseResolver">
        ///     The delegate used to resolve the <see cref="BrowseResponse"/> for an incoming <see cref="BrowseRequest"/>.
        /// </param>
        /// <param name="directoryContentsResponseResolver">
        ///     The delegate used to resolve the <see cref="FolderContentsResponse"/> for an incoming <see cref="FolderContentsRequest"/>.
        /// </param>
        /// <param name="userInfoResponseResolver">
        ///     The delegate used to resolve the <see cref="UserInfo"/> for an incoming <see cref="UserInfoRequest"/>.
        /// </param>
        /// <param name="enqueueDownloadAction">The delegate invoked upon an receipt of an incoming <see cref="QueueDownloadRequest"/>.</param>
        /// <param name="placeInQueueResponseResolver">
        ///     The delegate used to resolve the <see cref="PlaceInQueueResponse"/> for an incoming request.
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     Thrown when the value supplied for <paramref name="listenPort"/> is not between 1024 and 65535.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     Thrown when the value supplied for <paramref name="distributedChildLimit"/> is less than zero.
        /// </exception>
        public SoulseekClientOptions(
            bool enableListener                            = true,
            int listenPort                                 = 50000,
            bool enableDistributedNetwork                  = true,
            bool acceptDistributedChildren                 = true,
            int distributedChildLimit                      = 25,
            bool deduplicateSearchRequests                 = true,
            int messageTimeout                             = 5000,
            bool autoAcknowledgePrivateMessages            = true,
            bool autoAcknowledgePrivilegeNotifications     = true,
            bool acceptPrivateRoomInvitations              = false,
            DiagnosticLevel minimumDiagnosticLevel         = DiagnosticLevel.Info,
            int startingToken                              = 0,
            ConnectionOptions serverConnectionOptions      = null,
            ConnectionOptions peerConnectionOptions        = null,
            ConnectionOptions transferConnectionOptions    = null,
            ConnectionOptions incomingConnectionOptions    = null,
            ConnectionOptions distributedConnectionOptions = null,
            IUserEndPointCache userEndPointCache           = null,
            Func <string, int, SearchQuery, Task <SearchResponse> > searchResponseResolver = null,
            Func <string, IPEndPoint, Task <BrowseResponse> > browseResponseResolver       = null,
            Func <string, IPEndPoint, int, string, Task <Directory> > directoryContentsResponseResolver = null,
            Func <string, IPEndPoint, Task <UserInfo> > userInfoResponseResolver         = null,
            Func <string, IPEndPoint, string, Task> enqueueDownloadAction                = null,
            Func <string, IPEndPoint, string, Task <int?> > placeInQueueResponseResolver = null)
        {
            EnableListener = enableListener;
            ListenPort     = listenPort;

            if (ListenPort < 1024 || ListenPort > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException(nameof(listenPort), "Must be between 1024 and 65535");
            }

            EnableDistributedNetwork  = enableDistributedNetwork;
            AcceptDistributedChildren = acceptDistributedChildren;
            DistributedChildLimit     = distributedChildLimit;

            if (DistributedChildLimit < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(distributedChildLimit), "Must be greater than or equal to zero");
            }

            DeduplicateSearchRequests = deduplicateSearchRequests;

            MessageTimeout = messageTimeout;
            AutoAcknowledgePrivateMessages        = autoAcknowledgePrivateMessages;
            AutoAcknowledgePrivilegeNotifications = autoAcknowledgePrivilegeNotifications;
            AcceptPrivateRoomInvitations          = acceptPrivateRoomInvitations;
            MinimumDiagnosticLevel = minimumDiagnosticLevel;
            StartingToken          = startingToken;

            ServerConnectionOptions      = (serverConnectionOptions ?? new ConnectionOptions()).WithoutInactivityTimeout();
            PeerConnectionOptions        = peerConnectionOptions ?? new ConnectionOptions();
            TransferConnectionOptions    = (transferConnectionOptions ?? new ConnectionOptions()).WithoutInactivityTimeout();
            IncomingConnectionOptions    = incomingConnectionOptions ?? new ConnectionOptions();
            DistributedConnectionOptions = distributedConnectionOptions ?? new ConnectionOptions();

            UserEndPointCache = userEndPointCache;

            SearchResponseResolver            = searchResponseResolver;
            BrowseResponseResolver            = browseResponseResolver ?? defaultBrowseResponse;
            DirectoryContentsResponseResolver = directoryContentsResponseResolver;

            UserInfoResponseResolver     = userInfoResponseResolver ?? defaultUserInfoResponse;
            EnqueueDownloadAction        = enqueueDownloadAction ?? defaultEnqueueDownloadAction;
            PlaceInQueueResponseResolver = placeInQueueResponseResolver ?? defaultPlaceInQueueResponse;
        }
Пример #31
0
        public void Type_validation_narrowing_on_union_types(TypeSymbolValidationFlags validationFlags, DiagnosticLevel expectedDiagnosticLevel)
        {
            var customTypes = new[] {
                TestTypeHelper.CreateCustomResourceType("My.Rp/myType", "2020-01-01", validationFlags,
                                                        new TypeProperty("stringOrInt", TypeHelper.CreateTypeUnion(LanguageConstants.String, LanguageConstants.Int), TypePropertyFlags.AllowImplicitNull),
                                                        new TypeProperty("unspecifiedStringOrInt", TypeHelper.CreateTypeUnion(LanguageConstants.String, LanguageConstants.Int), TypePropertyFlags.AllowImplicitNull),
                                                        new TypeProperty("abcOrDef", TypeHelper.CreateTypeUnion(new StringLiteralType("abc"), new StringLiteralType("def")), TypePropertyFlags.AllowImplicitNull),
                                                        new TypeProperty("unspecifiedAbcOrDef", TypeHelper.CreateTypeUnion(new StringLiteralType("abc"), new StringLiteralType("def")), TypePropertyFlags.AllowImplicitNull)),
                TestTypeHelper.CreateCustomResourceType("My.Rp/myDependentType", "2020-01-01", validationFlags,
                                                        new TypeProperty("stringOnly", LanguageConstants.String, TypePropertyFlags.AllowImplicitNull),
                                                        new TypeProperty("abcOnly", new StringLiteralType("abc"), TypePropertyFlags.AllowImplicitNull),
                                                        new TypeProperty("abcOnlyUnNarrowed", new StringLiteralType("abc"), TypePropertyFlags.AllowImplicitNull),
                                                        new TypeProperty("stringOrIntUnNarrowed", TypeHelper.CreateTypeUnion(LanguageConstants.String, LanguageConstants.Int), TypePropertyFlags.AllowImplicitNull),
                                                        new TypeProperty("abcOrDefUnNarrowed", TypeHelper.CreateTypeUnion(new StringLiteralType("abc"), new StringLiteralType("def"), new StringLiteralType("ghi")), TypePropertyFlags.AllowImplicitNull)),
            };
            var program = @"
resource myRes 'My.Rp/myType@2020-01-01' = {
  name: 'steve'
  properties: {
    stringOrInt: 'abc'
    abcOrDef: 'abc'
  }
}

resource myDependentRes 'My.Rp/myDependentType@2020-01-01' = {
  name: 'steve'
  properties: {
    stringOnly: myRes.properties.stringOrInt // should be allowed
    abcOnly: myRes.properties.abcOrDef
    abcOnlyUnNarrowed: myRes.properties.unspecifiedAbcOrDef
    stringOrIntUnNarrowed: myRes.properties.unspecifiedStringOrInt
    abcOrDefUnNarrowed: myRes.properties.abcOrDef
  }
}
";

            var model = GetSemanticModelForTest(program, customTypes);

            model.GetAllDiagnostics().Should().SatisfyRespectively(
                x => x.Should().HaveCodeAndSeverity("BCP036", DiagnosticLevel.Warning).And.HaveMessage("The property \"abcOnlyUnNarrowed\" expected a value of type \"'abc' | null\" but the provided value is of type \"'abc' | 'def'\". If this is an inaccuracy in the documentation, please report it to the Bicep Team.")
                );
        }
Пример #32
0
 public Diagnostic(int offset, int length, string project, string file, int line, string message, string code, DiagnosticLevel level,
                   DiagnosticCategory category, DiagnosticSourceKind kind = DiagnosticSourceKind.Analysis)
 {
     StartOffset = offset;
     Length      = length;
     Project     = project;
     File        = file;
     Line        = line;
     Spelling    = message;
     Level       = level;
     Category    = category;
     Code        = code;
     Source      = kind;
 }
Пример #33
0
 public TargetDependencyViewModel(TargetFramework targetFramework, DiagnosticLevel diagnosticLevel)
 {
     Caption          = targetFramework.TargetFrameworkAlias;
     Flags            = GetCachedFlags(targetFramework);
     _diagnosticLevel = diagnosticLevel;
Пример #34
0
        public AndConstraint <DiagnosticCollectionAssertions> ContainSingleDiagnostic(string code, DiagnosticLevel level, string message, string because = "", params object[] becauseArgs)
        {
            AssertionExtensions.Should(Subject).ContainSingle(x => x.Code == code && x.Level == level && x.Message == message, because, becauseArgs);

            return(new AndConstraint <DiagnosticCollectionAssertions>(this));
        }
 private ObjectDef toObjectDef(DiagnosticLevel level)
 {
     return(theChain.As <IContainerModel>().ToObjectDef(level));
 }
        private IActionBehavior behavior(DiagnosticLevel level)
        {
            var objectDef = theNode.As<IContainerModel>().ToObjectDef(level);
            var instance = new ObjectDefInstance(objectDef);

            return theContainer.GetInstance<IActionBehavior>(instance);
        }
Пример #37
0
 private static int ToMonacoSeverity(DiagnosticLevel level)
 => level switch
 {