File: command_storage_backend_unittest.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 (858 lines) | stat: -rw-r--r-- 32,814 bytes parent folder | download | duplicates (6)
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "components/sessions/core/command_storage_backend.h"

#include <stddef.h>

#include <array>
#include <limits>
#include <utility>

#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/scoped_refptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/test/bind.h"
#include "base/test/simple_test_clock.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "components/sessions/core/command_storage_manager.h"
#include "components/sessions/core/session_constants.h"
#include "components/sessions/core/session_service_commands.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::MakeRefCounted;

namespace sessions {

using size_type = SessionCommand::size_type;

namespace {

using SessionCommands = std::vector<std::unique_ptr<SessionCommand>>;

struct TestData {
  SessionCommand::id_type command_id;
  std::string data;
};

std::unique_ptr<SessionCommand> CreateCommandFromData(const TestData& data) {
  std::unique_ptr<SessionCommand> command = std::make_unique<SessionCommand>(
      data.command_id,
      static_cast<SessionCommand::size_type>(data.data.size()));
  if (!data.data.empty())
    memcpy(command->contents(), data.data.c_str(), data.data.size());
  return command;
}

}  // namespace

class CommandStorageBackendTest : public testing::Test {
 protected:
  // testing::TestWithParam:
  void SetUp() override {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    file_path_ = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Session"));
    restore_path_ =
        temp_dir_.GetPath().Append(FILE_PATH_LITERAL("SessionTestDirs"));
    base::CreateDirectory(restore_path_);
  }

  void AssertCommandEqualsData(const TestData& data,
                               const SessionCommand* command) {
    EXPECT_EQ(data.command_id, command->id());
    EXPECT_EQ(data.data.size(), command->size());
    EXPECT_TRUE(
        memcmp(command->contents(), data.data.c_str(), command->size()) == 0);
  }

  void AssertCommandsEqualsData(
      const TestData* data,
      size_t data_length,
      const std::vector<std::unique_ptr<SessionCommand>>& commands) {
    ASSERT_EQ(data_length, commands.size());
    for (size_t i = 0; i < data_length; ++i)
      EXPECT_NO_FATAL_FAILURE(
          AssertCommandEqualsData(data[i], commands[i].get()));
  }

  scoped_refptr<CommandStorageBackend> CreateBackend(
      const std::vector<uint8_t>& decryption_key = {},
      base::Clock* clock = nullptr) {
    return MakeRefCounted<CommandStorageBackend>(
        task_environment_.GetMainThreadTaskRunner(), file_path_,
        CommandStorageManager::SessionType::kOther, decryption_key, clock);
  }

  scoped_refptr<CommandStorageBackend> CreateBackendWithRestoreType() {
    const CommandStorageManager::SessionType type =
        CommandStorageManager::SessionType::kSessionRestore;
    return MakeRefCounted<CommandStorageBackend>(
        task_environment_.GetMainThreadTaskRunner(), restore_path_, type);
  }

  // Functions that call into private members of CommandStorageBackend.
  std::optional<CommandStorageBackend::SessionInfo> GetLastSessionInfo(
      CommandStorageBackend* backend) {
    // Force `last_session_info_` to be updated.
    backend->InitIfNecessary();
    return backend->last_session_info_;
  }

  std::vector<base::FilePath> GetSessionFilePathsSortedByReverseTimestamp() {
    auto infos = CommandStorageBackend::GetSessionFilesSortedByReverseTimestamp(
        file_path_, CommandStorageManager::SessionType::kOther);
    std::vector<base::FilePath> result;
    for (const auto& info : infos)
      result.push_back(info.path);
    return result;
  }

  static base::FilePath FilePathFromTime(
      CommandStorageManager::SessionType type,
      const base::FilePath& path,
      base::Time time) {
    return CommandStorageBackend::FilePathFromTime(type, path, time);
  }

  const base::FilePath& file_path() const { return file_path_; }

  const base::FilePath& restore_path() const { return restore_path_; }

 private:
  base::test::TaskEnvironment task_environment_;
  // Path used by CreateBackend().
  base::FilePath file_path_;
  // Path used by CreateBackendWithRestoreType().
  base::FilePath restore_path_;
  base::ScopedTempDir temp_dir_;
};

TEST_F(CommandStorageBackendTest, MigrateOther) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  struct TestData data = {1, "a"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());
  const auto path = backend->current_path();
  EXPECT_EQ(file_path().DirName(), path.DirName());
  auto base_name = file_path().BaseName().value();
  EXPECT_EQ(base_name, path.BaseName().value().substr(0, base_name.length()));
  backend = nullptr;

  // Move the file to the original path. This gives the logic before kOther
  // started using timestamps.
  ASSERT_TRUE(base::PathExists(path));
  ASSERT_TRUE(base::Move(path, file_path()));

  // Create the backend, should get back the data written.
  backend = CreateBackend();
  commands = backend->ReadLastSessionCommands().commands;
  ASSERT_EQ(1U, commands.size());
  AssertCommandEqualsData(data, commands[0].get());

  // Write some more data.
  struct TestData data2 = {1, "b"};
  commands.clear();
  commands.push_back(CreateCommandFromData(data2));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());

  // Recreate, verify updated data read back and the original file has been
  // removed.
  backend = nullptr;
  backend = CreateBackend();
  commands = backend->ReadLastSessionCommands().commands;
  EXPECT_FALSE(base::PathExists(file_path()));
  ASSERT_EQ(1U, commands.size());
  AssertCommandEqualsData(data2, commands[0].get());
}

TEST_F(CommandStorageBackendTest, SimpleReadWriteEncrypted) {
  std::vector<uint8_t> key = CommandStorageManager::CreateCryptoKey();
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  struct TestData data = {1, "a"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing(), key);

  // Read it back in.
  backend = nullptr;
  backend = CreateBackend(key);
  commands = backend->ReadLastSessionCommands().commands;

  ASSERT_EQ(1U, commands.size());
  AssertCommandEqualsData(data, commands[0].get());

  // Repeat, but with the wrong key.
  backend = nullptr;
  ++(key[0]);
  backend = CreateBackend(key);
  commands = backend->ReadLastSessionCommands().commands;
  EXPECT_TRUE(commands.empty());
}

TEST_F(CommandStorageBackendTest, RandomDataEncrypted) {
  auto data = std::to_array<TestData>({
      {1, "a"},
      {2, "ab"},
      {3, "abc"},
      {4, "abcd"},
      {5, "abcde"},
      {6, "abcdef"},
      {7, "abcdefg"},
      {8, "abcdefgh"},
      {9, "abcdefghi"},
      {10, "abcdefghij"},
      {11, "abcdefghijk"},
      {12, "abcdefghijkl"},
      {13, "abcdefghijklm"},
  });

  const std::vector<uint8_t> key = CommandStorageManager::CreateCryptoKey();
  for (size_t i = 0; i < std::size(data); ++i) {
    scoped_refptr<CommandStorageBackend> backend = CreateBackend(key);
    SessionCommands commands;
    if (i != 0) {
      // Read previous data.
      commands = backend->ReadLastSessionCommands().commands;
      ASSERT_EQ(i, commands.size());
      for (auto j = commands.begin(); j != commands.end(); ++j)
        AssertCommandEqualsData(data[j - commands.begin()], j->get());

      backend->AppendCommands(std::move(commands), true, base::DoNothing(),
                              key);
      commands = SessionCommands{};
    }
    commands.push_back(CreateCommandFromData(data[i]));
    backend->AppendCommands(std::move(commands), i == 0, base::DoNothing(),
                            i == 0 ? key : std::vector<uint8_t>());
  }
}

TEST_F(CommandStorageBackendTest, BigDataEncrypted) {
  auto data = std::to_array<TestData>({
      {1, "a"},
      {2, "ab"},
  });

  const std::vector<uint8_t> key = CommandStorageManager::CreateCryptoKey();
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  std::vector<std::unique_ptr<SessionCommand>> commands;

  commands.push_back(CreateCommandFromData(data[0]));
  const SessionCommand::size_type big_size =
      CommandStorageBackend::kFileReadBufferSize + 100;
  const SessionCommand::id_type big_id = 50;
  std::unique_ptr<SessionCommand> big_command =
      std::make_unique<SessionCommand>(big_id, big_size);
  reinterpret_cast<char*>(big_command->contents())[0] = 'a';
  reinterpret_cast<char*>(big_command->contents())[big_size - 1] = 'z';
  commands.push_back(std::move(big_command));
  commands.push_back(CreateCommandFromData(data[1]));
  backend->AppendCommands(std::move(commands), true, base::DoNothing(), key);

  backend = nullptr;
  backend = CreateBackend(key);

  commands = backend->ReadLastSessionCommands().commands;
  ASSERT_EQ(3U, commands.size());
  AssertCommandEqualsData(data[0], commands[0].get());
  AssertCommandEqualsData(data[1], commands[2].get());

  EXPECT_EQ(big_id, commands[1]->id());
  ASSERT_EQ(big_size, commands[1]->size());
  EXPECT_EQ('a', reinterpret_cast<char*>(commands[1]->contents())[0]);
  EXPECT_EQ('z',
            reinterpret_cast<char*>(commands[1]->contents())[big_size - 1]);
}

TEST_F(CommandStorageBackendTest, MarkerOnlyEncrypted) {
  std::vector<uint8_t> key = CommandStorageManager::CreateCryptoKey();
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  SessionCommands commands;
  std::vector<uint8_t> key2 = key;
  ++(key2[0]);
  backend->AppendCommands(std::move(commands), true, base::DoNothing(), key2);

  backend = nullptr;
  backend = CreateBackend(key2);
  commands = backend->ReadLastSessionCommands().commands;
  ASSERT_TRUE(commands.empty());
}

// Writes a command, appends another command with reset to true, then reads
// making sure we only get back the second command.
TEST_F(CommandStorageBackendTest, TruncateEncrypted) {
  std::vector<uint8_t> key = CommandStorageManager::CreateCryptoKey();
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  struct TestData first_data = {1, "a"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(first_data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing(), key);

  // Write another command, this time resetting the file when appending.
  struct TestData second_data = {2, "b"};
  commands.clear();
  commands.push_back(CreateCommandFromData(second_data));
  std::vector<uint8_t> key2 = key;
  ++(key2[0]);
  backend->AppendCommands(std::move(commands), true, base::DoNothing(), key2);

  // Read it back in.
  backend = nullptr;
  backend = CreateBackend(key2);
  commands = backend->ReadLastSessionCommands().commands;

  // And make sure we get back the expected data.
  ASSERT_EQ(1U, commands.size());
  AssertCommandEqualsData(second_data, commands[0].get());
}

std::unique_ptr<SessionCommand> CreateCommandWithMaxSize() {
  const size_type max_size_value = std::numeric_limits<size_type>::max();
  std::unique_ptr<SessionCommand> command =
      std::make_unique<SessionCommand>(11, max_size_value);
  for (int i = 0; i <= max_size_value; ++i)
    (command->contents())[i] = i;
  return command;
}

TEST_F(CommandStorageBackendTest, MaxSizeTypeEncrypted) {
  std::vector<uint8_t> key = CommandStorageManager::CreateCryptoKey();
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();

  SessionCommands commands;
  commands.push_back(CreateCommandWithMaxSize());
  backend->AppendCommands(std::move(commands), true, base::DoNothing(), key);

  // Read it back in.
  backend = nullptr;
  backend = CreateBackend(key);
  commands = backend->ReadLastSessionCommands().commands;

  // Encryption restricts the main size, and results in truncation.
  ASSERT_EQ(1U, commands.size());
  auto expected_command = CreateCommandWithMaxSize();
  EXPECT_EQ(expected_command->id(), (commands[0])->id());
  const size_type expected_size =
      expected_command->size() -
      CommandStorageBackend::kEncryptionOverheadInBytes -
      sizeof(SessionCommand::id_type);
  ASSERT_EQ(expected_size, (commands[0])->size());
  EXPECT_TRUE(memcmp(commands[0]->contents(), expected_command->contents(),
                     expected_size) == 0);
}

TEST_F(CommandStorageBackendTest, MaxSizeType) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();

  SessionCommands commands;
  commands.push_back(CreateCommandWithMaxSize());
  backend->AppendCommands(std::move(commands), true, base::DoNothing());

  // Read it back in.
  backend = nullptr;
  backend = CreateBackend();
  commands = backend->ReadLastSessionCommands().commands;

  ASSERT_EQ(1U, commands.size());
  auto expected_command = CreateCommandWithMaxSize();
  EXPECT_EQ(expected_command->id(), (commands[0])->id());
  const size_type expected_size =
      expected_command->size() - sizeof(SessionCommand::id_type);
  ASSERT_EQ(expected_size, (commands[0])->size());
  EXPECT_TRUE(memcmp(commands[0]->contents(), expected_command->contents(),
                     expected_size) == 0);
}

TEST_F(CommandStorageBackendTest, IsValidFileWithInvalidFiles) {
  base::WriteFile(file_path(), "z");
  EXPECT_FALSE(CommandStorageBackend::IsValidFile(file_path()));

  base::WriteFile(file_path(), "a longer string that does not match header");
  EXPECT_FALSE(CommandStorageBackend::IsValidFile(file_path()));
}

TEST_F(CommandStorageBackendTest, IsNotValidFileWithoutMarker) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  const auto path = backend->current_path();
  backend->AppendCommands({}, true, base::DoNothing());
  backend = nullptr;

  EXPECT_FALSE(CommandStorageBackend::IsValidFile(path));
}

TEST_F(CommandStorageBackendTest, SimpleReadWriteWithRestoreType) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  struct TestData data = {1, "a"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());

  // Read it back in.
  backend = nullptr;
  backend = CreateBackendWithRestoreType();
  commands.clear();
  backend->AppendCommands(std::move(commands), true, base::DoNothing());
  commands = backend->ReadLastSessionCommands().commands;

  ASSERT_EQ(1U, commands.size());
  AssertCommandEqualsData(data, commands[0].get());

  backend = nullptr;
  backend = CreateBackendWithRestoreType();
  commands = backend->ReadLastSessionCommands().commands;

  ASSERT_EQ(0U, commands.size());

  // Make sure we can delete.
  backend->DeleteLastSession();
  commands = backend->ReadLastSessionCommands().commands;
  ASSERT_EQ(0U, commands.size());
}

TEST_F(CommandStorageBackendTest, RandomDataWithRestoreType) {
  auto data = std::to_array<TestData>({
      {1, "a"},
      {2, "ab"},
      {3, "abc"},
      {4, "abcd"},
      {5, "abcde"},
      {6, "abcdef"},
      {7, "abcdefg"},
      {8, "abcdefgh"},
      {9, "abcdefghi"},
      {10, "abcdefghij"},
      {11, "abcdefghijk"},
      {12, "abcdefghijkl"},
      {13, "abcdefghijklm"},
  });

  for (size_t i = 0; i < std::size(data); ++i) {
    scoped_refptr<CommandStorageBackend> backend =
        CreateBackendWithRestoreType();
    SessionCommands commands;
    if (i != 0) {
      // Read previous data.
      commands = backend->ReadLastSessionCommands().commands;
      ASSERT_EQ(i, commands.size());
      for (auto j = commands.begin(); j != commands.end(); ++j)
        AssertCommandEqualsData(data[j - commands.begin()], j->get());

      // Write the previous data back.
      backend->AppendCommands(std::move(commands), true, base::DoNothing());
      commands.clear();
    }
    commands.push_back(CreateCommandFromData(data[i]));
    backend->AppendCommands(std::move(commands), i == 0, base::DoNothing());
  }
}

TEST_F(CommandStorageBackendTest, BigDataWithRestoreType) {
  auto data = std::to_array<TestData>({
      {1, "a"},
      {2, "ab"},
  });

  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  std::vector<std::unique_ptr<SessionCommand>> commands;

  commands.push_back(CreateCommandFromData(data[0]));
  const SessionCommand::size_type big_size =
      CommandStorageBackend::kFileReadBufferSize + 100;
  const SessionCommand::id_type big_id = 50;
  std::unique_ptr<SessionCommand> big_command =
      std::make_unique<SessionCommand>(big_id, big_size);
  reinterpret_cast<char*>(big_command->contents())[0] = 'a';
  reinterpret_cast<char*>(big_command->contents())[big_size - 1] = 'z';
  commands.push_back(std::move(big_command));
  commands.push_back(CreateCommandFromData(data[1]));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());

  backend = nullptr;
  backend = CreateBackendWithRestoreType();

  commands = backend->ReadLastSessionCommands().commands;
  ASSERT_EQ(3U, commands.size());
  AssertCommandEqualsData(data[0], commands[0].get());
  AssertCommandEqualsData(data[1], commands[2].get());

  EXPECT_EQ(big_id, commands[1]->id());
  ASSERT_EQ(big_size, commands[1]->size());
  EXPECT_EQ('a', reinterpret_cast<char*>(commands[1]->contents())[0]);
  EXPECT_EQ('z',
            reinterpret_cast<char*>(commands[1]->contents())[big_size - 1]);
}

TEST_F(CommandStorageBackendTest, CommandWithRestoreType) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  SessionCommands commands;
  backend->AppendCommands(std::move(commands), true, base::DoNothing());
  backend->MoveCurrentSessionToLastSession();

  commands = backend->ReadLastSessionCommands().commands;
  ASSERT_EQ(0U, commands.size());
}

// Writes a command, appends another command with reset to true, then reads
// making sure we only get back the second command.
TEST_F(CommandStorageBackendTest, TruncateWithRestoreType) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  struct TestData first_data = {1, "a"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(first_data));
  backend->AppendCommands(std::move(commands), false, base::DoNothing());
  commands.clear();

  // Write another command, this time resetting the file when appending.
  struct TestData second_data = {2, "b"};
  commands.push_back(CreateCommandFromData(second_data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());

  // Read it back in.
  backend = nullptr;
  backend = CreateBackendWithRestoreType();
  commands = backend->ReadLastSessionCommands().commands;

  // And make sure we get back the expected data.
  ASSERT_EQ(1U, commands.size());
  AssertCommandEqualsData(second_data, commands[0].get());
}

// Test parsing the timestamp of a session from the path.
TEST_F(CommandStorageBackendTest, TimestampFromPathWithRestoreType) {
  const auto base_dir = base::FilePath(kSessionsDirectory);

  // Test parsing the timestamp from a valid session.
  const auto test_path_1 = base_dir.Append(FILE_PATH_LITERAL("Tabs_0"));
  base::Time result_time_1;
  EXPECT_TRUE(
      CommandStorageBackend::TimestampFromPath(test_path_1, result_time_1));
  EXPECT_EQ(base::Time(), result_time_1);

  const auto test_path_2 =
      base_dir.Append(FILE_PATH_LITERAL("Session_13234316721694577"));
  base::Time result_time_2;
  EXPECT_TRUE(
      CommandStorageBackend::TimestampFromPath(test_path_2, result_time_2));
  EXPECT_EQ(base::Time::FromDeltaSinceWindowsEpoch(
                base::Microseconds(13234316721694577)),
            result_time_2);

  // Test attempting to parse invalid file names.
  const auto invalid_path_1 =
      base_dir.Append(FILE_PATH_LITERAL("Session_nonsense"));
  base::Time invalid_result_1;
  EXPECT_FALSE(CommandStorageBackend::TimestampFromPath(invalid_path_1,
                                                        invalid_result_1));

  const auto invalid_path_2 = base_dir.Append(FILE_PATH_LITERAL("Arbitrary"));
  base::Time invalid_result_2;
  EXPECT_FALSE(CommandStorageBackend::TimestampFromPath(invalid_path_2,
                                                        invalid_result_2));
}

// Test serializing a timestamp to string.
TEST_F(CommandStorageBackendTest, FilePathFromTimeWithRestoreType) {
  const auto base_dir = base::FilePath(kSessionsDirectory);
  const auto test_time_1 = base::Time();
  const auto result_path_1 =
      FilePathFromTime(CommandStorageManager::SessionType::kSessionRestore,
                       base::FilePath(), test_time_1);
  EXPECT_EQ(base_dir.Append(FILE_PATH_LITERAL("Session_0")), result_path_1);

  const auto test_time_2 = base::Time::FromDeltaSinceWindowsEpoch(
      base::Microseconds(13234316721694577));
  const auto result_path_2 =
      FilePathFromTime(CommandStorageManager::SessionType::kTabRestore,
                       base::FilePath(), test_time_2);
  EXPECT_EQ(base_dir.Append(FILE_PATH_LITERAL("Tabs_13234316721694577")),
            result_path_2);
}

// Test that the previous session is empty if no session files exist.
TEST_F(CommandStorageBackendTest,
       DeterminePreviousSessionEmptyWithRestoreType) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  ASSERT_FALSE(GetLastSessionInfo(backend.get()));
}

// Test that the previous session is selected correctly when a file is present.
TEST_F(CommandStorageBackendTest,
       DeterminePreviousSessionSingleWithRestoreType) {
  const auto prev_path = restore_path().Append(
      base::FilePath(kSessionsDirectory)
          .Append(FILE_PATH_LITERAL("Session_13235178308836991")));
  ASSERT_TRUE(base::CreateDirectory(prev_path.DirName()));
  ASSERT_TRUE(base::WriteFile(prev_path, ""));

  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  auto last_session_info = GetLastSessionInfo(backend.get());
  ASSERT_TRUE(last_session_info);
  ASSERT_EQ(prev_path, last_session_info->path);
}

// Test that the previous session is selected correctly when multiple session
// files are present.
TEST_F(CommandStorageBackendTest,
       DeterminePreviousSessionMultipleWithRestoreType) {
  const auto sessions_dir =
      restore_path().Append(base::FilePath(kSessionsDirectory));
  const auto prev_path =
      sessions_dir.Append(FILE_PATH_LITERAL("Session_13235178308836991"));
  const auto old_path_1 =
      sessions_dir.Append(FILE_PATH_LITERAL("Session_13235178308548874"));
  const auto old_path_2 = sessions_dir.Append(FILE_PATH_LITERAL("Session_0"));
  ASSERT_TRUE(base::CreateDirectory(prev_path.DirName()));
  ASSERT_TRUE(base::WriteFile(prev_path, ""));
  ASSERT_TRUE(base::WriteFile(old_path_1, ""));
  ASSERT_TRUE(base::WriteFile(old_path_2, ""));

  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  auto last_session_info = GetLastSessionInfo(backend.get());
  ASSERT_TRUE(last_session_info);
  ASSERT_EQ(prev_path, last_session_info->path);
}

// Test that the a file with an invalid name won't be used.
TEST_F(CommandStorageBackendTest,
       DeterminePreviousSessionInvalidWithRestoreType) {
  const auto prev_path =
      restore_path().Append(base::FilePath(kSessionsDirectory)
                                .Append(FILE_PATH_LITERAL("Session_invalid")));
  ASSERT_TRUE(base::CreateDirectory(prev_path.DirName()));
  ASSERT_TRUE(base::WriteFile(prev_path, ""));

  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  auto last_session_info = GetLastSessionInfo(backend.get());
  ASSERT_FALSE(last_session_info);
}

// Tests that MoveCurrentSessionToLastSession deletes the last session file.
TEST_F(CommandStorageBackendTest,
       MoveCurrentSessionToLastDeletesLastSessionWithRestoreType) {
  const auto sessions_dir =
      restore_path().Append(base::FilePath(kSessionsDirectory));
  const auto last_session =
      sessions_dir.Append(FILE_PATH_LITERAL("Session_13235178308548874"));
  ASSERT_TRUE(base::CreateDirectory(last_session.DirName()));
  ASSERT_TRUE(base::WriteFile(last_session, ""));

  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  char buffer[1];
  ASSERT_EQ(0, base::ReadFile(last_session, buffer, 0));
  backend->MoveCurrentSessionToLastSession();
  ASSERT_EQ(-1, base::ReadFile(last_session, buffer, 0));
}

TEST_F(CommandStorageBackendTest, GetSessionFiles) {
  EXPECT_TRUE(CommandStorageBackend::GetSessionFilePaths(
                  file_path(), CommandStorageManager::kOther)
                  .empty());
  ASSERT_TRUE(base::WriteFile(file_path(), ""));
  // Not a valid name, as doesn't contain timestamp separator.
  ASSERT_TRUE(
      base::WriteFile(file_path().DirName().AppendASCII("Session 123"), ""));
  // Valid name.
  ASSERT_TRUE(
      base::WriteFile(file_path().DirName().AppendASCII("Session_124"), ""));
  // Valid name, but should not be returned as beginning doesn't match.
  ASSERT_TRUE(
      base::WriteFile(file_path().DirName().AppendASCII("Foo_125"), ""));
  auto paths = CommandStorageBackend::GetSessionFilePaths(
      file_path(), CommandStorageManager::kOther);
  ASSERT_EQ(1u, paths.size());
  EXPECT_EQ("Session_124", paths.begin()->BaseName().MaybeAsASCII());
}

TEST_F(CommandStorageBackendTest, TimestampSeparatorIsAscii) {
  // Code in WebLayer relies on the timestamp separator being ascii.
  ASSERT_TRUE(!base::FilePath(kTimestampSeparator).MaybeAsASCII().empty());
}

TEST_F(CommandStorageBackendTest, GetSessionFilesAreSortedByReverseTimestamp) {
  ASSERT_TRUE(
      base::WriteFile(file_path().DirName().AppendASCII("Session_130"), ""));
  ASSERT_TRUE(
      base::WriteFile(file_path().DirName().AppendASCII("Session_120"), ""));
  ASSERT_TRUE(
      base::WriteFile(file_path().DirName().AppendASCII("Session_125"), ""));
  ASSERT_TRUE(
      base::WriteFile(file_path().DirName().AppendASCII("Session_128"), ""));
  auto paths = GetSessionFilePathsSortedByReverseTimestamp();
  ASSERT_EQ(4u, paths.size());
  EXPECT_EQ("Session_130", paths[0].BaseName().MaybeAsASCII());
  EXPECT_EQ("Session_128", paths[1].BaseName().MaybeAsASCII());
  EXPECT_EQ("Session_125", paths[2].BaseName().MaybeAsASCII());
  EXPECT_EQ("Session_120", paths[3].BaseName().MaybeAsASCII());
}

TEST_F(CommandStorageBackendTest, UseMarkerWithoutValidMarker) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  struct TestData data = {1, "a"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), false, base::DoNothing());

  // Read it back in.
  backend = nullptr;
  backend = CreateBackendWithRestoreType();
  commands = backend->ReadLastSessionCommands().commands;
  // There should be no commands as a valid marker was not written.
  ASSERT_TRUE(commands.empty());

  // As there was no valid marker, there should be no last session file.
  EXPECT_FALSE(GetLastSessionInfo(backend.get()));
}

// This test moves a previously written file into the expected location and
// ensures it's read. This is to verify reading hasn't changed in an
// incompatible manner.
TEST_F(CommandStorageBackendTest, ReadPreviouslyWrittenData) {
  base::FilePath test_data_path;
  ASSERT_TRUE(
      base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &test_data_path));
  test_data_path = test_data_path.AppendASCII("components")
                       .AppendASCII("test")
                       .AppendASCII("data")
                       .AppendASCII("sessions")
                       .AppendASCII("last_session");
  struct TestData data[] = {
      {1, "a"},
      {2, "ab"},
      {3, "abc"},
      {4, "abcd"},
      {5, "abcde"},
      {6, "abcdef"},
      {7, "abcdefg"},
      {8, "abcdefgh"},
      {9, "abcdefghi"},
      {10, "abcdefghij"},
      {11, "abcdefghijk"},
      {12, "abcdefghijkl"},
      {13, "abcdefghijklm"},
  };

  ASSERT_TRUE(base::CopyFile(
      test_data_path, restore_path().Append(kLegacyCurrentSessionFileName)));
  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  AssertCommandsEqualsData(data, std::size(data),
                           backend->ReadLastSessionCommands().commands);
}

TEST_F(CommandStorageBackendTest, NewFileOnTruncate) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackendWithRestoreType();
  struct TestData data = {1, "a"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());
  const base::FilePath path1 = backend->current_path();

  // Path shouldn't change if truncate is false.
  commands.clear();
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), false, base::DoNothing());
  EXPECT_EQ(path1, backend->current_path());

  // Path should change on truncate, and `path1` should not be removed.
  commands.clear();
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());
  const base::FilePath path2 = backend->current_path();
  EXPECT_TRUE(!path2.empty());
  EXPECT_NE(path1, path2);
  EXPECT_TRUE(base::PathExists(path1));
  EXPECT_TRUE(base::PathExists(path2));

  // Repeat. This time `path1` should be removed.
  commands.clear();
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());
  const base::FilePath path3 = backend->current_path();
  EXPECT_TRUE(!path3.empty());
  EXPECT_NE(path1, path3);
  EXPECT_NE(path2, path3);
  EXPECT_FALSE(base::PathExists(path1));
  EXPECT_TRUE(base::PathExists(path2));
  EXPECT_TRUE(base::PathExists(path3));
}

TEST_F(CommandStorageBackendTest, AppendCommandsCallbackRunOnError) {
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  backend->ForceAppendCommandsToFailForTesting();
  base::RunLoop run_loop;
  backend->AppendCommands({}, true, run_loop.QuitClosure());
  run_loop.Run();
}

TEST_F(CommandStorageBackendTest, RestoresFileWithMarkerAfterFailure) {
  // Write `data` and a marker.
  scoped_refptr<CommandStorageBackend> backend = CreateBackend();
  struct TestData data = {11, "X"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());
  EXPECT_TRUE(backend->IsFileOpen());

  // Make appending fail, which should close the file.
  backend->ForceAppendCommandsToFailForTesting();
  backend->AppendCommands({}, false, base::DoNothing());
  EXPECT_FALSE(backend->IsFileOpen());

  // Append again, with another fail. Should attempt to reopen file and file.
  backend->ForceAppendCommandsToFailForTesting();
  backend->AppendCommands({}, true, base::DoNothing());
  EXPECT_FALSE(backend->IsFileOpen());

  // Reopen and read last session. Should get `data` and marker.
  backend = nullptr;
  backend = CreateBackend();
  backend->AppendCommands({}, false, base::DoNothing());
  commands = backend->ReadLastSessionCommands().commands;
  ASSERT_EQ(1u, commands.size());
  AssertCommandEqualsData(data, commands[0].get());
}

TEST_F(CommandStorageBackendTest, PathTimeIncreases) {
  base::SimpleTestClock test_clock;
  test_clock.SetNow(base::Time::Now());
  scoped_refptr<CommandStorageBackend> backend = CreateBackend({}, &test_clock);
  // Write `data` and a marker.
  struct TestData data = {11, "X"};
  SessionCommands commands;
  commands.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands), true, base::DoNothing());
  const base::FilePath path1 = backend->current_path();
  EXPECT_FALSE(path1.empty());
  base::Time path1_time;
  EXPECT_TRUE(CommandStorageBackend::TimestampFromPath(path1, path1_time));

  test_clock.Advance(base::Seconds(-1));
  SessionCommands commands2;
  commands2.push_back(CreateCommandFromData(data));
  backend->AppendCommands(std::move(commands2), true, base::DoNothing());
  const base::FilePath path2 = backend->current_path();
  EXPECT_FALSE(path2.empty());
  EXPECT_NE(path1, path2);
  base::Time path2_time;
  EXPECT_TRUE(CommandStorageBackend::TimestampFromPath(path2, path2_time));
  // Even though the current time is before the previous time, the timestamp
  // of the file should increase.
  EXPECT_GT(path2_time, path1_time);
  // Backend needs to be destroyed before test_clock so we don't end up with
  // dangling reference.
  backend.reset();
}

}  // namespace sessions