Simmy Chaos Engine for .NET – Part 5, Breaking Your Own Code

Full source code here.

Want to learn more about Polly? Check out my Pluralsight course on it.

The blog posts I have written so far about Simmy all deal with the scenario where you don’t have control over the source code that you want to break, in these cases Simmy policies are applied to the calling code.

In this post I’m going to show a very simple way of generating faults inside your own code. (For those of you familiar with Polly, you could use a policy registry, but I’m not going to in this example).

I have a Web Api application that has a very contrived RandomValueGenerator to return numbers and strings.

The RandomValueGenerator has fault policy that throws exceptions and a behavior policy that replaces good data with bad data.

The fault policy looks like this -

1InjectOutcomePolicy _faultPolicy = MonkeyPolicy.InjectFault( 
2    new Exception("Simmy threw an exception"),
3    injectionRate: .5,
4    enabled: () => true

50% of the time it will throw an exception.

The behavior policy looks like this -

1InjectOutcomePolicy<NameAndLength> _corruptDataPolicy = MonkeyPolicy.InjectFault<NameAndLength>(
2    new NameAndLength { Name = "xxxxx", Lenght = -100 },
3    injectionRate: .5,
4    enabled: () => true

50% of the time it will change the name to “xxxxx” and the length to -100.

Here’s how to use these policies inside the RandomValueGenerator -

 1public string GetRandomName()
 3    return _faultPolicy.Execute(() => names\[_random.Next(0, 5)\]);
 6public int GetRandomNumber()
 8    return _faultPolicy.Execute(() => _random.Next(0, 100));
11public NameAndLength GetNameAndLength()
13    string name = names\[_random.Next(0, 5)\];
14    NameAndLength nameAndLength = new NameAndLength { Name = name, Lenght = name.Length };
15    return _corruptDataPolicy.Execute(() => nameAndLength);

As mentioned earlier, a policy registry might be a better way of passing and reusing the Simmy policies and this will be covered in the next post on Simmy.

Full source code here.

comments powered by Disqus