I'm trying what, to me, seems like some fairly basic code contracts code. I've reduced it down to the following problem. The following fails the static analysis, with the message
CodeContracts: ensures unproven:
this.Frozen
using System;
using System.Diagnostics.Contracts;
namespace PlayAreaCollection2010
{
public class StrippedContract : IBasic
{
private bool _frozen = false;
public void Freeze()
{
_frozen = true;
}
public bool Frozen { get { return _frozen; } }
}
[ContractClass(typeof(IBasicContract))]
public interface IBasic
{
void Freeze();
bool Frozen { get; }
}
[ContractClassFor(typeof(IBasic))]
public abstract class IBasicContract : IBasic
{
#region IBasic Members
public void Freeze()
{
Contract.Ensures(this.Frozen);
}
public bool Frozen
{
get { return true;}
}
#endregion
}
}
However, the following works fine and satisfies all checks:
using System;
using System.Diagnostics.Contracts;
namespace PlayAreaCollection2010
{
public class StrippedContract
{
private bool _frozen = false;
public void Freeze()
{
Contract.Ensures(this.Frozen);
_frozen = true;
}
public bool Frozen { get { return _frozen; } }
}
}
CodeContracts: Checked 1 assertion: 1 correct
What do I need to do to satisfy the static checker, when I've placed my contracts in the interface?
In your implementation of IBasic, StrippedContract, you will need to add a post-condition to the Frozen property:
public bool Frozen {
get {
Contract.Ensures(Contract.Result<bool>() == this._frozen);
return _frozen;
}
}
Alternatively, you could add the -infer command line option to the static checker in the Code Contracts tab of your project's properties. That will allow the static checker to infer this automatically.
Related
Let's say we have this code
namespace app.Entities
{
public class school
{
public bool Addschool() { }
}
}
namespace app.layer1
{
public class ManageSchool
{
public bool schoolInfo() {
schoolInfo.addSchool();
}
}
}
namespace app.layer
{
public class schoolAPi
{
public bool GetAndAdd()
{
ManageSchool.schoolInfo();
}
}
}
i want to know which layers and fuctions called AddSchool() method in app.entitied namespace
for exp :
app.layer2.schoolAPi.GetAndAdd >> app.layer1.ManageSchool.schoolInfo >> app.Entities.school.Addschool
Try look at System.Diagnostics.StackTrace and System.Diagnostics.StackFrame classes.
You can create some Tracer class with Trace method to trace each call, but you supposed to put trace in each method to be able to trace it.
Example of Tracer.cs:
using System.Diagnostics;
public class Tracer
{
public static void Trace()
{
StackFrame sf = new StackTrace(true).GetFrame(1);
Console.WriteLine("Called {0} in {1} at line: {2}", sf.GetMethod().ToString(), sf.GetFileName(), sf.GetFileLineNumber());
}
}
Examples of your project:
Entities.cs:
namespace App.Entities
{
public class School
{
public static bool AddSchool()
{
Tracer.Trace();
return true;
}
}
}
LayerOne.cs:
using App.Entities;
namespace App.LayerOne
{
public class ManageSchool
{
public static bool SchoolInfo()
{
Tracer.Trace();
School.AddSchool();
return true;
}
}
}
LayerTwo.cs:
using App.LayerOne;
namespace App.LayerTwo
{
public class SchoolAPI
{
public static bool GetAndAdd()
{
Tracer.Trace();
ManageSchool.SchoolInfo();
return true;
}
}
}
And a Program.cs:
using System;
using App.LayerTwo;
namespace App
{
class Program
{
static void Main(string[] args)
{
Tracer.Trace();
SchoolMethod();
Console.ReadKey();
}
static void SchoolMethod()
{
Tracer.Trace();
SchoolAPI.GetAndAdd();
}
}
}
It will give you some kind of this result:
Also you can put Tracer.Trace() method under bool condition of some global setting and use it only when you need trace:
if (MySettingsClass.TraceEnabled)
Tracer.Trace();
Okay so I am working on a project that haves a abstract public abstract bool IsFull { get; } this is how the school wants me to set it up. I was trying to figure out a work around that but I can't. I have a few files not sure if I want them all to post. so in my class it is inherited from a different class. so when I initiate it from the program cs class I can't get the boolean to change with a simple IsFull = true. I tried IsFull.Equal(true); but read that just a comparison attribute. I will show my code. Remember this is 100% new to me so if you asked questions why don't i do it this way the answer is I never was taught that lol.
So is there a way I can override it within the sweettooth class?
My Ninja class
using System.Collections.Generic;
using IronNinja.Interfaces;
namespace IronNinja.Models
{
abstract class Ninja
{
protected int calorieIntake;
public List<IConsumable> ConsumptionHistory;
public Ninja()
{
calorieIntake = 0;
ConsumptionHistory = new List<IConsumable>();
}
public abstract bool IsFull { get; }
public abstract void Consume(IConsumable item);
}
}
my inherited class sweettooth
using IronNinja.Interfaces;
namespace IronNinja.Models
{
class SweetTooth : Ninja
{
public string Name;
public SweetTooth(string name)
{
Name = name;
}
public override bool IsFull { get; }
public override void Consume(IConsumable item)
{
// provide override for Consume
int sweet = 0;
if (calorieIntake >= 1500)
{
}
else
{
if (item.IsSweet)
{
sweet = 10;
}
ConsumptionHistory.Add(item);
calorieIntake += item.Calories + sweet;
}
item.GetInfo();
}
}
}
Lastly my Programs .cs file
using System;
using IronNinja.Models;
namespace IronNinja
{
class Program
{
static void Main(string[] args)
{
Buffet hungryJack = new Buffet();
SweetTooth Albert = new SweetTooth("Alby");
while (!Albert.IsFull)
{
Albert.Consume(hungryJack.Serve());
}
foreach (Food item in Albert.ConsumptionHistory)
{
Console.WriteLine(item.Name);
System.Console.WriteLine(item.GetInfo());
}
}
}
}
From my understanding, the IsFull property can simply provide the logic to return whether or not the SweetTooth is full:
public override bool IsFull => calorieIntake >= 1500;
And then in SweetTooth.Consume you would check if they are full before consuming more consumables:
public override void Consume(IConsumable item)
{
// provide override for Consume
int sweet = 0;
if (IsFull)
{
return;
}
else
{
if (item.IsSweet)
{
sweet = 10;
}
ConsumptionHistory.Add(item);
calorieIntake += item.Calories + sweet;
}
item.GetInfo();
}
You simply can't, by language design. You can't make your subclass "more permissive" than the parent class.
If you want to assign IsFull property, you have to do it into the SweetTooth class through the constructor. Generally if you set a property with private setter is because you want to manage its state internally and do not let the client code to handle it.
Then, change the SweetTooth constructor as per below:
public SweetTooth(string name, bool isFull)
{
Name = name;
IsFull = isFull;
}
The alternative is to add a private backing field, but again you can edit this only internally:
private bool _isFull;
public override bool IsFull => _isFull;
The Equal method compares two values. In your specific case you called bool.Equals(bool) overload which worked as Albert.IsFull == true
I am working on a workflow project that has 19 scenarios for testing the whole system and 34 steps.
So, my question is, how can I create an automation test for it?
My current approach is:
Create an integrated test per each scenario, and then create the main system test to run all integrated tests.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Project1
{
// Unit tests
public class UnitTest_step1
{
public void RunTest() { }
}
public class UnitTest_step2
{
public void RunTest() { }
}
public class UnitTest_step3
{
public void RunTest() { }
}
public class UnitTest_step4
{
public void RunTest() { }
}
// End of unit tests
public class IntegrationTests
{
public void IntegrationTest1()
{
UnitTest_step1.RunTest();
UnitTest_step2.RunTest();
UnitTest_step4.RunTest();
}
public void IntegrationTest2()
{
UnitTest_step1.RunTest();
UnitTest_step2.RunTest();
UnitTest_step3.RunTest();
UnitTest_step4.RunTest();
}
public void IntegrationTest3()
{
UnitTest_step1.RunTest();
UnitTest_step4.RunTest();
}
}
[TestClass]
public class SystemTests
{
[TestMethod]
public void Scenario1()
{
IntegrationTests.IntegrationTest1()
}
[TestMethod]
public void Scenario2()
{
IntegrationTests.IntegrationTest2();
}
[TestMethod]
public void Scenario3()
{
IntegrationTests.IntegrationTest3();
}
[TestMethod]
public void ScenarioN()
{
IntegrationTests.IntegrationTestN();
}
}
}
Best Regards.
Well, in my opinion, the information provided in your question is very abstract and the question is a bit too broad.
The answer depends on how your workflow engine is implemented and what are your system requirements.
Requirements and implementation details are what defines your approach to testing.
I would start with clarifying what kind of steps you have, is there any data context is passed,
what side effects these steps produce (writes data to database, sends events, call other system APIs, etc.),
do steps depend on each other and so on.
Another question is how do you need to assert the results, after each step or after scenario?
The system should be testable and normally, each step should be covered with unit tests.
So, suggested hypothetical approach is to cover each step with isolated unit tests
and scenarios with integration tests.
I came up with a simple example just to illustrate one of the general approaches.
For simplicity, I assume that steps have little or no data context and can be reordered.
namespace Workflow.Test
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
[TestClass]
public class SystemTests
{
[TestMethod]
public void Scenario1()
{
new Workflow().Run(new Scenario1());
}
[TestMethod]
public void Scenario2()
{
new Workflow().Run(new Scenario2());
}
// The advantage of explicit steps declaration is test readability.
// Declarative approach also enables the further possibility of test generation!
[TestMethod]
public void MoreExplicitAndDeclarative()
{
new Workflow().Run(new List<Type>
{
typeof(Step1),
typeof(Step2),
typeof(Step3),
});
}
// Step instantiation may be needed if you want to parameterize some steps.
[TestMethod]
[DataRow("Custom step")]
[DataRow("Another step")]
public void MoreExplicitParameterizedScenario(string customName)
{
new Workflow().Run(new List<IRunnable>{
new Step1(),
new Step3(customName)
});
}
}
[TestClass]
public class StepsUnitTests
{
[TestMethod]
public void Step1DoesWhatWeWant()
{
// Mock dependencies
new Step1().Run();
// Assert results
}
}
#region Workflow Engine Example
public interface IRunnable
{
void Run();
}
public class Workflow
{
public void Run(Scenario scenario)
{
Run(CreateSteps(scenario.GetStepTypes()));
}
public void Run(IEnumerable<Type> stepTypes)
{
Run(CreateSteps(stepTypes));
}
public void Run(List<IRunnable> steps)
{
steps.ForEach(step => step.Run());
}
private List<IRunnable> CreateSteps(IEnumerable<Type> stepTypes)
{
var steps = new List<IRunnable>();
foreach (var stepType in stepTypes)
{
steps.Add(CreateStep(stepType));
}
return steps;
}
private IRunnable CreateStep(Type stepType)
=> (IRunnable) Activator.CreateInstance(stepType);
}
#endregion
// Step structure can differ according to system requirements.
// We may add data context and link steps into pipeline if needed.
#region Steps
public abstract class Step : IRunnable
{
private readonly string _stepName;
protected Step(string name)
{
_stepName = name;
}
public void Run()
{
Console.WriteLine($"{_stepName} in action.");
Invoke();
}
public abstract void Invoke();
}
public class Step1 : Step
{
public Step1() : base(nameof(Step1))
{
}
public override void Invoke()
{
// do work
Console.WriteLine($"Step1 invoked.");
}
}
public class Step2 : Step
{
public Step2() : base(nameof(Step2))
{
}
public override void Invoke()
{
// do work
Console.WriteLine($"Step2 invoked.");
}
}
public class Step3 : Step
{
public Step3(string customName) : base(customName)
{
}
public Step3() : this(nameof(Step3))
{
}
public override void Invoke()
{
// do work
Console.WriteLine($"Step3 invoked.");
}
}
public class Step4 : Step
{
public Step4() : base(nameof(Step4))
{
}
public override void Invoke()
{
// do work
Console.WriteLine($"Step4 invoked.");
}
}
#endregion
// Scenarios should be as declarative as possible.
// Let's say the scenario is just specification of what steps (step Type)
// and in what order should be executed (List as a non-unique ordered collection).
#region Scenarios
public abstract class Scenario
{
public abstract List<Type> GetStepTypes();
}
public class Scenario1 : Scenario
{
public override List<Type> GetStepTypes()
=> new List<Type>
{
typeof(Step1),
typeof(Step2),
typeof(Step3)
};
}
public class Scenario2 : Scenario
{
public override List<Type> GetStepTypes()
=> new List<Type>
{
typeof(Step1),
typeof(Step2),
typeof(Step4)
};
}
#endregion
}
I'm using IoC to define some behavior in my inherited class. I have a property
protected virtual bool UsesThing { get { return true; } }
in my top-level class.
In my inherited class I have
protected override bool UsesThing { get { return false; } }
I'm using the property in my top level class, and it's using the top-level value. Is there a way to make it use the inherited value? I thought that's what virtual was supposed to do.
Code Example:
using System;
public class Program
{
public static void Main()
{
B b = new B();
b.PrintThing();
//I want this to print the value for B
}
public class A
{
protected virtual bool Enabled
{
get
{
return true;
}
}
public void PrintThing()
{
Console.WriteLine(this.Enabled.ToString());
}
}
public class B : A
{
protected override bool Enabled
{
get
{
return false;
}
}
}
}
Here's a Dot Net Fiddle demonstrating my problem
You could do something like this:
https://dotnetfiddle.net/SOiLni
A in of itself knows nothing of B's implementation, so you have to instantiate an object of B in order to access its overriden property.
Slightly modified version of your fiddle:
public class Program
{
public static void Main()
{
A a = new A();
a.PrintThing();
A newA = new B();
newA.PrintThing();
}
public class A
{
protected virtual bool Enabled
{
get
{
return true;
}
}
public void PrintThing()
{
Console.WriteLine(this.Enabled.ToString());
}
}
public class B : A
{
protected override bool Enabled
{
get
{
return false;
}
}
}
}
Given your code example, A's Enabled will be printed, as it should.
When you create an A it knows nothing about B, so polymorphically, you can't expect it to use its value. This makes since, because if you had a class C that also derived from A, it wouldn't know what to use!
On the other hand, if you had written:
public static void Main()
{
A a = new B();
a.PrintThing();
}
You would expect (correctly) that it would use B's override, as you created an instance of that type.
You must have some other issue with your code. This code will print 'true' and 'false' respectively:
public class BaseClass {
public virtual bool DoesSomething {
get {
return true;
}
}
public void Print() {
Console.WriteLine(DoesSomething);
}
}
public class ChildClass : BaseClass {
public override bool DoesSomething {
get {
return false;
}
}
}
Then using these classes:
BaseClass bc = new BaseClass();
bc.Print();
ChildClass sc = new ChildClass();
sc.Print();
If I was to guess you are probably creating instances of the parent class even though your intention is to create instances of the child class.
I have a class with many methods and a private readonly bool field called _isLoaded with its coresponding property: public bool IsLoaded:
class MyClass
{
readonly bool _isLoaded;
public bool IsLoaded
{
get { return _isLoaded; }
}
public void Method1()
{
//does whatever
}
public void Method2()
{
//does another thing
}
public void Load()
{
//does a lot of things and then...
_isLoaded = true;
}
}
I know there are object invariant methods that assure that after invoking any public method, certain objects still remain in a consistent state. Like, if I added this to my class:
[ContractInvariantMethod]
void checkState()
{
Contract.Invariant(!_isLoaded);
}
now, my problem is: is there a way to tell the runtime not to invoke the method annotated with ContractInvariantMethod for just one specific public method (in my case, Load), so I could be sure that only that one method would be changing the state of my field?
(Or some other way to achieve the same end)
Thanks.
Edit:
#Liel
Thanks a lot for the answer!
This pattern works perfectly when we have only one field to worry about. I also added this contract postcondition:
public abstract class BaseMyClass
{
private bool _isLoaded;
public bool IsLoaded
{
get { return _isLoaded; }
}
public virtual void Load()
{
Contract.Ensures(IsLoaded);
_isLoaded = true;
}
}
public class MyClass : BaseMyClass
{
public override void Load()
{
//does a lot of things and then...
base.Load();
}
}
Unfortunately, the static checker isn't smart enough to figure out I have to call base.Load() to fulfill the postcondition. It suggests I could just Contract.Assume(IsLoaded)... Apparently, The static checker is far from perfect.
If I understand what you want to achieve, you can use the Contract.OldValue() construct:
public class MyClass
{
bool _isLoaded;
public bool IsLoaded
{
get { return _isLoaded; }
}
public void Method1()
{
Contract.Ensures(this._isLoaded == Contract.OldValue(this._isLoaded));
//does whatever
_isLoaded = false;
}
public void Method2()
{
Contract.Ensures(this._isLoaded == Contract.OldValue(this._isLoaded));
//does another thing
}
public void Load()
{
//does a lot of things and then...
_isLoaded = true;
}
}
When you compile this, you'll get the following warning:
CodeContracts: ensures unproven: this._isLoaded == Contract.OldValue(this._isLoaded)
You can try the following approach:
public class BaseMyClass
{
private bool _isLoaded;
public bool IsLoaded
{
get { return _isLoaded; }
}
public virtual void Load()
{
_isLoaded = true;
}
}
public class MyClass : BaseMyClass
{
public void Method1()
{
//does whatever
}
public override void Load()
{
//does a lot of things and then...
base.Load();
}
}
This way you can access IsLoaded from MyClass, and make sure that only Load overrides are changing the _isLoaded property.