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