File: form_fetch_batcher_unittest.mm

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (425 lines) | stat: -rw-r--r-- 14,870 bytes parent folder | download | duplicates (5)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "components/autofill/ios/browser/form_fetch_batcher.h"

#import <memory>

#import "base/functional/bind.h"
#import "base/location.h"
#import "base/task/sequenced_task_runner.h"
#import "base/test/metrics/histogram_tester.h"
#import "base/test/task_environment.h"
#import "base/time/time.h"
#import "components/autofill/core/common/form_data.h"
#import "components/autofill/ios/browser/autofill_driver_ios_bridge.h"
#import "ios/web/public/js_messaging/web_frame.h"
#import "ios/web/public/test/fakes/fake_web_frame.h"
#import "testing/gtest/include/gtest/gtest.h"
#import "testing/platform_test.h"
#import "third_party/ocmock/OCMock/OCMock.h"
#import "third_party/ocmock/gtest_support.h"
#import "url/gurl.h"

namespace {

constexpr base::TimeDelta kBatchPeriodMs = base::Milliseconds(100);

// Generic form fetch completion callback that flips a bool to true when called.
void FormFetchCompletionCallback(
    bool* complete_ptr,
    std::optional<std::vector<autofill::FormData>> result) {
  *complete_ptr = true;
}

autofill::FormData MakeTestFormData(const std::u16string& name) {
  autofill::FormData form_data;
  form_data.set_name(name);
  return form_data;
}

}  // namespace

// AutofillDriverIosBridge used for testing. Provides a simple implementation of
// the methods that are used during testing, e.g. call the completion block upon
// calling -fetchFormsFiltered.
@interface TestAutofillDriverIOSBridge : NSObject <AutofillDriverIOSBridge>

// YES when the bridge does the form fetch asynchronously. Use RunUntilIdle() to
// run the async task.
@property(nonatomic, assign) BOOL async;

- (instancetype)init NS_UNAVAILABLE;

- (instancetype)initWithForms:(std::vector<autofill::FormData>)forms;

@end

@implementation TestAutofillDriverIOSBridge {
  std::vector<autofill::FormData> _forms;
}

- (instancetype)initWithForms:(std::vector<autofill::FormData>)forms {
  if ((self = [super init])) {
    _forms = std::move(forms);
  }
  return self;
}

- (void)fillData:(const std::vector<autofill::FormFieldData::FillData>&)form
         inFrame:(web::WebFrame*)frame {
}
- (void)fillSpecificFormField:(const autofill::FieldRendererId&)field
                    withValue:(const std::u16string)value
                      inFrame:(web::WebFrame*)frame {
}
- (void)handleParsedForms:
            (const std::vector<
                raw_ptr<autofill::FormStructure, VectorExperimental>>&)forms
                  inFrame:(web::WebFrame*)frame {
}
- (void)fillFormDataPredictions:
            (const std::vector<autofill::FormDataPredictions>&)forms
                        inFrame:(web::WebFrame*)frame {
}
- (void)scanFormsInWebState:(web::WebState*)webState
                    inFrame:(web::WebFrame*)webFrame {
}
- (void)notifyFormsSeen:(const std::vector<autofill::FormData>&)updatedForms
                inFrame:(web::WebFrame*)frame {
}
- (void)fetchFormsFiltered:(BOOL)filtered
                  withName:(const std::u16string&)formName
                   inFrame:(web::WebFrame*)frame
         completionHandler:(FormFetchCompletion)completionHandler {
  if (self.async) {
    auto asyncTask = base::BindOnce(
        [](FormFetchCompletion completion,
           std::vector<autofill::FormData>* result) {
          std::move(completion).Run(*result);
        },
        std::move(completionHandler), &_forms);
    // Push a task in the sequence.
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, std::move(asyncTask));
  } else {
    std::move(completionHandler).Run(_forms);
  }
}

@end

class FormFetchBatcherTest : public PlatformTest {
 protected:
  FormFetchBatcherTest()
      : test_bridge_([[TestAutofillDriverIOSBridge alloc]
            initWithForms:{MakeTestFormData(u"form1"),
                           MakeTestFormData(u"form2")}]),
        fake_web_frame_(web::FakeWebFrame::Create("main_frame_id", true)),
        batcher_(test_bridge_,
                 fake_web_frame_.get()->AsWeakPtr(),
                 kBatchPeriodMs) {}

  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  TestAutofillDriverIOSBridge* test_bridge_;
  std::unique_ptr<web::WebFrame> fake_web_frame_;
  autofill::FormFetchBatcher batcher_;
  base::HistogramTester histogram_tester_;
};

// Tests that the requests pushed to the scheduled batch are indeed completed
// once the batch is done. Tests with a batch of 2 requests, namely r1 and r2.
TEST_F(FormFetchBatcherTest, Batch) {
  // Completion trackers, true when the request is completed.
  bool r1_completed = false;
  bool r2_completed = false;

  // Verify that there is not any scheduled batch at this point, not until the
  // first request push.
  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  // Push request #1 (r1).
  {
    batcher_.PushRequest(
        base::BindOnce(&FormFetchCompletionCallback, &r1_completed));
  }

  // Verify that the batch was scheduled by the first push.
  ASSERT_EQ(1u, task_environment_.GetPendingMainThreadTaskCount());

  // Advance time but not enough to hit the schedule.
  base::TimeDelta remaining_time = base::Milliseconds(50);
  task_environment_.AdvanceClock(kBatchPeriodMs - remaining_time);

  EXPECT_FALSE(r1_completed);
  EXPECT_FALSE(r2_completed);

  // Verif that the batch is still scheduled as the delay wasn't reached.
  ASSERT_EQ(1u, task_environment_.GetPendingMainThreadTaskCount());

  // Push request #2 (r2).
  {
    batcher_.PushRequest(
        base::BindOnce(&FormFetchCompletionCallback, &r2_completed));
  }

  // Verify that the new request was included in the same batch as r1, where
  // there is still only one pending batch but now with 2 requests in it.
  ASSERT_EQ(1u, task_environment_.GetPendingMainThreadTaskCount());

  // Run the scheduled batch. Advance the time so the scheduled task is run.
  task_environment_.FastForwardBy(remaining_time + base::Milliseconds(10));

  // Verify that the batch is done and no other batch was rescheduled since
  // there are no more requests in the queue.
  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  // Verify that the batch of requests was completed by the batcher.
  EXPECT_TRUE(r1_completed);
  EXPECT_TRUE(r2_completed);

  histogram_tester_.ExpectUniqueSample(
      "Autofill.iOS.FormExtraction.ForScan.BatchSize",
      /*sample=*/2,
      /*expected_bucket_count=*/1);
}

// Tests that once a batch is done, another one can be scheduled.
TEST_F(FormFetchBatcherTest, Batch_Reschedule) {
  // Schedule an initial batch with request #1 in it (r1).

  // Completion tracker, true when the request is completed.
  auto r1_completed = std::make_unique<bool>(false);

  // Push request #1 (r1).
  {
    batcher_.PushRequest(
        base::BindOnce(&FormFetchCompletionCallback, r1_completed.get()));
  }

  // Advance time enough to trigger the first batch.
  task_environment_.FastForwardBy(kBatchPeriodMs + base::Milliseconds(50));

  EXPECT_TRUE(*r1_completed);
  *r1_completed = false;

  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  // Schedule a new batch with request 2 in it (r2).

  // Completion trackers, true when the request is completed.
  auto r2_completed = std::make_unique<bool>(false);

  // Push request #2 (r2).
  {
    batcher_.PushRequest(
        base::BindOnce(&FormFetchCompletionCallback, r2_completed.get()));
  }

  // Verify that a new batch was scheduled.
  ASSERT_EQ(1u, task_environment_.GetPendingMainThreadTaskCount());

  // Advance time enough to trigger the first batch.
  task_environment_.FastForwardBy(kBatchPeriodMs + base::Milliseconds(50));

  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  // Verify that the batch of requests was completed by the batcher.
  EXPECT_TRUE(*r2_completed);

  // As request #1 was already completed, it should not had been part of the
  // second batch.
  EXPECT_FALSE(*r1_completed);

  // Verify that each batch was recorded.
  histogram_tester_.ExpectUniqueSample(
      "Autofill.iOS.FormExtraction.ForScan.BatchSize",
      /*sample=*/1,
      /*expected_bucket_count=*/2);
}

// Tests that a batch isn't scheduled if not needed (i.e. there are requests to
// be completed).
TEST_F(FormFetchBatcherTest, Batch_OnlyWhenNeeded) {
  // Advance time enough to trigger the first batch if there was one needed.
  task_environment_.AdvanceClock(kBatchPeriodMs + base::Milliseconds(50));

  // Verify that no batch was scheduled.
  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  histogram_tester_.ExpectTotalCount(
      "Autofill.iOS.FormExtraction.ForScan.BatchSize",
      /*exprected_count=*/0);
}

// Tests that the pending batch task is canceled and the batch is run
// immediately when PushRequestAndRun() is used.
TEST_F(FormFetchBatcherTest, Batch_PushAndRun) {
  // Completion trackers, true when the request is completed.
  bool r1_completed = false;
  bool r2_completed = false;

  // Verify that there is not any scheduled batch at this point, not until the
  // first request push.
  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  // Push request #1 (r1).
  {
    batcher_.PushRequest(
        base::BindOnce(&FormFetchCompletionCallback, &r1_completed));
  }

  // Verify that the batch was scheduled by the first push.
  ASSERT_EQ(1u, task_environment_.GetPendingMainThreadTaskCount());

  ASSERT_FALSE(r1_completed);
  ASSERT_FALSE(r2_completed);

  // Push request #2 (r2) and run it immediately.
  {
    batcher_.PushRequestAndRun(
        base::BindOnce(&FormFetchCompletionCallback, &r2_completed));
  }

  // Verify that the scheduled batch was canceled.
  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  // Verify that the batch of requests was completed by the batcher.
  EXPECT_TRUE(r1_completed);
  EXPECT_TRUE(r2_completed);

  histogram_tester_.ExpectUniqueSample(
      "Autofill.iOS.FormExtraction.ForScan.BatchSize",
      /*sample=*/2,
      /*expected_bucket_count=*/1);
}

// Tests that tasks aren't scheduled as along as the form data isn't received
// for PushAndRun().
TEST_F(FormFetchBatcherTest, Batch_PushAndRun_AndRunAgain) {
  // Completion trackers, true when the request is completed.
  bool r1_completed = false;
  bool r2_completed = false;

  // Verify that there is not any scheduled batch at this point, not until the
  // first request push.
  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  // Switch the bridge to async so the fetch request for PushRequestAndRun()
  // isn't run immediately.
  test_bridge_.async = YES;

  // Push request #1 (r1) and run it immediately.
  {
    batcher_.PushRequestAndRun(
        base::BindOnce(&FormFetchCompletionCallback, &r1_completed));
  }

  // Verify that the fetch task was pushed in the sequence instead of run
  // immediately.
  ASSERT_EQ(1u, task_environment_.GetPendingMainThreadTaskCount());

  // Push request #2 (r2).
  {
    batcher_.PushRequest(
        base::BindOnce(&FormFetchCompletionCallback, &r2_completed));
  }

  // Verify that there is still only one task pending as PushRequest() should
  // not start another task.
  ASSERT_EQ(1u, task_environment_.GetPendingMainThreadTaskCount());

  // Run the task that was pushed.
  task_environment_.RunUntilIdle();

  // Both requests should have been batched together and run.
  EXPECT_TRUE(r1_completed);
  EXPECT_TRUE(r2_completed);

  // Verify that both fetch requests are counted even if only one batching task
  // was used.
  histogram_tester_.ExpectUniqueSample(
      "Autofill.iOS.FormExtraction.ForScan.BatchSize",
      /*sample=*/2,
      /*expected_bucket_count=*/1);
}

// Tests that the new requests that are added while completing the current
// batch of requests are pushed for later into the next batch. This test also
// ensures that doing that doesn't cause memory issues like what we've seen in
// http://crbug.com/379087890.
TEST_F(FormFetchBatcherTest, Batch_Completion_NewRequests) {
  // Schedule an initial batch with request #1 in it (r1).

  // Completion tracker, true when the request is completed.
  bool r1_completed = false;
  bool r2_completed = false;

  // Push request and run request #1 (r1). This request upon completion will
  // immediately push another request.
  {
    batcher_.PushRequest(base::BindOnce(
        [](autofill::FormFetchBatcher* batcher,
           FormFetchCompletion other_completion, bool* r1_completed,
           std::optional<std::vector<autofill::FormData>> result) {
          *r1_completed = true;
          batcher->PushRequest(std::move(other_completion));
        },
        &batcher_, base::BindOnce(&FormFetchCompletionCallback, &r2_completed),
        &r1_completed));
  }
  task_environment_.FastForwardBy(kBatchPeriodMs + base::Milliseconds(50));
  EXPECT_TRUE(r1_completed);
  r1_completed = false;

  // Verify that that request pushed by request #1 was enqueued for the next
  // batch.
  ASSERT_EQ(1u, task_environment_.GetPendingMainThreadTaskCount());

  // Advance time enough to trigger the following batch.
  task_environment_.FastForwardBy(kBatchPeriodMs + base::Milliseconds(50));

  ASSERT_EQ(0u, task_environment_.GetPendingMainThreadTaskCount());

  // Verify that the batch of requests was completed by the batcher.
  EXPECT_TRUE(r2_completed);

  // As request #1 was already completed, it should not had been part of the
  // second batch.
  EXPECT_FALSE(r1_completed);

  // Verify that each batch was recorded.
  histogram_tester_.ExpectUniqueSample(
      "Autofill.iOS.FormExtraction.ForScan.BatchSize",
      /*sample=*/1,
      /*expected_bucket_count=*/2);
}

// Tests fetch filtered requests.
TEST_F(FormFetchBatcherTest, Filtered) {
  // Hold the fetched forms for each request.
  std::vector<autofill::FormData> r1_forms;
  std::vector<autofill::FormData> r2_forms;

  auto callback = [](std::vector<autofill::FormData>* captured_forms,
                     std::optional<std::vector<autofill::FormData>> result) {
    CHECK(result);
    *captured_forms = *result;
  };

  // Push request #1 (r1).
  { batcher_.PushRequest(base::BindOnce(callback, &r1_forms), u"form1"); }
  // Push request #2 (r2).
  { batcher_.PushRequest(base::BindOnce(callback, &r2_forms), u"form2"); }

  task_environment_.FastForwardBy(kBatchPeriodMs + base::Milliseconds(50));

  // Verify that only the forms matching the name specified in the request are
  // returned for each request.
  EXPECT_THAT(r1_forms, testing::ElementsAre(testing::Property(
                            &autofill::FormData::name, u"form1")));
  EXPECT_THAT(r2_forms, testing::ElementsAre(testing::Property(
                            &autofill::FormData::name, u"form2")));
}