test_api.cpp 105 KB
Newer Older
1
// Copyright 2017-2021, Schlumberger
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "test_all.h"
#include "test_utils.h"
#include "../api.h"
18
#include "../iocontext.h"
19
20
#include "../exception.h"
#include "../impl/environment.h"
21
#include "../impl/mtguard.h"
22
23
24
25

#include <iostream>
#include <iomanip>
#include <sstream>
26
#include <fstream>
27
28
29
30
#include <memory>
#include <cstdint>
#include <cmath>
#include <numeric>
31
#include <limits>
32
33
#include <thread>
#include <chrono>
34
#include <algorithm>
35
#include <functional>
36
37
38
39

using namespace OpenZGY;
using namespace OpenZGY::Formatters;
using Test_Utils::LocalFileAutoDelete;
40
using Test_Utils::CloudFileAutoDelete;
41
using Test_Utils::must_throw;
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

namespace {
  template<typename T, std::size_t  N>
  std::ostream& operator<<(std::ostream& os, const std::array<T,N>& a)
  {
    os << "[";
    for (std::size_t ii=0; ii<N; ++ii)
      os << a[ii] << (ii == N-1 ? "" : ", ");
    os << "]";
    return os;
  }

  std::ostream& operator<<(std::ostream& os, const SampleStatistics& in)
  {
    os << "cnt: " << in.cnt
       << " sum: " << in.sum
       << " ssq: " << in.ssq
       << " min: " << in.min
       << " max: " << in.max;
    return os;
  }

  std::ostream& operator<<(std::ostream& os, const SampleHistogram& in)
  {
    os << "cnt: " << in.samplecount
       << " min: " << in.minvalue
       << " max: " << in.maxvalue
       << " bincount: " << in.bins.size();
    return os;
  }
}

namespace Test_API {
#if 0
}
#endif

static std::string
get_testdata(const std::string& name)
{
  using InternalZGY::Environment;
#ifdef _WIN32
  std::string result = Environment::getStringEnv("OPENZGY_TESTDATA", "..\\..\\build\\testdata");
  if (result.back() != '\\')
    result += "\\";
  result += name;
  return result;
#else
  return
    Environment::getStringEnv("OPENZGY_TESTDATA", "../../build/testdata")
    + "/" + name;
#endif
}

96
97
static bool
similar(double a, double b, double eps)
98
99
100
101
{
  return std::abs(a - b)  <= eps * 0.5 * (std::abs(a) + std::abs(b));
}

102
103
static void
dump_api(std::shared_ptr<OpenZGY::IZgyTools> rr, std::ostream& out)
104
{
105
  const OpenZGY::IZgyTools& r = *rr.get();
106
107
  std::streamsize oldprec = std::cout.precision();
  std::ios_base::fmtflags oldflags = std::cout.flags();
108
  out << "File format and version        = " << r.datatype()
109
      << " ZGY version " << r.filestats()->fileVersion() << "\n";
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
  out << "Size I,J,K                     = " << r.size() << "\n";
  out << "Brick size I,J,K               = " << r.bricksize() << "\n";
  out << "Number of bricks I,J,K         = " << r.brickcount()[0] << "\n";
  out << "Number of LODs                 = " << r.nlods() << "\n";
  out << "Coding range min/max           = " << r.datarange() << "\n";
  out << "Statistical min/max/count      = " << r.statistics() << "\n";
  out << "Histogram range min/max/count  = " << r.histogram() << "\n";
  out << "Inline start/increment/count   = "
      << r.annotstart()[0] << " "
      << r.annotinc()[0] << " "
      << r.size()[0] << "\n";
  out << "Xline  start/increment/count   = "
      << r.annotstart()[1] << " "
      << r.annotinc()[1] << " "
      << r.size()[1] << "\n";
  out << "Sample start/increment/count   = "
      << r.zstart() << " "
      << r.zinc() << " "
      << r.size()[2] << "\n";
  out << "Horizontal dim/factor/name     = "
      << r.hunitdim() << " "
      << r.hunitfactor() << " '"
      << r.hunitname() << "'\n";
  out << "Vertical dim/factor/name       = "
      << r.zunitdim() << " "
      << r.zunitfactor() << " '"
      << r.zunitname() << "'\n";
  out << "Ordered Corner Points Legend   = [  <i>,   <j>] { <inline>,   <xline>} (  <easting>,  <northing>)" << "\n";
138
  r.filestats()->dump(out);
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
  for (int ii=0; ii<4; ++ii)
    out << "Ordered Corner Point " << ii << "         = ["
        << std::fixed << std::setprecision(0)
        << std::setw(5) << r.indexcorners()[ii][0] << ", "
        << std::setw(5) << r.indexcorners()[ii][1] << "] {"
        << std::scientific << std::setprecision(6)
        << std::setw(9) << r.annotcorners()[ii][0] << ", "
        << std::setw(9) << r.annotcorners()[ii][1] << "} ("
        << std::fixed << std::setprecision(2)
        << std::setw(11) << r.corners()[ii][0] << ", "
        << std::setw(11) << r.corners()[ii][1] << ")\n"
        << std::scientific << std::setprecision(oldprec);
  // Note, I'd like defaultfloat instead of scientific
  // but the former is not supported on all compilers.
  // This is also why I need to reset the flags.
  std::cout.flags(oldflags);
}

157
158
159
160
161
/**
 * Read metadata from the well-known "Empty-v3.zgy" file.
 * Either directly from the reader, or from a writer that
 * is about to copy the file.
 */
162
163
static void
do_test_readmeta(const OpenZGY::IZgyTools& r, bool complete, int version)
164
165
{
  TEST_CHECK(r.datatype() == SampleDataType::int8);
166
167
168
169
170
171
172
173
174
175
176
177
  TEST_EQUAL(r.size()[0], 181);
  TEST_EQUAL(r.size()[1], 241);
  TEST_EQUAL(r.size()[2], 169);
  TEST_EQUAL(r.bricksize()[0], 64);
  TEST_EQUAL(r.bricksize()[1], 64);
  TEST_EQUAL(r.bricksize()[2], 64);
  TEST_EQUAL(r.brickcount()[0][0], 3);
  TEST_EQUAL(r.brickcount()[0][1], 4);
  TEST_EQUAL(r.brickcount()[0][2], 3);
  TEST_EQUAL(r.nlods(), (complete ? 3 : 1));
  TEST_EQUAL_FLOAT(r.datarange()[0], -10038.5, 0.5);
  TEST_EQUAL_FLOAT(r.datarange()[1], +9761.62, 0.5);
178
  if (complete) {
179
    // Skip these tests if still writing the file.
180
181
182
183
184
185
    TEST_EQUAL_FLOAT(r.statistics().min, -10038.5, 0.5);
    TEST_EQUAL_FLOAT(r.statistics().max, +9761.62, 0.5);
    TEST_EQUAL_FLOAT(r.histogram().minvalue, -10038.5, 0.5);
    TEST_EQUAL_FLOAT(r.histogram().maxvalue, +9761.62, 0.5);
    TEST_EQUAL(r.statistics().cnt, (version==1 ? 0 : 7371949));
    TEST_EQUAL(r.histogram().samplecount, (version==1 ? 0 : 7371949));
186
  }
187
  else {
188
189
190
191
192
193
    TEST_EQUAL(r.statistics().min, 0);
    TEST_EQUAL(r.statistics().max, 0);
    TEST_EQUAL(r.histogram().minvalue, 0);
    TEST_EQUAL(r.histogram().maxvalue, 0);
    TEST_EQUAL(r.statistics().cnt, 0);
    TEST_EQUAL(r.histogram().samplecount, 0);
194
  }
195
196
197
198
199
200
  TEST_EQUAL(r.annotstart()[0], 640);
  TEST_EQUAL(r.annotstart()[1], 920);
  TEST_EQUAL(r.annotinc()[0], 2);
  TEST_EQUAL(r.annotinc()[1], 2);
  TEST_EQUAL(r.zstart(), 648);
  TEST_EQUAL(r.zinc(), 6);
201
  TEST_CHECK(r.hunitdim() == UnitDimension::unknown);
202
203
  TEST_EQUAL(r.hunitfactor(), 1.0);
  TEST_EQUAL(r.hunitname(), "");
204
  TEST_CHECK(r.zunitdim() == UnitDimension::unknown);
205
206
  TEST_EQUAL(r.zunitfactor(), 1.0);
  TEST_EQUAL(r.zunitname(), "");
207
  std::shared_ptr<const FileStatistics>filestats = r.filestats();
208
  TEST_EQUAL(filestats->fileVersion(), version);
209
210
  if (complete) {
    // Skip these tests of wtill writing the file.
211
212
213
214
215
    TEST_EQUAL(filestats->fileSize(), (version==1 ? 11867826 : 12320768));
    TEST_EQUAL(filestats->alphaNormalCount(), (version==1 ? 17 : 5));
    TEST_EQUAL(filestats->alphaNormalSizePerEntry(), 64*64);
    TEST_EQUAL(filestats->brickNormalCount(), 45);
    TEST_EQUAL(filestats->brickNormalSizePerEntry(), 64*64*64);
216
  }
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

  // actual
  const IZgyReader::corners_t& index = r.indexcorners();
  const IZgyReader::corners_t& annot = r.annotcorners();
  const IZgyReader::corners_t& world = r.corners();

  // expect
  double ibeg[2] { 0, 0 };
  double iend[2] { (double)r.size()[0] - 1, (double)r.size()[1] - 1 };
  double abeg[2] { r.annotstart()[0], r.annotstart()[1] };
  double aend[2] { abeg[0] + r.annotinc()[0] * (r.size()[0] - 1),
                   abeg[1] + r.annotinc()[1] * (r.size()[1] - 1)};

  TEST_CHECK(index[0][0] == ibeg[0] && index[0][1] == ibeg[1]);
  TEST_CHECK(index[1][0] == iend[0] && index[1][1] == ibeg[1]);
  TEST_CHECK(index[2][0] == ibeg[0] && index[2][1] == iend[1]);
  TEST_CHECK(index[3][0] == iend[0] && index[3][1] == iend[1]);

  TEST_CHECK(annot[0][0] == abeg[0] && annot[0][1] == abeg[1]);
  TEST_CHECK(annot[1][0] == aend[0] && annot[1][1] == abeg[1]);
  TEST_CHECK(annot[2][0] == abeg[0] && annot[2][1] == aend[1]);
  TEST_CHECK(annot[3][0] == aend[0] && annot[3][1] == aend[1]);

240
241
242
243
244
245
246
247
  TEST_EQUAL_FLOAT(world[0][0],  564344.97, 0.1);
  TEST_EQUAL_FLOAT(world[0][1], 5917369.23, 0.1);
  TEST_EQUAL_FLOAT(world[1][0],  568209.86, 0.1);
  TEST_EQUAL_FLOAT(world[1][1], 5915035.21, 0.1);
  TEST_EQUAL_FLOAT(world[2][0],  567457.07, 0.1);
  TEST_EQUAL_FLOAT(world[2][1], 5922522.52, 0.1);
  TEST_EQUAL_FLOAT(world[3][0],  571321.95, 0.1);
  TEST_EQUAL_FLOAT(world[3][1], 5920188.49, 0.1);
248
249

  std::string nulluuid = "00000000-0000-0000-0000-000000000000";
250
  TEST_EQUAL(r.verid().size(), nulluuid.size());
251
252
  bool verid_missing = (r.verid() == nulluuid);
  TEST_CHECK(version == 1 ? verid_missing : !verid_missing);
253
254
}

255
256
static void
test_readmeta_r()
257
258
259
260
261
262
263
264
{
  std::string fname = get_testdata("Empty-v3.zgy");
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(fname);
  if (verbose()) {
    std::cout << "\n";
    dump_api(reader, std::cout);
    reader->filestats()->dump(std::cout, "filestats: ");
  }
265
  do_test_readmeta(*reader, true, 3);
266
267
268
  reader->close();
}

269
270
static void
test_readmeta_w()
271
272
273
274
275
276
277
278
279
280
281
282
283
{
  std::string fname = get_testdata("Empty-v3.zgy");
  LocalFileAutoDelete lad("testfile.zgy");
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(fname);
  ZgyWriterArgs args = ZgyWriterArgs()
    .metafrom(reader)
    .filename(lad.name());
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  if (verbose()) {
    std::cout << "\n";
    dump_api(writer, std::cout);
    writer->filestats()->dump(std::cout, "filestats: ");
  }
284
  do_test_readmeta(*writer, false, 3);
285
286
  writer->finalize();
  writer->close();
287
  reader->close();
288
}
289

290
291
static void
test_readmeta_v1_r()
292
293
294
295
296
297
298
299
300
301
{
  std::string fname = get_testdata("Empty-v1.zgy");
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(fname);
  if (verbose()) {
    std::cout << "\n";
    dump_api(reader, std::cout);
    reader->filestats()->dump(std::cout, "filestats: ");
  }
  do_test_readmeta(*reader, true, 1);
  reader->close();
302
303
}

Paal Kvamme's avatar
Paal Kvamme committed
304
#if 0 // The required data file is not checked in yet.
305
306
static void
test_readcmeta()
307
308
309
310
311
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Compressed.zgy"));
  if (verbose()) {
    std::cout << "\n";
    dump_api(reader, std::cout);
312
    reader->filestats()->dump(std::cout, "filestats: ");
313
314
  }
}
Paal Kvamme's avatar
Paal Kvamme committed
315
#endif
316

317
318
static void
test_readconst()
319
320
321
322
323
324
325
326
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  std::pair<bool,double> c = reader->readconst(std::array<std::int64_t,3>{0,0,0}, reader->size(), 0, true);
  //std::cout << "constant? " << std::boolalpha << c.first << std::noboolalpha << " value " << c.second << "\n";
  TEST_CHECK(!c.first);
  reader->close();
}

327
328
static void
test_readbulk()
329
330
331
332
333
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size = reader->size();
  std::unique_ptr<float[]>buf(new float[size[0] * size[1] * size[2]]);
334
  memset(buf.get(), 0, size[0] * size[1] * size[2] * sizeof(float));
335
  reader->read(orig, size, buf.get(), 0);
336
  // storage zero maps to 99.6137
337
338
339
340
  TEST_CHECK(std::abs(buf[0]+99.6137) < 0.001);
  reader->close();
}

341
342
343
344
345
346
347
348
349
350
351
352
353
/**
 * The first brick of the (now confusingly named) Empty-v3
 * has been patched by hand to have this test pattern:
 *
 *   offset             v3 sample  v1 sample
 *    0*64 ..  0*64+9 :  0 .. 9     0 .. 9
 *    8*64 ..  8*64+9 : 10 .. 19   20 .. 29
 *   64*64 .. 64*64+9 : 20 .. 29   10 .. 10
 *  all others        : 0          0
 *
 * Test reading back this brick from both files.
 * the result that the application sees should be the same.
 */
354
355
static void
test_readsubtiles()
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
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size{64,64,64};
  std::unique_ptr<std::int8_t[]>buf(new std::int8_t[64*64*64]);
  memset(buf.get(), 0, 64*64*64);
  reader->read(orig, size, buf.get(), 0);
  TEST_CHECK(buf[0] == 0);
  TEST_CHECK(buf[1] == 1);
  TEST_CHECK(buf[2] == 2);
  TEST_CHECK(buf[8*64+0] == 10);
  TEST_CHECK(buf[8*64+1] == 11);
  TEST_CHECK(buf[8*64+2] == 12);
  TEST_CHECK(buf[64*64+0] == 20);
  TEST_CHECK(buf[64*64+1] == 21);
  TEST_CHECK(buf[64*64+2] == 22);
  reader->close();

  reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v1.zgy"));
  memset(buf.get(), 0, 64*64*64);
  reader->read(orig, size, buf.get(), 0);
  TEST_CHECK(buf[0] == 0);
  TEST_CHECK(buf[1] == 1);
  TEST_CHECK(buf[2] == 2);
  TEST_CHECK(buf[8*64+0] == 10);
  TEST_CHECK(buf[8*64+1] == 11);
  TEST_CHECK(buf[8*64+2] == 12);
  TEST_CHECK(buf[64*64+0] == 20);
  TEST_CHECK(buf[64*64+1] == 21);
  TEST_CHECK(buf[64*64+2] == 22);
  reader->close();
}

389
390
static void
test_readbadvt()
391
392
393
394
395
396
397
398
399
400
401
402
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size{16,16,16};
  std::unique_ptr<std::int16_t[]>buf(new std::int16_t[size[0] * size[1] * size[2]]);
  must_throw("storage cannot be null", [&](){
    reader->read(orig, size, (std::int8_t*)nullptr, 0);});
  must_throw("data type not supported", [&](){
    reader->read(orig, size, buf.get(), 0);});
  reader->close();
}

403
404
static void
test_readbadpos()
405
406
407
408
409
410
411
{
  typedef OpenZGY::IZgyWriter::size3i_t size3i_t;
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  std::unique_ptr<std::int8_t[]>buf(new std::int8_t[1024]);
  // Negative size is caught when ZgyReader::read() wraps our raw buffer into
  // a DataBuffer, so the check in ZgyInternalBulk::readToExistingBuffer()
  // is not used.
412
  must_throw("size must be positive", [&](){
413
    reader->read(size3i_t{0,0,0}, size3i_t{1,-1,1}, buf.get(), 0);});
414
  must_throw("size must be positive", [&](){
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
    reader->read(size3i_t{0,0,0}, size3i_t{0,0,0}, buf.get(), 0);});
  must_throw("outside the valid range", [&](){
    reader->read(size3i_t{0,0,0}, size3i_t{1,1,1000}, buf.get(), 0);});
  must_throw("lod -1 is outside the valid range", [&](){
    reader->read(size3i_t{0,0,0}, size3i_t{1,1,1}, buf.get(), -1);});
  must_throw("lod 3 is outside the valid range", [&](){
    reader->read(size3i_t{0,0,0}, size3i_t{1,1,1}, buf.get(), 3);});
  // Repeat the tests using readconst.
  must_throw("outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{1,-1,1}, 0, true);});
  must_throw("empty or outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{0,0,0}, 0, true);});
  must_throw("outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{1,1,1000}, 0, true);});
  must_throw("lod -1 is outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{1,1,1}, -1, true);});
  must_throw("lod 3 is outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{1,1,1}, 3, true);});
  reader->close();
}

436
437
static void
test_readnotopen()
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
{
  std::string fname = get_testdata("Fancy-int8.zgy");
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(fname);
  reader->close();

  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size{1,1,1};

  must_throw("not open for read", [&](){
    reader->readconst(orig, size, 0, true);
  });

  must_throw("not open for read", [&](){
    std::int8_t data{0};
    reader->read(orig, size, &data);
  });

#if 0 // Need an int16_t file for this.
  must_throw("not open for read", [&](){
    std::int16_t data{0};
    reader->read(orig, size, &data);
  });
#endif

  must_throw("not open for read", [&](){
    float data{0};
    reader->read(orig, size, &data);
  });
}

/**
 * The file's type will match the template argumnent.
 * Access will be attempted both using T and float.
 */
template<typename T>
473
474
static void
test_writenotopen()
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
{
  typedef IZgyWriter::size3i_t size3i_t;
  LocalFileAutoDelete lad("testfile.zgy");
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> next{0,0,64};
  const std::array<std::int64_t,3> size{1,1,1};
  ZgyWriterArgs args = ZgyWriterArgs()
    .filename(lad.name())
    .size(33, 28, 92)
    .datatype(typeid(T)==typeid(std::int8_t) ? SampleDataType::int8 :
              typeid(T)==typeid(std::int16_t) ? SampleDataType::int16 :
              SampleDataType::float32)
    .datarange(-100,+100);
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  const T     tdata[6]{42,43,44,45,46,47};
  const float fdata[6]{42,43,44,45,46,47};
  writer->writeconst(size3i_t{0,0,0}, size3i_t{1,1,1}, &tdata[0]);
  writer->writeconst(size3i_t{0,0,1}, size3i_t{1,1,1}, &fdata[1]);
  writer->write     (size3i_t{0,0,2}, size3i_t{1,1,1}, &tdata[2]);
  writer->write     (size3i_t{0,0,3}, size3i_t{1,1,1}, &fdata[3]);
  writer->writeconst(size3i_t{0,0,4}, size3i_t{1,1,1}, &tdata[4]);
  writer->writeconst(size3i_t{0,0,5}, size3i_t{1,1,1}, &fdata[5]);
  writer->finalize();
  writer->close();

  // Overwriting
Paal Kvamme's avatar
Paal Kvamme committed
501
  must_throw("not open for write", [&](){
502
503
504
    const T data{0};
    writer->write(orig, size, &data);
  });
Paal Kvamme's avatar
Paal Kvamme committed
505
  must_throw("not open for write", [&](){
506
507
508
    const float data{0};
    writer->write(orig, size, &data);
  });
Paal Kvamme's avatar
Paal Kvamme committed
509
  must_throw("not open for write", [&](){
510
511
512
    const T data{0};
    writer->writeconst(orig, size, &data);
  });
Paal Kvamme's avatar
Paal Kvamme committed
513
  must_throw("not open for write", [&](){
514
515
516
517
518
519
520
521
522
    const float data{0};
    writer->writeconst(orig, size, &data);
  });

  // Writing new
  must_throw("not open for write", [&](){
    const T data{-1};
    writer->write(next, size, &data);
  });
Paal Kvamme's avatar
Paal Kvamme committed
523
524
525
526
527
  // Now that the error is reported at a high level
  // it will not be treated as an I/O error and will
  // not set the error flag. Which is correct.
  // Fake an I/O error.
  writer->set_errorflag(true);
528
529
530
531
532
  must_throw("previous errors", [&](){
    const float data{-1};
    writer->write(next, size, &data);
  });
  writer->set_errorflag(false);
533
534
535
536
537
538
539
540
541
542
543
544
545
546
  must_throw("not open for write", [&](){
    const float data{-1};
    writer->write(next, size, &data);
  });
  must_throw("not open for write", [&](){
    const T data{-1};
    writer->writeconst(next, size, &data);
  });
  must_throw("not open for write", [&](){
    const float data{-1};
    writer->writeconst(next, size, &data);
  });

  // Finish
Paal Kvamme's avatar
Paal Kvamme committed
547
  must_throw("not open for write", [&](){
548
    writer->finalize();
Paal Kvamme's avatar
Paal Kvamme committed
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
  // A double close is acceptable.
  //must_throw("not open for write", [&](){
  writer->close();
  //});

  // This is a mostly unrelated test.
  // Check that writeconst() uses a read-modify-write when needed
  // and doesn't just clobber the entire brick when the caller
  // didn't provide a brick aligned region.
  std::shared_ptr<IZgyReader> reader = IZgyReader::open(lad.name());
  float tcheck[6]{0};
  float fcheck[6]{0};
  reader->read(size3i_t{0,0,0}, size3i_t{1,1,6}, &fcheck[0], 0);
  reader->read(size3i_t{0,0,0}, size3i_t{1,1,6}, &tcheck[0], 0);
  reader->close();
  // Verify using the same valuetype as written:
  // storage for even numbers, float for odd.
  if (verbose())
    std::cout << "Read back: "
              << tcheck[0] << " "<< fcheck[1] << " "
              << tcheck[2] << " "<< fcheck[3] << " "
              << tcheck[4]<< " " << fcheck[5]
              << std::endl;
}

Paal Kvamme's avatar
Paal Kvamme committed
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
static void
test_createargs()
{
  LocalFileAutoDelete lad("createargs.zgy");
  const std::string filename = lad.name();
  lad.disarm(); // Don't expect to actually create it.
  must_throw("cannot be empty or negative", [&lad](){
    IZgyWriter::open(ZgyWriterArgs().filename(lad.name()).size(0,1,1));
    lad.arm();
  });
  must_throw("too large", [&lad](){
    IZgyWriter::open(ZgyWriterArgs().filename(lad.name()).size(1,1,1LL<<31));
    lad.arm();
  });
}

591
592
static void
test_ioerror()
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
{
  typedef OpenZGY::IZgyWriter::size3i_t size3i_t;
  LocalFileAutoDelete lad("ioerror.zgy");
  ZgyWriterArgs args = ZgyWriterArgs()
    .size(128, 128, 128)
    .filename(lad.name());
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  writer->set_errorflag(true);
  // TODO-Test: It would be better to provoke a real I/O error here,
  // but this might not be possible without breaking encapsulation.
  TEST_CHECK(writer->errorflag());
  must_throw("previous error", [writer](){
    const float fortytwo{42};
    writer->write(size3i_t{0,0,0}, size3i_t{1,1,1}, &fortytwo);
  });
  TEST_CHECK(writer->errorflag());
609
610
611
  // finalize() and close() are now allowed even after en error,
  // as they will try to salvage what they can and clear lowres etc.
  //must_throw("previous error", [writer](){
Paal Kvamme's avatar
Paal Kvamme committed
612
    writer->finalize();
613
614
  //});
  //must_throw("previous error", [writer](){
615
    writer->close();
616
  //});
617
618
}

Paal Kvamme's avatar
Paal Kvamme committed
619
static void
620
do_test_finalize(int mode)
Paal Kvamme's avatar
Paal Kvamme committed
621
622
{
  typedef OpenZGY::IZgyWriter::size3i_t size3i_t;
623
  LocalFileAutoDelete lad("incomplete_" + std::to_string(mode) + ".zgy");
Paal Kvamme's avatar
Paal Kvamme committed
624
625
626
  ZgyWriterArgs args = OpenZGY::ZgyWriterArgs()
    .size(128, 128, 128)
    .filename(lad.name());
627
628
  if (mode == 7)
    args.size(7, 13, 19);
Paal Kvamme's avatar
Paal Kvamme committed
629
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
630
  const float fortyone{41};
Paal Kvamme's avatar
Paal Kvamme committed
631
  const float fortytwo{42};
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
  switch (mode) {
  case 1: // write, implicit finalize, close.
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortyone);
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortytwo);
    writer->close();
    break;
  case 2: // write, finalize, close.
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortyone);
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortytwo);
    writer->finalize();
    writer->close();
    break;
  case 3: // write, finalize, write, finalize again, close.
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortyone);
    writer->finalize();
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortytwo);
    writer->finalize();
Paal Kvamme's avatar
Paal Kvamme committed
649
    writer->close();
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
    break;
  case 4: // write, finalize, close_incomplete should then be same as close.
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortyone);
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortytwo);
    writer->finalize();
    writer->close_incomplete();
    break;
  case 5: // write, close without finalize
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortyone);
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortytwo);
    writer->close_incomplete();
    break;
  case 6: // write, finalize, write, close without needed second finalize
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortyone);
    writer->finalize();
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortytwo);
    writer->close_incomplete();
    break;
  case 7: // as 6 but with a tiny file that had no lowres anyway.
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortyone);
    writer->finalize();
    writer->writeconst(size3i_t{0,0,0}, writer->size(), &fortytwo);
    writer->close_incomplete();
    break;
  default:
    TEST_CHECK_(false, "unrecognized testcase %d", mode);
    break;
Paal Kvamme's avatar
Paal Kvamme committed
677
678
679
680
  }
  writer.reset();
  std::shared_ptr<OpenZGY::IZgyReader> reader =
    OpenZGY::IZgyReader::open(lad.name());
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
  SampleStatistics stat = reader->statistics();
  SampleHistogram hist = reader->histogram();
  float first{0};
  reader->read(size3i_t{0,0,0}, size3i_t{1,1,1}, &first, 0);
  // Testing the #7 corner case in particular.
  TEST_CHECK_(first == 42, "first expect 42 got %g", first);
  switch (mode) {
  case 1:
  case 2:
  case 3:
  case 4: // Complete file ought to have been created.
    {
      TEST_CHECK(reader->nlods() == 2);
      std::pair<bool,double> constval =
        reader->readconst(size3i_t{0,0,0}, size3i_t{64,64,64}, 1, true);
      TEST_CHECK(constval.first);
      TEST_CHECK(constval.second == 42);
      TEST_CHECK(stat.cnt == 128*128*128LL);
      TEST_CHECK(stat.sum == 128*128*128*42.0);
      TEST_CHECK(stat.ssq == 128*128*128*42.0*42.0);
      TEST_CHECK(stat.min == 42.0);
      TEST_CHECK(stat.max == 42.0);
      TEST_CHECK(hist.samplecount == 128*128*128LL);
      //FAILS! TEST_CHECK_(hist.minvalue == 42, "minvalue expect 42 got %lg", hist.minvalue);
      TEST_CHECK_(hist.maxvalue == 42, "maxvalue expect 42 got %lg", hist.maxvalue);
    }
    break;
  case 5:
  case 6:
  case 7: // Lowres data, histogram, statistics not available.
    {
      TEST_CHECK(reader->nlods() == 1);
      must_throw("outside the valid range", [&](){
        reader->readconst(size3i_t{0,0,0}, size3i_t{2,2,2}, 1, true);
      });
      TEST_CHECK(stat.cnt == 0);
      TEST_CHECK(stat.sum == 0);
      TEST_CHECK(stat.ssq == 0);
719
720
      TEST_CHECK(stat.min == std::numeric_limits<double>::infinity());
      TEST_CHECK(stat.max == -std::numeric_limits<double>::infinity());
721
722
723
724
725
726
727
728
729
      TEST_CHECK(hist.samplecount == 0);
      TEST_CHECK_(hist.minvalue == 42, "minvalue expect 42 got %lg", hist.minvalue);
      TEST_CHECK_(hist.maxvalue == 42, "maxvalue expect 42 got %lg", hist.maxvalue);
    }
    break;
  default:
    TEST_CHECK_(false, "unrecognized testcase %d", mode);
    break;
  }
Paal Kvamme's avatar
Paal Kvamme committed
730
731
732
733
  reader->close();
  reader.reset();
}

734
template<int MODE>
Paal Kvamme's avatar
Paal Kvamme committed
735
static void
736
test_finalize()
Paal Kvamme's avatar
Paal Kvamme committed
737
{
738
  do_test_finalize(MODE);
Paal Kvamme's avatar
Paal Kvamme committed
739
740
}

Paal Kvamme's avatar
Paal Kvamme committed
741
#ifdef HAVE_SD
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
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
787
788
789
790
791
792

/**
 * Meant to be wrapped in a functor and uses as the token callback
 * in a IOContext.
 */
class SDTokenUpdater
{
  bool alive_;
  int count_;
  std::string token_;
  mutable std::mutex mutex_;
public:
  explicit SDTokenUpdater(const std::string& token)
    : alive_(true)
    , count_(0)
    , token_(token)
    , mutex_()
  {
  }
  SDTokenUpdater(const SDTokenUpdater&) = delete;
  SDTokenUpdater& operator=(const SDTokenUpdater&) = delete;
  std::string operator()() {
    std::lock_guard<std::mutex> lk(mutex_);
    //if (verbose())
    //  std::cout << "Fetching token, alive " << alive_ << std::endl;
    if (!alive_) {
      // Possibly invoked from a static destructor, so use a fairly
      // basic way of logging the message.
      const char *msg = "FATAL ERROR: Token callback invoked after destruction\n";
      fwrite(msg, 1, strlen(msg), stderr);
      abort();
    }
    ++count_;
    return token_;
  }
  int clearcount() {
    std::lock_guard<std::mutex> lk(mutex_);
    int result = count_;
    count_ = 0;
    return result;
  }
  void update(const std::string& token) {
    std::lock_guard<std::mutex> lk(mutex_);
    token_ = token;
  }
  void die() {
    std::lock_guard<std::mutex> lk(mutex_);
    alive_ = false;
  }
};

793
static bool
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
read_first_sample(const std::shared_ptr<OpenZGY::IZgyReader>& reader,
                  bool expect_ok,
                  const std::string& message)
{
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size{1,1,1};
  float bulk[1]{0};
  bool ok = false;

  if (verbose())
    std::cout << message << " is being tested." << std::endl;
  try {
    reader->read(orig, size, &bulk[0], 0);
    if (!expect_ok)
      std::cout << message << " ERROR, should not have worked."
                << std::endl;
    else if (std::abs(bulk[0]-0.0039) > 0.001)
      std::cout << message << " FAILED with wrong sample value "
                << bulk[0] << std::endl;
    else
      ok = true;
  }
  catch (const std::exception& ex) {
    if (expect_ok) {
      std::cout << message << " FAILED with: " << ex.what() << std::endl;
      ok = false;
    }
    else {
      ok = true;
      if (verbose())
        std::cout << "Got expected: " << ex.what() << std::endl;
    }
  }
  return ok;
}

830
static std::string
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
cloud_synt2_name()
{
  std::string testfolder = InternalZGY::Environment::getStringEnv("OPENZGY_SDTESTDATA", "sd://sntc/testdata");
  if (testfolder.back() != '/')
    testfolder += "/";
  return testfolder + "Synt2.zgy";
}

/**
 * When using a token refresh callback, make sure it isn't invoked
 * at a point where we cannot be sure it is still valid.
 *
 * We might decide that the application is required to provide a
 * callback that stays valid. In that case this test is N/A.
 */
846
static void
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
906
907
908
909
910
911
912
913
914
915
test_tokencb_destroy()
{
  using InternalZGY::Environment;
  std::string token = Environment::getStringEnv("OPENZGY_TOKEN");
  auto callback = std::make_shared<SDTokenUpdater>(token);
  std::function<std::string()> functor = [callback]() {return (*callback)();};
  auto context = SeismicStoreIOContext()
    .sdurl(Environment::getStringEnv("OPENZGY_SDURL"))
    .sdapikey(Environment::getStringEnv("OPENZGY_SDAPIKEY"))
    .sdtokencb(functor, "");
  std::shared_ptr<IZgyReader> reader =
    IZgyReader::open(cloud_synt2_name(), &context);

  // If the reader is destructed while still open then it is attempted
  // closed but it is forbidden to try to refresh the token because we
  // cannot know whether the callback is still valid. Especially if
  // triggered from a static destructor, although that might have its
  // own problems.
  (void)callback->clearcount();
  reader.reset();
  TEST_CHECK(callback->clearcount() == 0);

  // Also try to test the unlikely case that the callback is invoked
  // even later. The callback instance remains valid because the
  // functor captures a smart pointer reference to it. It is too late
  // to report that this particular test failed. Instead the call to
  // die() will make the test suite abort if the callback gets invoked
  // when it shouldn't have been.
  callback->die();
}

/**
 * \brief Check that the access token may be replaced on an open file.
 *
 * This is tricky. Manual steps are needed to run the full test.
 *
 * For example, even if the SAuth token expires in just a few minutes
 * it can be used to obtain a GCS token with a lifetime of (currently)
 * one hour. That token is cached which means the system won't even
 * try to use the new SAuth token for reading bulk until an hour has
 * elapsed. At least I think this is what is going on.
 *
 * There may be other places where a token is used past its expiry
 * date bacause it is too expensive to validate the token too often.
 *
 * So here is a possible test scenario:
 *
 *   \li Obtain a 24-hour token with $(echo $(sdutil auth idtoken))
 *   \li Open a file with that token and read a few bytes fron it.
 *   \li Sleep for 24 hours waiting for the token to expire.
 *   \li Sleep for 60 minutes to let GCS tokens expire.
 *   \li Sleep for 30 minutes or more to hopefully expire whatever is left.
 *   \li Continue reading from the file, verify you get an error.
 *   \li Obtain a new token with $(echo $(sdutil auth idtoken))
 *   \li (You may need to login if sdutil's 7-day(?) refresh token has expired).
 *   \li Store the new token in the SDManager.
 *   \li Continue reading and verify that it now works.
 *
 * Yes I realize it might be sufficient with max(24h,1h)+30min instead
 * of adding the numbers so I might shave off one hour. But if the
 * test fails it will take another day to run it again.
 *
 * If running a test for 26 hours is impractical then you can obtain
 * two sdutil tokens with 23 hours between them. You can then pass
 * both tokens to the test program and you will only need to sleep for
 * 2.5 hours. Or even less if you cut it fine with the interval
 * between tokens. This is what this test does; with the two tokens
 * in $OPENZGY_TOKEN (about to expire) and $OPENZGY_NEWTOKEN (fresh).
 */
916
static void
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
964
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
test_tokencb_normal()
{
  using InternalZGY::Environment;
  if (verbose())
    std::cout << std::endl;

  std::string oldtoken = Environment::getStringEnv("OPENZGY_TOKEN");
  auto callback = std::make_shared<SDTokenUpdater>("BOGUS.INVALID.TOKEN");
  std::function<std::string()> functor = [callback]() {return (*callback)();};
  auto context = SeismicStoreIOContext()
    .sdurl(Environment::getStringEnv("OPENZGY_SDURL"))
    .sdapikey(Environment::getStringEnv("OPENZGY_SDAPIKEY"))
    .sdtokencb(functor, "");
  callback->update(oldtoken);

  // Reading from a file should work just as normal;
  // the only difference is that the token is picked up
  // via the callback.
  std::shared_ptr<IZgyReader> reader =
    IZgyReader::open(cloud_synt2_name(), &context);

  TEST_CHECK(read_first_sample(reader, true, "Normal read"));
  TEST_CHECK(callback->clearcount() > 0);

  int sleeptime = Environment::getNumericEnv("OPENZGY_TEST_TOKENCB_SLEEP", -1);
  std::string newtoken = Environment::getStringEnv("OPENZGY_NEWTOKEN", "");
  if (sleeptime >= 0 && !newtoken.empty()) {
    // This test can literally take hours to run, so it can only be
    // run manually. Read some data, wait for token to expire, read
    // some more, get a new token. This check verifies that that both
    // OpenZGY and SDAPI can properly recover from an expired token. A
    // variant of this test could pre-emptively replace the expired
    // token before trying to read from it.
    std::cout << "Sleeping " << sleeptime
              << " minutes waiting for token to expire."
              << std::endl;
    std::this_thread::sleep_for (std::chrono::minutes(sleeptime));
    std::cout << "Awake!" << std::endl;
    TEST_CHECK(read_first_sample(reader, false, "Expired token"));
    callback->update(newtoken);
    TEST_CHECK(read_first_sample(reader, true, "Restored token"));
  }
  else if (sleeptime >= 0 && !oldtoken.empty()) {
    // Run a simpler version of the above that doesn't match a real
    // scenario and I can't really complain if it fails.
    // Caveat: SDManager might choose to keep its existing token if it
    // realizes that its existing token is still valid, or the new
    // token is bogus, or both. That is a completely reasonable
    // behavior. The test will set an expired or otherwise bad token
    // and make sure the read fails. Then set back the original and it
    // should work again. $OPENZGY_BADTOKEN should preferably be a
    // real token that has expired so it is closer to reality.
    // Experiments show that the test still needs to wait 60 minutes for
    // any cached GCS tokens to expire. See comment at start of function.
    if (verbose())
      std::cout << "Running the simplified tokencallback test." << std::endl;
    std::string badtoken = Environment::getStringEnv("OPENZGY_BADTOKEN", "BOGUS");
    callback->update(badtoken);
    if (sleeptime > 0) {
      std::cout << "Sleeping " << sleeptime
                << " minutes waiting for token to expire."
                << std::endl;
      std::this_thread::sleep_for (std::chrono::minutes(sleeptime));
      std::cout << "Awake!" << std::endl;
    }
    TEST_CHECK(read_first_sample(reader, false, "Bogus token"));
    TEST_CHECK(callback->clearcount() > 0);
    callback->update(oldtoken);
    TEST_CHECK(read_first_sample(reader, true, "Restored token"));
    TEST_CHECK(callback->clearcount() > 0);
  }

  // If there is something wrong with the token now then the close might
  // also throw. The actual message from this secondary error is not important.
  try {
    reader->close();
    TEST_CHECK(callback->clearcount() > 0);
  }
  catch (const std::exception& ex)
  {
    std::cout << "Exception closing the dataset: " << ex.what() << std::endl;
    TEST_CHECK(false && "failed in close");
  }