File: integration_tests_helper.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (695 lines) | stat: -rw-r--r-- 28,831 bytes parent folder | download | duplicates (3)
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
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <utility>

#include "base/at_exit.h"
#include "base/check.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/task_environment.h"
#include "base/test/test_suite.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "base/version.h"
#include "build/build_config.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/updater/app/app.h"
#include "chrome/updater/constants.h"
#include "chrome/updater/external_constants.h"
#include "chrome/updater/ipc/ipc_support.h"
#include "chrome/updater/test/integration_tests_impl.h"
#include "chrome/updater/test/unit_test_util.h"
#include "chrome/updater/updater_scope.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_com_initializer.h"
#include "chrome/updater/util/win_util.h"
#endif

namespace updater::test {
namespace {

using ::testing::EmptyTestEventListener;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::UnitTest;

constexpr int kSuccess = 0;
constexpr int kUnknownSwitch = 101;
constexpr int kBadCommand = 102;

base::Value ValueFromString(const std::string& values) {
  std::optional<base::Value> results_value = base::JSONReader::Read(values);
  EXPECT_TRUE(results_value) << values;
  return results_value->Clone();
}

template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(const std::string&, Args...)> callback) {
  return base::BindLambdaForTesting([=](Args... args) {
    const base::CommandLine* command_line =
        base::CommandLine::ForCurrentProcess();
    if (command_line->HasSwitch(flag)) {
      return callback.Run(command_line->GetSwitchValueUTF8(flag),
                          std::move(args)...);
    }
    LOG(ERROR) << "Missing switch: " << flag;
    return false;
  });
}

// Overload for bool switches, represented by literals "false" and "true".
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(bool, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        if (flag == "false" || flag == "true") {
          return callback.Run(flag == "true", std::move(args)...);
        }
        return false;
      }));
}

// Overload for int switches.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(int, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        int flag_int = -1;
        if (base::StringToInt(flag, &flag_int)) {
          return callback.Run(flag_int, std::move(args)...);
        }
        return false;
      }));
}

// Overload for GURL switches.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(const GURL&, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        return callback.Run(GURL(flag), std::move(args)...);
      }));
}

// Overload for FilePath switches.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(const base::FilePath&, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        return callback.Run(base::FilePath::FromUTF8Unsafe(flag),
                            std::move(args)...);
      }));
}

// Overload for Version switches.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(const base::Version&, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        return callback.Run(base::Version(flag), std::move(args)...);
      }));
}

// Overload for Time switches.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(base::Time, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        double flag_value;
        if (base::StringToDouble(flag, &flag_value)) {
          return callback.Run(
              base::Time::FromMillisecondsSinceUnixEpoch(flag_value),
              std::move(args)...);
        }
        return false;
      }));
}

// Overload for TimeDelta switches.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(base::TimeDelta, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        int flag_value;
        if (base::StringToInt(flag, &flag_value)) {
          return callback.Run(base::Seconds(flag_value), std::move(args)...);
        }
        return false;
      }));
}

// Overload for base::Value::Dict switches.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(const base::Value::Dict&, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        return callback.Run(std::move(ValueFromString(flag).GetDict()),
                            std::move(args)...);
      }));
}

// Overload for base::Value::List switches.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(const base::Value::List&, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        return callback.Run(std::move(ValueFromString(flag).GetList()),
                            std::move(args)...);
      }));
}

// Overload for `AppBundleWebCreateMode` switches, represented by ints.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSwitch(
    const std::string& flag,
    base::RepeatingCallback<bool(AppBundleWebCreateMode, Args...)> callback) {
  return WithSwitch(
      flag,
      base::BindLambdaForTesting([=](const std::string& flag, Args... args) {
        int flag_app_bundle_web_create_mode = -1;
        if (base::StringToInt(flag, &flag_app_bundle_web_create_mode) &&
            flag_app_bundle_web_create_mode >=
                static_cast<int>(AppBundleWebCreateMode::kCreateApp) &&
            flag_app_bundle_web_create_mode <=
                static_cast<int>(AppBundleWebCreateMode::kCreateInstalledApp)) {
          return callback.Run(static_cast<AppBundleWebCreateMode>(
                                  flag_app_bundle_web_create_mode),
                              std::move(args)...);
        }
        return false;
      }));
}

template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithEventLoggingPermissionProviderSwitch(
    base::RepeatingCallback<bool(std::optional<EventLoggingPermissionProvider>,
                                 Args...)> callback) {
  return base::BindLambdaForTesting([=](Args... args) {
    const base::CommandLine* command_line =
        base::CommandLine::ForCurrentProcess();
    if (!command_line->HasSwitch("event_logging_permission_provider_app_id")) {
      LOG(ERROR) << "Missing switch: "
                 << "event_logging_permission_provider_app_id";
      return false;
    }

    EventLoggingPermissionProvider provider;
    provider.app_id = command_line->GetSwitchValueUTF8(
        "event_logging_permission_provider_app_id");

#if BUILDFLAG(IS_MAC)
    if (!command_line->HasSwitch(
            "event_logging_permission_provider_directory_name")) {
      LOG(ERROR) << "Missing switch: "
                 << "event_logging_permission_provider_directory_name";
      return false;
    }
    provider.directory_name = command_line->GetSwitchValueUTF8(
        "event_logging_permission_provider_directory_name");
#endif

    return callback.Run(std::move(provider), std::move(args)...);
  });
}

template <typename Arg, typename... RemainingArgs>
base::RepeatingCallback<bool(RemainingArgs...)> WithArg(
    Arg arg,
    base::RepeatingCallback<bool(Arg, RemainingArgs...)> callback) {
  return base::BindRepeating(callback, arg);
}

// Adapts the input callback to take a shutdown callback as the final parameter.
template <typename... Args>
base::RepeatingCallback<bool(Args..., base::OnceCallback<void(int)>)>
WithShutdown(base::RepeatingCallback<int(Args...)> callback) {
  return base::BindLambdaForTesting(
      [=](Args... args, base::OnceCallback<void(int)> shutdown) {
        std::move(shutdown).Run(callback.Run(args...));
        return true;
      });
}

// Short-named wrapper around BindOnce.
template <typename... Args, typename... ProvidedArgs>
base::RepeatingCallback<bool(Args..., base::OnceCallback<void(int)>)> Wrap(
    int (*func)(Args...),
    ProvidedArgs... provided_args) {
  return WithShutdown(base::BindRepeating(func, provided_args...));
}

// Overload of Wrap for functions that return void. (Returns kSuccess.)
template <typename... Args>
base::RepeatingCallback<bool(Args..., base::OnceCallback<void(int)>)> Wrap(
    void (*func)(Args...)) {
  return WithShutdown(base::BindLambdaForTesting([=](Args... args) {
    func(args...);
    return kSuccess;
  }));
}

// Helper to shorten lines below.
template <typename... Args>
base::RepeatingCallback<bool(Args...)> WithSystemScope(
    base::RepeatingCallback<bool(UpdaterScope, Args...)> callback) {
  return WithArg(UpdaterScope::kSystem, callback);
}

class AppTestHelper : public App {
 private:
  ~AppTestHelper() override = default;
  void FirstTaskRun() override;
};

void AppTestHelper::FirstTaskRun() {
  std::map<std::string,
           base::RepeatingCallback<bool(base::OnceCallback<void(int)>)>>
      commands = {
          // To add additional commands, first Wrap a pointer to the target
          // function (which should be declared in integration_tests_impl.h),
          // and then use the With* helper functions to provide its arguments.
          {"clean", WithSystemScope(Wrap(&Clean))},
          {"enter_test_mode",
           WithEventLoggingPermissionProviderSwitch(
               WithSwitch(
                   "ceca_connection_timeout",
                   WithSwitch(
                       "server_keep_alive_time",
                       WithSwitch(
                           "idle_timeout",
                           WithSwitch(
                                "event_logging_url",
                                WithSwitch(
                                    "app_logo_url",
                                    WithSwitch(
                                        "crash_upload_url",
                                        WithSwitch("update_url",
                                                   Wrap(&EnterTestMode)))))))))},  // NOLINT
          {"exit_test_mode", WithSystemScope(Wrap(&ExitTestMode))},
          {"set_dict_policies", WithSwitch("values", Wrap(&SetDictPolicies))},
          {"set_platform_policies",
           WithSwitch("values", Wrap(&SetPlatformPolicies))},
          {"set_machine_managed",
           WithSwitch("managed", Wrap(&SetMachineManaged))},
          {"fill_log", WithSystemScope(Wrap(&FillLog))},
          {"expect_log_rotated", WithSystemScope(Wrap(&ExpectLogRotated))},
          {"expect_registered",
           WithSwitch("app_id", WithSystemScope(Wrap(&ExpectRegistered)))},
          {"expect_not_registered",
           WithSwitch("app_id", WithSystemScope(Wrap(&ExpectNotRegistered)))},
          {"expect_app_tag",
           WithSwitch("tag", WithSwitch("app_id",
                                        WithSystemScope(Wrap(&ExpectAppTag))))},
          {"set_app_tag",
           WithSwitch("tag",
                      WithSwitch("app_id", WithSystemScope(Wrap(&SetAppTag))))},
          {"expect_app_version",
           WithSwitch(
               "app_version",
               WithSwitch("app_id", WithSystemScope(Wrap(&ExpectAppVersion))))},
          {"expect_candidate_uninstalled",
           WithSystemScope(Wrap(&ExpectCandidateUninstalled))},
          {"expect_clean", WithSystemScope(Wrap(&ExpectClean))},
          {"expect_installed", WithSystemScope(Wrap(&ExpectInstalled))},
#if BUILDFLAG(IS_WIN)
          {"expect_interfaces_registered",
           WithSystemScope(Wrap(&ExpectInterfacesRegistered))},
          {"expect_marshal_interface_succeeds",
           WithSystemScope(Wrap(&ExpectMarshalInterfaceSucceeds))},
          {"expect_legacy_update3web_succeeds",
           WithSwitch(
               "cancel_when_downloading",
               WithSwitch(
                   "expected_error_code",
                   WithSwitch(
                       "expected_final_state",
                       WithSwitch(
                           "app_bundle_web_create_mode",
                           WithSwitch(
                               "app_id",
                               WithSystemScope(
                                   Wrap(&ExpectLegacyUpdate3WebSucceeds)))))))},
          {"expect_legacy_process_launcher_succeeds",
           WithSystemScope(Wrap(&ExpectLegacyProcessLauncherSucceeds))},
          {"expect_legacy_app_command_web_succeeds",
           WithSwitch(
               "expected_exit_code",
               WithSwitch(
                   "parameters",
                   WithSwitch(
                       "command_id",
                       WithSwitch("app_id",
                                  WithSystemScope(Wrap(
                                      &ExpectLegacyAppCommandWebSucceeds))))))},
          {"expect_legacy_policy_status_succeeds",
           WithSwitch(
               "updater_version",
               WithSystemScope(Wrap(&ExpectLegacyPolicyStatusSucceeds)))},
          {"legacy_install_app",
           WithSwitch(
               "app_version",
               WithSwitch("app_id", WithSystemScope(Wrap(&LegacyInstallApp))))},
          {"run_uninstall_cmd_line",
           WithSystemScope(Wrap(&RunUninstallCmdLine))},
          {"run_handoff",
           WithSwitch("app_id", WithSystemScope(Wrap(&RunHandoff)))},
#endif  // BUILDFLAG(IS_WIN)
          {"expect_version_active",
           WithSwitch("updater_version",
                      WithSystemScope(Wrap(&ExpectVersionActive)))},
          {"expect_version_not_active",
           WithSwitch("updater_version",
                      WithSystemScope(Wrap(&ExpectVersionNotActive)))},
          {"install", WithSwitch("switches", WithSystemScope(Wrap(&Install)))},
          {"install_updater_and_app",
           WithSwitch(
               "updater_path",
               WithSwitch(
                   "additional_switches",
                   WithSwitch(
                       "expected_exit_code",
                       WithSwitch(
                           "wait_for_the_installer",
                           WithSwitch(
                               "expect_success",
                               WithSwitch(
                                   "verify_app_logo_loaded",
                                   WithSwitch(
                                       "always_launch_cmd",
                                       WithSwitch(
                                           "child_window_text_to_find",
                                           WithSwitch(
                                               "tag",
                                               WithSwitch(
                                                   "is_silent_install",
                                                   WithSwitch(
                                                       "app_id",
                                                       WithSystemScope(Wrap(
                                                           &InstallUpdaterAndApp)))))))))))))},  // NOLINT
          {"print_log", WithSystemScope(Wrap(&PrintLog))},
          {"run_wake",
           WithSwitch("version", WithSwitch("exit_code",
                                            WithSystemScope(Wrap(&RunWake))))},
          {"run_wake_all", WithSystemScope(Wrap(&RunWakeAll))},
          {"run_wake_active",
           WithSwitch("exit_code", WithSystemScope(Wrap(&RunWakeActive)))},
          {"run_crash_me", WithSystemScope(Wrap(&RunCrashMe))},
          {"run_server",
           WithSwitch("internal", WithSwitch("exit_code", WithSystemScope(Wrap(
                                                              &RunServer))))},
          {"update",
           WithSwitch("install_data_index",
                      (WithSwitch("app_id", WithSystemScope(Wrap(&Update)))))},
          {"register_app",
           WithSwitch("registration",
                      WithSystemScope(Wrap(&RegisterAppByValue)))},
          {"check_for_update",
           (WithSwitch("app_id", WithSystemScope(Wrap(&CheckForUpdate))))},
          {"expect_check_for_update_opposite_scope_fails",
           (WithSwitch("app_id",
                       WithSystemScope(
                           Wrap(&ExpectCheckForUpdateOppositeScopeFails))))},
          {"update_all", WithSystemScope(Wrap(&UpdateAll))},
          {"get_app_states", WithSwitch("expected_app_states",
                                        WithSystemScope(Wrap(&GetAppStates)))},
          {"delete_updater_directory",
           WithSystemScope(Wrap(&DeleteUpdaterDirectory))},
          {"delete_active_updater_executable",
           WithSystemScope(Wrap(&DeleteActiveUpdaterExecutable))},
          {"delete_file",
           (WithSwitch("path", WithSystemScope(Wrap(&DeleteFile))))},
          {"install_app",
           WithSwitch("app_version", WithSwitch("app_id", WithSystemScope(Wrap(
                                                              &InstallApp))))},
          {"install_app_via_service",
           WithSwitch("expected_final_values",
                      WithSwitch("app_id", WithSystemScope(
                                               Wrap(&InstallAppViaService))))},
          {"uninstall_app",
           WithSwitch("app_id", WithSystemScope(Wrap(&UninstallApp)))},
          {"set_existence_checker_path",
           WithSwitch("path",
                      (WithSwitch("app_id", WithSystemScope(Wrap(
                                                &SetExistenceCheckerPath)))))},
          {"setup_fake_updater_higher_version",
           WithSystemScope(Wrap(&SetupFakeUpdaterHigherVersion))},
          {"setup_fake_updater_lower_version",
           WithSystemScope(Wrap(&SetupFakeUpdaterLowerVersion))},
          {"setup_real_updater",
           WithSwitch("switches",
                      WithSwitch("updater_path",
                                 WithSystemScope(Wrap(&SetupRealUpdater))))},
          {"set_first_registration_counter",
           WithSwitch("value", WithSystemScope(Wrap(&SetServerStarts)))},
          {"stress_update_service",
           WithSystemScope(Wrap(&StressUpdateService))},
          {"uninstall", WithSystemScope(Wrap(&Uninstall))},
          {"call_service_update",
           WithSwitch(
               "same_version_update_allowed",
               WithSwitch("install_data_index",
                          WithSwitch("app_id", WithSystemScope(Wrap(
                                                   &CallServiceUpdate)))))},
          {"setup_fake_legacy_updater",
           WithSystemScope(Wrap(&SetupFakeLegacyUpdater))},
#if BUILDFLAG(IS_WIN)
          {"run_fake_legacy_updater",
           WithSystemScope(Wrap(&RunFakeLegacyUpdater))},
#endif  // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_MAC)
          {"privileged_helper_install",
           WithSystemScope(Wrap(&PrivilegedHelperInstall))},
          {"delete_legacy_updater",
           WithSystemScope(Wrap(&DeleteLegacyUpdater))},
          {"expect_prepare_to_run_bundle_success",
           WithSwitch("bundle_path", Wrap(&ExpectPrepareToRunBundleSuccess))},
#endif  // BUILDFLAG(IS_MAC)
          {"expect_legacy_updater_migrated",
           WithSystemScope(Wrap(&ExpectLegacyUpdaterMigrated))},
          {"run_recovery_component",
           WithSwitch("browser_version",
                      WithSwitch("app_id", WithSystemScope(
                                               Wrap(&RunRecoveryComponent))))},
          {"set_last_checked",
           WithSwitch("time", WithSystemScope(Wrap(&SetLastChecked)))},
          {"expect_last_checked", WithSystemScope(Wrap(&ExpectLastChecked))},
          {"expect_last_started", WithSystemScope(Wrap(&ExpectLastStarted))},
          {"run_offline_install",
           WithSwitch(
               "installer_error",
               WithSwitch("installer_result",
                          WithSwitch("silent",
                                     WithSwitch("legacy_install",
                                                WithSystemScope(Wrap(
                                                    &RunOfflineInstall))))))},
          {"run_offline_install_os_not_supported",
           WithSwitch(
               "language",
               WithSwitch("silent",
                          WithSwitch("legacy_install",
                                     WithSystemScope(Wrap(
                                         &RunOfflineInstallOsNotSupported)))))},
          {"run_mock_offline_meta_install",
           WithSwitch(
               "expect_success",
               WithSwitch(
                   "expected_exit_code",
                   WithSwitch(
                       "always_launch_cmd",
                       WithSwitch(
                           "installer_text",
                           WithSwitch(
                               "platform",
                               WithSwitch(
                                   "is_silent_install",
                                   WithSwitch(
                                       "arguments",
                                       WithSwitch(
                                           "installer_path",
                                           WithSwitch(
                                               "tag",
                                               WithSwitch(
                                                   "version",
                                                   WithSwitch(
                                                       "app_id",
                                                       WithSystemScope(Wrap(
                                                           &RunMockOfflineMetaInstall)))))))))))))},  // NOLINT
          {"dm_push_enrollment_token",
           WithSwitch("enrollment_token", Wrap(DMPushEnrollmentToken))},
          {"dm_deregister_device", WithSystemScope(Wrap(&DMDeregisterDevice))},
          {"dm_cleanup", WithSystemScope(Wrap(&DMCleanup))},
          {"install_enterprise_companion_app",
           Wrap(&InstallEnterpriseCompanionApp)},
          {"install_broken_enterprise_companion_app",
           Wrap(&InstallBrokenEnterpriseCompanionApp)},
          {"uninstall_broken_enterprise_companion_app",
           Wrap(&UninstallBrokenEnterpriseCompanionApp)},
          {"install_enterprise_companion_app_overrides",
           WithSwitch("external_overrides",
                      Wrap(&InstallEnterpriseCompanionAppOverrides))},
          {"expect_enterprise_companion_app_not_installed",
           Wrap(&ExpectEnterpriseCompanionAppNotInstalled)},
          {"uninstall_enterprise_companion_app",
           Wrap(&UninstallEnterpriseCompanionApp)},
          {"set_app_allows_usage_stats",
           WithSwitch(
               "allowed",
               WithSwitch(
                   "identifier",
                   WithSystemScope(Wrap(&SetAppAllowsUsageStats))))},
          {"clear_app_allows_usage_stats",
           WithSwitch(
               "identifier",
               WithSystemScope(Wrap(&ClearAppAllowsUsageStats)))},
      };

  const base::CommandLine* command_line =
      base::CommandLine::ForCurrentProcess();
  for (const auto& [command, callback] : commands) {
    if (command_line->HasSwitch(command)) {
      base::ScopedAllowBlockingForTesting allow_blocking;
      if (!callback.Run(base::BindOnce(&AppTestHelper::Shutdown, this))) {
        Shutdown(kBadCommand);
      }
      return;
    }
  }

  LOG(ERROR) << "No supported switch provided. Command: "
             << command_line->GetCommandLineString();
  Shutdown(kUnknownSwitch);
}

scoped_refptr<App> MakeAppTestHelper() {
  return base::MakeRefCounted<AppTestHelper>();
}

// Provides custom formatting for the unit test output.
class TersePrinter : public EmptyTestEventListener {
 private:
  // Called before any test activity starts.
  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}

  // Called after all test activities have ended.
  void OnTestProgramEnd(const UnitTest& unit_test) override {
    VLOG(0) << "Command " << (unit_test.Passed() ? "SUCCEEDED" : "FAILED")
            << ".";
  }

  // Called before a test starts.
  void OnTestStart(const TestInfo& /*test_info*/) override {}

  // Called after a failed assertion or a SUCCEED() invocation. Prints a
  // backtrace showing the failure.
  void OnTestPartResult(const TestPartResult& result) override {
    if (!result.failed()) {
      return;
    }
    logging::LogMessage(result.file_name(), result.line_number(),
                        logging::LOGGING_ERROR)
            .stream()
        << "*** Failure" << std::endl
        << result.message();
  }

  // Called after a test ends.
  void OnTestEnd(const TestInfo& /*test_info*/) override {}
};

int IntegrationTestsHelperMain(int argc, char** argv) {
  base::PlatformThread::SetName("IntegrationTestsHelperMain");
  base::CommandLine::Init(argc, argv);

  // Use the ${ISOLATED_OUTDIR} as a log destination. `test_suite` must be
  // defined before setting log items. The integration test helper always
  // logs into the same file as the `updater_tests_system` because the programs
  // are used together.
  base::TestSuite test_suite(argc, argv);
  updater::test::InitLoggingForUnitTest(
      base::FilePath(FILE_PATH_LITERAL("updater_test_system.log")));
#if BUILDFLAG(IS_WIN)
  auto scoped_com_initializer =
      std::make_unique<base::win::ScopedCOMInitializer>(
          base::win::ScopedCOMInitializer::kMTA);
  // Failing to disable COM exception handling is a critical error.
  CHECK(SUCCEEDED(DisableCOMExceptionHandling()))
      << "Failed to disable COM exception handling.";
#endif
  chrome::RegisterPathProvider();
  TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
  delete listeners.Release(listeners.default_result_printer());
  listeners.Append(new TersePrinter);
  return base::LaunchUnitTestsSerially(
      argc, argv,
      base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite)));
}

// Do not disable this test when encountering integration tests failures.
// This is not a unit test. It just wraps the execution of an integration test
// command, which is typical a step of an integration test.
TEST(TestHelperCommandRunner, Run) {
  base::test::TaskEnvironment environment;
  ScopedIPCSupportWrapper ipc_support_;
  ASSERT_EQ(MakeAppTestHelper()->Run(), 0);
}

}  // namespace
}  // namespace updater::test

// Wraps the execution of one integration test command in a unit test. The test
// commands contain gtest assertions, therefore the invocation of test commands
// must occur within the scope of a unit test of a gtest program. The test
// helper defines a unit test "TestHelperCommandRunner.Run", which runs the
// actual test command. Returns 0 if the test command succeeded.
int main(int argc, char** argv) {
  return updater::test::IntegrationTestsHelperMain(argc, argv);
}