Prevent the spec version attribute from being removed via Remove calls

Signed-off-by: Jon Skeet <jonskeet@google.com>
This commit is contained in:
Jon Skeet 2020-08-03 10:59:00 +01:00 committed by Jon Skeet
parent c95871b782
commit 4aa5a481e3
2 changed files with 26 additions and 0 deletions

View File

@ -267,11 +267,19 @@ namespace CloudNative.CloudEvents
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
{
if (item.Key.Equals(SpecVersionAttributeName(this.SpecVersion), StringComparison.InvariantCultureIgnoreCase))
{
throw new InvalidOperationException(Strings.ErrorSpecVersionCannotBeCleared);
}
return dict.Remove(item);
}
bool IDictionary<string, object>.Remove(string key)
{
if (key.Equals(SpecVersionAttributeName(this.SpecVersion), StringComparison.InvariantCultureIgnoreCase))
{
throw new InvalidOperationException(Strings.ErrorSpecVersionCannotBeCleared);
}
return dict.Remove(key);
}

View File

@ -62,5 +62,23 @@ namespace CloudNative.CloudEvents.UnitTests
Assert.Equal(CloudEventAttributes.SpecVersionAttributeName(), entry.Key);
Assert.Equal(specVersionValue, entry.Value);
}
[Fact]
public void Dictionary_Remove_SpecVersion()
{
IDictionary<string, object> attributes = new CloudEventAttributes(CloudEventsSpecVersion.Default, emptyExtensions);
string specVersionAttributeName = CloudEventAttributes.SpecVersionAttributeName();
Assert.Throws<InvalidOperationException>(() => attributes.Remove(specVersionAttributeName));
}
[Fact]
public void Collection_Remove_SpecVersion()
{
ICollection<KeyValuePair<string, object>> attributes = new CloudEventAttributes(CloudEventsSpecVersion.Default, emptyExtensions);
string specVersionAttributeName = CloudEventAttributes.SpecVersionAttributeName();
// The value part is irrelevant; we throw on any attempt to remove a pair with a key that's the spec attribute version.
var pair = KeyValuePair.Create(specVersionAttributeName, new object());
Assert.Throws<InvalidOperationException>(() => attributes.Remove(pair));
}
}
}