views:

131

answers:

1

I am writing a markdown compiler in Erlang for server-side use. Because it will need to work with clients I have decided to adopt the client side library (showdown.js) as the specification and then test my code for compatibility with that.

In the first couple of iterations I built up 260-odd unit tests which checked that my programme produced output which was compatible with what I thought was valid markdown based on reading the syntax notes.

But now I am trying to write a javascript programme to generate my unit tests.

I have an input like:

"3 > 4\na"

I want to run 'showdown' on it to get:

"<p>3 &gt; 4\na</p>"

and I want to stitch this up into an EUnit assertion:

"?_assert(conv(\"3 > 4\na\") == \"<p>3 &gt; 4\na</p>\"),",

which is the valid Erlang syntax for the unit test. To make life easy, and to make the unit test generator portable I am doing it inside a web page so that by appending some lines to a javascript file and then view the page you get the new set of unit tests inside a <textarea /> which you then copy down into the module to run EUnit.

The problem is that I can't get the line breaks to convert to \n in the string so I end up with:

"?_assert(conv(\"3 > 4
a\") == \"<p>3 &gt; 4
a</p>\"),",

I've tried converting the linefeeds to their escaped versions using code like:

text.replace("\\", "\\\\");
text.replace("\n", "\\n");

but no joy...

+2  A: 

Tom McNulty helped me out and pointed out that my regex's were super-pants, in particular I wasn't using the global flag :(

The working code is:

var converter;
var text = "";
var item;
var input;
var output;
var head;
var tail;
converter = new Attacklab.showdown.converter();
item = document.getElementById("tests");
for (var test in tests) {
  input = tests[test].replace(/[\n\r]+/gi,"\\n" );
  input = input.replace(/[\"]+/gi, "\\\"");
  output = converter.makeHtml(tests[test]).replace(/[\n\r]+/gi, "\\n");
  output = output.replace(/[\"]+/gi, "\\\"");
  text += "     ?_assert(conv(\"" + input + "\") == \"" + output + "\"),\n";
};
head = "unit_test_() -> \n    [\n";
tail = "\n    ].";
text = text.slice(0, text.length - 2);
item.value = head + text + tail;
Gordon Guthrie