summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/nfc/nfc_proxy_test.cc
blob: 08f2b7c01f26f3be5c85bb53ecb7f732eb3fddd9 (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
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <map>
#include <memory>
#include <utility>

#include "base/run_loop.h"
#include "base/test/bind_test_util.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/modules/nfc/ndef_reader.h"
#include "third_party/blink/renderer/modules/nfc/ndef_scan_options.h"
#include "third_party/blink/renderer/modules/nfc/nfc_proxy.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"

namespace blink {
namespace {

using ::testing::_;
using ::testing::Invoke;

static const char kTestUrl[] = "https://w3c.github.io/web-nfc/";
static const char kFakeNfcTagSerialNumber[] = "c0:45:00:02";

MATCHER_P(MessageEquals, expected, "") {
  // Only check the first data array.
  if (arg.data.size() != 1)
    return false;

  const auto& received_data = arg.data[0]->data;
  if (received_data.size() != expected.size())
    return false;

  for (WTF::wtf_size_t i = 0; i < received_data.size(); i++) {
    if (received_data[i] != expected[i]) {
      return false;
    }
  }
  return true;
}

class MockNDEFReader : public NDEFReader {
 public:
  explicit MockNDEFReader(ExecutionContext* execution_context)
      : NDEFReader(execution_context) {}

  MOCK_METHOD2(OnReading,
               void(const String& serial_number,
                    const device::mojom::blink::NDEFMessage& message));
};

class FakeNfcService : public device::mojom::blink::NFC {
 public:
  FakeNfcService() : receiver_(this) {}
  ~FakeNfcService() override = default;

  void BindRequest(mojo::ScopedMessagePipeHandle handle) {
    DCHECK(!receiver_.is_bound());
    receiver_.Bind(
        mojo::PendingReceiver<device::mojom::blink::NFC>(std::move(handle)));
    receiver_.set_disconnect_handler(
        WTF::Bind(&FakeNfcService::OnConnectionError, WTF::Unretained(this)));
  }

  void OnConnectionError() {
    receiver_.reset();
    client_.reset();
  }

  void TriggerWatchEvent() {
    if (!client_ || !tag_message_)
      return;

    // Only match the watches using |url| in options.
    WTF::Vector<uint32_t> ids;
    for (auto& pair : watches_) {
      if (pair.second->id == tag_message_->url) {
        ids.push_back(pair.first);
      }
    }

    if (!ids.IsEmpty()) {
      client_->OnWatch(std::move(ids), kFakeNfcTagSerialNumber,
                       tag_message_.Clone());
    }
  }

  void set_tag_message(device::mojom::blink::NDEFMessagePtr message) {
    tag_message_ = std::move(message);
  }

  void set_watch_error(device::mojom::blink::NDEFErrorPtr error) {
    watch_error_ = std::move(error);
  }

  WTF::Vector<uint32_t> GetWatches() {
    WTF::Vector<uint32_t> ids;
    for (auto& pair : watches_) {
      ids.push_back(pair.first);
    }
    return ids;
  }

 private:
  // Override methods from device::mojom::blink::NFC.
  void SetClient(
      mojo::PendingRemote<device::mojom::blink::NFCClient> client) override {
    client_.Bind(std::move(client));
  }
  void Push(device::mojom::blink::NDEFMessagePtr message,
            device::mojom::blink::NDEFPushOptionsPtr options,
            PushCallback callback) override {
    set_tag_message(std::move(message));
    std::move(callback).Run(nullptr);
  }
  void CancelPush(device::mojom::blink::NDEFPushTarget target,
                  CancelPushCallback callback) override {
    std::move(callback).Run(nullptr);
  }
  void Watch(device::mojom::blink::NDEFScanOptionsPtr options,
             uint32_t id,
             WatchCallback callback) override {
    if (watch_error_) {
      std::move(callback).Run(watch_error_.Clone());
      return;
    }
    watches_.emplace(id, std::move(options));
    std::move(callback).Run(nullptr);
  }
  void CancelWatch(uint32_t id, CancelWatchCallback callback) override {
    if (watches_.erase(id) < 1) {
      std::move(callback).Run(device::mojom::blink::NDEFError::New(
          device::mojom::blink::NDEFErrorType::NOT_FOUND));
    } else {
      std::move(callback).Run(nullptr);
    }
  }
  void CancelAllWatches(CancelAllWatchesCallback callback) override {
    watches_.clear();
    std::move(callback).Run(nullptr);
  }
  void SuspendNFCOperations() override {}
  void ResumeNFCOperations() override {}

  device::mojom::blink::NDEFErrorPtr watch_error_;
  device::mojom::blink::NDEFMessagePtr tag_message_;
  mojo::Remote<device::mojom::blink::NFCClient> client_;
  std::map<uint32_t, device::mojom::blink::NDEFScanOptionsPtr> watches_;
  mojo::Receiver<device::mojom::blink::NFC> receiver_;
};

// Overrides requests for NFC mojo requests with FakeNfcService instances.
class NFCProxyTest : public PageTestBase {
 public:
  NFCProxyTest() { nfc_service_ = std::make_unique<FakeNfcService>(); }

  void SetUp() override {
    PageTestBase::SetUp(IntSize());
    GetDocument().GetBrowserInterfaceBroker().SetBinderForTesting(
        device::mojom::blink::NFC::Name_,
        WTF::BindRepeating(&FakeNfcService::BindRequest,
                           WTF::Unretained(nfc_service())));
  }

  void TearDown() override {
    GetDocument().GetBrowserInterfaceBroker().SetBinderForTesting(
        device::mojom::blink::NFC::Name_, {});
  }

  FakeNfcService* nfc_service() { return nfc_service_.get(); }

 private:
  std::unique_ptr<FakeNfcService> nfc_service_;
};

TEST_F(NFCProxyTest, SuccessfulPath) {
  auto& document = GetDocument();
  auto* nfc_proxy = NFCProxy::From(document);
  auto* scan_options = NDEFScanOptions::Create();
  scan_options->setId(kTestUrl);
  auto* reader = MakeGarbageCollected<MockNDEFReader>(&document);

  {
    base::RunLoop loop;
    nfc_proxy->StartReading(reader, scan_options,
                            base::BindLambdaForTesting(
                                [&](device::mojom::blink::NDEFErrorPtr error) {
                                  EXPECT_TRUE(error.is_null());
                                  loop.Quit();
                                }));
    EXPECT_TRUE(nfc_proxy->IsReading(reader));
    loop.Run();
    EXPECT_EQ(nfc_service()->GetWatches().size(), 1u);
  }

  // Construct a NDEFMessagePtr
  auto message = device::mojom::blink::NDEFMessage::New();
  message->url = kTestUrl;
  auto record = device::mojom::blink::NDEFRecord::New();
  WTF::Vector<uint8_t> record_data(
      {0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10});
  record->record_type = "mime";
  record->data = WTF::Vector<uint8_t>(record_data);
  message->data.push_back(std::move(record));

  {
    base::RunLoop loop;
    EXPECT_CALL(*reader, OnReading(String(kFakeNfcTagSerialNumber),
                                   MessageEquals(record_data)))
        .WillOnce(Invoke([&](const String& serial_number,
                             const device::mojom::blink::NDEFMessage& message) {
          loop.Quit();
        }));

    nfc_proxy->Push(std::move(message), /*options=*/nullptr,
                    base::BindLambdaForTesting(
                        [&](device::mojom::blink::NDEFErrorPtr error) {
                          nfc_service()->TriggerWatchEvent();
                        }));
    loop.Run();
  }

  nfc_proxy->StopReading(reader);
  EXPECT_FALSE(nfc_proxy->IsReading(reader));
  test::RunPendingTasks();
  EXPECT_EQ(nfc_service()->GetWatches().size(), 0u);
}

TEST_F(NFCProxyTest, ErrorPath) {
  auto& document = GetDocument();
  auto* nfc_proxy = NFCProxy::From(document);
  auto* scan_options = NDEFScanOptions::Create();
  scan_options->setId(kTestUrl);
  auto* reader = MakeGarbageCollected<MockNDEFReader>(&document);

  // Make the fake NFC service return an error for the incoming watch request.
  nfc_service()->set_watch_error(device::mojom::blink::NDEFError::New(
      device::mojom::blink::NDEFErrorType::NOT_READABLE));
  base::RunLoop loop;
  nfc_proxy->StartReading(
      reader, scan_options,
      base::BindLambdaForTesting([&](device::mojom::blink::NDEFErrorPtr error) {
        // We got the error prepared before.
        EXPECT_FALSE(error.is_null());
        EXPECT_EQ(error->error_type,
                  device::mojom::blink::NDEFErrorType::NOT_READABLE);
        loop.Quit();
      }));
  EXPECT_TRUE(nfc_proxy->IsReading(reader));
  loop.Run();

  EXPECT_EQ(nfc_service()->GetWatches().size(), 0u);
  EXPECT_FALSE(nfc_proxy->IsReading(reader));
}

}  // namespace
}  // namespace blink