Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added schema validation rule that ensures that interfaces are implemented. #979

Merged
merged 5 commits into from
Aug 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Core/Core/Execution/Utilities/ValueCompletion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using HotChocolate.Properties;
using HotChocolate.Types;
using HotChocolate.Utilities;
using HotChocolate.Configuration;

namespace HotChocolate.Execution
{
Expand Down Expand Up @@ -176,7 +175,8 @@ private static void CompleteCompositeType(
b.SetMessage(string.Format(
CultureInfo.InvariantCulture,
CoreResources.CompleteCompositeType_UnknownSchemaType,
context.Value.GetType().GetTypeName())));
result.GetType().GetTypeName(),
type.NamedType().Name.Value)));
context.Value = null;
}
else
Expand Down
63 changes: 33 additions & 30 deletions src/Core/Core/Properties/CoreResources.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema

Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,40 +26,43 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple

There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:schema id="root"
xmlns=""
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
Expand Down Expand Up @@ -118,7 +121,7 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CompleteCompositeType_UnknownSchemaType" xml:space="preserve">
<value>Could not resolve the schema type from `{0}`.</value>
<value>Could not resolve the actual object type from `{0}` for the abstract type `{1}`.</value>
</data>
<data name="CompleteLeadType_UndefinedError" xml:space="preserve">
<value>Undefined scalar field serialization error.</value>
Expand Down Expand Up @@ -214,4 +217,4 @@ The maximum allowed query complexity is {1}.</value>
<data name="RequestTimeoutMiddleware_Timeout" xml:space="preserve">
<value>Execution timeout has been exceeded.</value>
</data>
</root>
</root>
59 changes: 57 additions & 2 deletions src/Core/Types.Tests/Configuration/TypeInitializerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public void Register_SchemaType_ClrTypeExists()
t => t is FooType);

// act
typeInitializer.Initialize(() => null);
typeInitializer.Initialize(() => null, new SchemaOptions());

// assert
bool exists = typeInitializer.Types.TryGetValue(
Expand Down Expand Up @@ -79,7 +79,7 @@ public void Register_ClrType_InferSchemaTypes()
t => t is ObjectType<Foo>);

// act
typeInitializer.Initialize(() => null);
typeInitializer.Initialize(() => null, new SchemaOptions());

// assert
bool exists = typeInitializer.Types.TryGetValue(
Expand All @@ -105,6 +105,61 @@ public void Register_ClrType_InferSchemaTypes()
.MatchSnapshot(new SnapshotNameExtension("BarType"));
}

[Fact]
public void Initializer_SchemaResolver_Is_Null()
{
// arrange
var initialTypes = new List<ITypeReference>();
initialTypes.Add(new ClrTypeReference(
typeof(Foo),
TypeContext.Output));

var serviceProvider = new EmptyServiceProvider();

var typeInitializer = new TypeInitializer(
serviceProvider,
DescriptorContext.Create(),
initialTypes,
new List<Type>(),
new Dictionary<string, object>(),
null,
t => t is ObjectType<Foo>);

// act
Action action =
() => typeInitializer.Initialize(null, new SchemaOptions());

// assert
Assert.Throws<ArgumentNullException>(action);
}

[Fact]
public void Initializer_SchemaOptions_Are_Null()
{
// arrange
var initialTypes = new List<ITypeReference>();
initialTypes.Add(new ClrTypeReference(
typeof(Foo),
TypeContext.Output));

var serviceProvider = new EmptyServiceProvider();

var typeInitializer = new TypeInitializer(
serviceProvider,
DescriptorContext.Create(),
initialTypes,
new List<Type>(),
new Dictionary<string, object>(),
null,
t => t is ObjectType<Foo>);

// act
Action action =
() => typeInitializer.Initialize(() => null, null);

// assert
Assert.Throws<ArgumentNullException>(action);
}

public class FooType
: ObjectType<Foo>
Expand Down
94 changes: 94 additions & 0 deletions src/Core/Types.Tests/SchemaBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,88 @@ public void Could_Not_Resolve_Type()
Assert.Throws<SchemaException>(action).Message);
}

[Fact]
public void Interface_Without_Implementation()
{
// arrange
// act
Action action = () => SchemaBuilder.New()
.AddDocumentFromString(@"
type Query {
foo : Bar
}
interface Bar {
baz: String
}")
.AddResolver("Query", "foo", "bar")
.Create();

// assert
Assert.Equal(
"There is no object type implementing interface `Bar`. - Type: Bar",
Assert.Throws<SchemaException>(action).Message);
}

[Fact]
public void Interface_Without_Implementation_Not_Strict()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddDocumentFromString(@"
type Query {
foo : Bar
}
interface Bar {
baz: String
}")
.AddResolver("Query", "foo", "bar")
.ModifyOptions(o => o.StrictValidation = false)
.Create();

// assert
Assert.NotNull(schema);
}

[Fact]
public async Task Execute_Agains_Interface_Without_Impl_Field()
{
// arrange
ISchema schema = SchemaBuilder.New()
.AddDocumentFromString(@"
type Query {
foo : Bar
}
interface Bar {
baz: String
}")
.AddResolver("Query", "foo", "bar")
.ModifyOptions(o => o.StrictValidation = false)
.Create();

IQueryExecutor executor = schema.MakeExecutable();

// act
IExecutionResult result =
await executor.ExecuteAsync("{ foo { baz } }");

// assert
result.ToJson().MatchSnapshot();
}

[Fact]
public void Abstract_Classes_Are_Allowed_As_Object_Types()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<AbstractQuery>()
.Create();

// assert
schema.ToString().MatchSnapshot();
}

public class DynamicFooType
: ObjectType
{
Expand Down Expand Up @@ -1055,5 +1137,17 @@ public class QueryWithIntField
{
public int Foo { get; set; }
}

public abstract class AbstractQuery
{
public string Foo { get; set; }

public AbstractChild Object { get; set; }
}

public abstract class AbstractChild
{
public string Foo { get; set; }
}
}
}
1 change: 1 addition & 0 deletions src/Core/Types.Tests/SchemaFirstTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public async Task DescriptionsAreCorrectlyRead()
source,
c =>
{
c.Options.StrictValidation = false;
c.Use(next => context => next(context));
});

Expand Down
12 changes: 11 additions & 1 deletion src/Core/Types.Tests/Types/Directives/CostDirectiveTypeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ public void AnnotateCostToInterfaceFieldCodeFirst()
.Type<StringType>()
.Cost(5)));

t.Options.StrictValidation = false;

t.Use(next => context => Task.CompletedTask);
});

Expand Down Expand Up @@ -139,6 +141,8 @@ public void AnnotateCostToInterfaceFieldCodeFirstOneMultiplier()
.Type<StringType>()
.Cost(5, "a")));

t.Options.StrictValidation = false;

t.Use(next => context => Task.CompletedTask);
});

Expand Down Expand Up @@ -172,6 +176,8 @@ public void AnnotateCostToInterfaceFieldCodeFirstTwoMultiplier()
.Type<StringType>()
.Cost(5, "a", "b")));

t.Options.StrictValidation = false;

t.Use(next => context => Task.CompletedTask);
});

Expand Down Expand Up @@ -223,7 +229,11 @@ interface IQuery {
@cost(complexity: 5 multipliers: [""a""])
}
",
t => t.Use(next => context => Task.CompletedTask));
t =>
{
t.Use(next => context => Task.CompletedTask);
t.Options.StrictValidation = false;
});

InterfaceType queryInterface = schema.GetType<InterfaceType>("IQuery");
IDirective directive = queryInterface.Fields["field"].Directives
Expand Down
Loading