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

Full source code here.

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 –

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

50% of the time it will throw an exception.

The behavior policy looks like this –

InjectOutcomePolicy<NameAndLength> _corruptDataPolicy = MonkeyPolicy.InjectFault<NameAndLength>(
    new NameAndLength { Name = "xxxxx", Lenght = -100 },
    injectionRate: .5,
    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

public string GetRandomName()
{
    return _faultPolicy.Execute(() => names[_random.Next(0, 5)]);
}

public int GetRandomNumber()
{
    return _faultPolicy.Execute(() => _random.Next(0, 100));
}

public NameAndLength GetNameAndLength()
{
    string name = names[_random.Next(0, 5)];
    NameAndLength nameAndLength = new NameAndLength { Name = name, Lenght = name.Length };
    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.