Added a test utility marcos TL_ASSERT, TL_ASSERT2
[idzebra-moved-to-github.git] / test / api / testlib.c
1 /* $Id: testlib.c,v 1.29 2005-12-15 13:28:32 adam Exp $
2    Copyright (C) 1995-2005
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23 /** testlib - utilities for the api tests */
24
25 #if HAVE_SYS_TIME_H
26 #include <sys/time.h>
27 #endif
28 #if HAVE_SYS_RESOURCE_H
29 #include <sys/resource.h>
30 #endif
31 #if HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34
35 #include <assert.h>
36 #include <yaz/log.h>
37 #include <yaz/pquery.h>
38 #include <idzebra/api.h>
39 #include "testlib.h"
40
41 /** start_log: open a log file */
42 /*    FIXME - parse command line arguments to set log levels etc */
43 int log_level=0; /* not static, t*.c may use it */
44
45 void start_log(int argc, char **argv)
46 {
47     int cmd_level = 0;
48     char logname[2048];
49     if (!argv) 
50         return;
51     if (!argv[0])
52         return;
53     sprintf(logname, "%s.log", argv[0]);
54     yaz_log_init_file(logname);
55     log_level = yaz_log_mask_str_x(argv[0], 0);
56     if (argc >= 2)
57         cmd_level |= yaz_log_mask_str_x(argv[1], 0);
58     yaz_log_init_level(YLOG_DEFAULT_LEVEL | log_level | cmd_level);
59     yaz_log(log_level, "starting %s", argv[0]);
60 }
61
62 /** 
63  * start_up : do common start things, and a zebra_start
64  *    - nmem_init
65  *    - build the name of logfile from argv[0], and open it
66  *      if no argv passed, do not open a log
67  *    - read zebra.cfg from env var srcdir if it exists; otherwise current dir 
68  *      default to zebra.cfg, if no name is given
69  */
70 ZebraService start_up(char *cfgname, int argc, char **argv)
71 {
72 #if HAVE_SYS_RESOURCE_H
73 #if HAVE_SYS_TIME_H
74     struct rlimit rlim;
75     rlim.rlim_cur = 20;
76     rlim.rlim_max = 20;
77     setrlimit(RLIMIT_CPU, &rlim);
78 #endif
79 #endif
80     nmem_init();
81     start_log(argc, argv);
82     return start_service(cfgname);
83 }
84
85 /**
86  * get_srcdir: return env srcdir or . (if does does not exist)
87  */
88 const char *get_srcdir()
89 {
90     const char *srcdir = getenv("srcdir");
91     if (!srcdir || ! *srcdir)
92         srcdir = ".";
93     return srcdir;
94
95 }
96 /** start_service - do a zebra_start with a decent config name */
97 ZebraService start_service(const char *cfgname)
98 {
99     char cfg[256];
100     const char *srcdir = get_srcdir();
101     ZebraService zs;
102     if (!cfgname || ! *cfgname )
103         cfgname="zebra.cfg";
104
105     sprintf(cfg, "%.200s/%.50s", srcdir, cfgname);
106     zs = zebra_start(cfg);
107     TL_ASSERT2(zs, "zebra_start_failed. Missing config file?");
108     return zs;
109 }
110
111
112 /** close_down closes down the zebra, logfile, nmem, xmalloc etc. logs an OK */
113 int close_down(ZebraHandle zh, ZebraService zs, int retcode)
114 {
115     if (zh)
116         zebra_close(zh);
117     if (zs)
118         zebra_stop(zs);
119
120     if (retcode)
121         yaz_log(log_level,"========= Exiting with return code %d", retcode);
122     else
123         yaz_log(log_level,"========= All tests OK");
124     nmem_exit();
125     xmalloc_trav("x");
126     return retcode;
127 }
128
129 /** inits the database and inserts test data */
130
131 void init_data(ZebraHandle zh, const char **recs)
132 {
133     int i;
134     char *addinfo;
135     assert(zh);
136     zebra_select_database(zh, "Default");
137     yaz_log(log_level, "going to call init");
138     i = zebra_init(zh);
139     yaz_log(log_level, "init_data returned %d", i);
140     if (i) 
141     {
142         yaz_log(log_level, "init_data: zebra_init failed with %d", i);
143         printf("init_data failed with %d\n", i);
144         zebra_result(zh, &i, &addinfo);
145         yaz_log(log_level, "Error %d  %s", i, addinfo);
146         printf("  Error %d   %s\n", i, addinfo);
147         TL_ASSERT(i == 0);
148     }
149     if (recs)
150     {
151         zebra_begin_trans (zh, 1);
152         for (i = 0; recs[i]; i++)
153             zebra_add_record(zh, recs[i], strlen(recs[i]));
154         zebra_end_trans(zh);
155         zebra_commit(zh);
156     }
157
158 }
159
160 int do_query_x(int lineno, ZebraHandle zh, const char *query, zint exphits,
161                int experror)
162 {
163     ODR odr;
164     YAZ_PQF_Parser parser;
165     Z_RPNQuery *rpn;
166     const char *setname="rsetname";
167     zint hits;
168     ZEBRA_RES rc;
169
170     yaz_log(log_level, "======================================");
171     yaz_log(log_level, "qry[%d]: %s", lineno, query);
172     odr = odr_createmem (ODR_DECODE);    
173
174     parser = yaz_pqf_create();
175     rpn = yaz_pqf_parse(parser, odr, query);
176     yaz_pqf_destroy(parser);
177     TL_ASSERT2(rpn, "Parse of pqf failed");
178     rc = zebra_search_RPN(zh, odr, rpn, setname, &hits);
179     if (experror)
180     {
181         int code;
182         if (rc != ZEBRA_FAIL)
183         {
184             yaz_log(log_level, "search returned %d (OK), but error was "
185                     "expected", rc);
186             printf("Error: search returned %d (OK), but error was expected\n"
187                    "%s\n",  rc, query);
188             TL_ASSERT(rc == ZEBRA_FAIL);
189         }
190         code = zebra_errCode(zh);
191         if (code != experror)
192         {
193             yaz_log(log_level, "search returned error code %d, but error %d "
194                     "was expected", code, experror);
195             printf("Error: search returned error code %d, but error %d was "
196                    "expected\n%s\n",
197                    code, experror, query);
198             TL_ASSERT(code == experror);
199         }
200     }
201     else
202     {
203         if (rc == ZEBRA_FAIL) {
204             int code = zebra_errCode(zh);
205             yaz_log(log_level, "search returned %d. Code %d", rc, code);
206             
207             printf("Error: search returned %d. Code %d\n%s\n", rc, 
208                    code, query);
209             exit (1);
210         }
211         if (exphits != -1 && hits != exphits)
212         {
213             yaz_log(log_level, "search returned " ZINT_FORMAT 
214                    " hits instead of " ZINT_FORMAT, hits, exphits);
215             printf("Error: search returned " ZINT_FORMAT 
216                    " hits instead of " ZINT_FORMAT "\n%s\n",
217                    hits, exphits, query);
218             exit (1);
219         }
220     }
221     odr_destroy (odr);
222     return hits;
223 }
224
225
226 int do_query(int lineno, ZebraHandle zh, const char *query, zint exphits)
227 {
228     return do_query_x(lineno, zh, query, exphits, 0);
229 }
230
231 void do_scan(int lineno, ZebraHandle zh, const char *query,
232              int pos, int num,
233              int exp_pos, int exp_num, int exp_partial,
234              const char **exp_entries)
235 {
236     ODR odr = odr_createmem(ODR_ENCODE);
237     ZebraScanEntry *entries = 0;
238     int partial = -123;
239     ZEBRA_RES res;
240
241     yaz_log(log_level, "======================================");
242     yaz_log(log_level, "scan[%d]: pos=%d num=%d %s", lineno, pos, num, query);
243
244     res = zebra_scan_PQF(zh, odr, query, &pos, &num, &entries, &partial, 
245                          0 /* setname */);
246     if (res != ZEBRA_OK)
247     {
248         printf("Error: scan returned %d (FAIL), but no error was expected\n"
249                "%s\n",  res, query);
250         exit(1);
251     }
252     else
253     {
254         int fails = 0;
255         if (partial == -123)
256         {
257             printf("Error: scan returned OK, but partial was not set\n"
258                    "%s\n", query);
259             fails++;
260         }
261         if (partial != exp_partial)
262         {
263             printf("Error: scan returned OK, with partial/expected %d/%d\n"
264                    "%s\n", partial, exp_partial, query);
265             fails++;
266         }
267         if (num != exp_num)
268         {
269             printf("Error: scan returned OK, with num/expected %d/%d\n"
270                    "%s\n", num, exp_num, query);
271             fails++;
272         }
273         if (pos != exp_pos)
274         {
275             printf("Error: scan returned OK, with pos/expected %d/%d\n"
276                    "%s\n", pos, exp_pos, query);
277             fails++;
278         }
279         if (fails)
280             exit(1);
281         fails = 0;
282         if (exp_entries)
283         {
284             int i;
285             for (i = 0; i<num; i++)
286             {
287                 if (strcmp(exp_entries[i], entries[i].term))
288                 {
289                     printf("Error: scan OK, but entry %d term/exp %s/%s\n"
290                            "%s\n",
291                            i, entries[i].term, exp_entries[i], query);
292                     fails++;
293                 }
294             }
295         }
296         if (fails)
297             exit(0);
298     }
299     odr_destroy(odr);
300 }
301
302 /** 
303  * makes a query, checks number of hits, and for the first hit, that 
304  * it contains the given string, and that it gets the right score
305  */
306 void ranking_query(int lineno, ZebraHandle zh, char *query, 
307                    int exphits, char *firstrec, int firstscore)
308 {
309     ZebraRetrievalRecord retrievalRecord[10];
310     ODR odr_output = odr_createmem (ODR_ENCODE);    
311     const char *setname="rsetname";
312     int hits;
313     int rc;
314     int i;
315         
316     hits = do_query(lineno, zh, query, exphits);
317
318     for (i = 0; i<10; i++)
319         retrievalRecord[i].position = i+1;
320
321     rc = zebra_records_retrieve (zh, odr_output, setname, 0,
322                                  VAL_TEXT_XML, hits, retrievalRecord);
323     
324     if (rc)
325     {
326         printf("Error: retrieve returned %d \n%s\n",rc,query);
327         exit (1);
328     }
329
330     if (!strstr(retrievalRecord[0].buf, firstrec))
331     {
332         printf("Error: Got the wrong record first\n");
333         printf("Expected '%s' but got\n", firstrec);
334         printf("%.*s\n", retrievalRecord[0].len, retrievalRecord[0].buf);
335         exit(1);
336     }
337     
338     if (retrievalRecord[0].score != firstscore)
339     {
340         printf("Error: first rec got score %d instead of %d\n",
341                retrievalRecord[0].score, firstscore);
342         exit(1);
343     }
344     odr_destroy (odr_output);
345 }
346
347 void meta_query(int lineno, ZebraHandle zh, char *query, int exphits,
348                 zint *ids)
349 {
350     ZebraMetaRecord *meta;
351     ODR odr_output = odr_createmem (ODR_ENCODE);    
352     const char *setname="rsetname";
353     zint *positions = (zint *) malloc(1 + (exphits * sizeof(zint)));
354     int hits;
355     int i;
356         
357     hits = do_query(lineno, zh, query, exphits);
358     
359     for (i = 0; i<exphits; i++)
360         positions[i] = i+1;
361
362     meta = zebra_meta_records_create (zh, setname,  exphits, positions);
363     
364     if (!meta)
365     {
366         printf("Error: retrieve returned error\n%s\n", query);
367         exit (1);
368     }
369
370     for (i = 0; i<exphits; i++)
371     {
372         if (meta[i].sysno != ids[i])
373         {
374             printf("Expected id=" ZINT_FORMAT " but got id=" ZINT_FORMAT "\n",
375                    ids[i], meta[i].sysno);
376             exit(1);
377         }
378     }
379     zebra_meta_records_destroy(zh, meta, exphits);
380     odr_destroy (odr_output);
381     free(positions);
382 }
383
384 void do_sort(ZebraHandle zh, const char *query, zint hits, zint *exp)
385 {
386     ZebraMetaRecord *recs;
387     zint i;
388     int errs = 0;
389     zint min_val_recs = 0;
390     zint min_val_exp = 0;
391
392     assert(query);
393     do_query(__LINE__, zh, query, hits);
394
395     recs = zebra_meta_records_create_range (zh, "rsetname", 1, 4);
396     if (!recs)
397     {
398         fprintf(stderr, "recs==0\n");
399         exit(1);
400     }
401     /* find min for each sequence to get proper base offset */
402     for (i = 0; i<hits; i++)
403     {
404         if (min_val_recs == 0 || recs[i].sysno < min_val_recs)
405             min_val_recs = recs[i].sysno;
406         if (min_val_exp == 0 || exp[i] < min_val_exp)
407             min_val_exp = exp[i];
408     }
409             
410     /* compare sequences using base offset */
411     for (i = 0; i<hits; i++)
412         if ((recs[i].sysno-min_val_recs) != (exp[i]-min_val_exp))
413             errs++;
414     if (errs)
415     {
416         printf("Sequence not in right order for query\n%s\ngot exp\n",
417                query);
418         for (i = 0; i<hits; i++)
419             printf(" " ZINT_FORMAT "   " ZINT_FORMAT "\n",
420                    recs[i].sysno, exp[i]);
421     }
422     zebra_meta_records_destroy (zh, recs, 4);
423
424     if (errs)
425         exit(1);
426 }
427
428
429 struct finfo {
430     const char *name;
431     int occurred;
432 };
433
434 static void filter_cb(void *cd, const char *name)
435 {
436     struct finfo *f = (struct finfo*) cd;
437     if (!strcmp(f->name, name))
438         f->occurred = 1;
439 }
440
441 void check_filter(ZebraService zs, const char *name)
442 {
443     struct finfo f;
444
445     f.name = name;
446     f.occurred = 0;
447     zebra_filter_info(zs, &f, filter_cb);
448     if (!f.occurred)
449     {
450         yaz_log(YLOG_WARN, "Filter %s does not exist.", name);
451         exit(0);
452     }
453 }
454
455
456
457