Use HAVE_UNISTD_H when including unistd.h.
[idzebra-moved-to-github.git] / test / api / testlib.c
1 /* $Id: testlib.c,v 1.23 2005-06-14 20:28:54 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(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     if (!zs)
108     {
109         printf("zebra_start failed, probably because missing config file \n"
110                "check %s\n", cfg);
111         exit(9);
112     }
113     return zs;
114 }
115
116
117 /** close_down closes down the zebra, logfile, nmem, xmalloc etc. logs an OK */
118 int close_down(ZebraHandle zh, ZebraService zs, int retcode)
119 {
120     if (zh)
121         zebra_close(zh);
122     if (zs)
123         zebra_stop(zs);
124
125     if (retcode)
126         yaz_log(log_level,"========= Exiting with return code %d", retcode);
127     else
128         yaz_log(log_level,"========= All tests OK");
129     nmem_exit();
130     xmalloc_trav("x");
131     return retcode;
132 }
133
134 /** inits the database and inserts test data */
135
136 void init_data(ZebraHandle zh, const char **recs)
137 {
138     int i;
139     char *addinfo;
140     assert(zh);
141     zebra_select_database(zh, "Default");
142     yaz_log(log_level, "going to call init");
143     i = zebra_init(zh);
144     yaz_log(log_level, "init returned %d", i);
145     if (i) 
146     {
147         printf("init failed with %d\n",i);
148         zebra_result(zh, &i, &addinfo);
149         printf("  Error %d   %s\n", i, addinfo);
150         exit(1);
151     }
152     if (recs)
153     {
154         zebra_begin_trans (zh, 1);
155         for (i = 0; recs[i]; i++)
156             zebra_add_record(zh, recs[i], strlen(recs[i]));
157         zebra_end_trans(zh);
158         zebra_commit(zh);
159     }
160
161 }
162
163 int do_query_x(int lineno, ZebraHandle zh, const char *query, zint exphits,
164                int experror)
165 {
166     ODR odr;
167     YAZ_PQF_Parser parser;
168     Z_RPNQuery *rpn;
169     const char *setname="rsetname";
170     zint hits;
171     ZEBRA_RES rc;
172
173     yaz_log(log_level, "======================================");
174     yaz_log(log_level, "qry[%d]: %s", lineno, query);
175     odr = odr_createmem (ODR_DECODE);    
176
177     parser = yaz_pqf_create();
178     rpn = yaz_pqf_parse(parser, odr, query);
179     yaz_pqf_destroy(parser);
180     if (!rpn) {
181         printf("Error: Parse failed \n%s\n", query);
182         exit(1);
183     }
184     rc = zebra_search_RPN(zh, odr, rpn, setname, &hits);
185     if (experror)
186     {
187         int code;
188         if (rc != ZEBRA_FAIL)
189         {
190             printf("Error: search returned %d (OK), but error was expected\n"
191                    "%s\n",  rc, query);
192             exit(1);
193         }
194         code = zebra_errCode(zh);
195         if (code != experror)
196         {
197             printf("Error: search returned error code %d, but error %d was "
198                    "expected\n%s\n",
199                    code, experror, query);
200             exit(1);
201         }
202     }
203     else
204     {
205         if (rc == ZEBRA_FAIL) {
206             int code = zebra_errCode(zh);
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             printf("Error: search returned " ZINT_FORMAT 
213                    " hits instead of " ZINT_FORMAT "\n%s\n",
214                    hits, exphits, query);
215             exit (1);
216         }
217     }
218     odr_destroy (odr);
219     return hits;
220 }
221
222
223 int do_query(int lineno, ZebraHandle zh, const char *query, zint exphits)
224 {
225     return do_query_x(lineno, zh, query, exphits, 0);
226 }
227
228 void do_scan(int lineno, ZebraHandle zh, const char *query,
229              int pos, int num,
230              int exp_pos, int exp_num, int exp_partial,
231              const char **exp_entries)
232 {
233     ODR odr = odr_createmem(ODR_ENCODE);
234     ZebraScanEntry *entries = 0;
235     int partial = -123;
236     ZEBRA_RES res;
237
238     yaz_log(log_level, "======================================");
239     yaz_log(log_level, "scan[%d]: pos=%d num=%d %s", lineno, pos, num, query);
240
241     res = zebra_scan_PQF(zh, odr, query, &pos, &num, &entries, &partial);
242     if (res != ZEBRA_OK)
243     {
244         printf("Error: scan returned %d (FAIL), but no error was expected\n"
245                "%s\n",  res, query);
246         exit(1);
247     }
248     else
249     {
250         int fails = 0;
251         if (partial == -123)
252         {
253             printf("Error: scan returned OK, but partial was not set\n"
254                    "%s\n", query);
255             fails++;
256         }
257         if (partial != exp_partial)
258         {
259             printf("Error: scan returned OK, with partial/expected %d/%d\n"
260                    "%s\n", partial, exp_partial, query);
261             fails++;
262         }
263         if (num != exp_num)
264         {
265             printf("Error: scan returned OK, with num/expected %d/%d\n"
266                    "%s\n", num, exp_num, query);
267             fails++;
268         }
269         if (pos != exp_pos)
270         {
271             printf("Error: scan returned OK, with pos/expected %d/%d\n"
272                    "%s\n", pos, exp_pos, query);
273             fails++;
274         }
275         if (fails)
276             exit(1);
277         fails = 0;
278         if (exp_entries)
279         {
280             int i;
281             for (i = 0; i<num; i++)
282             {
283                 if (strcmp(exp_entries[i], entries[i].term))
284                 {
285                     printf("Error: scan OK, but entry %d term/exp %s/%s\n"
286                            "%s\n",
287                            i, entries[i].term, exp_entries[i], query);
288                     fails++;
289                 }
290             }
291         }
292         if (fails)
293             exit(0);
294     }
295     odr_destroy(odr);
296 }
297
298 /** 
299  * makes a query, checks number of hits, and for the first hit, that 
300  * it contains the given string, and that it gets the right score
301  */
302 void ranking_query(int lineno, ZebraHandle zh, char *query, 
303                    int exphits, char *firstrec, int firstscore)
304 {
305     ZebraRetrievalRecord retrievalRecord[10];
306     ODR odr_output = odr_createmem (ODR_ENCODE);    
307     const char *setname="rsetname";
308     int hits;
309     int rc;
310     int i;
311         
312     hits = do_query(lineno, zh, query, exphits);
313
314     for (i = 0; i<10; i++)
315         retrievalRecord[i].position = i+1;
316
317     rc = zebra_records_retrieve (zh, odr_output, setname, 0,
318                                  VAL_TEXT_XML, hits, retrievalRecord);
319     
320     if (rc)
321     {
322         printf("Error: retrieve returned %d \n%s\n",rc,query);
323         exit (1);
324     }
325
326     if (!strstr(retrievalRecord[0].buf, firstrec))
327     {
328         printf("Error: Got the wrong record first\n");
329         printf("Expected '%s' but got\n", firstrec);
330         printf("%.*s\n", retrievalRecord[0].len, retrievalRecord[0].buf);
331         exit(1);
332     }
333     
334     if (retrievalRecord[0].score != firstscore)
335     {
336         printf("Error: first rec got score %d instead of %d\n",
337                retrievalRecord[0].score, firstscore);
338         exit(1);
339     }
340     odr_destroy (odr_output);
341 }
342
343 void meta_query(int lineno, ZebraHandle zh, char *query, int exphits,
344                 zint *ids)
345 {
346     ZebraMetaRecord *meta;
347     ODR odr_output = odr_createmem (ODR_ENCODE);    
348     const char *setname="rsetname";
349     zint *positions = (zint *) malloc(1 + (exphits * sizeof(zint)));
350     int hits;
351     int i;
352         
353     hits = do_query(lineno, zh, query, exphits);
354     
355     for (i = 0; i<exphits; i++)
356         positions[i] = i+1;
357
358     meta = zebra_meta_records_create (zh, setname,  exphits, positions);
359     
360     if (!meta)
361     {
362         printf("Error: retrieve returned error\n%s\n", query);
363         exit (1);
364     }
365
366     for (i = 0; i<exphits; i++)
367     {
368         if (meta[i].sysno != ids[i])
369         {
370             printf("Expected id=" ZINT_FORMAT " but got id=" ZINT_FORMAT "\n",
371                    ids[i], meta[i].sysno);
372             exit(1);
373         }
374     }
375     zebra_meta_records_destroy(zh, meta, exphits);
376     odr_destroy (odr_output);
377     free(positions);
378 }
379
380 struct finfo {
381     const char *name;
382     int occurred;
383 };
384
385 static void filter_cb(void *cd, const char *name)
386 {
387     struct finfo *f = (struct finfo*) cd;
388     if (!strcmp(f->name, name))
389         f->occurred = 1;
390 }
391
392 void check_filter(ZebraService zs, const char *name)
393 {
394     struct finfo f;
395
396     f.name = name;
397     f.occurred = 0;
398     zebra_filter_info(zs, &f, filter_cb);
399     if (!f.occurred)
400     {
401         yaz_log(YLOG_WARN, "Filter %s does not exist.", name);
402         exit(0);
403     }
404 }
405
406
407
408