summaryrefslogtreecommitdiff
path: root/render-test/runner.cpp
blob: 5df167431f8e8ef269e558e785f0871dc591b5b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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
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
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
536
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
647
648
649
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
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
703
704
705
706
707
708
709
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
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
793
794
795
796
797
798
799
800
801
802
#include <mbgl/map/camera.hpp>
#include <mbgl/map/map_observer.hpp>
#include <mbgl/renderer/renderer.hpp>
#include <mbgl/style/conversion/filter.hpp>
#include <mbgl/style/conversion/layer.hpp>
#include <mbgl/style/conversion/light.hpp>
#include <mbgl/style/conversion/source.hpp>
#include <mbgl/style/image.hpp>
#include <mbgl/style/layer.hpp>
#include <mbgl/style/light.hpp>
#include <mbgl/style/rapidjson_conversion.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/util/chrono.hpp>
#include <mbgl/util/image.hpp>
#include <mbgl/util/io.hpp>
#include <mbgl/util/run_loop.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/util/timer.hpp>

#include <mapbox/pixelmatch.hpp>

#include <../expression-test/test_runner_common.hpp>
#include "allocation_index.hpp"
#include "metadata.hpp"
#include "parser.hpp"
#include "runner.hpp"

#include <algorithm>
#include <cassert>
#include <utility>
#include <sstream>

using namespace mbgl;

// static 
const std::string& TestRunner::getBasePath() {
    const static std::string result = std::string(TEST_RUNNER_ROOT_PATH).append("/mapbox-gl-js/test/integration");
    return result;
}

// static
const std::vector<std::string>& TestRunner::getPlatformExpectationsPaths() {
    // TODO: Populate from command line.
    const static std::vector<std::string> result {
        std::string(TEST_RUNNER_ROOT_PATH).append("/render-test/expected")
    };
    return result;
}

std::string simpleDiff(const Value& result, const Value& expected) {
    std::vector<std::string> resultTokens{tokenize(toJSON(result, 2, false))};
    std::vector<std::string> expectedTokens{tokenize(toJSON(expected, 2, false))};
    std::size_t maxLength = std::max(resultTokens.size(), expectedTokens.size());
    std::ostringstream diff;

    diff << "<pre>" << std::endl;
    const auto flush =
        [](const std::vector<std::string>& vec, std::size_t pos, std::ostringstream& out, std::string separator) {
            for (std::size_t j = pos; j < vec.size(); ++j) {
                out << separator << vec[j] << std::endl;
            }
        };

    for (std::size_t i = 0; i < maxLength; ++i) {
        if (resultTokens.size() <= i) {
            flush(expectedTokens, i, diff, "-");
            break;
        }

        if (expectedTokens.size() <= i) {
            flush(resultTokens, i, diff, "+");
            break;
        }

        if (!deepEqual(resultTokens[i], expectedTokens[i])) {
            diff << "<b>"
                 << "-" << expectedTokens[i] << "</b>" << std::endl;
            diff << "<b>"
                 << "+" << resultTokens[i] << "</b>" << std::endl;
        } else {
            diff << resultTokens[i] << std::endl;
        }
    }
    diff << "</pre>" << std::endl;
    return diff.str();
}

bool TestRunner::checkQueryTestResults(mbgl::PremultipliedImage&& actualImage,
                                       std::vector<mbgl::Feature>&& features,
                                       TestMetadata& metadata) {
    const std::string& base = metadata.paths.defaultExpectations();
    const std::vector<mbgl::filesystem::path>& expectations = metadata.paths.expectations;

    metadata.actual = mbgl::encodePNG(actualImage);

    if (actualImage.size.isEmpty()) {
        metadata.errorMessage = "Invalid size for actual image";
        return false;
    }

    metadata.actualJson = toJSON(features, 2, false);

    if (metadata.actualJson.empty()) {
        metadata.errorMessage = "Invalid size for actual JSON";
        return false;
    }

#if !TEST_READ_ONLY
    if (getenv("UPDATE_PLATFORM")) {
        mbgl::filesystem::create_directories(expectations.back());
        mbgl::util::write_file(expectations.back().string() + "/expected.json", metadata.actualJson);
        return true;
    } else if (getenv("UPDATE_DEFAULT")) {
        mbgl::util::write_file(base + "/expected.json", metadata.actualJson);
        return true;
    }

    mbgl::util::write_file(base + "/actual.json", metadata.actualJson);
#endif

    std::vector<std::string> expectedJsonPaths;
    mbgl::filesystem::path expectedMetricsPath;
    for (auto rit = expectations.rbegin(); rit != expectations.rend(); ++rit) {
        if (mbgl::filesystem::exists(*rit)) {
            expectedJsonPaths = readExpectedJSONEntries(*rit);
            if (!expectedJsonPaths.empty()) break;
        }
    }

    if (expectedJsonPaths.empty()) {
        metadata.errorMessage = "Failed to find expectations for: " + metadata.paths.stylePath.string();
        return false;
    }

    for (const auto& entry : expectedJsonPaths) {
        auto maybeExpectedJson = readJson(entry);
        if (maybeExpectedJson.is<mbgl::JSDocument>()) {
            auto& expected = maybeExpectedJson.get<mbgl::JSDocument>();

            mbgl::JSDocument actual;
            actual.Parse<0>(metadata.actualJson);
            if (actual.HasParseError()) {
                metadata.errorMessage = "Error parsing actual JSON for: " + metadata.paths.stylePath.string();
                return false;
            }

            auto actualVal = mapbox::geojson::convert<mapbox::geojson::value>(actual);
            auto expectedVal = mapbox::geojson::convert<mapbox::geojson::value>(expected);
            bool equal = deepEqual(actualVal, expectedVal);

            metadata.difference = !equal;
            if (equal) {
                metadata.diff = "Match";
            } else {
                metadata.diff = simpleDiff(actualVal, expectedVal);
            }
        } else {
            metadata.errorMessage = "Failed to load expected JSON " + entry;
            return false;
        }
    }

    return true;
}

bool TestRunner::checkRenderTestResults(mbgl::PremultipliedImage&& actualImage, TestMetadata& metadata) {
    const std::string& base = metadata.paths.defaultExpectations();
    const std::vector<mbgl::filesystem::path>& expectations = metadata.paths.expectations;

    metadata.actual = mbgl::encodePNG(actualImage);

    if (actualImage.size.isEmpty()) {
        metadata.errorMessage = "Invalid size for actual image";
        return false;
    }

#if !TEST_READ_ONLY
    if (getenv("UPDATE_PLATFORM")) {
        mbgl::filesystem::create_directories(expectations.back());
        mbgl::util::write_file(expectations.back().string() + "/expected.png", mbgl::encodePNG(actualImage));
        return true;
    } else if (getenv("UPDATE_DEFAULT")) {
        mbgl::util::write_file(base + "/expected.png", mbgl::encodePNG(actualImage));
        return true;
    } else if (getenv("UPDATE_METRICS")) {
        if (!metadata.metrics.isEmpty()) {
            mbgl::filesystem::create_directories(expectations.back());
            mbgl::util::write_file(expectations.back().string() + "/metrics.json", serializeMetrics(metadata.metrics));
            return true;
        }
    }

    mbgl::util::write_file(base + "/actual.png", metadata.actual);
#endif

    mbgl::PremultipliedImage expectedImage { actualImage.size };
    mbgl::PremultipliedImage imageDiff { actualImage.size };

    double pixels = 0.0;
    std::vector<std::string> expectedImagesPaths;
    mbgl::filesystem::path expectedMetricsPath;
    for (auto rit = expectations.rbegin(); rit!= expectations.rend(); ++rit) {
        if (mbgl::filesystem::exists(*rit)) {
            if (metadata.expectedMetrics.isEmpty()) {
                mbgl::filesystem::path maybeExpectedMetricsPath{ *rit };
                maybeExpectedMetricsPath.replace_filename("metrics.json");
                metadata.expectedMetrics = readExpectedMetrics(maybeExpectedMetricsPath);
            }
            expectedImagesPaths = readExpectedImageEntries(*rit);
            if (!expectedImagesPaths.empty()) break;
        }
    }

    if (expectedImagesPaths.empty()) {
        metadata.errorMessage = "Failed to find expectations for: " + metadata.paths.stylePath.string();
        return false;
    }
    
    for (const auto& entry: expectedImagesPaths) {
        mbgl::optional<std::string> maybeExpectedImage = mbgl::util::readFile(entry);
        if (!maybeExpectedImage) {
            metadata.errorMessage = "Failed to load expected image " + entry;
            return false;
        }

        metadata.expected = *maybeExpectedImage;

        expectedImage = mbgl::decodeImage(*maybeExpectedImage);

        pixels = // implicitly converting from uint64_t
            mapbox::pixelmatch(actualImage.data.get(), expectedImage.data.get(), expectedImage.size.width,
                               expectedImage.size.height, imageDiff.data.get(), 0.1285); // Defined in GL JS

        metadata.diff = mbgl::encodePNG(imageDiff);

#if !TEST_READ_ONLY
        mbgl::util::write_file(base + "/diff.png", metadata.diff);
#endif

        metadata.difference = pixels / expectedImage.size.area();
        if (metadata.difference <= metadata.allowed) {
            break;
        }
    }
    // Check memory metrics.
    for (const auto& expected : metadata.expectedMetrics.memory) {
        auto actual = metadata.metrics.memory.find(expected.first);
        if (actual == metadata.metrics.memory.end()) {
            metadata.errorMessage = "Failed to find memory probe: " + expected.first;
            return false;
        }
        if (actual->second.peak > expected.second.peak) {
            std::stringstream ss;
            ss << "Allocated memory peak size at probe \"" << expected.first << "\" is "
               << actual->second.peak << " bytes, expected is " << expected.second.peak << " bytes.";

            metadata.errorMessage = ss.str();
            return false;
        }

        if (actual->second.allocations > expected.second.allocations) {
            std::stringstream ss;
            ss << "Number of allocations at probe \"" << expected.first << "\" is "
               << actual->second.allocations << ", expected is " << expected.second.allocations << ".";

            metadata.errorMessage = ss.str();
            return false;
        }
    }

    return true;
}

bool TestRunner::runOperations(const std::string& key, TestMetadata& metadata) {
    if (!metadata.document.HasMember("metadata") ||
        !metadata.document["metadata"].HasMember("test") ||
        !metadata.document["metadata"]["test"].HasMember("operations")) {
        return true;
    }

    assert(metadata.document["metadata"]["test"]["operations"].IsArray());

    const auto& operationsArray = metadata.document["metadata"]["test"]["operations"].GetArray();
    if (operationsArray.Empty()) {
        return true;
    }

    const auto& operationIt = operationsArray.Begin();
    assert(operationIt->IsArray());

    const auto& operationArray = operationIt->GetArray();
    assert(operationArray.Size() >= 1u);

    auto& frontend = maps[key]->frontend;
    auto& map = maps[key]->map;

    static const std::string waitOp("wait");
    static const std::string sleepOp("sleep");
    static const std::string addImageOp("addImage");
    static const std::string updateImageOp("updateImage");
    static const std::string removeImageOp("removeImage");
    static const std::string setStyleOp("setStyle");
    static const std::string setCenterOp("setCenter");
    static const std::string setZoomOp("setZoom");
    static const std::string setBearingOp("setBearing");
    static const std::string setPitchOp("setPitch");
    static const std::string setFilterOp("setFilter");
    static const std::string setLayerZoomRangeOp("setLayerZoomRange");
    static const std::string setLightOp("setLight");
    static const std::string addLayerOp("addLayer");
    static const std::string removeLayerOp("removeLayer");
    static const std::string addSourceOp("addSource");
    static const std::string removeSourceOp("removeSource");
    static const std::string setPaintPropertyOp("setPaintProperty");
    static const std::string setLayoutPropertyOp("setLayoutProperty");
    static const std::string memoryProbeOp("probeMemory");
    static const std::string memoryProbeStartOp("probeMemoryStart");
    static const std::string memoryProbeEndOp("probeMemoryEnd");
    static const std::string setFeatureStateOp("setFeatureState");
    static const std::string getFeatureStateOp("getFeatureState");
    static const std::string removeFeatureStateOp("removeFeatureState");

    // wait
    if (operationArray[0].GetString() == waitOp) {
        try {
            frontend.render(map);
        } catch (const std::exception&) {
            return false;
        }
    // sleep
    } else if (operationArray[0].GetString() == sleepOp) {
        mbgl::util::Timer sleepTimer;
        bool sleeping = true;

        mbgl::Duration duration = mbgl::Seconds(3);
        if (operationArray.Size() >= 2u) {
            duration = mbgl::Milliseconds(operationArray[1].GetUint());
        }

        sleepTimer.start(duration, mbgl::Duration::zero(), [&]() {
            sleeping = false;
        });

        while (sleeping) {
            mbgl::util::RunLoop::Get()->runOnce();
        }

    // addImage | updateImage
    } else if (operationArray[0].GetString() == addImageOp || operationArray[0].GetString() == updateImageOp) {
        assert(operationArray.Size() >= 3u);

        float pixelRatio = 1.0f;
        bool sdf = false;

        if (operationArray.Size() == 4u) {
            assert(operationArray[3].IsObject());
            const auto& imageOptions = operationArray[3].GetObject();
            if (imageOptions.HasMember("pixelRatio")) {
                pixelRatio = imageOptions["pixelRatio"].GetFloat();
            }
            if (imageOptions.HasMember("sdf")) {
                sdf = imageOptions["sdf"].GetBool();
            }
        }

        std::string imageName = operationArray[1].GetString();
        imageName.erase(std::remove(imageName.begin(), imageName.end(), '"'), imageName.end());

        std::string imagePath = operationArray[2].GetString();
        imagePath.erase(std::remove(imagePath.begin(), imagePath.end(), '"'), imagePath.end());

        const mbgl::filesystem::path filePath(std::string(TEST_RUNNER_ROOT_PATH) + "/mapbox-gl-js/test/integration/" + imagePath);

        mbgl::optional<std::string> maybeImage = mbgl::util::readFile(filePath.string());
        if (!maybeImage) {
            metadata.errorMessage = std::string("Failed to load expected image ") + filePath.string();
            return false;
        }

        map.getStyle().addImage(std::make_unique<mbgl::style::Image>(imageName, mbgl::decodeImage(*maybeImage), pixelRatio, sdf));

    // removeImage
    } else if (operationArray[0].GetString() == removeImageOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsString());

        const std::string imageName { operationArray[1].GetString(), operationArray[1].GetStringLength() };
        map.getStyle().removeImage(imageName);

    // setStyle
    } else if (operationArray[0].GetString() == setStyleOp) {
        assert(operationArray.Size() >= 2u);
        if (operationArray[1].IsString()) {
            std::string stylePath = localizeURL(operationArray[1].GetString());
            auto maybeStyle = readJson(stylePath);
            if (maybeStyle.is<mbgl::JSDocument>()) {
                auto& style = maybeStyle.get<mbgl::JSDocument>();
                localizeStyleURLs((mbgl::JSValue&)style, style);
                map.getStyle().loadJSON(serializeJsonValue(style));
            }
        } else {
            localizeStyleURLs(operationArray[1], metadata.document);
            map.getStyle().loadJSON(serializeJsonValue(operationArray[1]));
        }

    // setCenter
    } else if (operationArray[0].GetString() == setCenterOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsArray());

        const auto& centerArray = operationArray[1].GetArray();
        assert(centerArray.Size() == 2u);

        map.jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng(centerArray[1].GetDouble(), centerArray[0].GetDouble())));

    // setZoom
    } else if (operationArray[0].GetString() == setZoomOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsNumber());
        map.jumpTo(mbgl::CameraOptions().withZoom(operationArray[1].GetDouble()));

    // setBearing
    } else if (operationArray[0].GetString() == setBearingOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsNumber());
        map.jumpTo(mbgl::CameraOptions().withBearing(operationArray[1].GetDouble()));

        // setPitch
    } else if (operationArray[0].GetString() == setPitchOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsNumber());
        map.jumpTo(mbgl::CameraOptions().withPitch(operationArray[1].GetDouble()));

        // setFilter
    } else if (operationArray[0].GetString() == setFilterOp) {
        assert(operationArray.Size() >= 3u);
        assert(operationArray[1].IsString());

        const std::string layerName { operationArray[1].GetString(), operationArray[1].GetStringLength() };

        mbgl::style::conversion::Error error;
        auto converted = mbgl::style::conversion::convert<mbgl::style::Filter>(operationArray[2], error);
        if (!converted) {
            metadata.errorMessage = std::string("Unable to convert filter: ")  + error.message;
            return false;
        } else {
            auto layer = map.getStyle().getLayer(layerName);
            if (!layer) {
                metadata.errorMessage = std::string("Layer not found: ")  + layerName;
                return false;
            } else {
                layer->setFilter(std::move(*converted));
            }
        }

    // setLayerZoomRange
    } else if (operationArray[0].GetString() == setLayerZoomRangeOp) {
        assert(operationArray.Size() >= 4u);
        assert(operationArray[1].IsString());
        assert(operationArray[2].IsNumber());
        assert(operationArray[3].IsNumber());

        const std::string layerName { operationArray[1].GetString(), operationArray[1].GetStringLength() };
        auto layer = map.getStyle().getLayer(layerName);
        if (!layer) {
            metadata.errorMessage = std::string("Layer not found: ")  + layerName;
            return false;
        } else {
            layer->setMinZoom(operationArray[2].GetFloat());
            layer->setMaxZoom(operationArray[3].GetFloat());
        }

    // setLight
    } else if (operationArray[0].GetString() == setLightOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsObject());

        mbgl::style::conversion::Error error;
        auto converted = mbgl::style::conversion::convert<mbgl::style::Light>(operationArray[1], error);
        if (!converted) {
            metadata.errorMessage = std::string("Unable to convert light: ")  + error.message;
            return false;
        } else {
            map.getStyle().setLight(std::make_unique<mbgl::style::Light>(std::move(*converted)));
        }

    // addLayer
    } else if (operationArray[0].GetString() == addLayerOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsObject());

        mbgl::style::conversion::Error error;
        auto converted = mbgl::style::conversion::convert<std::unique_ptr<mbgl::style::Layer>>(operationArray[1], error);
        if (!converted) {
            metadata.errorMessage = std::string("Unable to convert layer: ")  + error.message;
            return false;
        } else {
            map.getStyle().addLayer(std::move(*converted));
        }

    // removeLayer
    } else if (operationArray[0].GetString() == removeLayerOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsString());
        map.getStyle().removeLayer(operationArray[1].GetString());

    // addSource
    } else if (operationArray[0].GetString() == addSourceOp) {
        assert(operationArray.Size() >= 3u);
        assert(operationArray[1].IsString());
        assert(operationArray[2].IsObject());

        localizeSourceURLs(operationArray[2], metadata.document);

        mbgl::style::conversion::Error error;
        auto converted = mbgl::style::conversion::convert<std::unique_ptr<mbgl::style::Source>>(operationArray[2], error, operationArray[1].GetString());
        if (!converted) {
            metadata.errorMessage = std::string("Unable to convert source: ")  + error.message;
            return false;
        } else {
            map.getStyle().addSource(std::move(*converted));
        }

    // removeSource
    } else if (operationArray[0].GetString() == removeSourceOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsString());
        map.getStyle().removeSource(operationArray[1].GetString());

    // setPaintProperty
    } else if (operationArray[0].GetString() == setPaintPropertyOp) {
        assert(operationArray.Size() >= 4u);
        assert(operationArray[1].IsString());
        assert(operationArray[2].IsString());

        const std::string layerName { operationArray[1].GetString(), operationArray[1].GetStringLength() };
        const std::string propertyName { operationArray[2].GetString(), operationArray[2].GetStringLength() };

        auto layer = map.getStyle().getLayer(layerName);
        if (!layer) {
            metadata.errorMessage = std::string("Layer not found: ")  + layerName;
            return false;
        } else {
            const mbgl::JSValue* propertyValue = &operationArray[3];
            layer->setPaintProperty(propertyName, propertyValue);
        }

    // setLayoutProperty
    } else if (operationArray[0].GetString() == setLayoutPropertyOp) {
        assert(operationArray.Size() >= 4u);
        assert(operationArray[1].IsString());
        assert(operationArray[2].IsString());

        const std::string layerName { operationArray[1].GetString(), operationArray[1].GetStringLength() };
        const std::string propertyName { operationArray[2].GetString(), operationArray[2].GetStringLength() };

        auto layer = map.getStyle().getLayer(layerName);
        if (!layer) {
            metadata.errorMessage = std::string("Layer not found: ")  + layerName;
            return false;
        } else {
            const mbgl::JSValue* propertyValue = &operationArray[3];
            layer->setLayoutProperty(propertyName, propertyValue);
        }
    // probeMemoryStart
    } else if (operationArray[0].GetString() == memoryProbeStartOp) {
        assert(!AllocationIndex::isActive());
        AllocationIndex::setActive(true);
    // probeMemory
    } else if (operationArray[0].GetString() == memoryProbeOp) {
        assert(AllocationIndex::isActive());
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsString());
        std::string mark = std::string(operationArray[1].GetString(), operationArray[1].GetStringLength());

        metadata.metrics.memory.emplace(std::piecewise_construct,
                                        std::forward_as_tuple(std::move(mark)), 
                                        std::forward_as_tuple(AllocationIndex::getAllocatedSizePeak(), AllocationIndex::getAllocationsCount()));
    // probeMemoryEnd
    } else if (operationArray[0].GetString() == memoryProbeEndOp) {
        assert(AllocationIndex::isActive());
        AllocationIndex::setActive(false);
        AllocationIndex::reset();

        // setFeatureState
    } else if (operationArray[0].GetString() == setFeatureStateOp) {
        assert(operationArray.Size() >= 3u);
        assert(operationArray[1].IsObject());
        assert(operationArray[2].IsObject());

        using namespace mbgl;
        using namespace mbgl::style::conversion;

        std::string sourceID;
        mbgl::optional<std::string> sourceLayer;
        std::string featureID;
        std::string stateKey;
        Value stateValue;
        bool valueParsed = false;
        FeatureState parsedState;

        const auto& featureOptions = operationArray[1].GetObject();
        if (featureOptions.HasMember("source")) {
            sourceID = featureOptions["source"].GetString();
        }
        if (featureOptions.HasMember("sourceLayer")) {
            sourceLayer = {featureOptions["sourceLayer"].GetString()};
        }
        if (featureOptions.HasMember("id")) {
            if (featureOptions["id"].IsString()) {
                featureID = featureOptions["id"].GetString();
            } else if (featureOptions["id"].IsNumber()) {
                featureID = mbgl::util::toString(featureOptions["id"].GetUint64());
            }
        }
        const JSValue* state = &operationArray[2];

        const std::function<optional<Error>(const std::string&, const Convertible&)> convertFn =
            [&](const std::string& k, const Convertible& v) -> optional<Error> {
            optional<Value> value = toValue(v);
            if (value) {
                stateValue = std::move(*value);
                valueParsed = true;
            } else if (isArray(v)) {
                std::vector<Value> array;
                std::size_t length = arrayLength(v);
                array.reserve(length);
                for (size_t i = 0; i < length; ++i) {
                    optional<Value> arrayVal = toValue(arrayMember(v, i));
                    if (arrayVal) {
                        array.emplace_back(*arrayVal);
                    }
                }
                std::unordered_map<std::string, Value> result;
                result[k] = std::move(array);
                stateValue = std::move(result);
                valueParsed = true;
                return nullopt;

            } else if (isObject(v)) {
                eachMember(v, convertFn);
            }

            if (!valueParsed) {
                metadata.errorMessage = std::string("Could not get feature state value, state key: ") + k;
                return nullopt;
            }
            stateKey = k;
            parsedState[stateKey] = stateValue;
            return nullopt;
        };

        eachMember(state, convertFn);

        try {
            frontend.render(map);
        } catch (const std::exception&) {
            return false;
        }
        frontend.getRenderer()->setFeatureState(sourceID, sourceLayer, featureID, parsedState);

        // getFeatureState
    } else if (operationArray[0].GetString() == getFeatureStateOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsObject());

        std::string sourceID;
        mbgl::optional<std::string> sourceLayer;
        std::string featureID;

        const auto& featureOptions = operationArray[1].GetObject();
        if (featureOptions.HasMember("source")) {
            sourceID = featureOptions["source"].GetString();
        }
        if (featureOptions.HasMember("sourceLayer")) {
            sourceLayer = {featureOptions["sourceLayer"].GetString()};
        }
        if (featureOptions.HasMember("id")) {
            if (featureOptions["id"].IsString()) {
                featureID = featureOptions["id"].GetString();
            } else if (featureOptions["id"].IsNumber()) {
                featureID = mbgl::util::toString(featureOptions["id"].GetUint64());
            }
        }

        try {
            frontend.render(map);
        } catch (const std::exception&) {
            return false;
        }
        mbgl::FeatureState state;
        frontend.getRenderer()->getFeatureState(state, sourceID, sourceLayer, featureID);

        // removeFeatureState
    } else if (operationArray[0].GetString() == removeFeatureStateOp) {
        assert(operationArray.Size() >= 2u);
        assert(operationArray[1].IsObject());

        std::string sourceID;
        mbgl::optional<std::string> sourceLayer;
        std::string featureID;
        mbgl::optional<std::string> stateKey;

        const auto& featureOptions = operationArray[1].GetObject();
        if (featureOptions.HasMember("source")) {
            sourceID = featureOptions["source"].GetString();
        }
        if (featureOptions.HasMember("sourceLayer")) {
            sourceLayer = {featureOptions["sourceLayer"].GetString()};
        }
        if (featureOptions.HasMember("id")) {
            if (featureOptions["id"].IsString()) {
                featureID = featureOptions["id"].GetString();
            } else if (featureOptions["id"].IsNumber()) {
                featureID = mbgl::util::toString(featureOptions["id"].GetUint64());
            }
        }

        if (operationArray.Size() >= 3u) {
            assert(operationArray[2].IsString());
            stateKey = {operationArray[2].GetString()};
        }

        try {
            frontend.render(map);
        } catch (const std::exception&) {
            return false;
        }
        frontend.getRenderer()->removeFeatureState(sourceID, sourceLayer, featureID, stateKey);

    } else {
        metadata.errorMessage = std::string("Unsupported operation: ")  + operationArray[0].GetString();
        return false;
    }

    operationsArray.Erase(operationIt);
    return runOperations(key, metadata);
}

TestRunner::Impl::Impl(const TestMetadata& metadata)
    : frontend(metadata.size, metadata.pixelRatio),
      map(frontend,
          mbgl::MapObserver::nullObserver(),
          mbgl::MapOptions()
              .withMapMode(metadata.mapMode)
              .withSize(metadata.size)
              .withPixelRatio(metadata.pixelRatio)
              .withCrossSourceCollisions(metadata.crossSourceCollisions),
          mbgl::ResourceOptions().withCacheOnlyRequestsSupport(false)) {}

bool TestRunner::run(TestMetadata& metadata) {
    AllocationIndex::setActive(false);
    AllocationIndex::reset();
    std::string key = mbgl::util::toString(uint32_t(metadata.mapMode))
        + "/" + mbgl::util::toString(metadata.pixelRatio)
        + "/" + mbgl::util::toString(uint32_t(metadata.crossSourceCollisions));

    if (maps.find(key) == maps.end()) {
        maps[key] = std::make_unique<TestRunner::Impl>(metadata);
    }

    auto& frontend = maps[key]->frontend;
    auto& map = maps[key]->map;

    frontend.setSize(metadata.size);
    map.setSize(metadata.size);

    map.setProjectionMode(mbgl::ProjectionMode().withAxonometric(metadata.axonometric).withXSkew(metadata.xSkew).withYSkew(metadata.ySkew));
    map.setDebug(metadata.debug);

    map.getStyle().loadJSON(serializeJsonValue(metadata.document));
    map.jumpTo(map.getStyle().getDefaultCamera());

    if (!runOperations(key, metadata)) {
        return false;
    }

    mbgl::PremultipliedImage image;
    try {
        image = frontend.render(map);
    } catch (const std::exception&) {
        return false;
    }

    if (metadata.renderTest) {
        return checkRenderTestResults(std::move(image), metadata);
    } else {
        std::vector<mbgl::Feature> features;
        assert(metadata.document["metadata"]["test"]["queryGeometry"].IsArray());
        if (metadata.document["metadata"]["test"]["queryGeometry"][0].IsNumber() &&
            metadata.document["metadata"]["test"]["queryGeometry"][1].IsNumber()) {
            features = frontend.getRenderer()->queryRenderedFeatures(metadata.queryGeometry, metadata.queryOptions);
        } else {
            features = frontend.getRenderer()->queryRenderedFeatures(metadata.queryGeometryBox, metadata.queryOptions);
        }
        return checkQueryTestResults(std::move(image), std::move(features), metadata);
    }
}

void TestRunner::reset() {
    maps.clear();
}