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

base / message_loop / work_id_provider_unittest.cc [blame]

// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/message_loop/work_id_provider.h"

#include <limits>
#include <memory>
#include <utility>

#include "base/functional/callback.h"
#include "base/test/bind.h"
#include "base/threading/simple_thread.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {

namespace {

class TestThread : public SimpleThread {
 public:
  TestThread(OnceCallback<void(WorkIdProvider*)> validate_func)
      : SimpleThread("WorkIdProviderTestThread"),
        validate_func_(std::move(validate_func)) {}

  void Run() override {
    std::move(validate_func_).Run(WorkIdProvider::GetForCurrentThread());
  }

 private:
  OnceCallback<void(WorkIdProvider*)> validate_func_;
};

template <class Func>
void RunTest(const Func& func) {
  TestThread thread(BindLambdaForTesting(func));

  thread.Start();
  thread.Join();
}

}  // namespace

TEST(WorkIdProviderTest, StartsAtZero) {
  RunTest(
      [](WorkIdProvider* provider) { EXPECT_EQ(0u, provider->GetWorkId()); });
}

TEST(WorkIdProviderTest, Increment) {
  RunTest([](WorkIdProvider* provider) {
    provider->IncrementWorkIdForTesting();
    EXPECT_EQ(1u, provider->GetWorkId());

    provider->IncrementWorkIdForTesting();
    EXPECT_EQ(2u, provider->GetWorkId());

    provider->IncrementWorkIdForTesting();
    EXPECT_EQ(3u, provider->GetWorkId());
  });
}

TEST(WorkIdProviderTest, SkipsZeroOnOverflow) {
  RunTest([](WorkIdProvider* provider) {
    provider->SetCurrentWorkIdForTesting(
        std::numeric_limits<unsigned int>::max());
    provider->IncrementWorkIdForTesting();
    EXPECT_EQ(1u, provider->GetWorkId());
  });
}

}  // namespace base