blob: 377f344506a5fb0f196ad9531f58603974204d53 [file] [log] [blame]
Lukas Zilkaa6ddd4a2019-01-04 15:37:46 +01001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "actions/zlib-utils.h"
18
19#include <memory>
20
21#include "actions/actions_model_generated.h"
22#include "utils/zlib/zlib.h"
23#include "gmock/gmock.h"
24#include "gtest/gtest.h"
25
26namespace libtextclassifier3 {
27
28namespace {
29
30TEST(ZlibUtilsTest, CompressModel) {
31 ActionsModelT model;
32 constexpr char kTestPattern1[] = "this is a test pattern";
33 constexpr char kTestPattern2[] = "this is a second test pattern";
34 model.rules.reset(new RulesModelT);
35 model.rules->rule.emplace_back(new RulesModel_::RuleT);
36 model.rules->rule.back()->pattern = kTestPattern1;
37 model.rules->rule.emplace_back(new RulesModel_::RuleT);
38 model.rules->rule.back()->pattern = kTestPattern2;
39
40 // Compress the model.
41 EXPECT_TRUE(CompressActionsModel(&model));
42
43 // Sanity check that uncompressed field is removed.
44 EXPECT_TRUE(model.rules->rule[0]->pattern.empty());
45 EXPECT_TRUE(model.rules->rule[1]->pattern.empty());
46 // Pack and load the model.
47 flatbuffers::FlatBufferBuilder builder;
48 FinishActionsModelBuffer(builder, ActionsModel::Pack(builder, &model));
49 const ActionsModel* compressed_model = GetActionsModel(
50 reinterpret_cast<const char*>(builder.GetBufferPointer()));
51 ASSERT_TRUE(compressed_model != nullptr);
52
53 // Decompress the fields again and check that they match the original.
54 std::unique_ptr<ZlibDecompressor> decompressor = ZlibDecompressor::Instance();
55 ASSERT_TRUE(decompressor != nullptr);
56 std::string uncompressed_pattern;
57 EXPECT_TRUE(decompressor->MaybeDecompress(
58 compressed_model->rules()->rule()->Get(0)->compressed_pattern(),
59 &uncompressed_pattern));
60 EXPECT_EQ(uncompressed_pattern, kTestPattern1);
61 EXPECT_TRUE(decompressor->MaybeDecompress(
62 compressed_model->rules()->rule()->Get(1)->compressed_pattern(),
63 &uncompressed_pattern));
64 EXPECT_EQ(uncompressed_pattern, kTestPattern2);
65 EXPECT_TRUE(DecompressActionsModel(&model));
66 EXPECT_EQ(model.rules->rule[0]->pattern, kTestPattern1);
67 EXPECT_EQ(model.rules->rule[1]->pattern, kTestPattern2);
68}
69
70} // namespace
71
72} // namespace libtextclassifier3