summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/webshare/navigator_share_test.cc
blob: a0c8268afa46369e4b4c9a995efa5220c214863d (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
// 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 "third_party/blink/renderer/modules/webshare/navigator_share.h"

#include <memory>
#include <utility>
#include "services/service_manager/public/cpp/interface_provider.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/fileapi/file.h"
#include "third_party/blink/renderer/core/fileapi/file_property_bag.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/modules/webshare/share_data.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"

namespace blink {

using mojom::blink::SharedFile;
using mojom::blink::SharedFilePtr;
using mojom::blink::ShareService;

// A mock ShareService used to intercept calls to the mojo methods.
class MockShareService : public ShareService {
 public:
  MockShareService() : error_(mojom::ShareError::OK) {}
  ~MockShareService() override = default;

  void Bind(mojo::ScopedMessagePipeHandle handle) {
    receiver_.Bind(
        mojo::PendingReceiver<mojom::blink::ShareService>(std::move(handle)));
  }

  void set_error(mojom::ShareError value) { error_ = value; }

  const WTF::String& title() const { return title_; }
  const WTF::String& text() const { return text_; }
  const KURL& url() const { return url_; }
  const WTF::Vector<SharedFilePtr>& files() const { return files_; }
  mojom::ShareError error() const { return error_; }

 private:
  void Share(const WTF::String& title,
             const WTF::String& text,
             const KURL& url,
             WTF::Vector<SharedFilePtr> files,
             ShareCallback callback) override {
    title_ = title;
    text_ = text;
    url_ = url;

    files_.clear();
    files_.ReserveInitialCapacity(files.size());
    for (const auto& entry : files) {
      files_.push_back(entry->Clone());
    }

    std::move(callback).Run(error_);
  }

  mojo::Receiver<ShareService> receiver_{this};
  WTF::String title_;
  WTF::String text_;
  KURL url_;
  WTF::Vector<SharedFilePtr> files_;
  mojom::ShareError error_;
};

class NavigatorShareTest : public testing::Test {
 public:
  NavigatorShareTest()
      : holder_(std::make_unique<DummyPageHolder>()),
        handle_scope_(GetScriptState()->GetIsolate()),
        context_(GetScriptState()->GetContext()),
        context_scope_(context_) {}

  Document& GetDocument() { return holder_->GetDocument(); }

  LocalFrame& GetFrame() { return holder_->GetFrame(); }

  ScriptState* GetScriptState() const {
    return ToScriptStateForMainWorld(&holder_->GetFrame());
  }

  void Share(const ShareData& share_data) {
    std::unique_ptr<UserGestureIndicator> gesture =
        LocalFrame::NotifyUserActivation(&GetFrame(),
                                         UserGestureToken::kNewGesture);
    Navigator* navigator = GetFrame().DomWindow()->navigator();
    ScriptPromise promise =
        NavigatorShare::share(GetScriptState(), *navigator, &share_data);
    test::RunPendingTasks();
    EXPECT_EQ(mock_share_service_.error() == mojom::ShareError::OK
                  ? v8::Promise::kFulfilled
                  : v8::Promise::kRejected,
              promise.V8Value().As<v8::Promise>()->State());
  }

  MockShareService& mock_share_service() { return mock_share_service_; }

 protected:
  void SetUp() override {
    GetFrame().Loader().CommitNavigation(
        WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
                                                  KURL("https://example.com")),
        nullptr /* extra_data */);
    test::RunPendingTasks();

    service_manager::InterfaceProvider::TestApi test_api(
        &GetFrame().GetInterfaceProvider());
    test_api.SetBinderForName(
        ShareService::Name_,
        WTF::BindRepeating(&MockShareService::Bind,
                           WTF::Unretained(&mock_share_service_)));
  }

 public:
  MockShareService mock_share_service_;

  std::unique_ptr<DummyPageHolder> holder_;
  v8::HandleScope handle_scope_;
  v8::Local<v8::Context> context_;
  v8::Context::Scope context_scope_;
};

TEST_F(NavigatorShareTest, ShareText) {
  const String title = "Subject";
  const String message = "Body";
  const String url = "https://example.com/path?query#fragment";

  ShareData share_data;
  share_data.setTitle(title);
  share_data.setText(message);
  share_data.setURL(url);
  Share(share_data);

  EXPECT_EQ(mock_share_service().title(), title);
  EXPECT_EQ(mock_share_service().text(), message);
  EXPECT_EQ(mock_share_service().url(), KURL(url));
  EXPECT_EQ(mock_share_service().files().size(), 0U);
  EXPECT_TRUE(
      GetDocument().IsUseCounted(WebFeature::kWebShareSuccessfulWithoutFiles));
}

File* CreateSampleFile(ExecutionContext* context,
                       const String& file_name,
                       const String& content_type,
                       const String& file_contents) {
  HeapVector<ArrayBufferOrArrayBufferViewOrBlobOrUSVString> blob_parts;
  blob_parts.push_back(ArrayBufferOrArrayBufferViewOrBlobOrUSVString());
  blob_parts.back().SetUSVString(file_contents);

  FilePropertyBag file_property_bag;
  file_property_bag.setType(content_type);
  return File::Create(context, blob_parts, file_name, &file_property_bag);
}

TEST_F(NavigatorShareTest, ShareFile) {
  const String file_name = "chart.svg";
  const String content_type = "image/svg+xml";
  const String file_contents = "<svg></svg>";

  HeapVector<Member<File>> files;
  files.push_back(CreateSampleFile(ExecutionContext::From(GetScriptState()),
                                   file_name, content_type, file_contents));

  ShareData share_data;
  share_data.setFiles(files);
  Share(share_data);

  EXPECT_EQ(mock_share_service().files().size(), 1U);
  EXPECT_EQ(mock_share_service().files()[0]->name, file_name);
  EXPECT_EQ(mock_share_service().files()[0]->blob->GetType(), content_type);
  EXPECT_EQ(mock_share_service().files()[0]->blob->size(),
            file_contents.length());
  EXPECT_TRUE(GetDocument().IsUseCounted(
      WebFeature::kWebShareSuccessfulContainingFiles));
}

TEST_F(NavigatorShareTest, CancelShare) {
  const String title = "Subject";
  ShareData share_data;
  share_data.setTitle(title);

  mock_share_service().set_error(mojom::blink::ShareError::CANCELED);
  Share(share_data);
  EXPECT_TRUE(GetDocument().IsUseCounted(
      WebFeature::kWebShareUnsuccessfulWithoutFiles));
}

TEST_F(NavigatorShareTest, CancelShareWithFile) {
  const String file_name = "counts.csv";
  const String content_type = "text/csv";
  const String file_contents = "1,2,3";

  HeapVector<Member<File>> files;
  files.push_back(CreateSampleFile(ExecutionContext::From(GetScriptState()),
                                   file_name, content_type, file_contents));

  ShareData share_data;
  share_data.setFiles(files);

  mock_share_service().set_error(mojom::blink::ShareError::CANCELED);
  Share(share_data);
  EXPECT_TRUE(GetDocument().IsUseCounted(
      WebFeature::kWebShareUnsuccessfulContainingFiles));
}

}  // namespace blink