sstest.c 89.2 KB
Newer Older
1 2 3
/*
 * sstest.c: Test code for Gnumeric
 *
4
 * Copyright (C) 2009,2017 Morten Welinder (terra@gnome.org)
5 6 7 8
 */
#include <gnumeric-config.h>
#include "gnumeric.h"
#include "libgnumeric.h"
9
#include <goffice/goffice.h>
10 11 12 13 14 15 16
#include "command-context-stderr.h"
#include "workbook-view.h"
#include "workbook.h"
#include "gutils.h"
#include "gnm-plugin.h"
#include "parse-util.h"
#include "expr-name.h"
17
#include "expr.h"
18 19 20 21 22 23 24
#include "search.h"
#include "sheet.h"
#include "cell.h"
#include "value.h"
#include "func.h"
#include "parse-util.h"
#include "sheet-object-cell-comment.h"
25
#include "mathfunc.h"
26
#include "gnm-random.h"
27
#include "sf-dpq.h"
28
#include "sf-gamma.h"
29
#include "rangefunc.h"
30 31 32

#include <gsf/gsf-input-stdio.h>
#include <gsf/gsf-input-textline.h>
33
#include <glib/gstdio.h>
34 35
#include <glib/gi18n.h>
#include <string.h>
36
#include <errno.h>
37 38

static gboolean sstest_show_version = FALSE;
39
static gboolean sstest_fast = FALSE;
40
static gchar *func_def_file = NULL;
41
static gchar *func_state_file = NULL;
42
static gchar *ext_refs_file = NULL;
43
static gchar *samples_file = NULL;
44 45

static GOptionEntry const sstest_options [] = {
46 47 48 49 50 51 52
	{
		"fast", 'f',
		0, G_OPTION_ARG_NONE, &sstest_fast,
		N_("Run fewer iterations"),
		NULL
	},

53 54 55 56 57 58 59
	{
		"dump-func-defs", 0,
		0, G_OPTION_ARG_FILENAME, &func_def_file,
		N_("Dumps the function definitions"),
		N_("FILE")
	},

60 61 62 63 64 65 66
	{
		"dump-func-state", 0,
		0, G_OPTION_ARG_FILENAME, &func_state_file,
		N_("Dumps the function definitions"),
		N_("FILE")
	},

67 68 69 70 71 72 73
	{
		"ext-refs-file", 0,
		0, G_OPTION_ARG_FILENAME, &ext_refs_file,
		N_("Dumps web page for function help"),
		N_("FILE")
	},

74 75 76 77 78 79 80
	{
		"samples-file", 0,
		0, G_OPTION_ARG_FILENAME, &samples_file,
		N_("Dumps list of samples in function help"),
		N_("FILE")
	},

81 82 83 84 85 86 87 88 89 90
	{
		"version", 'V',
		0, G_OPTION_ARG_NONE, &sstest_show_version,
		N_("Display program version"),
		NULL
	},

	{ NULL }
};

91 92
/* ------------------------------------------------------------------------- */

93
#define UNICODE_ELLIPSIS "\xe2\x80\xa6"
94
#define F2(func,s) dgettext ((func)->tdomain->str, (s))
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

static char *
split_at_colon (char const *s, char **rest)
{
	char *dup = g_strdup (s);
	char *colon = strchr (dup, ':');
	if (colon) {
		*colon = 0;
		if (rest) *rest = colon + 1;
	} else {
		if (rest) *rest = NULL;
	}
	return dup;
}


static void
dump_externals (GPtrArray *defs, FILE *out)
{
	unsigned int ui;

	fprintf (out, "<!--#set var=\"title\" value=\"Gnumeric Web Documentation\" -->");
	fprintf (out, "<!--#set var=\"rootdir\" value=\".\" -->");
	fprintf (out, "<!--#include virtual=\"header-begin.shtml\" -->");
	fprintf (out, "<link rel=\"stylesheet\" href=\"style/index.css\" type=\"text/css\"/>");
	fprintf (out, "<!--#include virtual=\"header-end.shtml\" -->");
	fprintf (out, "<!--#set var=\"wolfram\" value=\"none\" -->");
	fprintf (out, "<!--#set var=\"wiki\" value=\"none\" -->");
	fprintf (out, "<!--\n\n-->");

	for (ui = 0; ui < defs->len; ui++) {
		GnmFunc const *fd = g_ptr_array_index (defs, ui);
		gboolean any = FALSE;
		int j;

		for (j = 0; fd->help[j].type != GNM_FUNC_HELP_END; j++) {
			const char *s = F2(fd, fd->help[j].text);

			switch (fd->help[j].type) {
			case GNM_FUNC_HELP_EXTREF:
				if (!any) {
					any = TRUE;
					fprintf (out, "<!--#if expr=\"${QUERY_STRING} = %s\" -->", fd->name);
				}

				if (strncmp (s, "wolfram:", 8) == 0) {
					fprintf (out, "<!--#set var=\"wolfram\" value=\"%s\" -->", s + 8);
				}
				if (strncmp (s, "wiki:", 5) == 0) {
					char *lang, *page;
					lang = split_at_colon (s + 5, &page);
					fprintf (out, "<!--#set var=\"wiki_lang\" value=\"%s\" -->", lang);
					fprintf (out, "<!--#set var=\"wiki\" value=\"%s\" -->", page);
					g_free (lang);
				}
				break;
			default:
				break;
			}
		}

		if (any)
			fprintf (out, "<!--#endif\n\n-->");
	}

	fprintf (out, "<div class=\"floatflush\">\n");
	fprintf (out, "<h1>Online Documentation for \"<!--#echo var=\"QUERY_STRING\" -->\"</h1>\n");
	fprintf (out, "<p>When last checked, these sources provided useful information about\n");
	fprintf (out, "this function.  However, since the links are not controlled by the\n");
	fprintf (out, "Gnumeric Team, we cannot guarantee that the links still work.  If\n");
	fprintf (out, "you find that they do not work, please drop us a line.</p>\n");
	fprintf (out, "<ul>");
	fprintf (out, "<!--#if expr=\"${wolfram} != none\"-->");
	fprintf (out, "<li><a href=\"http://mathworld.wolfram.com/<!--#echo var=\"wolfram\" -->\">Wolfram Mathworld\nentry</a>.</li><!--#endif-->");
	fprintf (out, "<!--#if expr=\"${wiki} != none\"--><li><a href=\"http://<!--#echo var=\"wiki_lang\" -->.wikipedia.org/wiki/<!--#echo var=\"wiki\" -->\">Wikipedia\nentry</a>.</li><!--#endif-->");
	fprintf (out, "<li><a href=\"http://www.google.com/#q=<!--#echo var=\"QUERY_STRING\" -->\">Google Search</a>.</li>");
	fprintf (out, "</ul>");
	fprintf (out, "</div>\n");

	fprintf (out, "<!--#include virtual=\"footer.shtml\" -->\n");
}

static void
csv_quoted_print (FILE *out, const char *s)
{
	char quote = '"';
	fputc (quote, out);
	while (*s) {
		if (*s == quote) {
			fputc (quote, out);
			fputc (quote, out);
			s++;
		} else {
			int len = g_utf8_skip[(unsigned char)*s];
			fprintf (out, "%-.*s", len, s);
			s += len;
		}
	}
	fputc ('"', out);
}

static void
dump_samples (GPtrArray *defs, FILE *out)
{
	unsigned ui;
	GnmFuncGroup *last_group = NULL;

	for (ui = 0; ui < defs->len; ui++) {
		GnmFunc const *fd = g_ptr_array_index (defs, ui);
		int j;
		const char *last = NULL;
		gboolean has_sample = FALSE;

		if (last_group != fd->fn_group) {
			last_group = fd->fn_group;
			csv_quoted_print (out, last_group->display_name->str);
			fputc ('\n', out);
		}

		for (j = 0; fd->help[j].type != GNM_FUNC_HELP_END; j++) {
			const char *s = fd->help[j].text;

			if (fd->help[j].type != GNM_FUNC_HELP_EXAMPLES)
				continue;

			has_sample = TRUE;

			/*
			 * Some of the random numbers functions have duplicate
			 * samples.  We don't want the duplicates here.
			 */
			if (s[0] != '=' || (last && strcmp (last, s) == 0))
				continue;

			fputc (',', out);
			if (!last)
				csv_quoted_print (out, fd->name);
			last = s;

			fputc (',', out);
			csv_quoted_print (out, s);
			fputc ('\n', out);
		}

		if (!has_sample)
			g_printerr ("No samples for %s\n", fd->name);
	}
}

static void
cb_dump_usage (GnmFunc const *fd, FILE *out)
{
	if (fd->usage_count > 0)
		fprintf (out, "%d,%s\n", fd->usage_count, fd->name);
}



static int
func_def_cmp (gconstpointer a, gconstpointer b)
{
	GnmFunc const *fda = *(GnmFunc const **)a ;
	GnmFunc const *fdb = *(GnmFunc const **)b ;

	g_return_val_if_fail (fda->name != NULL, 0);
	g_return_val_if_fail (fdb->name != NULL, 0);

	if (fda->fn_group != NULL && fdb->fn_group != NULL) {
		int res = go_string_cmp (fda->fn_group->display_name,
					 fdb->fn_group->display_name);
		if (res != 0)
			return res;
	}

	return g_ascii_strcasecmp (fda->name, fdb->name);
}

static GPtrArray *
enumerate_functions (gboolean filter)
{
	GPtrArray *res = gnm_func_enumerate ();
276
	unsigned ui;
277

278 279 280 281 282 283 284 285 286 287 288 289 290
	for (ui = 0; ui < res->len; ui++) {
		GnmFunc *fd = g_ptr_array_index (res, ui);

		if (filter &&
		    (fd->name == NULL ||
		     strcmp (fd->name, "perl_adder") == 0 ||
		     strcmp (fd->name, "perl_date") == 0 ||
		     strcmp (fd->name, "perl_sed") == 0 ||
		     strcmp (fd->name, "py_capwords") == 0 ||
		     strcmp (fd->name, "py_printf") == 0 ||
		     strcmp (fd->name, "py_bitand") == 0)) {
			g_ptr_array_remove_index_fast (res, ui);
			ui--;
291
		}
292 293

		gnm_func_load_if_stub (fd);
294 295
	}

296
	g_ptr_array_sort (res, func_def_cmp);
297 298 299 300 301

	return res;
}

/**
Morten Welinder's avatar
Morten Welinder committed
302
 * function_dump_defs:
303 304 305 306 307 308 309
 * @filename:
 * @dump_type:
 *
 * A generic utility routine to operate on all funtion defs
 * in various ways.  @dump_type will change/extend as needed
 * Right now
 * 0 : www.gnumeric.org's function.shtml page
Morten Welinder's avatar
Morten Welinder committed
310
 * 1:
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
 * 2 : (obsolete)
 * 3 : dump function usage count
 * 4 : external refs
 * 5 : all sample expressions
 **/
static void
function_dump_defs (char const *filename, int dump_type)
{
	FILE *output_file;
	char *up, *catname;
	unsigned i;
	GPtrArray *ordered;
	GnmFuncGroup const *group = NULL;

	g_return_if_fail (filename != NULL);

	if ((output_file = g_fopen (filename, "w")) == NULL){
		g_printerr (_("Cannot create file %s\n"), filename);
		exit (1);
	}

	if (dump_type == 3) {
		GPtrArray *funcs = enumerate_functions (FALSE);
		g_ptr_array_foreach (funcs, (GFunc)cb_dump_usage, output_file);
		g_ptr_array_free (funcs, TRUE);
		fclose (output_file);
		return;
	}

	/* TODO : Use the translated names and split by fn_group. */
	ordered = enumerate_functions (TRUE);

	if (dump_type == 4) {
		dump_externals (ordered, output_file);
		g_ptr_array_free (ordered, TRUE);
		fclose (output_file);
		return;
	}

	if (dump_type == 5) {
		dump_samples (ordered, output_file);
		g_ptr_array_free (ordered, TRUE);
		fclose (output_file);
		return;
	}

	if (dump_type == 0) {
		int unique = 0;
		for (i = 0; i < ordered->len; i++) {
			GnmFunc const *fd = g_ptr_array_index (ordered, i);
			switch (fd->impl_status) {
			case GNM_FUNC_IMPL_STATUS_UNIQUE_TO_GNUMERIC:
				unique++;
				break;
			default: ;
			}
		}

		fprintf (output_file,
			 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
			 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
			 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
			 "<!-- DEFINE current=Home -->\n"
			 "<!-- MARKER: start-header -->\n"
			 "<head>\n"
			 "<title>Gnumeric</title>\n"
			 "<link rel=\"stylesheet\" href=\"style/style.css\" type=\"text/css\" />\n"
			 "<link rel=\"icon\" type=\"image/png\" href=\"logo.png\" />\n"
			 "<style type=\"text/css\"><!--\n"
			 "  div.functiongroup {\n"
			 "    margin-top: 1em;\n"
			 "    margin-bottom: 1em;\n"
			 "  }\n"
			 "  table.functiongroup {\n"
			 "    border-style: solid;\n"
			 "    border-width: 1px;\n"
			 "    border-spacing: 0px;\n"
			 "  }\n"
			 "  tr.header td {\n"
			 "    font-weight: bold;\n"
			 "    font-size: 14pt;\n"
			 "    border-style: solid;\n"
			 "    border-width: 1px;\n"
			 "    text-align: center;\n"
			 "  }\n"
			 "  tr.function td {\n"
			 "    border: solid 1px;\n"
			 "  }\n"
			 "  td.testing-unknown    { background: #ffffff; }\n"
			 "  td.testing-nosuite    { background: #ff7662; }\n"
			 "  td.testing-basic      { background: #fff79d; }\n"
			 "  td.testing-exhaustive { background: #aef8b5; }\n"
			 "  td.testing-devel      { background: #ff6c00; }\n"
			 "  td.imp-exists         { background: #ffffff; }\n"
			 "  td.imp-no             { background: #ff7662; }\n"
			 "  td.imp-subset         { background: #fff79d; }\n"
			 "  td.imp-complete       { background: #aef8b5; }\n"
			 "  td.imp-superset       { background: #16e49e; }\n"
			 "  td.imp-subsetext      { background: #59fff2; }\n"
			 "  td.imp-devel          { background: #ff6c00; }\n"
			 "  td.imp-gnumeric       { background: #44be18; }\n"
			 "--></style>\n"
			 "</head>\n"
			 "<body>\n"
			 "<div id=\"wrap\">\n"
			 "  <a href=\"/\"><div id=\"header\">\n"
			 "    <h1 id=\"logo-text\"><span>Gnumeric</span></h1>\n"
			 "    <p id=\"slogan\">Free, Fast, Accurate &mdash; Pick Any Three!</p>\n"
			 "    <img id=\"logo\" src=\"gnumeric.png\" alt=\"logo\" class=\"float-right\"/>\n"
			 "    </div></a>\n"
			 "\n"
			 "  <div id=\"nav\">\n"
			 "    <ul>\n"
			 "      <li id=\"current\"><a href=\"/\">Home</a></li>\n"
			 "      <li><a href=\"development.html\">Development</a></li>\n"
			 "      <li><a href=\"contact.html\">Contact</a></li>\n"
			 "    </ul>\n"
			 "  </div>\n"
			 "\n"
			 "  <div id=\"content-wrap\">\n"
			 "    <!-- MARKER: start-main -->\n"
			 "    <div id=\"main\">\n"
			 "      <div class=\"generalitem\">\n"
			 "	<h2><span class=\"gnumeric-bullet\"></span>Gnumeric Sheet Functions</h2>\n"
			 "	<p>Gnumeric currently has %d functions for use in spreadsheets.\n"
			 "      %d of these are unique to Gnumeric.</p>\n",
			 ordered->len, unique);
	}

	for (i = 0; i < ordered->len; i++) {
		GnmFunc const *fd = g_ptr_array_index (ordered, i);
442 443 444 445 446 447 448 449 450

		// Skip internal-use function
		if (g_ascii_strcasecmp (fd->name, "TABLE") == 0)
			continue;

		// Skip demo function
		if (g_ascii_strcasecmp (fd->name, "ATL_LAST") == 0)
			continue;

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
		if (dump_type == 1) {
			int i;
			gboolean first_arg = TRUE;
			GString *syntax = g_string_new (NULL);
			GString *arg_desc = g_string_new (NULL);
			GString *desc = g_string_new (NULL);
			GString *odf = g_string_new (NULL);
			GString *excel = g_string_new (NULL);
			GString *note = g_string_new (NULL);
			GString *seealso = g_string_new (NULL);
			gint min, max;

			fprintf (output_file, "@CATEGORY=%s\n",
				 F2(fd, fd->fn_group->display_name->str));
			for (i = 0;
			     fd->help[i].type != GNM_FUNC_HELP_END;
			     i++) {
				switch (fd->help[i].type) {
				case GNM_FUNC_HELP_NAME: {
					char *short_desc;
					char *name = split_at_colon (F2(fd, fd->help[i].text), &short_desc);
					fprintf (output_file,
						 "@FUNCTION=%s\n",
						 name);
					fprintf (output_file,
						 "@SHORTDESC=%s\n",
						 short_desc);
					g_string_append (syntax, name);
					g_string_append_c (syntax, '(');
					g_free (name);
					break;
				}
				case GNM_FUNC_HELP_SEEALSO:
					if (seealso->len > 0)
						g_string_append (seealso, ",");
					g_string_append (seealso, F2(fd, fd->help[i].text));
					break;
				case GNM_FUNC_HELP_DESCRIPTION:
					if (desc->len > 0)
						g_string_append (desc, "\n");
					g_string_append (desc, F2(fd, fd->help[i].text));
					break;
				case GNM_FUNC_HELP_NOTE:
					if (note->len > 0)
						g_string_append (note, " ");
					g_string_append (note, F2(fd, fd->help[i].text));
					break;
				case GNM_FUNC_HELP_ARG: {
					char *argdesc;
					char *name = split_at_colon (F2(fd, fd->help[i].text), &argdesc);
					if (first_arg)
						first_arg = FALSE;
					else
						g_string_append_c (syntax, go_locale_get_arg_sep ());
					g_string_append (syntax, name);
					if (argdesc) {
						g_string_append_printf (arg_desc,
									"@{%s}: %s\n",
									name,
									argdesc);
					}
					g_free (name);
					/* FIXME: Optional args?  */
					break;
				}
				case GNM_FUNC_HELP_ODF:
					if (odf->len > 0)
						g_string_append (odf, " ");
					g_string_append (odf, F2(fd, fd->help[i].text));
					break;
				case GNM_FUNC_HELP_EXCEL:
					if (excel->len > 0)
						g_string_append (excel, " ");
					g_string_append (excel, F2(fd, fd->help[i].text));
					break;

				case GNM_FUNC_HELP_EXTREF:
					/* FIXME! */
				case GNM_FUNC_HELP_EXAMPLES:
					/* FIXME! */
				case GNM_FUNC_HELP_END:
					break;
				}
			}

Morten Welinder's avatar
Morten Welinder committed
536
			gnm_func_count_args (fd, &min, &max);
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
			if (max == G_MAXINT)
				fprintf (output_file,
					 "@SYNTAX=%s," UNICODE_ELLIPSIS ")\n",
					 syntax->str);
			else
				fprintf (output_file, "@SYNTAX=%s)\n",
					 syntax->str);

			if (arg_desc->len > 0)
				fprintf (output_file, "@ARGUMENTDESCRIPTION=%s", arg_desc->str);
			if (desc->len > 0)
				fprintf (output_file, "@DESCRIPTION=%s\n", desc->str);
			if (note->len > 0)
				fprintf (output_file, "@NOTE=%s\n", note->str);
			if (excel->len > 0)
				fprintf (output_file, "@EXCEL=%s\n", excel->str);
			if (odf->len > 0)
				fprintf (output_file, "@ODF=%s\n", odf->str);
			if (seealso->len > 0)
				fprintf (output_file, "@SEEALSO=%s\n", seealso->str);

			g_string_free (syntax, TRUE);
			g_string_free (arg_desc, TRUE);
			g_string_free (desc, TRUE);
			g_string_free (odf, TRUE);
			g_string_free (excel, TRUE);
			g_string_free (note, TRUE);
			g_string_free (seealso, TRUE);

			fputc ('\n', output_file);
		} else if (dump_type == 0) {
			static struct {
				char const *name;
				char const *klass;
			} const testing [] = {
				{ "Unknown",		"testing-unknown" },
				{ "No Testsuite",	"testing-nosuite" },
				{ "Basic",		"testing-basic" },
				{ "Exhaustive",		"testing-exhaustive" },
				{ "Under Development",	"testing-devel" }
			};
			static struct {
				char const *name;
				char const *klass;
			} const implementation [] = {
				{ "Exists",			"imp-exists" },
				{ "Unimplemented",		"imp-no" },
				{ "Subset",			"imp-subset" },
				{ "Complete",			"imp-complete" },
				{ "Superset",			"imp-superset" },
				{ "Subset with_extensions",	"imp-subsetext" },
				{ "Under development",		"imp-devel" },
				{ "Unique to Gnumeric",		"imp-gnumeric" },
			};
			if (group != fd->fn_group) {
				if (group) fprintf (output_file, "</table></div>\n");
				group = fd->fn_group;
				fprintf (output_file,
					 "<h2>%s</h2>\n"
					 "<div class=\"functiongroup\"><table class=\"functiongroup\">\n"
					 "<tr class=\"header\">"
					 "<td>Function</td>"
					 "<td>Implementation</td>"
					 "<td>Testing</td>"
					 "</tr>\n",
					 group->display_name->str);
			}
			up = g_ascii_strup (fd->name, -1);
			catname = g_strdup (group->display_name->str);
			while (strchr (catname, ' '))
				*strchr (catname, ' ') = '_';
			fprintf (output_file, "<tr class=\"function\">\n");
			fprintf (output_file,
				 "<td><a href =\"https://help.gnome.org/users/gnumeric/stable/gnumeric.html#gnumeric-function-%s\">%s</a></td>\n",
				 up, fd->name);
			g_free (up);
			g_free (catname);
			fprintf (output_file,
				 "<td class=\"%s\"><a href=\"mailto:gnumeric-list@gnome.org?subject=Re: %s implementation\">%s</a></td>\n",
				 implementation[fd->impl_status].klass,
				 fd->name,
				 implementation[fd->impl_status].name);
			fprintf (output_file,
				 "<td class=\"%s\"><a href=\"mailto:gnumeric-list@gnome.org?subject=Re: %s testing\">%s</a></td>\n",
				 testing[fd->test_status].klass,
				 fd->name,
				 testing[fd->test_status].name);
			fprintf (output_file,"</tr>\n");
		}
	}
	if (dump_type == 0) {
		if (group) fprintf (output_file, "</table></div>\n");
		fprintf (output_file,
			 "      </div>\n"
			 "    </div>\n"
			 "    <!-- MARKER: end-main -->\n"
			 "    <!-- MARKER: start-sidebar -->\n"
			 "    <!-- MARKER: end-sidebar -->\n"
			 "  </div>\n"
			 "</div>\n"
			 "</body>\n"
			 "</html>\n");
	}

	g_ptr_array_free (ordered, TRUE);
	fclose (output_file);
}

/* ------------------------------------------------------------------------- */

647 648 649 650 651 652 653 654 655 656 657 658 659
static void
mark_test_start (const char *name)
{
	g_printerr ("-----------------------------------------------------------------------------\nStart: %s\n-----------------------------------------------------------------------------\n\n", name);
}

static void
mark_test_end (const char *name)
{
	g_printerr ("End: %s\n\n", name);
}

static void
660
cb_collect_names (G_GNUC_UNUSED const char *name, GnmNamedExpr *nexpr, GSList **names)
661 662 663 664
{
	*names = g_slist_prepend (*names, nexpr);
}

665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
static GnmCell *
fetch_cell (Sheet *sheet, const char *where)
{
	GnmCellPos cp;
	gboolean ok = cellpos_parse (where,
				     gnm_sheet_get_size (sheet),
				     &cp, TRUE) != NULL;
	g_return_val_if_fail (ok, NULL);
	return sheet_cell_fetch (sheet, cp.col, cp.row);
}

static void
set_cell (Sheet *sheet, const char *where, const char *what)
{
	GnmCell *cell = fetch_cell (sheet, where);
	if (cell)
		gnm_cell_set_text (cell, what);
}

static void
dump_sheet (Sheet *sheet, const char *header)
{
	GPtrArray *cells = sheet_cells (sheet, NULL);
	unsigned ui;

	if (header)
		g_printerr ("# %s\n", header);
	for (ui = 0; ui < cells->len; ui++) {
		GnmCell *cell = g_ptr_array_index (cells, ui);
		char *txt = gnm_cell_get_entered_text (cell);
		g_printerr ("%s: %s\n",
			    cellpos_as_string (&cell->pos), txt);
		g_free (txt);
	}
	g_ptr_array_free (cells, TRUE);
}


703 704 705 706 707 708 709
static void
dump_names (Workbook *wb)
{
	GSList *l, *names = NULL;

	workbook_foreach_name (wb, FALSE, (GHFunc)cb_collect_names, &names);
	names = g_slist_sort (names, (GCompareFunc)expr_name_cmp_by_name);
Morten Welinder's avatar
Morten Welinder committed
710

711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
	g_printerr ("Dumping names...\n");
	for (l = names; l; l = l->next) {
		GnmNamedExpr *nexpr = l->data;
		GnmConventionsOut out;

		out.accum = g_string_new (NULL);
		out.pp = &nexpr->pos;
		out.convs = gnm_conventions_default;

		g_string_append (out.accum, "Scope=");
		if (out.pp->sheet)
			g_string_append (out.accum, out.pp->sheet->name_quoted);
		else
			g_string_append (out.accum, "Global");

		g_string_append (out.accum, " Name=");
		go_strescape (out.accum, expr_name_name (nexpr));

		g_string_append (out.accum, " Expr=");
		gnm_expr_top_as_gstring (nexpr->texpr, &out);

		g_printerr ("%s\n", out.accum->str);
		g_string_free (out.accum, TRUE);
	}
	g_printerr ("Dumping names... Done\n");

	g_slist_free (names);
}

static void
define_name (const char *name, const char *expr_txt, gpointer scope)
{
	GnmParsePos pos;
	GnmExprTop const *texpr;
	GnmNamedExpr const *nexpr;
746
	GnmConventions const *convs;
747 748 749

	if (IS_SHEET (scope)) {
		parse_pos_init_sheet (&pos, scope);
750
		convs = sheet_get_conventions (pos.sheet);
751 752
	} else {
		parse_pos_init (&pos, WORKBOOK (scope), NULL, 0, 0);
753
		convs = gnm_conventions_default;
754 755
	}

756 757 758
	texpr = gnm_expr_parse_str (expr_txt, &pos,
				    GNM_EXPR_PARSE_DEFAULT,
				    convs, NULL);
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
	if (!texpr) {
		g_printerr ("Failed to parse %s for name %s\n",
			    expr_txt, name);
		return;
	}

	nexpr = expr_name_add (&pos, name, texpr, NULL, TRUE, NULL);
	if (!nexpr)
		g_printerr ("Failed to add name %s\n", name);
}

static void
test_insdel_rowcol_names (void)
{
	Workbook *wb;
	Sheet *sheet1,*sheet2;
	const char *test_name = "test_insdel_rowcol_names";
	GOUndo *undo;
	int i;

	mark_test_start (test_name);

	wb = workbook_new ();
	sheet1 = workbook_sheet_add (wb, -1,
				     GNM_DEFAULT_COLS, GNM_DEFAULT_ROWS);
	sheet2 = workbook_sheet_add (wb, -1,
				     GNM_DEFAULT_COLS, GNM_DEFAULT_ROWS);

787 788 789
	define_name ("Print_Area", "Sheet1!$A$1:$IV$65536", sheet1);
	define_name ("Print_Area", "Sheet2!$A$1:$IV$65536", sheet2);

790 791 792 793 794 795 796 797 798 799 800
	define_name ("NAMEGA1", "A1", wb);
	define_name ("NAMEG2", "$A$14+Sheet1!$A$14+Sheet2!$A$14", wb);

	define_name ("NAMEA1", "A1", sheet1);
	define_name ("NAMEA2", "A2", sheet1);
	define_name ("NAMEA1ABS", "$A$1", sheet1);
	define_name ("NAMEA2ABS", "$A$2", sheet1);

	dump_names (wb);

	for (i = 3; i >= 0; i--) {
801 802
		g_printerr ("About to insert before column %s on %s\n",
			    col_name (i), sheet1->name_unquoted);
803 804 805 806 807 808 809 810 811
		sheet_insert_cols (sheet1, i, 12, &undo, NULL);
		dump_names (wb);
		g_printerr ("Undoing.\n");
		go_undo_undo_with_data (undo, NULL);
		g_object_unref (undo);
		g_printerr ("Done.\n");
	}

	for (i = 3; i >= 0; i--) {
812 813
		g_printerr ("About to insert before column %s on %s\n",
			    col_name (i), sheet2->name_unquoted);
814 815 816 817 818 819 820 821 822
		sheet_insert_cols (sheet2, i, 12, &undo, NULL);
		dump_names (wb);
		g_printerr ("Undoing.\n");
		go_undo_undo_with_data (undo, NULL);
		g_object_unref (undo);
		g_printerr ("Done.\n");
	}

	for (i = 3; i >= 0; i--) {
823 824
		g_printerr ("About to delete column %s on %s\n",
			    col_name (i), sheet1->name_unquoted);
825 826 827 828 829 830 831 832 833 834 835 836 837
		sheet_delete_cols (sheet1, i, 1, &undo, NULL);
		dump_names (wb);
		g_printerr ("Undoing.\n");
		go_undo_undo_with_data (undo, NULL);
		g_object_unref (undo);
		g_printerr ("Done.\n");
	}

	g_object_unref (wb);

	mark_test_end (test_name);
}

838
/* ------------------------------------------------------------------------- */
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905

static void
test_insert_delete (void)
{
	const char *test_name = "test_insert_delete";
	Workbook *wb;
	Sheet *sheet1;
	int i;
	GOUndo *u = NULL, *u1;

	mark_test_start (test_name);

	wb = workbook_new ();
	sheet1 = workbook_sheet_add (wb, -1,
				     GNM_DEFAULT_COLS, GNM_DEFAULT_ROWS);
	set_cell (sheet1, "B2", "=D4+1");
	set_cell (sheet1, "D2", "=if(TRUE,B2,2)");

	dump_sheet (sheet1, "Init");

	for (i = 5; i >= 0; i--) {
		g_printerr ("# About to insert column before %s\n",
			    col_name (i));
		sheet_insert_cols (sheet1, i, 1, &u1, NULL);
		u = go_undo_combine (u, u1);
		dump_sheet (sheet1, NULL);
	}

	for (i = 5; i >= 0; i--) {
		g_printerr ("# About to insert row before %s\n",
			    row_name (i));
		sheet_insert_rows (sheet1, i, 1, &u1, NULL);
		u = go_undo_combine (u, u1);
		dump_sheet (sheet1, NULL);
	}

	go_undo_undo (u);
	g_object_unref (u);
	u = NULL;
	dump_sheet (sheet1, "Undo the lot");

	for (i = 5; i >= 0; i--) {
		g_printerr ("# About to delete column %s\n",
			    col_name (i));
		sheet_delete_cols (sheet1, i, 1, &u1, NULL);
		u = go_undo_combine (u, u1);
		dump_sheet (sheet1, NULL);
	}

	for (i = 5; i >= 0; i--) {
		g_printerr ("# About to delete row %s\n",
			    row_name (i));
		sheet_delete_rows (sheet1, i, 1, &u1, NULL);
		u = go_undo_combine (u, u1);
		dump_sheet (sheet1, NULL);
	}

	go_undo_undo (u);
	g_object_unref (u);
	u = NULL;
	dump_sheet (sheet1, "Undo the lot");

	g_object_unref (wb);

	mark_test_end (test_name);
}

906
/* ------------------------------------------------------------------------- */
907

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
/* ------------------------------------------------------------------------- */

static gboolean
check_help_expression (const char *text, GnmFunc const *fd)
{
	GnmConventions const *convs = gnm_conventions_default;
	GnmParsePos pp;
	GnmExprTop const *texpr;
	Workbook *wb;
	GnmParseError perr;

	/* Create a dummy workbook with no sheets for interesting effects.  */
	wb = workbook_new ();
	parse_pos_init (&pp, wb, NULL, 0, 0);

	parse_error_init (&perr);

	texpr = gnm_expr_parse_str (text, &pp,
				    GNM_EXPR_PARSE_DEFAULT,
				    convs,
				    &perr);
	if (perr.err) {
		g_printerr ("Error parsing %s: %s\n",
			    text, perr.err->message);
	}
	parse_error_free (&perr);
	g_object_unref (wb);

	if (!texpr)
		return TRUE;

	gnm_expr_top_unref (texpr);
	return FALSE;
}

static gboolean
check_argument_refs (const char *text, GnmFunc const *fd)
{
	if (fd->fn_type != GNM_FUNC_TYPE_ARGS)
		return FALSE;

	while (1) {
		const char *at = strchr (text, '@');
		char *argname;
		int i;

		if (!at)
			return FALSE;
		if (at[1] != '{')
			return TRUE;
		text = strchr (at + 2, '}');
		if (!text)
			return FALSE;
		argname = g_strndup (at + 2, text - at - 2);

		for (i = 0; TRUE; i++) {
Morten Welinder's avatar
Morten Welinder committed
964
			char *thisarg = gnm_func_get_arg_name (fd, i);
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
			gboolean found;
			if (!thisarg) {
				g_free (argname);
				return TRUE;
			}
			found = strcmp (argname, thisarg) == 0;
			g_free (thisarg);
			if (found)
				break;
		}
		g_free (argname);
	}
}


static int
gnm_func_sanity_check1 (GnmFunc const *fd)
{
	GnmFuncHelp const *h;
	int counts[(int)GNM_FUNC_HELP_ODF + 1];
	int res = 0;
	size_t nlen = strlen (fd->name);
	GHashTable *allargs;

	allargs = g_hash_table_new_full
		(g_str_hash, g_str_equal, (GDestroyNotify)g_free, NULL);

	memset (counts, 0, sizeof (counts));
	for (h = fd->help; h->type != GNM_FUNC_HELP_END; h++) {
		g_assert (h->type <= GNM_FUNC_HELP_ODF);
		counts[h->type]++;

		if (!g_utf8_validate (h->text, -1, NULL)) {
			g_printerr ("%s: Invalid UTF-8 in type %i\n",
				    fd->name, h->type);
				res = 1;
				continue;
		}

		switch (h->type) {
		case GNM_FUNC_HELP_NAME:
			if (g_ascii_strncasecmp (fd->name, h->text, nlen) ||
			    h->text[nlen] != ':') {
				g_printerr ("%s: Invalid NAME record\n",
					    fd->name);
				res = 1;
			} else if (h->text[nlen + 1] == ' ') {
				g_printerr ("%s: Unwanted space in NAME record\n",
					    fd->name);
				res = 1;
			} else if (h->text[strlen (h->text) - 1] == '.') {
				g_printerr ("%s: Unwanted period in NAME record\n",
					    fd->name);
				res = 1;
			}
			break;
		case GNM_FUNC_HELP_ARG: {
			const char *aend = strchr (h->text, ':');
			char *argname;

			if (aend == NULL || aend == h->text) {
				g_printerr ("%s: Invalid ARG record\n",
					    fd->name);
				res = 1;
				break;
			}

			if (aend[1] == ' ') {
				g_printerr ("%s: Unwanted space in ARG record\n",
					    fd->name);
				res = 1;
			}
			if (aend[1] == '\0') {
				g_printerr ("%s: Empty ARG record\n",
					    fd->name);
				res = 1;
			}
			if (h->text[strlen (h->text) - 1] == '.') {
				g_printerr ("%s: Unwanted period in ARG record\n",
					    fd->name);
				res = 1;
			}
			if (check_argument_refs (aend + 1, fd)) {
				g_printerr ("%s: Invalid argument reference in argument\n",
					    fd->name);
				res = 1;
			}
			argname = g_strndup (h->text, aend - h->text);
			if (g_hash_table_lookup (allargs, argname)) {
				g_printerr ("%s: Duplicate argument name %s\n",
					    fd->name, argname);
				res = 1;
				g_free (argname);
				g_printerr ("%s\n", h->text);
			} else
				g_hash_table_insert (allargs, argname, argname);
			break;
		}
		case GNM_FUNC_HELP_DESCRIPTION: {
			const char *p;

			if (check_argument_refs (h->text, fd)) {
				g_printerr ("%s: Invalid argument reference in description\n",
					    fd->name);
				res = 1;
			}

			p = h->text;
			while (g_ascii_isupper (*p) ||
			       (p != h->text && (*p == '_' ||
						 *p == '.' ||
						 g_ascii_isdigit (*p))))
				p++;
			if (*p == ' ' &&
			    p - h->text >= 2 &&
			    strncmp (h->text, "CP1252", 6) != 0) {
				if (g_ascii_strncasecmp (h->text, fd->name, nlen)) {
					g_printerr ("%s: Wrong function name in description\n",
						    fd->name);
					res = 1;
				}
			}
			break;
		}

		case GNM_FUNC_HELP_EXAMPLES:
			if (h->text[0] == '=') {
				if (check_help_expression (h->text + 1, fd)) {
					g_printerr ("%s: Invalid EXAMPLES record\n",
						    fd->name);
					res = 1;
				}
			}
			break;
		default:
			; /* Nothing */
		}
	}

	g_hash_table_destroy (allargs);

	if (fd->fn_type == GNM_FUNC_TYPE_ARGS) {
		int n = counts[GNM_FUNC_HELP_ARG];
		if (n != fd->fn.args.max_args) {
			g_printerr ("%s: Help for %d args, but takes %d-%d\n",
				    fd->name, n,
				    fd->fn.args.min_args, fd->fn.args.max_args);
			res = 1;
		}
	}

#if 0
	if (counts[GNM_FUNC_HELP_DESCRIPTION] != 1) {
		g_printerr ("%s: Help has %d descriptions.\n",
			    fd->name, counts[GNM_FUNC_HELP_DESCRIPTION]);
		res = 1;
	}
#endif

	if (counts[GNM_FUNC_HELP_NAME] != 1) {
		g_printerr ("%s: Help has %d NAME records.\n",
			    fd->name, counts[GNM_FUNC_HELP_NAME]);
		res = 1;
	}

	if (counts[GNM_FUNC_HELP_EXCEL] > 1) {
		g_printerr ("%s: Help has %d Excel notes.\n",
			    fd->name, counts[GNM_FUNC_HELP_EXCEL]);
		res = 1;
	}

	if (counts[GNM_FUNC_HELP_ODF] > 1) {
		g_printerr ("%s: Help has %d ODF notes.\n",
			    fd->name, counts[GNM_FUNC_HELP_ODF]);
		res = 1;
	}

	return res;
}

static int
gnm_func_sanity_check (void)
{
	int res = 0;
	GPtrArray *ordered;
	unsigned ui;

	ordered = enumerate_functions (TRUE);

	for (ui = 0; ui < ordered->len; ui++) {
		GnmFunc const *fd = g_ptr_array_index (ordered, ui);
		if (gnm_func_sanity_check1 (fd))
			res = 1;
	}

	g_ptr_array_free (ordered, TRUE);

	return res;
}

1165 1166 1167
static void
test_func_help (void)
{
1168
	const char *test_name = "test_func_help";
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
	int res;

	mark_test_start (test_name);

	res = gnm_func_sanity_check ();
	g_printerr ("Result = %d\n", res);

	mark_test_end (test_name);
}

1179
/* ------------------------------------------------------------------------- */
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232

static int
test_strtol_ok (const char *s, long l, size_t expected_len)
{
	long l2;
	char *end;
	int save_errno;

	l2 = gnm_utf8_strtol (s, &end);
	save_errno = errno;

	if (end != s + expected_len) {
		g_printerr ("Unexpect conversion end of [%s]\n", s);
		return 1;
	}
	if (l != l2) {
		g_printerr ("Unexpect conversion result of [%s]\n", s);
		return 1;
	}
	if (save_errno != 0) {
		g_printerr ("Unexpect conversion errno of [%s]\n", s);
		return 1;
	}

	return 0;
}

static int
test_strtol_noconv (const char *s)
{
	long l;
	char *end;
	int save_errno;

	l = gnm_utf8_strtol (s, &end);
	save_errno = errno;

	if (end != s) {
		g_printerr ("Unexpect conversion end of [%s]\n", s);
		return 1;
	}
	if (l != 0) {
		g_printerr ("Unexpect conversion result of [%s]\n", s);
		return 1;
	}
	if (save_errno != 0) {
		g_printerr ("Unexpect conversion errno of [%s]\n", s);
		return 1;
	}

	return 0;
}

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
static int
test_strtol_overflow (const char *s, gboolean pos)
{
	long l;
	char *end;
	int save_errno;
	size_t expected_len = strlen (s);

	l = gnm_utf8_strtol (s, &end);
	save_errno = errno;

	if (end != s + expected_len) {
		g_printerr ("Unexpect conversion end of [%s]\n", s);
		return 1;
	}
	if (l != (pos ? LONG_MAX : LONG_MIN)) {
		g_printerr ("Unexpect conversion result of [%s]\n", s);
		return 1;
	}
	if (save_errno != ERANGE) {
		g_printerr ("Unexpect conversion errno of [%s]\n", s);
		return 1;
	}

	return 0;
}

1260 1261
static int
test_strtol_reverse (long l)
1262
{
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
	char buffer[4*sizeof(l) + 4];
	int res = 0;

	sprintf(buffer, "%ld", l);
	res |= test_strtol_ok (buffer, l, strlen (buffer));

	sprintf(buffer, " %ld", l);
	res |= test_strtol_ok (buffer, l, strlen (buffer));

	sprintf(buffer, "\xc2\xa0\n\t%ld", l);
	res |= test_strtol_ok (buffer, l, strlen (buffer));

	sprintf(buffer, " \t%ldx", l);
	res |= test_strtol_ok (buffer, l, strlen (buffer) - 1);

	return res;
}

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
static int
test_strtod_ok (const char *s, double d, size_t expected_len)
{
	gnm_float d2;
	char *end;
	int save_errno;

	d2 = gnm_utf8_strto (s, &end);
	save_errno = errno;

	if (end != s + expected_len) {
		g_printerr ("Unexpect conversion end of [%s]\n", s);
		return 1;
	}
	if (d != d2) {
		g_printerr ("Unexpect conversion result of [%s]\n", s);
		return 1;
	}
	if (save_errno != 0) {
		g_printerr ("Unexpect conversion errno of [%s]\n", s);
		return 1;
	}

	return 0;
}

1307 1308 1309 1310 1311 1312
static void
test_nonascii_numbers (void)
{
	const char *test_name = "test_nonascii_numbers";
	int res = 0;

1313 1314
	mark_test_start (test_name);

1315 1316 1317 1318 1319 1320 1321 1322
	res |= test_strtol_reverse (0);
	res |= test_strtol_reverse (1);
	res |= test_strtol_reverse (-1);
	res |= test_strtol_reverse (LONG_MIN);
	res |= test_strtol_reverse (LONG_MIN + 1);
	res |= test_strtol_reverse (LONG_MAX - 1);

	res |= test_strtol_ok ("\xef\xbc\x8d\xef\xbc\x91", -1, 6);
1323
	res |= test_strtol_ok ("\xc2\xa0+1", 1, 4);
1324 1325 1326 1327 1328 1329 1330 1331 1332

	res |= test_strtol_ok ("000000000000000000000000000000", 0, 30);

	res |= test_strtol_noconv ("");
	res |= test_strtol_noconv (" ");
	res |= test_strtol_noconv (" +");
	res |= test_strtol_noconv (" -");
	res |= test_strtol_noconv (" .00");
	res |= test_strtol_noconv (" e0");
1333 1334 1335 1336
	res |= test_strtol_noconv ("--0");
	res |= test_strtol_noconv ("+-0");
	res |= test_strtol_noconv ("+ 0");
	res |= test_strtol_noconv ("- 0");
1337

1338 1339 1340
	{
		char buffer[4 * sizeof (long) + 2];

1341
		sprintf (buffer, "-%lu", 1 + (unsigned long)LONG_MIN);
1342
		res |= test_strtol_overflow (buffer, FALSE);
1343
		sprintf (buffer, "-%lu", 10 + (unsigned long)LONG_MIN);
1344
		res |= test_strtol_overflow (buffer, FALSE);
1345

1346
		sprintf (buffer, "%lu", 1 + (unsigned long)LONG_MAX);
1347
		res |= test_strtol_overflow (buffer, TRUE);
1348
		sprintf (buffer, "%lu", 10 + (unsigned long)LONG_MAX);
1349
		res |= test_strtol_overflow (buffer, TRUE);
1350 1351
	}

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
	/* -------------------- */

	res |= test_strtod_ok ("0", 0, 1);
	res |= test_strtod_ok ("1", 1, 1);
	res |= test_strtod_ok ("-1", -1, 2);
	res |= test_strtod_ok ("+1", 1, 2);
	res |= test_strtod_ok (" +1", 1, 3);
	res |= test_strtod_ok ("\xc2\xa0+1", 1, 4);
	res |= test_strtod_ok ("\xc2\xa0+1x", 1, 4);
	res |= test_strtod_ok ("\xc2\xa0+1e", 1, 4);
	res |= test_strtod_ok ("\xc2\xa0+1e+", 1, 4);
	res |= test_strtod_ok ("\xc2\xa0+1e+0", 1, 7);
	res |= test_strtod_ok ("-1e1", -10, 4);
	res |= test_strtod_ok ("100e-2", 1, 6);
	res |= test_strtod_ok ("100e+2", 10000, 6);
	res |= test_strtod_ok ("1x0p0", 1, 1);
	res |= test_strtod_ok ("+inf", gnm_pinf, 4);
	res |= test_strtod_ok ("-inf", gnm_ninf, 4);
	res |= test_strtod_ok ("1.25", 1.25, 4);
	res |= test_strtod_ok ("1.25e1", 12.5, 6);
	res |= test_strtod_ok ("12.5e-1", 1.25, 7);

1374 1375 1376 1377 1378
	g_printerr ("Result = %d\n", res);

	mark_test_end (test_name);
}

1379
/* ------------------------------------------------------------------------- */
1380

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
static char *random_summary = NULL;

static void
add_random_fail (const char *s)
{
	if (random_summary) {
		char *t = g_strconcat (random_summary, ", ", s, NULL);
		g_free (random_summary);
		random_summary = t;
	} else
		random_summary = g_strdup (s);
}

1394 1395 1396 1397 1398 1399 1400
static void
define_cell (Sheet *sheet, int c, int r, const char *expr)
{
	GnmCell *cell = sheet_cell_fetch (sheet, c, r);
	sheet_cell_set_text (cell, expr, NULL);
}

1401 1402
#define GET_PROB(i_) ((i_) <= 0 ? 0 : ((i_) >= nf ? 1 : probs[(i_)]))

1403
static gboolean
1404 1405
rand_fractile_test (gnm_float const *vals, int N, int nf,
		    gnm_float const *fractiles, gnm_float const *probs)
1406
{
1407
	gnm_float f = 1.0 / nf;
1408
	int *fractilecount = g_new (int, nf + 1);
1409
	int *expected = g_new (int, nf + 1);
1410 1411
	int i;
	gboolean ok = TRUE;
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
	gboolean debug = TRUE;

	if (debug) {
		g_printerr ("Bin upper limit:");
		for (i = 1; i <= nf; i++) {
			gnm_float U = (i == nf) ? gnm_pinf : fractiles[i];
			g_printerr ("%s%" GNM_FORMAT_g,
				    (i == 1) ? " " : ", ",
				    U);
		}
		g_printerr (".\n");
	}

	if (debug && probs) {
		g_printerr ("Cumulative probabilities:");
		for (i = 1; i <= nf; i++)
			g_printerr ("%s%.1" GNM_FORMAT_f "%%",
				    (i == 1) ? " " : ", ", 100 * GET_PROB (i));
		g_printerr (".\n");
	}
1432

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
	for (i = 1; i < nf - 1; i++) {
		if (!(fractiles[i] <= fractiles[i + 1])) {
			g_printerr ("Severe fractile ordering problem.\n");
			return FALSE;
		}

		if (probs && !(probs[i] <= probs[i + 1])) {
			g_printerr ("Severe cumulative probabilities ordering problem.\n");
			return FALSE;
		}
	}
	if (probs && (probs[1] < 0 || probs[nf - 1] > 1)) {
		g_printerr ("Severe cumulative probabilities range problem.\n");
		return FALSE;
	}

1449 1450 1451 1452 1453 1454 1455
	for (i = 0; i <= nf; i++)
		fractilecount[i] = 0;

	for (i = 0; i < N; i++) {
		gnm_float r = vals[i];
		int j;
		for (j = 1; j < nf; j++)
1456
			if (r <= fractiles[j])
1457 1458 1459 1460 1461 1462
				break;
		fractilecount[j]++;
	}
	g_printerr ("Fractile counts:");
	for (i = 1; i <= nf; i++)
		g_printerr ("%s%d", (i == 1) ? " " : ", ", fractilecount[i]);
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
	g_printerr (".\n");

	if (probs) {
		g_printerr ("Expected counts:");
		for (i = 1; i <= nf; i++) {
			gnm_float p = GET_PROB (i) - GET_PROB (i-1);
			expected[i] = gnm_floor (p * N + 0.5);
			g_printerr ("%s%d", (i == 1) ? " " : ", ", expected[i]);
		}
		g_printerr (".\n");
	} else {
		gnm_float T = f * N;
		g_printerr ("Expected count in each fractile: %.10" GNM_FORMAT_g "\n", T);
		for (i = 0; i <= nf; i++)
			expected[i] = T;
	}
1479 1480

	for (i = 1; i <= nf; i++) {
1481
		gnm_float T = expected[i];
1482
		if (!(gnm_abs (fractilecount[i] - T) <= 4 * gnm_sqrt (T))) {
1483
			g_printerr ("Fractile test failure for bin %d.\n", i);
1484 1485 1486 1487 1488
			ok = FALSE;
		}
	}

	g_free (fractilecount);
Morten Welinder's avatar
Morten Welinder committed
1489
	g_free (expected);
1490 1491 1492 1493

	return ok;
}

1494 1495
#undef GET_PROB

1496 1497 1498 1499 1500 1501
static gnm_float *
test_random_1 (int N, const char *expr,
	       gnm_float *mean, gnm_float *var,
	       gnm_float *skew, gnm_float *kurt)
{
	Workbook *wb = workbook_new ();
1502
	Sheet *sheet;
1503 1504 1505
	gnm_float *res = g_new (gnm_float, N);
	int i;
	char *s;
1506
	int cols = 2, rows = N;
1507 1508 1509

	g_printerr ("Testing %s\n", expr);

1510 1511 1512
	gnm_sheet_suggest_size (&cols, &rows);
	sheet = workbook_sheet_add (wb, -1, cols, rows);

1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
	for (i = 0; i < N; i++)
		define_cell (sheet, 0, i, expr);

	s = g_strdup_printf ("=average(a1:a%d)", N);
	define_cell (sheet, 1, 0, s);
	g_free (s);

	s = g_strdup_printf ("=var(a1:a%d)", N);
	define_cell (sheet, 1, 1, s);
	g_free (s);

	s = g_strdup_printf ("=skew(a1:a%d)", N);
	define_cell (sheet, 1, 2, s);
	g_free (s);

	s = g_strdup_printf ("=kurt(a1:a%d)", N);
	define_cell (sheet, 1, 3, s);
	g_free (s);

1532
	/* Force recalc of all dirty cells even in manual mode.  */
1533
	workbook_recalc (sheet->workbook);
1534

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
	for (i = 0; i < N; i++)
		res[i] = value_get_as_float (sheet_cell_get (sheet, 0, i)->value);
	*mean = value_get_as_float (sheet_cell_get (sheet, 1, 0)->value);
	g_printerr ("Mean: %.10" GNM_FORMAT_g "\n", *mean);

	*var = value_get_as_float (sheet_cell_get (sheet, 1, 1)->value);
	g_printerr ("Var: %.10" GNM_FORMAT_g "\n", *var);

	*skew = value_get_as_float (sheet_cell_get (sheet, 1, 2)->value);
	g_printerr ("Skew: %.10" GNM_FORMAT_g "\n", *skew);

	*kurt = value_get_as_float (sheet_cell_get (sheet, 1, 3)->value);
	g_printerr ("Kurt: %.10" GNM_FORMAT_g "\n", *kurt);

	g_object_unref (wb);
	return res;
}

1553 1554 1555 1556 1557 1558 1559
static gnm_float *
test_random_normality (int N, const char *expr,
		       gnm_float *mean, gnm_float *var,
		       gnm_float *adtest, gnm_float *cvmtest,
		       gnm_float *lkstest, gnm_float *sftest)
{
	Workbook *wb = workbook_new ();
1560
	Sheet *sheet;
1561 1562 1563
	gnm_float *res = g_new (gnm_float, N);
	int i;
	char *s;
1564
	int cols = 2, rows = N;
1565 1566 1567

	g_printerr ("Testing %s\n", expr);

1568 1569 1570
	gnm_sheet_suggest_size (&cols, &rows);
	sheet = workbook_sheet_add (wb, -1, cols, rows);

1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
	for (i = 0; i < N; i++)
		define_cell (sheet, 0, i, expr);

	s = g_strdup_printf ("=average(a1:a%d)", N);
	define_cell (sheet, 1, 0, s);
	g_free (s);

	s = g_strdup_printf ("=var(a1:a%d)", N);
	define_cell (sheet, 1, 1, s);
	g_free (s);

	s = g_strdup_printf ("=adtest(a1:a%d)", N);
	define_cell (sheet, 1, 2, s);
	g_free (s);

	s = g_strdup_printf ("=cvmtest(a1:a%d)", N);
	define_cell (sheet, 1, 3, s);
	g_free (s);

	s = g_strdup_printf ("=lkstest(a1:a%d)", N);
	define_cell (sheet, 1, 4, s);
	g_free (s);

	s = g_strdup_printf ("=sftest(a1:a%d)", N > 5000 ? 5000 : N);
	define_cell (sheet, 1, 5, s);
	g_free (s);

1598
	/* Force recalc of all dirty cells even in manual mode.  */
1599
	workbook_recalc (sheet->workbook);
1600

1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
	for (i = 0; i < N; i++)
		res[i] = value_get_as_float (sheet_cell_get (sheet, 0, i)->value);
	*mean = value_get_as_float (sheet_cell_get (sheet, 1, 0)->value);
	g_printerr ("Mean: %.10" GNM_FORMAT_g "\n", *mean);

	*var = value_get_as_float (sheet_cell_get (sheet, 1, 1)->value);
	g_printerr ("Var: %.10" GNM_FORMAT_g "\n", *var);

	*adtest = value_get_as_float (sheet_cell_get (sheet, 1, 2)->value);
	g_printerr ("ADTest: %.10" GNM_FORMAT_g "\n", *adtest);

	*cvmtest = value_get_as_float (sheet_cell_get (sheet, 1, 3)->value);
	g_printerr ("CVMTest: %.10" GNM_FORMAT_g "\n", *cvmtest);

	*lkstest = value_get_as_float (sheet_cell_get (sheet, 1, 4)->value);
	g_printerr ("LKSTest: %.10" GNM_FORMAT_g "\n", *lkstest);

	*sftest = value_get_as_float (sheet_cell_get (sheet, 1, 5)->value);
1619
	g_printerr ("SFTest: %.10" GNM_FORMAT_g "\n", *sftest);
1620 1621 1622 1623 1624

	g_object_unref (wb);
	return res;
}

1625 1626 1627 1628
static void
test_random_rand (int N)
{
	gnm_float mean, var, skew, kurt;
1629 1630 1631 1632
	gnm_float mean_target = 0.5;
	gnm_float var_target = 1.0 / 12;
	gnm_float skew_target = 0;
	gnm_float kurt_target = -6.0 / 5;
1633 1634 1635 1636
	gnm_float *vals;
	int i;
	gboolean ok;
	gnm_float T;
1637 1638
	gnm_float fractiles[10];
	const int nf = G_N_ELEMENTS (fractiles);
1639 1640 1641 1642 1643

	vals = test_random_1 (N, "=RAND()", &mean, &var, &skew, &kurt);
	ok = TRUE;
	for (i = 0; i < N; i++) {
		gnm_float r = vals[i];
1644
		if (!(r >= 0 && r < 1)) {
1645 1646 1647 1648 1649 1650
			g_printerr ("Range failure.\n");
			ok = FALSE;
			break;
		}
	}

1651 1652 1653
	T = mean_target;
	if (!(gnm_abs (mean - T) <= 3 * gnm_sqrt (var_target / N))) {
		g_printerr ("Mean failure [%.1" GNM_FORMAT_f " stdev]\n", (mean - T) / gnm_sqrt (var_target / N));
1654 1655
		ok = FALSE;
	}
1656
	T = var_target;
1657
	if (gnm_abs (var - T) > 0.01) {
1658
		g_printerr ("Var failure.\n");
1659 1660
		ok = FALSE;
	}
1661
	T = skew_target;
1662
	if (gnm_abs (skew - T) > 0.05) {
1663
		g_printerr ("Skew failure.\n");
1664 1665
		ok = FALSE;
	}
1666
	T = kurt_target;
1667
	if (gnm_abs (kurt - T) > 0.05) {
1668
		g_printerr ("Kurt failure.\n");
1669 1670
		ok = FALSE;
	}
1671 1672 1673 1674

	/* Fractile test */
	for (i = 1; i < nf; i++)
		fractiles[i] = i / (double)nf;
1675
	if (!rand_fractile_test (vals, N, nf, fractiles, NULL))
1676 1677
		ok = FALSE;

1678 1679
	if (ok)
		g_printerr ("OK\n");
1680 1681
	else
		add_random_fail ("RAND");
1682
	g_printerr ("\n");
1683 1684

	g_free (vals);
1685 1686
}

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
static void
test_random_randuniform (int N)
{
	gnm_float mean, var, skew, kurt;
	gnm_float *vals;
	gboolean ok;
	gnm_float lsign = (random_01 () > 0.75 ? 1 : -1);
	gnm_float param_l = lsign * gnm_floor (1 / (0.0001 + gnm_pow (random_01 (), 4)));
	gnm_float param_h = param_l + gnm_floor (1 / (0.0001 + gnm_pow (random_01 () / 2, 4)));
	gnm_float n = param_h - param_l;
	gnm_float mean_target = (param_l + param_h) / 2;
	gnm_float var_target = (n * n) / 12;
	gnm_float skew_target = 0;
	gnm_float kurt_target = -6 / 5.0;
	char *expr;
	gnm_float T;
	int i;
1704 1705
	gnm_float fractiles[10];
	const int nf = G_N_ELEMENTS (fractiles);
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722

	expr = g_strdup_printf ("=RANDUNIFORM(%.10" GNM_FORMAT_g ",%.10" GNM_FORMAT_g ")", param_l, param_h);
	vals = test_random_1 (N, expr, &mean, &var, &skew, &kurt);
	g_free (expr);

	ok = TRUE;
	for (i = 0; i < N; i++) {
		gnm_float r = vals[i];
		if (!(r >= param_l && r < param_h)) {
			g_printerr ("Range failure.\n");
			ok = FALSE;
			break;
		}
	}

	T = mean_target;
	g_printerr ("Expected mean: %.10" GNM_FORMAT_g "\n", T);
1723
	if (!(gnm_abs (mean - T) <= 3 * gnm_sqrt (var_target / N))) {
1724
		g_printerr ("Mean failure [%.1" GNM_FORMAT_f " stdev]\n", (mean - T) / gnm_sqrt (var_target / N));
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
		ok = FALSE;
	}

	T = var_target;
	g_printerr ("Expected var: %.10" GNM_FORMAT_g "\n", T);
	if (!(var >= 0 && gnm_finite (var))) {
		/* That is a very simplistic test! */
		g_printerr ("Var failure.\n");
		ok = FALSE;
	}

	T = skew_target;
	g_printerr ("Expected skew: %.10" GNM_FORMAT_g "\n", T);
	if (!gnm_finite (skew)) {
		/* That is a very simplistic test! */
		g_printerr ("Skew failure.\n");
		ok = FALSE;
	}

	T = kurt_target;
	g_printerr ("Expected kurt: %.10" GNM_FORMAT_g "\n", T);
	if (!(kurt >= -3 && gnm_finite (kurt))) {
		/* That is a very simplistic test! */
		g_printerr ("Kurt failure.\n");
		ok = FALSE;
	}

1752 1753 1754
	/* Fractile test */
	for (i = 1; i < nf; i++)
		fractiles[i] = param_l + n * i / (double)nf;
1755
	if (!rand_fractile_test (vals, N, nf, fractiles, NULL))
1756 1757
		ok = FALSE;

1758 1759
	if (ok)
		g_printerr ("OK\n");
1760 1761
	else
		add_random_fail ("RANDUNIFORM");
1762
	g_printerr ("\n");
1763 1764

	g_free (vals);
1765 1766
}

1767 1768 1769
static void
test_random_randbernoulli (int N)
{
1770 1771
	gnm_float p = 0.3;
	gnm_float q = 1 - p;
1772
	gnm_float mean, var, skew, kurt;
1773 1774 1775 1776
	gnm_float mean_target = p;
	gnm_float var_target = p * (1 - p);
	gnm_float skew_target = (q - p) / gnm_sqrt (p * q);
	gnm_float kurt_target = (1 - 6 * p * q) / (p * q);
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
	gnm_float *vals;
	int i;
	gboolean ok;
	char *expr;
	gnm_float T;

	expr = g_strdup_printf ("=RANDBERNOULLI(%.10" GNM_FORMAT_g ")", p);
	vals = test_random_1 (N, expr, &mean, &var, &skew, &kurt);
	g_free (expr);

	ok = TRUE;
	for (i = 0; i < N; i++) {
		gnm_float r = vals[i];
		if (!(r == 0 || r == 1)) {
			g_printerr ("Range failure.\n");
			ok = FALSE;
			break;
		}
	}

1797
	T = mean_target;
1798
	g_printerr ("Expected mean: %.10" GNM_FORMAT_g "\n", T);
1799
	if (gnm_abs (mean - p) > 0.01) {
1800
		g_printerr ("Mean failure [%.1" GNM_FORMAT_f " stdev]\n", (mean - T) / gnm_sqrt (var_target / N));
1801 1802
		ok = FALSE;
	}
1803

1804
	T = var_target;
1805
	g_printerr ("Expected var: %.10" GNM_FORMAT_g "\n", T);
1806
	if (gnm_abs (var - T) > 0.01) {
1807
		g_printerr ("Var failure.\n");
1808 1809
		ok = FALSE;
	}
1810

1811
	T = skew_target;
1812
	g_printerr ("Expected skew: %.10" GNM_FORMAT_g "\n", T);
1813 1814
	if (!(gnm_abs (skew - T) <= 0.10 * gnm_abs (T))) {
		g_printerr ("Skew failure.\n");
1815 1816
		ok = FALSE;
	}
1817

1818
	T = kurt_target;
1819
	g_printerr ("Expected kurt: %.10" GNM_FORMAT_g "\n", T);
1820 1821
	if (!(gnm_abs (kurt - T) <= 0.15 * gnm_abs (T))) {
		g_printerr ("Kurt failure.\n");
1822 1823 1824 1825
		ok = FALSE;
	}
	if (ok)
		g_printerr ("OK\n");
1826 1827
	else
		add_random_fail ("RANDBERNOULLI");
1828
	g_printerr ("\n");
1829 1830

	g_free (vals);
1831 1832
}

1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
static void
test_random_randdiscrete (int N)
{
	gnm_float mean, var, skew, kurt;
	gnm_float *vals;
	int i;
	gboolean ok;
	gnm_float mean_target = 13;
	gnm_float var_target = 156;
	gnm_float skew_target = 0.6748;
	gnm_float kurt_target = -0.9057;
	char *expr;
	gnm_float T;

	expr = g_strdup_printf ("=RANDDISCRETE({0;1;4;9;16;25;36})");
	vals = test_random_1 (N, expr, &mean, &var, &skew, &kurt);
	g_free (expr);

	ok = TRUE;
	for (i = 0; i < N; i++) {
		gnm_float r = vals[i];
		if (!(r >= 0 && r <= 36 && gnm_sqrt (r) == gnm_floor (gnm_sqrt (r)))) {
			g_printerr ("Range failure.\n");
			ok = FALSE;
			break;
		}
	}

	T = mean_target;
	g_printerr ("Expected mean: %.10" GNM_FORMAT_g "\n", T);
1863
	if (!(gnm_abs (mean - T) <= 3 * gnm_sqrt (var_target / N))) {
1864
		g_printerr ("Mean failure [%.1" GNM_FORMAT_f " stdev]\n", (mean - T) / gnm_sqrt (var_target / N));
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
		ok = FALSE;
	}

	T = var_target;
	g_printerr ("Expected var: %.10" GNM_FORMAT_g "\n", T);
	if (!(var >= 0 && gnm_finite (var))) {
		/* That is a very simplistic test! */
		g_printerr ("Var failure.\n");
		ok = FALSE;
	}

	T = skew_target;
	g_printerr ("Expected skew: %.10" GNM_FORMAT_g "\n", T);
	if (!gnm_finite (skew)) {
		/* That is a very simplistic test! */
		g_printerr ("Skew failure.\n");
		ok = FALSE;
	}

	T = kurt_target;
	g_printerr ("Expected kurt: %.10" GNM_FORMAT_g "\n", T);
	if (!(kurt >= -3 && gnm_finite (kurt))) {
		/* That is a very simplistic test! */
		g_printerr ("Kurt failure.\n");
		ok = FALSE;
	}

	if (ok)
		g_printerr ("OK\n");
1894 1895
	else
		add_random_fail ("RANDDISCRETE");
1896
	g_printerr ("\n");
1897 1898

	g_free (vals);
1899 1900
}

1901 1902 1903
static void
test_random_randnorm (int N)
{
1904
	gnm_float mean, var, adtest, cvmtest, lkstest, sftest;
1905 1906 1907 1908 1909
	gnm_float mean_target = 0, var_target = 1;
	gnm_float *vals;
	gboolean ok;
	char *expr;
	gnm_float T;
1910
	int i;
1911 1912
	gnm_float fractiles[10];
	const int nf = G_N_ELEMENTS (fractiles);
1913

1914
	expr = g_strdup_printf ("=RANDNORM(%.10" GNM_FORMAT_g ",%.10" GNM_FORMAT_g ")",
1915 1916 1917 1918 1919
				mean_target, var_target);
	vals = test_random_normality (N, expr, &mean, &var, &adtest, &cvmtest, &lkstest, &sftest);
	g_free (expr);

	ok = TRUE;
1920 1921 1922 1923 1924 1925 1926 1927
	for (i = 0; i < N; i++) {
		gnm_float r = vals[i];
		if (!gnm_finite (r)) {
			g_printerr ("Range failure.\n");
			ok = FALSE;
			break;
		}
	}
1928 1929 1930

	T = mean_target;
	if (gnm_abs (mean - T) > 0.02) {
1931
		g_printerr ("Mean failure [%.1" GNM_FORMAT_f " stdev]\n", (mean - T) / gnm_sqrt (var_target / N));
1932 1933 1934 1935
		ok = FALSE;
	}
	T = var_target;
	if (gnm_abs (var - T) > 0.02) {
1936
		g_printerr ("Var failure.\n");
1937 1938 1939
		ok = FALSE;
	}

1940 1941 1942 1943 1944 1945
	/* Fractile test */
	for (i = 1; i < nf; i++)
		fractiles[i] = qnorm (i / (double)nf, mean_target, gnm_sqrt (var_target), TRUE, FALSE);
	if (!rand_fractile_test (vals, N, nf, fractiles, NULL))
		ok = FALSE;

1946
	if (adtest < 0.01) {
1947 1948 1949
		g_printerr ("Anderson Darling Test rejected [%.10" GNM_FORMAT_g "]\n", adtest);
		ok = FALSE;
	}
1950
	if (cvmtest < 0.01) {
1951 1952 1953
		g_printerr ("Cramér-von Mises Test rejected [%.10" GNM_FORMAT_g "]\n", cvmtest);
		ok = FALSE;
	}
1954
	if (lkstest < 0.01) {
1955 1956 1957 1958
		g_printerr ("Lilliefors (Kolmogorov-Smirnov) Test rejected [%.10" GNM_FORMAT_g "]\n",
			    lkstest);
		ok = FALSE;
	}
1959
	if (sftest < 0.01) {
1960 1961 1962 1963 1964 1965
		g_printerr ("Shapiro-Francia Test rejected [%.10" GNM_FORMAT_g "]\n", sftest);
		ok = FALSE;
	}

	if (ok)
		g_printerr ("OK\n");
1966 1967
	else
		add_random_fail ("RANDNORM");
1968
	g_printerr ("\n");
1969 1970

	g_free (vals);
1971 1972
}

1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
static void
test_random_randsnorm (int N)
{
	gnm_float mean, var, skew, kurt;
	gnm_float *vals;
	gboolean ok;
	gnm_float alpha = 5;
	gnm_float delta = alpha/gnm_sqrt(1+alpha*alpha);
	gnm_float mean_target = delta * gnm_sqrt (2/M_PIgnum);
	gnm_float var_target = 1-mean_target*mean_target;
	char *expr;
	gnm_float T;
1985
	int i;
1986 1987 1988 1989 1990 1991

	expr = g_strdup_printf ("=RANDSNORM(%.10" GNM_FORMAT_g ")", alpha);
	vals = test_random_1 (N, expr, &mean, &var, &skew, &kurt);
	g_free (expr);

	ok = TRUE;
1992 1993 1994 1995 1996 1997 1998 1999
	for (i = 0; i < N; i++) {
		gnm_float r = vals[i];
		if (!gnm_finite (r)) {
			g_printerr ("Range failure.\n");
			ok = FALSE;
			break;
		}
	}
2000 2001

	T = mean_target;
2002
	g_printerr ("Expected mean: %.10" GNM_FORMAT_g "\n", T);
2003
	if (gnm_abs (mean - T) > 0.01) {
2004
		g_printerr ("Mean failure [%.1" GNM_FORMAT_f " stdev]\n", (mean - T) / gnm_sqrt (var_target / N));
2005 2006
		ok = FALSE;
	}
2007

2008
	T = var_target;
2009
	g_printerr ("Expected var: %.10" GNM_FORMAT_g "\n", T);
2010
	if (gnm_abs (var - T) > 0.01) {
2011
		g_printerr ("Var failure.\n");
2012 2013
		ok = FALSE;
	}
2014

2015 2016
	T = mean_target/gnm_sqrt(var_target);
	T = T*T*T*(4-M_PIgnum)/2;
2017
	g_printerr ("Expected skew: %.10" GNM_FORMAT_g "\n", T);
2018
	if (gnm_abs (skew - T) > 0.05) {