Thursday, August 28, 2008

Graph Walk Algrithm for Testing

Diane talked with me about the idea of finding all routes for her testing cases. We realized it is pretty much an algrithm of graph walk. I did it for her with c#


//GraphPaths.cs
//By S.Luan
//2008-08-26

using System;
using System.Collections.Generic;
using System.Text;
namespace TestingPath
{
class Program
{
static List _startNodes = new List();
static List _endNodes = new List();
static List _workingNodes = new List();
static List _paths = new List();
static List _connections = new List();
static List _rollbacks = new List();
static void Main(string[] args)
{
InitData();
FindNext(_startNodes);
foreach (string path in _paths)
{
Console.WriteLine(path);
}
Console.Read();
}
static void FindNext(List nodes)
{
foreach (int i in nodes)
{
_workingNodes.Add(i);
//if (HasNode(_endNodes, i))
if (_endNodes.Exists(delegate(int node) { return (node == i); }))
{
_paths.Add(GetPath(_workingNodes));
}
else
{
FindNext(GetLinkedNotes(i));
}
_workingNodes.Remove(i);
}
}

static void InitData()
{
_startNodes.Add(1);
_startNodes.Add(2);
_startNodes.Add(3);
_endNodes.Add(6);
_endNodes.Add(7);
_connections.Add(new Connection(1, 2));
_connections.Add(new Connection(1, 3));
_connections.Add(new Connection(1, 6));
_connections.Add(new Connection(1, 5));
_connections.Add(new Connection(2, 4));
_connections.Add(new Connection(2, 5));
_connections.Add(new Connection(3, 4));
_connections.Add(new Connection(3, 2));
_connections.Add(new Connection(4, 6));
_connections.Add(new Connection(4, 5));
_connections.Add(new Connection(5, 7));
}
static List GetLinkedNotes(int left)
{
List nodes = new List();
foreach (Connection c in _connections)
{
if (c._left == left)
{
nodes.Add(c._right);
}
}
return nodes;
}
static string GetPath(List nodes)
{
StringBuilder sb = new StringBuilder();
foreach (int i in nodes)
{
sb.Append(i).Append("->");
}
string result = sb.ToString();
if (result.Length > 0)
{
result = result.Substring(0, result.Length - 2);
}
return result;
}
static bool HasNode(List nodes, int node)
{
bool result = false;
foreach (int i in nodes)
{
if (i == node)
{
result = true;
break;
}
}
return result;
}
}
public class Connection
{
public int _left;
public int _right;
public Connection(int left, int right)
{
_left = left;
_right = right;
}
}
}

No comments: